\n * All color values (diffuse, specular, emissive) are in linear color space.\n *
\n *\n * @name czm_modelMaterial\n * @glslStruct\n *\n * @property {vec3} diffuse Incoming light that scatters evenly in all directions.\n * @property {float} alpha Alpha of this material. 0.0 is completely transparent; 1.0 is completely opaque.\n * @property {vec3} specular Color of reflected light at normal incidence in PBR materials. This is sometimes referred to as f0 in the literature.\n * @property {float} roughness A number from 0.0 to 1.0 representing how rough the surface is. Values near 0.0 produce glossy surfaces, while values near 1.0 produce rough surfaces.\n * @property {vec3} normalEC Surface's normal in eye coordinates. It is used for effects such as normal mapping. The default is the surface's unmodified normal.\n * @property {float} occlusion Ambient occlusion recieved at this point on the material. 1.0 means fully lit, 0.0 means fully occluded.\n * @property {vec3} emissive Light emitted by the material equally in all directions. The default is vec3(0.0), which emits no light.\n */\nstruct 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Structs/modelVertexOutput.js
var modelVertexOutput_default = "/**\n * Struct for representing the output of a custom vertex shader.\n * \n * @name czm_modelVertexOutput\n * @glslStruct\n *\n * @see {@link CustomShader}\n * @see {@link Model}\n *\n * @property {vec3} positionMC The position of the vertex in model coordinates\n * @property {float} pointSize A custom value for gl_PointSize. This is only used for point primitives. \n */\nstruct czm_modelVertexOutput {\n vec3 positionMC;\n float pointSize;\n};\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Structs/pbrParameters.js
var pbrParameters_default = "/**\n * Parameters for {@link czm_pbrLighting}\n *\n * @name czm_material\n * @glslStruct\n *\n * @property {vec3} diffuseColor the diffuse color of the material for the lambert term of the rendering equation\n * @property {float} roughness a value from 0.0 to 1.0 that indicates how rough the surface of the material is.\n * @property {vec3} f0 The reflectance of the material at normal incidence\n */\nstruct czm_pbrParameters\n{\n vec3 diffuseColor;\n float roughness;\n vec3 f0;\n};\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Structs/ray.js
var ray_default = "/**\n * DOC_TBA\n *\n * @name czm_ray\n * @glslStruct\n */\nstruct czm_ray\n{\n vec3 origin;\n vec3 direction;\n};\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Structs/raySegment.js
var raySegment_default = "/**\n * DOC_TBA\n *\n * @name czm_raySegment\n * @glslStruct\n */\nstruct czm_raySegment\n{\n float start;\n float stop;\n};\n\n/**\n * DOC_TBA\n *\n * @name czm_emptyRaySegment\n * @glslConstant \n */\nconst czm_raySegment czm_emptyRaySegment = czm_raySegment(-czm_infinity, -czm_infinity);\n\n/**\n * DOC_TBA\n *\n * @name czm_fullRaySegment\n * @glslConstant \n */\nconst czm_raySegment czm_fullRaySegment = czm_raySegment(0.0, czm_infinity);\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Structs/shadowParameters.js
var shadowParameters_default = "struct czm_shadowParameters\n{\n#ifdef USE_CUBE_MAP_SHADOW\n vec3 texCoords;\n#else\n vec2 texCoords;\n#endif\n\n float depthBias;\n float depth;\n float nDotL;\n vec2 texelStepSize;\n float normalShadingSmooth;\n float darkness;\n};\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/HSBToRGB.js
var HSBToRGB_default = "/**\n * Converts an HSB color (hue, saturation, brightness) to RGB\n * HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}\n *\n * @name czm_HSBToRGB\n * @glslFunction\n * \n * @param {vec3} hsb The color in HSB.\n *\n * @returns {vec3} The color in RGB.\n *\n * @example\n * vec3 hsb = czm_RGBToHSB(rgb);\n * hsb.z *= 0.1;\n * rgb = czm_HSBToRGB(hsb);\n */\n\nconst vec4 K_HSB2RGB = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n\nvec3 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/HSLToRGB.js
var HSLToRGB_default = "/**\n * Converts an HSL color (hue, saturation, lightness) to RGB\n * HSL <-> RGB conversion: {@link http://www.chilliant.com/rgb2hsv.html}\n *\n * @name czm_HSLToRGB\n * @glslFunction\n * \n * @param {vec3} rgb The color in HSL.\n *\n * @returns {vec3} The color in RGB.\n *\n * @example\n * vec3 hsl = czm_RGBToHSL(rgb);\n * hsl.z *= 0.1;\n * rgb = czm_HSLToRGB(hsl);\n */\n\nvec3 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\nvec3 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/RGBToHSB.js
var RGBToHSB_default = "/**\n * Converts an RGB color to HSB (hue, saturation, brightness)\n * HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}\n *\n * @name czm_RGBToHSB\n * @glslFunction\n * \n * @param {vec3} rgb The color in RGB.\n *\n * @returns {vec3} The color in HSB.\n *\n * @example\n * vec3 hsb = czm_RGBToHSB(rgb);\n * hsb.z *= 0.1;\n * rgb = czm_HSBToRGB(hsb);\n */\n\nconst vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\nvec3 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\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/RGBToHSL.js
var RGBToHSL_default = "/**\n * Converts an RGB color to HSL (hue, saturation, lightness)\n * HSL <-> RGB conversion: {@link http://www.chilliant.com/rgb2hsv.html}\n *\n * @name czm_RGBToHSL\n * @glslFunction\n * \n * @param {vec3} rgb The color in RGB.\n *\n * @returns {vec3} The color in HSL.\n *\n * @example\n * vec3 hsl = czm_RGBToHSL(rgb);\n * hsl.z *= 0.1;\n * rgb = czm_HSLToRGB(hsl);\n */\n \nvec3 RGBtoHCV(vec3 rgb)\n{\n // Based on work by Sam Hocevar and Emil Persson\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\nvec3 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/RGBToXYZ.js
var RGBToXYZ_default = "/**\n * Converts an RGB color to CIE Yxy.\n *
The conversion is described in\n * {@link http://content.gpwiki.org/index.php/D3DBook:High-Dynamic_Range_Rendering#Luminance_Transform|Luminance Transform}\n *
\n * \n * @name czm_RGBToXYZ\n * @glslFunction\n * \n * @param {vec3} rgb The color in RGB.\n *\n * @returns {vec3} The color in CIE Yxy.\n *\n * @example\n * vec3 xyz = czm_RGBToXYZ(rgb);\n * xyz.x = max(xyz.x - luminanceThreshold, 0.0);\n * rgb = czm_XYZToRGB(xyz);\n */\nvec3 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/XYZToRGB.js
var XYZToRGB_default = "/**\n * Converts a CIE Yxy color to RGB.\n *
The conversion is described in\n * {@link http://content.gpwiki.org/index.php/D3DBook:High-Dynamic_Range_Rendering#Luminance_Transform|Luminance Transform}\n *
\n * \n * @name czm_XYZToRGB\n * @glslFunction\n * \n * @param {vec3} Yxy The color in CIE Yxy.\n *\n * @returns {vec3} The color in RGB.\n *\n * @example\n * vec3 xyz = czm_RGBToXYZ(rgb);\n * xyz.x = max(xyz.x - luminanceThreshold, 0.0);\n * rgb = czm_XYZToRGB(xyz);\n */\nvec3 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 \n return XYZ2RGB * xyz;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/acesTonemapping.js
var acesTonemapping_default = "// See:\n// https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/\n\nvec3 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\n color = (color * (color + a) - b) / (color * (g * color + c) + d);\n\n color = clamp(color, 0.0, 1.0);\n\n return color;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/alphaWeight.js
var alphaWeight_default = "/**\n * @private\n */\nfloat czm_alphaWeight(float a)\n{\n float z = (gl_FragCoord.z - czm_viewportTransformation[3][2]) / czm_viewportTransformation[2][2];\n\n // See Weighted Blended Order-Independent Transparency for examples of different weighting functions:\n // http://jcgt.org/published/0002/02/09/\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/antialias.js
var antialias_default = "/**\n * Procedural anti-aliasing by blurring two colors that meet at a sharp edge.\n *\n * @name czm_antialias\n * @glslFunction\n *\n * @param {vec4} color1 The color on one side of the edge.\n * @param {vec4} color2 The color on the other side of the edge.\n * @param {vec4} currentcolor The current color, either color1 or color2.\n * @param {float} dist The distance to the edge in texture coordinates.\n * @param {float} [fuzzFactor=0.1] Controls the blurriness between the two colors.\n * @returns {vec4} The anti-aliased color.\n *\n * @example\n * // GLSL declarations\n * vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist, float fuzzFactor);\n * vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist);\n *\n * // get the color for a material that has a sharp edge at the line y = 0.5 in texture space\n * float dist = abs(textureCoordinates.t - 0.5);\n * vec4 currentColor = mix(bottomColor, topColor, step(0.5, textureCoordinates.t));\n * vec4 color = czm_antialias(bottomColor, topColor, currentColor, dist, 0.1);\n */\nvec4 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); //makes the transition nicer\n \n vec4 midColor = (color1 + color2) * 0.5;\n return mix(midColor, currentColor, val1);\n}\n\nvec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist)\n{\n return czm_antialias(color1, color2, currentColor, dist, 0.1);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/approximateSphericalCoordinates.js
var approximateSphericalCoordinates_default = "/**\n * Approximately computes spherical coordinates given a normal.\n * Uses approximate inverse trigonometry for speed and consistency,\n * since inverse trigonometry can differ from vendor-to-vendor and when compared with the CPU.\n *\n * @name czm_approximateSphericalCoordinates\n * @glslFunction\n *\n * @param {vec3} normal arbitrary-length normal.\n *\n * @returns {vec2} Approximate latitude and longitude spherical coordinates.\n */\nvec2 czm_approximateSphericalCoordinates(vec3 normal) {\n // Project into plane with vertical for latitude\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/backFacing.js
var backFacing_default = "/**\n * Determines if the fragment is back facing\n *\n * @name czm_backFacing\n * @glslFunction \n * \n * @returns {bool} true if the fragment is back facing; otherwise, false.\n */\nbool czm_backFacing()\n{\n // !gl_FrontFacing doesn't work as expected on Mac/Intel so use the more verbose form instead. See https://github.com/CesiumGS/cesium/pull/8494.\n return gl_FrontFacing == false;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/branchFreeTernary.js
var branchFreeTernary_default = "/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a float expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {float} a Value to return if the comparison is true.\n * @param {float} b Value to return if the comparison is false.\n *\n * @returns {float} equivalent of comparison ? a : b\n */\nfloat czm_branchFreeTernary(bool comparison, float a, float b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n\n/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a vec2 expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {vec2} a Value to return if the comparison is true.\n * @param {vec2} b Value to return if the comparison is false.\n *\n * @returns {vec2} equivalent of comparison ? a : b\n */\nvec2 czm_branchFreeTernary(bool comparison, vec2 a, vec2 b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n\n/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a vec3 expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {vec3} a Value to return if the comparison is true.\n * @param {vec3} b Value to return if the comparison is false.\n *\n * @returns {vec3} equivalent of comparison ? a : b\n */\nvec3 czm_branchFreeTernary(bool comparison, vec3 a, vec3 b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n\n/**\n * Branchless ternary operator to be used when it's inexpensive to explicitly\n * evaluate both possibilities for a vec4 expression.\n *\n * @name czm_branchFreeTernary\n * @glslFunction\n *\n * @param {bool} comparison A comparison statement\n * @param {vec3} a Value to return if the comparison is true.\n * @param {vec3} b Value to return if the comparison is false.\n *\n * @returns {vec3} equivalent of comparison ? a : b\n */\nvec4 czm_branchFreeTernary(bool comparison, vec4 a, vec4 b) {\n float useA = float(comparison);\n return a * useA + b * (1.0 - useA);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/cascadeColor.js
var cascadeColor_default = "\nvec4 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/cascadeDistance.js
var cascadeDistance_default = "\nuniform vec4 shadowMap_cascadeDistances;\n\nfloat czm_cascadeDistance(vec4 weights)\n{\n return dot(shadowMap_cascadeDistances, weights);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/cascadeMatrix.js
var cascadeMatrix_default = "\nuniform mat4 shadowMap_cascadeMatrices[4];\n\nmat4 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/cascadeWeights.js
var cascadeWeights_default = "\nuniform vec4 shadowMap_cascadeSplits[2];\n\nvec4 czm_cascadeWeights(float depthEye)\n{\n // One component is set to 1.0 and all others set to 0.0.\n vec4 near = step(shadowMap_cascadeSplits[0], vec4(depthEye));\n vec4 far = step(depthEye, shadowMap_cascadeSplits[1]);\n return near * far;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/columbusViewMorph.js
var columbusViewMorph_default = "/**\n * DOC_TBA\n *\n * @name czm_columbusViewMorph\n * @glslFunction\n */\nvec4 czm_columbusViewMorph(vec4 position2D, vec4 position3D, float time)\n{\n // Just linear for now.\n vec3 p = mix(position2D.xyz, position3D.xyz, time);\n return vec4(p, 1.0);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/computePosition.js
var computePosition_default = "/**\n * Returns a position in model coordinates relative to eye taking into\n * account the current scene mode: 3D, 2D, or Columbus view.\n *
\n * This uses standard position attributes, position3DHigh, \n * position3DLow, position2DHigh, and position2DLow, \n * and should be used when writing a vertex shader for an {@link Appearance}.\n *
\n *\n * @name czm_computePosition\n * @glslFunction\n *\n * @returns {vec4} The position relative to eye.\n *\n * @example\n * vec4 p = czm_computePosition();\n * v_positionEC = (czm_modelViewRelativeToEye * p).xyz;\n * gl_Position = czm_modelViewProjectionRelativeToEye * p;\n *\n * @see czm_translateRelativeToEye\n */\nvec4 czm_computePosition();\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/cosineAndSine.js
var cosineAndSine_default = "/**\n * @private\n */\nvec2 cordic(float angle)\n{\n// Scale the vector by the appropriate factor for the 24 iterations to follow.\n vec2 vector = vec2(6.0725293500888267e-1, 0.0);\n// Iteration 1\n float sense = (angle < 0.0) ? -1.0 : 1.0;\n // float factor = sense * 1.0; // 2^-0\n mat2 rotation = mat2(1.0, sense, -sense, 1.0);\n vector = rotation * vector;\n angle -= sense * 7.8539816339744828e-1; // atan(2^-0)\n// Iteration 2\n sense = (angle < 0.0) ? -1.0 : 1.0;\n float factor = sense * 5.0e-1; // 2^-1\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 4.6364760900080609e-1; // atan(2^-1)\n// Iteration 3\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 2.5e-1; // 2^-2\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 2.4497866312686414e-1; // atan(2^-2)\n// Iteration 4\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 1.25e-1; // 2^-3\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 1.2435499454676144e-1; // atan(2^-3)\n// Iteration 5\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 6.25e-2; // 2^-4\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 6.2418809995957350e-2; // atan(2^-4)\n// Iteration 6\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 3.125e-2; // 2^-5\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 3.1239833430268277e-2; // atan(2^-5)\n// Iteration 7\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 1.5625e-2; // 2^-6\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 1.5623728620476831e-2; // atan(2^-6)\n// Iteration 8\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 7.8125e-3; // 2^-7\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 7.8123410601011111e-3; // atan(2^-7)\n// Iteration 9\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 3.90625e-3; // 2^-8\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 3.9062301319669718e-3; // atan(2^-8)\n// Iteration 10\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 1.953125e-3; // 2^-9\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 1.9531225164788188e-3; // atan(2^-9)\n// Iteration 11\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 9.765625e-4; // 2^-10\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 9.7656218955931946e-4; // atan(2^-10)\n// Iteration 12\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 4.8828125e-4; // 2^-11\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 4.8828121119489829e-4; // atan(2^-11)\n// Iteration 13\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 2.44140625e-4; // 2^-12\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 2.4414062014936177e-4; // atan(2^-12)\n// Iteration 14\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 1.220703125e-4; // 2^-13\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 1.2207031189367021e-4; // atan(2^-13)\n// Iteration 15\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 6.103515625e-5; // 2^-14\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 6.1035156174208773e-5; // atan(2^-14)\n// Iteration 16\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 3.0517578125e-5; // 2^-15\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 3.0517578115526096e-5; // atan(2^-15)\n// Iteration 17\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 1.52587890625e-5; // 2^-16\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 1.5258789061315762e-5; // atan(2^-16)\n// Iteration 18\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 7.62939453125e-6; // 2^-17\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 7.6293945311019700e-6; // atan(2^-17)\n// Iteration 19\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 3.814697265625e-6; // 2^-18\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 3.8146972656064961e-6; // atan(2^-18)\n// Iteration 20\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 1.9073486328125e-6; // 2^-19\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 1.9073486328101870e-6; // atan(2^-19)\n// Iteration 21\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 9.5367431640625e-7; // 2^-20\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 9.5367431640596084e-7; // atan(2^-20)\n// Iteration 22\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 4.76837158203125e-7; // 2^-21\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 4.7683715820308884e-7; // atan(2^-21)\n// Iteration 23\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 2.384185791015625e-7; // 2^-22\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n angle -= sense * 2.3841857910155797e-7; // atan(2^-22)\n// Iteration 24\n sense = (angle < 0.0) ? -1.0 : 1.0;\n factor = sense * 1.1920928955078125e-7; // 2^-23\n rotation[0][1] = factor;\n rotation[1][0] = -factor;\n vector = rotation * vector;\n// angle -= sense * 1.1920928955078068e-7; // atan(2^-23)\n\n return vector;\n}\n\n/**\n * Computes the cosine and sine of the provided angle using the CORDIC algorithm.\n *\n * @name czm_cosineAndSine\n * @glslFunction\n *\n * @param {float} angle The angle in radians.\n *\n * @returns {vec2} The resulting cosine of the angle (as the x coordinate) and sine of the angle (as the y coordinate).\n *\n * @example\n * vec2 v = czm_cosineAndSine(czm_piOverSix);\n * float cosine = v.x;\n * float sine = v.y;\n */\nvec2 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/decompressTextureCoordinates.js
var decompressTextureCoordinates_default = "/**\n * Decompresses texture coordinates that were packed into a single float.\n *\n * @name czm_decompressTextureCoordinates\n * @glslFunction\n *\n * @param {float} encoded The compressed texture coordinates.\n * @returns {vec2} The decompressed texture coordinates.\n */\n 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/defaultPbrMaterial.js
var defaultPbrMaterial_default = "/**\n * Get default parameters for physically based rendering. These defaults\n * describe a rough dielectric (non-metal) surface (e.g. rough plastic).\n *\n * @return {czm_pbrParameters} Default parameters for {@link czm_pbrLighting}\n */\nczm_pbrParameters czm_defaultPbrMaterial()\n{\n czm_pbrParameters results;\n results.diffuseColor = vec3(1.0);\n results.roughness = 1.0;\n\n const vec3 REFLECTANCE_DIELECTRIC = vec3(0.04);\n results.f0 = REFLECTANCE_DIELECTRIC;\n return results;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/depthClamp.js
var depthClamp_default = "// emulated noperspective\n#if (__VERSION__ == 300 || defined(GL_EXT_frag_depth)) && !defined(LOG_DEPTH)\nout float v_WindowZ;\n#endif\n\n/**\n * Emulates GL_DEPTH_CLAMP, which is not available in WebGL 1 or 2.\n * GL_DEPTH_CLAMP clamps geometry that is outside the near and far planes, \n * capping the shadow volume. More information here: \n * https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_depth_clamp.txt.\n *\n * When GL_EXT_frag_depth is available we emulate GL_DEPTH_CLAMP by ensuring \n * no geometry gets clipped by setting the clip space z value to 0.0 and then\n * sending the unaltered screen space z value (using emulated noperspective\n * interpolation) to the frag shader where it is clamped to [0,1] and then\n * written with gl_FragDepth (see czm_writeDepthClamp). This technique is based on:\n * https://stackoverflow.com/questions/5960757/how-to-emulate-gl-depth-clamp-nv.\n *\n * When GL_EXT_frag_depth is not available, which is the case on some mobile \n * devices, we must attempt to fix this only in the vertex shader. \n * The approach is to clamp the z value to the far plane, which closes the \n * shadow volume but also distorts the geometry, so there can still be artifacts\n * on frustum seams.\n *\n * @name czm_depthClamp\n * @glslFunction\n *\n * @param {vec4} coords The vertex in clip coordinates.\n * @returns {vec4} The modified vertex.\n *\n * @example\n * gl_Position = czm_depthClamp(czm_modelViewProjection * vec4(position, 1.0));\n *\n * @see czm_writeDepthClamp\n */\nvec4 czm_depthClamp(vec4 coords)\n{\n#ifndef LOG_DEPTH\n#if __VERSION__ == 300 || defined(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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/eastNorthUpToEyeCoordinates.js
var eastNorthUpToEyeCoordinates_default = "/**\n * Computes a 3x3 rotation matrix that transforms vectors from an ellipsoid's east-north-up coordinate system \n * to eye coordinates. In east-north-up coordinates, x points east, y points north, and z points along the \n * surface normal. East-north-up can be used as an ellipsoid's tangent space for operations such as bump mapping.\n *
\n * The ellipsoid is assumed to be centered at the model coordinate's origin.\n *\n * @name czm_eastNorthUpToEyeCoordinates\n * @glslFunction\n *\n * @param {vec3} positionMC The position on the ellipsoid in model coordinates.\n * @param {vec3} normalEC The normalized ellipsoid surface normal, at positionMC, in eye coordinates.\n *\n * @returns {mat3} A 3x3 rotation matrix that transforms vectors from the east-north-up coordinate system to eye coordinates.\n *\n * @example\n * // Transform a vector defined in the east-north-up coordinate \n * // system, (0, 0, 1) which is the surface normal, to eye \n * // coordinates.\n * mat3 m = czm_eastNorthUpToEyeCoordinates(positionMC, normalEC);\n * vec3 normalEC = m * vec3(0.0, 0.0, 1.0);\n */\nmat3 czm_eastNorthUpToEyeCoordinates(vec3 positionMC, vec3 normalEC)\n{\n vec3 tangentMC = normalize(vec3(-positionMC.y, positionMC.x, 0.0)); // normalized surface tangent in model coordinates\n vec3 tangentEC = normalize(czm_normal3D * tangentMC); // normalized surface tangent in eye coordiantes\n vec3 bitangentEC = normalize(cross(normalEC, tangentEC)); // normalized surface bitangent in eye coordinates\n\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/ellipsoidContainsPoint.js
var ellipsoidContainsPoint_default = "/**\n * DOC_TBA\n *\n * @name czm_ellipsoidContainsPoint\n * @glslFunction\n *\n */\nbool 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/ellipsoidWgs84TextureCoordinates.js
var ellipsoidWgs84TextureCoordinates_default = "/**\n * DOC_TBA\n *\n * @name czm_ellipsoidWgs84TextureCoordinates\n * @glslFunction\n */\nvec2 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/equalsEpsilon.js
var equalsEpsilon_default = "/**\n * Compares left and right componentwise. Returns true\n * if they are within epsilon and false otherwise. The inputs\n * left and right can be floats, vec2s,\n * vec3s, or vec4s.\n *\n * @name czm_equalsEpsilon\n * @glslFunction\n *\n * @param {} left The first vector.\n * @param {} right The second vector.\n * @param {float} epsilon The epsilon to use for equality testing.\n * @returns {bool} true if the components are within epsilon and false otherwise.\n *\n * @example\n * // GLSL declarations\n * bool czm_equalsEpsilon(float left, float right, float epsilon);\n * bool czm_equalsEpsilon(vec2 left, vec2 right, float epsilon);\n * bool czm_equalsEpsilon(vec3 left, vec3 right, float epsilon);\n * bool czm_equalsEpsilon(vec4 left, vec4 right, float epsilon);\n */\nbool czm_equalsEpsilon(vec4 left, vec4 right, float epsilon) {\n return all(lessThanEqual(abs(left - right), vec4(epsilon)));\n}\n\nbool czm_equalsEpsilon(vec3 left, vec3 right, float epsilon) {\n return all(lessThanEqual(abs(left - right), vec3(epsilon)));\n}\n\nbool czm_equalsEpsilon(vec2 left, vec2 right, float epsilon) {\n return all(lessThanEqual(abs(left - right), vec2(epsilon)));\n}\n\nbool czm_equalsEpsilon(float left, float right, float epsilon) {\n return (abs(left - right) <= epsilon);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/eyeOffset.js
var eyeOffset_default = "/**\n * DOC_TBA\n *\n * @name czm_eyeOffset\n * @glslFunction\n *\n * @param {vec4} positionEC DOC_TBA.\n * @param {vec3} eyeOffset DOC_TBA.\n *\n * @returns {vec4} DOC_TBA.\n */\nvec4 czm_eyeOffset(vec4 positionEC, vec3 eyeOffset)\n{\n // This equation is approximate in x and y.\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/eyeToWindowCoordinates.js
var eyeToWindowCoordinates_default = "/**\n * Transforms a position from eye to window coordinates. The transformation\n * from eye to clip coordinates is done using {@link czm_projection}.\n * The transform from normalized device coordinates to window coordinates is\n * done using {@link czm_viewportTransformation}, which assumes a depth range\n * of near = 0 and far = 1.\n *
\n * This transform is useful when there is a need to manipulate window coordinates\n * in a vertex shader as done by {@link BillboardCollection}.\n *\n * @name czm_eyeToWindowCoordinates\n * @glslFunction\n *\n * @param {vec4} position The position in eye coordinates to transform.\n *\n * @returns {vec4} The transformed position in window coordinates.\n *\n * @see czm_modelToWindowCoordinates\n * @see czm_projection\n * @see czm_viewportTransformation\n * @see BillboardCollection\n *\n * @example\n * vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);\n */\nvec4 czm_eyeToWindowCoordinates(vec4 positionEC)\n{\n vec4 q = czm_projection * positionEC; // clip coordinates\n q.xyz /= q.w; // normalized device coordinates\n q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // window coordinates\n return q;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/fastApproximateAtan.js
var fastApproximateAtan_default = `/**
* Approxiamtes atan over the range [0, 1]. Safe to flip output for negative input.
*
* 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.
*
* Chosen for the following characteristics over range [0, 1]:
* - basically no error at 0 and 1, important for getting around range limit (naive atan2 via atan requires infinite range atan)
* - no visible artifacts from first-derivative discontinuities, unlike latitude via range-reduced sqrt asin approximations (at equator)
*
* The original code is x * (-0.1784 * abs(x) - 0.0663 * x * x + 1.0301);
* Removed the abs() in here because it isn't needed, the input range is guaranteed as [0, 1] by how we're approximating atan2.
*
* @name czm_fastApproximateAtan
* @glslFunction
*
* @param {float} x Value between 0 and 1 inclusive.
*
* @returns {float} Approximation of atan(x)
*/
float czm_fastApproximateAtan(float x) {
return x * (-0.1784 * x - 0.0663 * x * x + 1.0301);
}
/**
* Approximation of atan2.
*
* Range reduction math based on nvidia's cg reference implementation for atan2: http://developer.download.nvidia.com/cg/atan2.html
* However, we replaced their atan curve with Michael Drobot's (see above).
*
* @name czm_fastApproximateAtan
* @glslFunction
*
* @param {float} x Value between -1 and 1 inclusive.
* @param {float} y Value between -1 and 1 inclusive.
*
* @returns {float} Approximation of atan2(x, y)
*/
float czm_fastApproximateAtan(float x, float y) {
// atan approximations are usually only reliable over [-1, 1], or, in our case, [0, 1] due to modifications.
// So range-reduce using abs and by flipping whether x or y is on top.
float t = abs(x); // t used as swap and atan result.
float opposite = abs(y);
float adjacent = max(t, opposite);
opposite = min(t, opposite);
t = czm_fastApproximateAtan(opposite / adjacent);
// Undo range reduction
t = czm_branchFreeTernary(abs(y) > abs(x), czm_piOverTwo - t, t);
t = czm_branchFreeTernary(x < 0.0, czm_pi - t, t);
t = czm_branchFreeTernary(y < 0.0, -t, t);
return t;
}
`;
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/fog.js
var fog_default = "/**\n * Gets the color with fog at a distance from the camera.\n *\n * @name czm_fog\n * @glslFunction\n *\n * @param {float} distanceToCamera The distance to the camera in meters.\n * @param {vec3} color The original color.\n * @param {vec3} fogColor The color of the fog.\n *\n * @returns {vec3} The color adjusted for fog at the distance from the camera.\n */\nvec3 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\n/**\n * Gets the color with fog at a distance from the camera.\n *\n * @name czm_fog\n * @glslFunction\n *\n * @param {float} distanceToCamera The distance to the camera in meters.\n * @param {vec3} color The original color.\n * @param {vec3} fogColor The color of the fog.\n * @param {float} fogModifierConstant A constant to modify the appearance of fog.\n *\n * @returns {vec3} The color adjusted for fog at the distance from the camera.\n */\nvec3 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/gammaCorrect.js
var gammaCorrect_default = "/**\n * Converts a color from RGB space to linear space.\n *\n * @name czm_gammaCorrect\n * @glslFunction\n *\n * @param {vec3} color The color in RGB space.\n * @returns {vec3} The color in linear space.\n */\nvec3 czm_gammaCorrect(vec3 color) {\n#ifdef HDR\n color = pow(color, vec3(czm_gamma));\n#endif\n return color;\n}\n\nvec4 czm_gammaCorrect(vec4 color) {\n#ifdef HDR\n color.rgb = pow(color.rgb, vec3(czm_gamma));\n#endif\n return color;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/geodeticSurfaceNormal.js
var geodeticSurfaceNormal_default = "/**\n * DOC_TBA\n *\n * @name czm_geodeticSurfaceNormal\n * @glslFunction\n *\n * @param {vec3} positionOnEllipsoid DOC_TBA\n * @param {vec3} ellipsoidCenter DOC_TBA\n * @param {vec3} oneOverEllipsoidRadiiSquared DOC_TBA\n * \n * @returns {vec3} DOC_TBA.\n */\nvec3 czm_geodeticSurfaceNormal(vec3 positionOnEllipsoid, vec3 ellipsoidCenter, vec3 oneOverEllipsoidRadiiSquared)\n{\n return normalize((positionOnEllipsoid - ellipsoidCenter) * oneOverEllipsoidRadiiSquared);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/getDefaultMaterial.js
var getDefaultMaterial_default = "/**\n * An czm_material with default values. Every material's czm_getMaterial\n * should use this default material as a base for the material it returns.\n * The default normal value is given by materialInput.normalEC.\n *\n * @name czm_getDefaultMaterial\n * @glslFunction\n *\n * @param {czm_materialInput} input The input used to construct the default material.\n *\n * @returns {czm_material} The default material.\n *\n * @see czm_materialInput\n * @see czm_material\n * @see czm_getMaterial\n */\nczm_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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/getLambertDiffuse.js
var getLambertDiffuse_default = "/**\n * Calculates the intensity of diffusely reflected light.\n *\n * @name czm_getLambertDiffuse\n * @glslFunction\n *\n * @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.\n * @param {vec3} normalEC The surface normal in eye coordinates.\n *\n * @returns {float} The intensity of the diffuse reflection.\n *\n * @see czm_phong\n *\n * @example\n * float diffuseIntensity = czm_getLambertDiffuse(lightDirectionEC, normalEC);\n * float specularIntensity = czm_getSpecular(lightDirectionEC, toEyeEC, normalEC, 200);\n * vec3 color = (diffuseColor * diffuseIntensity) + (specularColor * specularIntensity);\n */\nfloat czm_getLambertDiffuse(vec3 lightDirectionEC, vec3 normalEC)\n{\n return max(dot(lightDirectionEC, normalEC), 0.0);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/getSpecular.js
var getSpecular_default = "/**\n * Calculates the specular intensity of reflected light.\n *\n * @name czm_getSpecular\n * @glslFunction\n *\n * @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.\n * @param {vec3} toEyeEC Unit vector pointing to the eye position in eye coordinates.\n * @param {vec3} normalEC The surface normal in eye coordinates.\n * @param {float} shininess The sharpness of the specular reflection. Higher values create a smaller, more focused specular highlight.\n *\n * @returns {float} The intensity of the specular highlight.\n *\n * @see czm_phong\n *\n * @example\n * float diffuseIntensity = czm_getLambertDiffuse(lightDirectionEC, normalEC);\n * float specularIntensity = czm_getSpecular(lightDirectionEC, toEyeEC, normalEC, 200);\n * vec3 color = (diffuseColor * diffuseIntensity) + (specularColor * specularIntensity);\n */\nfloat 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\n // pow has undefined behavior if both parameters <= 0.\n // Prevent this by making sure shininess is at least czm_epsilon2.\n return pow(specular, max(shininess, czm_epsilon2));\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/getWaterNoise.js
var getWaterNoise_default = "/**\n * @private\n */\nvec4 czm_getWaterNoise(sampler2D normalMap, vec2 uv, float time, float angleInRadians)\n{\n float cosAngle = cos(angleInRadians);\n float sinAngle = sin(angleInRadians);\n\n // time dependent sampling directions\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\n // rotate sampling direction by specified angle\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\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\n uv0 = fract(uv0);\n uv1 = fract(uv1);\n uv2 = fract(uv2);\n uv3 = fract(uv3);\n vec4 noise = (texture(normalMap, uv0)) +\n (texture(normalMap, uv1)) +\n (texture(normalMap, uv2)) +\n (texture(normalMap, uv3));\n\n // average and scale to between -1 and 1\n return ((noise / 4.0) - 0.5) * 2.0;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/hue.js
var hue_default = "/**\n * Adjusts the hue of a color.\n * \n * @name czm_hue\n * @glslFunction\n * \n * @param {vec3} rgb The color.\n * @param {float} adjustment The amount to adjust the hue of the color in radians.\n *\n * @returns {float} The color with the hue adjusted.\n *\n * @example\n * vec3 adjustHue = czm_hue(color, czm_pi); // The same as czm_hue(color, -czm_pi)\n */\nvec3 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 \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 \n vec3 color = vec3(yiq.x, chroma * cos(hue), chroma * sin(hue));\n return toRGB * color;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/inverseGamma.js
var inverseGamma_default = "/**\n * Converts a color in linear space to RGB space.\n *\n * @name czm_inverseGamma\n * @glslFunction\n *\n * @param {vec3} color The color in linear space.\n * @returns {vec3} The color in RGB space.\n */\nvec3 czm_inverseGamma(vec3 color) {\n return pow(color, vec3(1.0 / czm_gamma));\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/isEmpty.js
var isEmpty_default = "/**\n * Determines if a time interval is empty.\n *\n * @name czm_isEmpty\n * @glslFunction \n * \n * @param {czm_raySegment} interval The interval to test.\n * \n * @returns {bool} true if the time interval is empty; otherwise, false.\n *\n * @example\n * bool b0 = czm_isEmpty(czm_emptyRaySegment); // true\n * bool b1 = czm_isEmpty(czm_raySegment(0.0, 1.0)); // false\n * bool b2 = czm_isEmpty(czm_raySegment(1.0, 1.0)); // false, contains 1.0.\n */\nbool czm_isEmpty(czm_raySegment interval)\n{\n return (interval.stop < 0.0);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/isFull.js
var isFull_default = "/**\n * Determines if a time interval is empty.\n *\n * @name czm_isFull\n * @glslFunction \n * \n * @param {czm_raySegment} interval The interval to test.\n * \n * @returns {bool} true if the time interval is empty; otherwise, false.\n *\n * @example\n * bool b0 = czm_isEmpty(czm_emptyRaySegment); // true\n * bool b1 = czm_isEmpty(czm_raySegment(0.0, 1.0)); // false\n * bool b2 = czm_isEmpty(czm_raySegment(1.0, 1.0)); // false, contains 1.0.\n */\nbool czm_isFull(czm_raySegment interval)\n{\n return (interval.start == 0.0 && interval.stop == czm_infinity);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/latitudeToWebMercatorFraction.js
var latitudeToWebMercatorFraction_default = "/**\n * Computes the fraction of a Web Wercator rectangle at which a given geodetic latitude is located.\n *\n * @name czm_latitudeToWebMercatorFraction\n * @glslFunction\n *\n * @param {float} latitude The geodetic latitude, in radians.\n * @param {float} southMercatorY The Web Mercator coordinate of the southern boundary of the rectangle.\n * @param {float} oneOverMercatorHeight The total height of the rectangle in Web Mercator coordinates.\n *\n * @returns {float} The fraction of the rectangle at which the latitude occurs. If the latitude is the southern\n * boundary of the rectangle, the return value will be zero. If it is the northern boundary, the return\n * value will be 1.0. Latitudes in between are mapped according to the Web Mercator projection.\n */ \nfloat 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 \n return (mercatorY - southMercatorY) * oneOverMercatorHeight;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/lineDistance.js
var lineDistance_default = "/**\n * Computes distance from an point in 2D to a line in 2D.\n *\n * @name czm_lineDistance\n * @glslFunction\n *\n * param {vec2} point1 A point along the line.\n * param {vec2} point2 A point along the line.\n * param {vec2} point A point that may or may not be on the line.\n * returns {float} The distance from the point to the line.\n */\nfloat 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/linearToSrgb.js
var linearToSrgb_default = "/**\n * Converts a linear RGB color to an sRGB color.\n *\n * @param {vec3|vec4} linearIn The color in linear color space.\n * @returns {vec3|vec4} The color in sRGB color space. The vector type matches the input.\n */\nvec3 czm_linearToSrgb(vec3 linearIn) \n{\n return pow(linearIn, vec3(1.0/2.2));\n}\n\nvec4 czm_linearToSrgb(vec4 linearIn) \n{\n vec3 srgbOut = pow(linearIn.rgb, vec3(1.0/2.2));\n return vec4(srgbOut, linearIn.a);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/luminance.js
var luminance_default = "/**\n * Computes the luminance of a color. \n *\n * @name czm_luminance\n * @glslFunction\n *\n * @param {vec3} rgb The color.\n * \n * @returns {float} The luminance.\n *\n * @example\n * float light = czm_luminance(vec3(0.0)); // 0.0\n * float dark = czm_luminance(vec3(1.0)); // ~1.0 \n */\nfloat czm_luminance(vec3 rgb)\n{\n // Algorithm from Chapter 10 of Graphics Shaders.\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n return dot(rgb, W);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/metersPerPixel.js
var metersPerPixel_default = "/**\n * Computes the size of a pixel in meters at a distance from the eye.\n *
\n * Use this version when passing in a custom pixel ratio. For example, passing in 1.0 will return meters per native device pixel.\n *
\n * @name czm_metersPerPixel\n * @glslFunction\n *\n * @param {vec3} positionEC The position to get the meters per pixel in eye coordinates.\n * @param {float} pixelRatio The scaling factor from pixel space to coordinate space\n *\n * @returns {float} The meters per pixel at positionEC.\n */\nfloat 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\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\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\n return max(pixelWidth, pixelHeight) * pixelRatio;\n}\n\n/**\n * Computes the size of a pixel in meters at a distance from the eye.\n *
\n * Use this version when scaling by pixel ratio.\n *
\n * @name czm_metersPerPixel\n * @glslFunction\n *\n * @param {vec3} positionEC The position to get the meters per pixel in eye coordinates.\n *\n * @returns {float} The meters per pixel at positionEC.\n */\nfloat czm_metersPerPixel(vec4 positionEC)\n{\n return czm_metersPerPixel(positionEC, czm_pixelRatio);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/modelToWindowCoordinates.js
var modelToWindowCoordinates_default = "/**\n * Transforms a position from model to window coordinates. The transformation\n * from model to clip coordinates is done using {@link czm_modelViewProjection}.\n * The transform from normalized device coordinates to window coordinates is\n * done using {@link czm_viewportTransformation}, which assumes a depth range\n * of near = 0 and far = 1.\n *
\n * This transform is useful when there is a need to manipulate window coordinates\n * in a vertex shader as done by {@link BillboardCollection}.\n *
\n * This function should not be confused with {@link czm_viewportOrthographic},\n * which is an orthographic projection matrix that transforms from window \n * coordinates to clip coordinates.\n *\n * @name czm_modelToWindowCoordinates\n * @glslFunction\n *\n * @param {vec4} position The position in model coordinates to transform.\n *\n * @returns {vec4} The transformed position in window coordinates.\n *\n * @see czm_eyeToWindowCoordinates\n * @see czm_modelViewProjection\n * @see czm_viewportTransformation\n * @see czm_viewportOrthographic\n * @see BillboardCollection\n *\n * @example\n * vec4 positionWC = czm_modelToWindowCoordinates(positionMC);\n */\nvec4 czm_modelToWindowCoordinates(vec4 position)\n{\n vec4 q = czm_modelViewProjection * position; // clip coordinates\n q.xyz /= q.w; // normalized device coordinates\n q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // window coordinates\n return q;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/multiplyWithColorBalance.js
var multiplyWithColorBalance_default = "/**\n * DOC_TBA\n *\n * @name czm_multiplyWithColorBalance\n * @glslFunction\n */\nvec3 czm_multiplyWithColorBalance(vec3 left, vec3 right)\n{\n // Algorithm from Chapter 10 of Graphics Shaders.\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n \n vec3 target = left * right;\n float leftLuminance = dot(left, W);\n float rightLuminance = dot(right, W);\n float targetLuminance = dot(target, W);\n \n return ((leftLuminance + rightLuminance) / (2.0 * targetLuminance)) * target;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/nearFarScalar.js
var nearFarScalar_default = "/**\n * Computes a value that scales with distance. The scaling is clamped at the near and\n * far distances, and does not extrapolate. This function works with the\n * {@link NearFarScalar} JavaScript class.\n *\n * @name czm_nearFarScalar\n * @glslFunction\n *\n * @param {vec4} nearFarScalar A vector with 4 components: Near distance (x), Near value (y), Far distance (z), Far value (w).\n * @param {float} cameraDistSq The square of the current distance from the camera.\n *\n * @returns {float} The value at this distance.\n */\nfloat 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\n float t = (cameraDistSq - nearDistanceSq) / (farDistanceSq - nearDistanceSq);\n\n t = pow(clamp(t, 0.0, 1.0), 0.2);\n\n return mix(valueAtMin, valueAtMax, t);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/octDecode.js
var octDecode_default = ` /**
* Decodes a unit-length vector in 'oct' encoding to a normalized 3-component Cartesian vector.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {vec2} encoded The oct-encoded, unit-length vector
* @param {float} range The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
* @returns {vec3} The decoded and normalized vector
*/
vec3 czm_octDecode(vec2 encoded, float range)
{
if (encoded.x == 0.0 && encoded.y == 0.0) {
return vec3(0.0, 0.0, 0.0);
}
encoded = encoded / range * 2.0 - 1.0;
vec3 v = vec3(encoded.x, encoded.y, 1.0 - abs(encoded.x) - abs(encoded.y));
if (v.z < 0.0)
{
v.xy = (1.0 - abs(v.yx)) * czm_signNotZero(v.xy);
}
return normalize(v);
}
/**
* Decodes a unit-length vector in 'oct' encoding to a normalized 3-component Cartesian vector.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {vec2} encoded The oct-encoded, unit-length vector
* @returns {vec3} The decoded and normalized vector
*/
vec3 czm_octDecode(vec2 encoded)
{
return czm_octDecode(encoded, 255.0);
}
/**
* Decodes a unit-length vector in 'oct' encoding packed into a floating-point number to a normalized 3-component Cartesian vector.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {float} encoded The oct-encoded, unit-length vector
* @returns {vec3} The decoded and normalized vector
*/
vec3 czm_octDecode(float encoded)
{
float temp = encoded / 256.0;
float x = floor(temp);
float y = (temp - x) * 256.0;
return czm_octDecode(vec2(x, y));
}
/**
* Decodes three unit-length vectors in 'oct' encoding packed into two floating-point numbers to normalized 3-component Cartesian vectors.
* The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
* Cigolle et al 2014: http://jcgt.org/published/0003/02/01/
*
* @name czm_octDecode
* @param {vec2} encoded The packed oct-encoded, unit-length vectors.
* @param {vec3} vector1 One decoded and normalized vector.
* @param {vec3} vector2 One decoded and normalized vector.
* @param {vec3} vector3 One decoded and normalized vector.
*/
void czm_octDecode(vec2 encoded, out vec3 vector1, out vec3 vector2, out vec3 vector3)
{
float temp = encoded.x / 65536.0;
float x = floor(temp);
float encodedFloat1 = (temp - x) * 65536.0;
temp = encoded.y / 65536.0;
float y = floor(temp);
float encodedFloat2 = (temp - y) * 65536.0;
vector1 = czm_octDecode(encodedFloat1);
vector2 = czm_octDecode(encodedFloat2);
vector3 = czm_octDecode(vec2(x, y));
}
`;
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/packDepth.js
var packDepth_default = "/**\n * Packs a depth value into a vec3 that can be represented by unsigned bytes.\n *\n * @name czm_packDepth\n * @glslFunction\n *\n * @param {float} depth The floating-point depth.\n * @returns {vec3} The packed depth.\n */\nvec4 czm_packDepth(float depth)\n{\n // See Aras Pranckevi\u010Dius' post Encoding Floats to RGBA\n // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/pbrLighting.js
var pbrLighting_default = "vec3 lambertianDiffuse(vec3 diffuseColor)\n{\n return diffuseColor / czm_pi;\n}\n\nvec3 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\nfloat smithVisibilityG1(float NdotV, float roughness)\n{\n // this is the k value for direct lighting.\n // for image based lighting it will be roughness^2 / 2\n float k = (roughness + 1.0) * (roughness + 1.0) / 8.0;\n return NdotV / (NdotV * (1.0 - k) + k);\n}\n\nfloat smithVisibilityGGX(float roughness, float NdotL, float NdotV)\n{\n return (\n smithVisibilityG1(NdotL, roughness) *\n smithVisibilityG1(NdotV, roughness)\n );\n}\n\nfloat 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\n/**\n * Compute the diffuse and specular contributions using physically based\n * rendering. This function only handles direct lighting.\n *
\n * This function only handles the lighting calculations. Metallic/roughness\n * and specular/glossy must be handled separately. See {@czm_pbrMetallicRoughnessMaterial}, {@czm_pbrSpecularGlossinessMaterial} and {@czm_defaultPbrMaterial}\n *
\n *\n * @name czm_pbrlighting\n * @glslFunction\n *\n * @param {vec3} positionEC The position of the fragment in eye coordinates\n * @param {vec3} normalEC The surface normal in eye coordinates\n * @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.\n * @param {vec3} lightColorHdr radiance of the light source. This is a HDR value.\n * @param {czm_pbrParameters} The computed PBR parameters.\n * @return {vec3} The computed HDR color\n *\n * @example\n * czm_pbrParameters pbrParameters = czm_pbrMetallicRoughnessMaterial(\n * baseColor,\n * metallic,\n * roughness\n * );\n * vec3 color = czm_pbrlighting(\n * positionEC,\n * normalEC,\n * lightDirectionEC,\n * lightColorHdr,\n * pbrParameters);\n */\nvec3 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\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\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\n vec3 diffuseColor = pbrParameters.diffuseColor;\n // F here represents the specular contribution\n vec3 diffuseContribution = (1.0 - F) * lambertianDiffuse(diffuseColor);\n\n // Lo = (diffuse + specular) * Li * NdotL\n return (diffuseContribution + specularContribution) * NdotL * lightColorHdr;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/pbrMetallicRoughnessMaterial.js
var pbrMetallicRoughnessMaterial_default = "/**\n * Compute parameters for physically based rendering using the\n * metallic/roughness workflow. All inputs are linear; sRGB texture values must\n * be decoded beforehand\n *\n * @name czm_pbrMetallicRoughnessMaterial\n * @glslFunction\n *\n * @param {vec3} baseColor For dielectrics, this is the base color. For metals, this is the f0 value (reflectance at normal incidence)\n * @param {float} metallic 0.0 indicates dielectric. 1.0 indicates metal. Values in between are allowed (e.g. to model rust or dirt);\n * @param {float} roughness A value between 0.0 and 1.0\n * @return {czm_pbrParameters} parameters to pass into {@link czm_pbrLighting}\n */\nczm_pbrParameters czm_pbrMetallicRoughnessMaterial(\n vec3 baseColor,\n float metallic,\n float roughness\n) \n{\n czm_pbrParameters results;\n\n // roughness is authored as perceptual roughness\n // square it to get material roughness\n roughness = clamp(roughness, 0.0, 1.0);\n results.roughness = roughness * roughness;\n\n // dielectrics use f0 = 0.04, metals use albedo as f0\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\n // diffuse only applies to dielectrics.\n results.diffuseColor = baseColor * (1.0 - f0) * (1.0 - metallic);\n\n return results;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/pbrSpecularGlossinessMaterial.js
var pbrSpecularGlossinessMaterial_default = "/**\n * Compute parameters for physically based rendering using the\n * specular/glossy workflow. All inputs are linear; sRGB texture values must\n * be decoded beforehand\n *\n * @name czm_pbrSpecularGlossinessMaterial\n * @glslFunction\n *\n * @param {vec3} diffuse The diffuse color for dielectrics (non-metals)\n * @param {vec3} specular The reflectance at normal incidence (f0)\n * @param {float} glossiness A number from 0.0 to 1.0 indicating how smooth the surface is.\n * @return {czm_pbrParameters} parameters to pass into {@link czm_pbrLighting}\n */\nczm_pbrParameters czm_pbrSpecularGlossinessMaterial(\n vec3 diffuse,\n vec3 specular,\n float glossiness\n) \n{\n czm_pbrParameters results;\n\n // glossiness is the opposite of roughness, but easier for artists to use.\n float roughness = 1.0 - glossiness;\n results.roughness = roughness * roughness;\n\n results.diffuseColor = diffuse * (1.0 - max(max(specular.r, specular.g), specular.b));\n results.f0 = specular;\n\n return results;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/phong.js
var phong_default = "float czm_private_getLambertDiffuseOfMaterial(vec3 lightDirectionEC, czm_material material)\n{\n return czm_getLambertDiffuse(lightDirectionEC, material.normal);\n}\n\nfloat czm_private_getSpecularOfMaterial(vec3 lightDirectionEC, vec3 toEyeEC, czm_material material)\n{\n return czm_getSpecular(lightDirectionEC, toEyeEC, material.normal, material.shininess);\n}\n\n/**\n * Computes a color using the Phong lighting model.\n *\n * @name czm_phong\n * @glslFunction\n *\n * @param {vec3} toEye A normalized vector from the fragment to the eye in eye coordinates.\n * @param {czm_material} material The fragment's material.\n *\n * @returns {vec4} The computed color.\n *\n * @example\n * vec3 positionToEyeEC = // ...\n * czm_material material = // ...\n * vec3 lightDirectionEC = // ...\n * out_FragColor = czm_phong(normalize(positionToEyeEC), material, lightDirectionEC);\n *\n * @see czm_getMaterial\n */\nvec4 czm_phong(vec3 toEye, czm_material material, vec3 lightDirectionEC)\n{\n // Diffuse from directional light sources at eye (for top-down)\n float diffuse = czm_private_getLambertDiffuseOfMaterial(vec3(0.0, 0.0, 1.0), material);\n if (czm_sceneMode == czm_sceneMode3D) {\n // (and horizon views in 3D)\n diffuse += czm_private_getLambertDiffuseOfMaterial(vec3(0.0, 1.0, 0.0), material);\n }\n\n float specular = czm_private_getSpecularOfMaterial(lightDirectionEC, toEye, material);\n\n // Temporary workaround for adding ambient.\n vec3 materialDiffuse = material.diffuse * 0.5;\n\n vec3 ambient = materialDiffuse;\n vec3 color = ambient + material.emission;\n color += materialDiffuse * diffuse * czm_lightColor;\n color += material.specular * specular * czm_lightColor;\n\n return vec4(color, material.alpha);\n}\n\nvec4 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\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\n return vec4(color, material.alpha);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/planeDistance.js
var planeDistance_default = "/**\n * Computes distance from a point to a plane.\n *\n * @name czm_planeDistance\n * @glslFunction\n *\n * param {vec4} plane A Plane in Hessian Normal Form. See Plane.js\n * param {vec3} point A point in the same space as the plane.\n * returns {float} The distance from the point to the plane.\n */\nfloat czm_planeDistance(vec4 plane, vec3 point) {\n return (dot(plane.xyz, point) + plane.w);\n}\n\n/**\n * Computes distance from a point to a plane.\n *\n * @name czm_planeDistance\n * @glslFunction\n *\n * param {vec3} planeNormal Normal for a plane in Hessian Normal Form. See Plane.js\n * param {float} planeDistance Distance for a plane in Hessian Normal form. See Plane.js\n * param {vec3} point A point in the same space as the plane.\n * returns {float} The distance from the point to the plane.\n */\nfloat czm_planeDistance(vec3 planeNormal, float planeDistance, vec3 point) {\n return (dot(planeNormal, point) + planeDistance);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/pointAlongRay.js
var pointAlongRay_default = "/**\n * Computes the point along a ray at the given time. time can be positive, negative, or zero.\n *\n * @name czm_pointAlongRay\n * @glslFunction\n *\n * @param {czm_ray} ray The ray to compute the point along.\n * @param {float} time The time along the ray.\n * \n * @returns {vec3} The point along the ray at the given time.\n * \n * @example\n * czm_ray ray = czm_ray(vec3(0.0), vec3(1.0, 0.0, 0.0)); // origin, direction\n * vec3 v = czm_pointAlongRay(ray, 2.0); // (2.0, 0.0, 0.0)\n */\nvec3 czm_pointAlongRay(czm_ray ray, float time)\n{\n return ray.origin + (time * ray.direction);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/rayEllipsoidIntersectionInterval.js
var rayEllipsoidIntersectionInterval_default = "/**\n * DOC_TBA\n *\n * @name czm_rayEllipsoidIntersectionInterval\n * @glslFunction\n */\nczm_raySegment czm_rayEllipsoidIntersectionInterval(czm_ray ray, vec3 ellipsoid_center, vec3 ellipsoid_inverseRadii)\n{\n // ray and ellipsoid center in eye coordinates. radii in model coordinates.\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\n q = q - ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ellipsoid_center, 1.0)).xyz;\n\n float q2 = dot(q, q);\n float qw = dot(q, w);\n\n if (q2 > 1.0) // Outside ellipsoid.\n {\n if (qw >= 0.0) // Looking outward or tangent (0 intersections).\n {\n return czm_emptyRaySegment;\n }\n else // qw < 0.0.\n {\n float qw2 = qw * qw;\n float difference = q2 - 1.0; // Positively valued.\n float w2 = dot(w, w);\n float product = w2 * difference;\n\n if (qw2 < product) // Imaginary roots (0 intersections).\n {\n return czm_emptyRaySegment;\n }\n else if (qw2 > product) // Distinct roots (2 intersections).\n {\n float discriminant = qw * qw - product;\n float temp = -qw + sqrt(discriminant); // Avoid cancellation.\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 // qw2 == product. Repeated roots (2 intersections).\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) // Inside ellipsoid (2 intersections).\n {\n float difference = q2 - 1.0; // Negatively valued.\n float w2 = dot(w, w);\n float product = w2 * difference; // Negatively valued.\n float discriminant = qw * qw - product;\n float temp = -qw + sqrt(discriminant); // Positively valued.\n czm_raySegment i = czm_raySegment(0.0, temp / w2);\n return i;\n }\n else // q2 == 1.0. On ellipsoid.\n {\n if (qw < 0.0) // Looking inward.\n {\n float w2 = dot(w, w);\n czm_raySegment i = czm_raySegment(0.0, -qw / w2);\n return i;\n }\n else // qw >= 0.0. Looking outward or tangent.\n {\n return czm_emptyRaySegment;\n }\n }\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/raySphereIntersectionInterval.js
var raySphereIntersectionInterval_default = "/**\n * Compute the intersection interval of a ray with a sphere.\n *\n * @name czm_raySphereIntersectionInterval\n * @glslFunction\n *\n * @param {czm_ray} ray The ray.\n * @param {vec3} center The center of the sphere.\n * @param {float} radius The radius of the sphere.\n * @return {czm_raySegment} The intersection interval of the ray with the sphere.\n */\nczm_raySegment czm_raySphereIntersectionInterval(czm_ray ray, vec3 center, float radius)\n{\n vec3 o = ray.origin;\n vec3 d = ray.direction;\n\n vec3 oc = o - center;\n\n float a = dot(d, d);\n float b = 2.0 * dot(d, oc);\n float c = dot(oc, oc) - (radius * radius);\n\n float det = (b * b) - (4.0 * a * c);\n\n if (det < 0.0) {\n return czm_emptyRaySegment;\n }\n\n float sqrtDet = sqrt(det);\n\n float t0 = (-b - sqrtDet) / (2.0 * a);\n float t1 = (-b + sqrtDet) / (2.0 * a);\n\n czm_raySegment result = czm_raySegment(t0, t1);\n return result;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/readDepth.js
var readDepth_default = "float czm_readDepth(sampler2D depthTexture, vec2 texCoords)\n{\n return czm_reverseLogDepth(texture(depthTexture, texCoords).r);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/readNonPerspective.js
var readNonPerspective_default = "/**\n * Reads a value previously transformed with {@link czm_writeNonPerspective}\n * by dividing it by `w`, the value used in the perspective divide.\n * This function is intended to be called in a fragment shader to access a\n * `varying` that should not be subject to perspective interpolation.\n * For example, screen-space texture coordinates. The value should have been\n * previously written in the vertex shader with a call to\n * {@link czm_writeNonPerspective}.\n *\n * @name czm_readNonPerspective\n * @glslFunction\n *\n * @param {float|vec2|vec3|vec4} value The non-perspective value to be read.\n * @param {float} oneOverW One over the perspective divide value, `w`. Usually this is simply `gl_FragCoord.w`.\n * @returns {float|vec2|vec3|vec4} The usable value.\n */\nfloat czm_readNonPerspective(float value, float oneOverW) {\n return value * oneOverW;\n}\n\nvec2 czm_readNonPerspective(vec2 value, float oneOverW) {\n return value * oneOverW;\n}\n\nvec3 czm_readNonPerspective(vec3 value, float oneOverW) {\n return value * oneOverW;\n}\n\nvec4 czm_readNonPerspective(vec4 value, float oneOverW) {\n return value * oneOverW;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/reverseLogDepth.js
var reverseLogDepth_default = "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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/round.js
var round_default = "/**\n * Round a floating point value. This function exists because round() doesn't\n * exist in GLSL 1.00. \n *\n * @param {float|vec2|vec3|vec4} value The value to round\n * @param {float|vec2|vec3|vec3} The rounded value. The type matches the input.\n */\nfloat czm_round(float value) {\n return floor(value + 0.5);\n}\n\nvec2 czm_round(vec2 value) {\n return floor(value + 0.5);\n}\n\nvec3 czm_round(vec3 value) {\n return floor(value + 0.5);\n}\n\nvec4 czm_round(vec4 value) {\n return floor(value + 0.5);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/sampleOctahedralProjection.js
var sampleOctahedralProjection_default = "/**\n * Samples the 4 neighboring pixels and return the weighted average.\n *\n * @private\n */\nvec3 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\n if (lod > 0.0)\n {\n // Each subseqeuent mip level is half the size\n float scale = 1.0 / pow(2.0, lod);\n float offset = ((textureSize.y + 1.0) / textureSize.x);\n\n coord.x *= offset;\n coord *= scale;\n\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\n // Do bilinear filtering\n #ifndef OES_texture_float_linear\n vec3 color1 = texture(projectedMap, coord + vec2(0.0, pixel.y)).rgb;\n vec3 color2 = texture(projectedMap, coord + vec2(pixel.x, 0.0)).rgb;\n vec3 color3 = texture(projectedMap, coord + pixel).rgb;\n vec3 color4 = texture(projectedMap, coord).rgb;\n\n vec2 texturePosition = coord * textureSize;\n\n float fu = fract(texturePosition.x);\n float fv = fract(texturePosition.y);\n\n vec3 average1 = mix(color4, color2, fu);\n vec3 average2 = mix(color1, color3, fu);\n\n vec3 color = mix(average1, average2, fv);\n #else\n vec3 color = texture(projectedMap, coord).rgb;\n #endif\n\n return color;\n}\n\n\n/**\n * Samples from a cube map that has been projected using an octahedral projection from the given direction.\n *\n * @name czm_sampleOctahedralProjection\n * @glslFunction\n *\n * @param {sampler2D} projectedMap The texture with the octahedral projected cube map.\n * @param {vec2} textureSize The width and height dimensions in pixels of the projected map.\n * @param {vec3} direction The normalized direction used to sample the cube map.\n * @param {float} lod The level of detail to sample.\n * @param {float} maxLod The maximum level of detail.\n * @returns {vec3} The color of the cube map at the direction.\n */\nvec3 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\n vec3 colorCurrentLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, currentLod);\n vec3 colorNextLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, nextLod);\n\n return mix(colorNextLod, colorCurrentLod, nextLod - lod);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/saturation.js
var saturation_default = "/**\n * Adjusts the saturation of a color.\n * \n * @name czm_saturation\n * @glslFunction\n * \n * @param {vec3} rgb The color.\n * @param {float} adjustment The amount to adjust the saturation of the color.\n *\n * @returns {float} The color with the saturation adjusted.\n *\n * @example\n * vec3 greyScale = czm_saturation(color, 0.0);\n * vec3 doubleSaturation = czm_saturation(color, 2.0);\n */\nvec3 czm_saturation(vec3 rgb, float adjustment)\n{\n // Algorithm from Chapter 16 of OpenGL Shading Language\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/shadowDepthCompare.js
var shadowDepthCompare_default = "\nfloat czm_sampleShadowMap(highp samplerCube shadowMap, vec3 d)\n{\n return czm_unpackDepth(czm_textureCube(shadowMap, d));\n}\n\nfloat czm_sampleShadowMap(highp sampler2D shadowMap, vec2 uv)\n{\n#ifdef USE_SHADOW_DEPTH_TEXTURE\n return texture(shadowMap, uv).r;\n#else\n return czm_unpackDepth(texture(shadowMap, uv));\n#endif\n}\n\nfloat czm_shadowDepthCompare(samplerCube shadowMap, vec3 uv, float depth)\n{\n return step(depth, czm_sampleShadowMap(shadowMap, uv));\n}\n\nfloat czm_shadowDepthCompare(sampler2D shadowMap, vec2 uv, float depth)\n{\n return step(depth, czm_sampleShadowMap(shadowMap, uv));\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/shadowVisibility.js
var shadowVisibility_default = "\nfloat 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\n visibility = max(visibility, darkness);\n return visibility;\n}\n\n#ifdef USE_CUBE_MAP_SHADOW\nfloat 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\n depth -= depthBias;\n float visibility = czm_shadowDepthCompare(shadowMap, uvw, depth);\n return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);\n}\n#else\nfloat 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\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\n return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);\n}\n#endif\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/signNotZero.js
var signNotZero_default = "/**\n * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative. This is similar to the GLSL\n * built-in function sign except that returns 1.0 instead of 0.0 when the input value is 0.0.\n * \n * @name czm_signNotZero\n * @glslFunction\n *\n * @param {} value The value for which to determine the sign.\n * @returns {} 1.0 if the value is positive or zero, -1.0 if the value is negative.\n */\nfloat czm_signNotZero(float value)\n{\n return value >= 0.0 ? 1.0 : -1.0;\n}\n\nvec2 czm_signNotZero(vec2 value)\n{\n return vec2(czm_signNotZero(value.x), czm_signNotZero(value.y));\n}\n\nvec3 czm_signNotZero(vec3 value)\n{\n return vec3(czm_signNotZero(value.x), czm_signNotZero(value.y), czm_signNotZero(value.z));\n}\n\nvec4 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/sphericalHarmonics.js
var sphericalHarmonics_default = "/**\n * Computes a color from the third order spherical harmonic coefficients and a normalized direction vector.\n *
\n * The order of the coefficients is [L00, L1_1, L10, L11, L2_2, L2_1, L20, L21, L22].\n *
\n *\n * @name czm_sphericalHarmonics\n * @glslFunction\n *\n * @param {vec3} normal The normalized direction.\n * @param {vec3[9]} coefficients The third order spherical harmonic coefficients.\n * @returns {vec3} The color at the direction.\n *\n * @see https://graphics.stanford.edu/papers/envmap/envmap.pdf\n */\nvec3 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\n float x = normal.x;\n float y = normal.y;\n float z = normal.z;\n\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/srgbToLinear.js
var srgbToLinear_default = "/**\n * Converts an sRGB color to a linear RGB color.\n *\n * @param {vec3|vec4} srgbIn The color in sRGB space\n * @returns {vec3|vec4} The color in linear color space. The vector type matches the input.\n */\nvec3 czm_srgbToLinear(vec3 srgbIn)\n{\n return pow(srgbIn, vec3(2.2));\n}\n\nvec4 czm_srgbToLinear(vec4 srgbIn) \n{\n vec3 linearOut = pow(srgbIn.rgb, vec3(2.2));\n return vec4(linearOut, srgbIn.a);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/tangentToEyeSpaceMatrix.js
var tangentToEyeSpaceMatrix_default = "/**\n * Creates a matrix that transforms vectors from tangent space to eye space.\n *\n * @name czm_tangentToEyeSpaceMatrix\n * @glslFunction\n *\n * @param {vec3} normalEC The normal vector in eye coordinates.\n * @param {vec3} tangentEC The tangent vector in eye coordinates.\n * @param {vec3} bitangentEC The bitangent vector in eye coordinates.\n *\n * @returns {mat3} The matrix that transforms from tangent space to eye space.\n *\n * @example\n * mat3 tangentToEye = czm_tangentToEyeSpaceMatrix(normalEC, tangentEC, bitangentEC);\n * vec3 normal = tangentToEye * texture(normalMap, st).xyz;\n */\nmat3 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/textureCube.js
var textureCube_default = "/**\n * A wrapper around the texture (WebGL2) / textureCube (WebGL1)\n * function to allow for WebGL 1 support.\n * \n * @name czm_textureCube\n * @glslFunction\n *\n * @param {samplerCube} sampler The sampler.\n * @param {vec3} p The coordinates to sample the texture at.\n */\nvec4 czm_textureCube(samplerCube sampler, vec3 p) {\n#if __VERSION__ == 300\n return texture(sampler, p);\n#else \n return textureCube(sampler, p);\n#endif\n}";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/transformPlane.js
var transformPlane_default = "/**\n * Transforms a plane.\n * \n * @name czm_transformPlane\n * @glslFunction\n *\n * @param {vec4} plane The plane in Hessian Normal Form.\n * @param {mat4} transform The inverse-transpose of a transformation matrix.\n */\nvec4 czm_transformPlane(vec4 plane, mat4 transform) {\n vec4 transformedPlane = transform * plane;\n // Convert the transformed plane to Hessian Normal Form\n float normalMagnitude = length(transformedPlane.xyz);\n return transformedPlane / normalMagnitude;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/translateRelativeToEye.js
var translateRelativeToEye_default = "/**\n * Translates a position (or any vec3) that was encoded with {@link EncodedCartesian3},\n * and then provided to the shader as separate high and low bits to\n * be relative to the eye. As shown in the example, the position can then be transformed in eye\n * or clip coordinates using {@link czm_modelViewRelativeToEye} or {@link czm_modelViewProjectionRelativeToEye},\n * respectively.\n *
\n * This technique, called GPU RTE, eliminates jittering artifacts when using large coordinates as\n * described in {@link http://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.\n *
\n *\n * @name czm_translateRelativeToEye\n * @glslFunction\n *\n * @param {vec3} high The position's high bits.\n * @param {vec3} low The position's low bits.\n * @returns {vec3} The position translated to be relative to the camera's position.\n *\n * @example\n * in vec3 positionHigh;\n * in vec3 positionLow;\n *\n * void main()\n * {\n * vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);\n * gl_Position = czm_modelViewProjectionRelativeToEye * p;\n * }\n *\n * @see czm_modelViewRelativeToEye\n * @see czm_modelViewProjectionRelativeToEye\n * @see czm_computePosition\n * @see EncodedCartesian3\n */\nvec4 czm_translateRelativeToEye(vec3 high, vec3 low)\n{\n vec3 highDifference = high - czm_encodedCameraPositionMCHigh;\n vec3 lowDifference = low - czm_encodedCameraPositionMCLow;\n\n return vec4(highDifference + lowDifference, 1.0);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/translucentPhong.js
var translucentPhong_default = "/**\n * @private\n */\nvec4 czm_translucentPhong(vec3 toEye, czm_material material, vec3 lightDirectionEC)\n{\n // Diffuse from directional light sources at eye (for top-down and horizon views)\n float diffuse = czm_getLambertDiffuse(vec3(0.0, 0.0, 1.0), material.normal);\n\n if (czm_sceneMode == czm_sceneMode3D) {\n // (and horizon views in 3D)\n diffuse += czm_getLambertDiffuse(vec3(0.0, 1.0, 0.0), material.normal);\n }\n\n diffuse = clamp(diffuse, 0.0, 1.0);\n\n float specular = czm_getSpecular(lightDirectionEC, toEye, material.normal, material.shininess);\n\n // Temporary workaround for adding ambient.\n vec3 materialDiffuse = material.diffuse * 0.5;\n\n vec3 ambient = materialDiffuse;\n vec3 color = ambient + material.emission;\n color += materialDiffuse * diffuse * czm_lightColor;\n color += material.specular * specular * czm_lightColor;\n\n return vec4(color, material.alpha);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/transpose.js
var transpose_default = "/**\n * Returns the transpose of the matrix. The input matrix can be\n * a mat2, mat3, or mat4.\n *\n * @name czm_transpose\n * @glslFunction\n *\n * @param {} matrix The matrix to transpose.\n *\n * @returns {} The transposed matrix.\n *\n * @example\n * // GLSL declarations\n * mat2 czm_transpose(mat2 matrix);\n * mat3 czm_transpose(mat3 matrix);\n * mat4 czm_transpose(mat4 matrix);\n *\n * // Transpose a 3x3 rotation matrix to find its inverse.\n * mat3 eastNorthUpToEye = czm_eastNorthUpToEyeCoordinates(\n * positionMC, normalEC);\n * mat3 eyeToEastNorthUp = czm_transpose(eastNorthUpToEye);\n */\nmat2 czm_transpose(mat2 matrix)\n{\n return mat2(\n matrix[0][0], matrix[1][0],\n matrix[0][1], matrix[1][1]);\n}\n\nmat3 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\nmat4 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/unpackDepth.js
var unpackDepth_default = "/**\n * Unpacks a vec4 depth value to a float in [0, 1) range.\n *\n * @name czm_unpackDepth\n * @glslFunction\n *\n * @param {vec4} packedDepth The packed depth.\n *\n * @returns {float} The floating-point depth in [0, 1) range.\n */\n float czm_unpackDepth(vec4 packedDepth)\n {\n // See Aras Pranckevi\u010Dius' post Encoding Floats to RGBA\n // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/\n return dot(packedDepth, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n }\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/unpackFloat.js
var unpackFloat_default = "/**\n * Unpack an IEEE 754 single-precision float that is packed as a little-endian unsigned normalized vec4.\n *\n * @name czm_unpackFloat\n * @glslFunction\n *\n * @param {vec4} packedFloat The packed float.\n *\n * @returns {float} The floating-point depth in arbitrary range.\n */\nfloat czm_unpackFloat(vec4 packedFloat)\n{\n // Convert to [0.0, 255.0] and round to integer\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/unpackUint.js
var unpackUint_default = "/**\n * Unpack unsigned integers of 1-4 bytes. in WebGL 1, there is no uint type,\n * so the return value is an int.\n *
\n * There are also precision limitations in WebGL 1. highp int is still limited\n * to 24 bits. Above the value of 2^24 = 16777216, precision loss may occur.\n *
\n *\n * @param {float|vec2|vec3|vec4} packed The packed value. For vectors, the components are listed in little-endian order.\n *\n * @return {int} The unpacked value.\n */\n int czm_unpackUint(float packedValue) {\n float rounded = czm_round(packedValue * 255.0);\n return int(rounded);\n }\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\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\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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/valueTransform.js
var valueTransform_default = "/**\n * Transform metadata values following the EXT_structural_metadata spec\n * by multiplying by scale and adding the offset. Operations are always\n * performed component-wise, even for matrices.\n * \n * @param {float|vec2|vec3|vec4|mat2|mat3|mat4} offset The offset to add\n * @param {float|vec2|vec3|vec4|mat2|mat3|mat4} scale The scale factor to multiply\n * @param {float|vec2|vec3|vec4|mat2|mat3|mat4} value The original value.\n *\n * @return {float|vec2|vec3|vec4|mat2|mat3|mat4} The transformed value of the same scalar/vector/matrix type as the input.\n */\nfloat czm_valueTransform(float offset, float scale, float value) {\n return scale * value + offset;\n}\n\nvec2 czm_valueTransform(vec2 offset, vec2 scale, vec2 value) {\n return scale * value + offset;\n}\n\nvec3 czm_valueTransform(vec3 offset, vec3 scale, vec3 value) {\n return scale * value + offset;\n}\n\nvec4 czm_valueTransform(vec4 offset, vec4 scale, vec4 value) {\n return scale * value + offset;\n}\n\nmat2 czm_valueTransform(mat2 offset, mat2 scale, mat2 value) {\n return matrixCompMult(scale, value) + offset;\n}\n\nmat3 czm_valueTransform(mat3 offset, mat3 scale, mat3 value) {\n return matrixCompMult(scale, value) + offset;\n}\n\nmat4 czm_valueTransform(mat4 offset, mat4 scale, mat4 value) {\n return matrixCompMult(scale, value) + offset;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/vertexLogDepth.js
var vertexLogDepth_default = "#ifdef LOG_DEPTH\n// 1.0 at the near plane, increasing linearly from there.\nout float v_depthFromNearPlusOne;\n#ifdef SHADOW_MAP\nout vec3 v_logPositionEC;\n#endif\n#endif\n\nvec4 czm_updatePositionDepth(vec4 coords) {\n#if defined(LOG_DEPTH)\n\n#ifdef SHADOW_MAP\n vec3 logPositionEC = (czm_inverseProjection * coords).xyz;\n v_logPositionEC = logPositionEC;\n#endif\n\n // With the very high far/near ratios used with the logarithmic depth\n // buffer, floating point rounding errors can cause linear depth values\n // to end up on the wrong side of the far plane, even for vertices that\n // are really nowhere near it. Since we always write a correct logarithmic\n // depth value in the fragment shader anyway, we just need to make sure\n // such errors don't cause the primitive to be clipped entirely before\n // we even get to the fragment shader.\n coords.z = clamp(coords.z / coords.w, -1.0, 1.0) * coords.w;\n#endif\n\n return coords;\n}\n\n/**\n * Writes the logarithmic depth to gl_Position using the already computed gl_Position.\n *\n * @name czm_vertexLogDepth\n * @glslFunction\n */\nvoid 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\n/**\n * Writes the logarithmic depth to gl_Position using the provided clip coordinates.\n *
\n * An example use case for this function would be moving the vertex in window coordinates\n * before converting back to clip coordinates. Use the original vertex clip coordinates.\n *
\n * @name czm_vertexLogDepth\n * @glslFunction\n *\n * @param {vec4} clipCoords The vertex in clip coordinates.\n *\n * @example\n * czm_vertexLogDepth(czm_projection * vec4(positionEyeCoordinates, 1.0));\n */\nvoid 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";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/windowToEyeCoordinates.js
var windowToEyeCoordinates_default = "vec4 czm_screenToEyeCoordinates(vec4 screenCoordinate)\n{\n // Reconstruct NDC coordinates\n float x = 2.0 * screenCoordinate.x - 1.0;\n float y = 2.0 * screenCoordinate.y - 1.0;\n float z = (screenCoordinate.z - czm_viewportTransformation[3][2]) / czm_viewportTransformation[2][2];\n vec4 q = vec4(x, y, z, 1.0);\n\n // Reverse the perspective division to obtain clip coordinates.\n q /= screenCoordinate.w;\n\n // Reverse the projection transformation to obtain eye coordinates.\n if (!(czm_inverseProjection == mat4(0.0))) // IE and Edge sometimes do something weird with != between mat4s\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\n float near = czm_currentFrustum.x;\n float far = czm_currentFrustum.y;\n\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\n return q;\n}\n\n/**\n * Transforms a position from window to eye coordinates.\n * The transform from window to normalized device coordinates is done using components\n * of (@link czm_viewport} and {@link czm_viewportTransformation} instead of calculating\n * the inverse of czm_viewportTransformation. The transformation from\n * normalized device coordinates to clip coordinates is done using fragmentCoordinate.w,\n * which is expected to be the scalar used in the perspective divide. The transformation\n * from clip to eye coordinates is done using {@link czm_inverseProjection}.\n *\n * @name czm_windowToEyeCoordinates\n * @glslFunction\n *\n * @param {vec4} fragmentCoordinate The position in window coordinates to transform.\n *\n * @returns {vec4} The transformed position in eye coordinates.\n *\n * @see czm_modelToWindowCoordinates\n * @see czm_eyeToWindowCoordinates\n * @see czm_inverseProjection\n * @see czm_viewport\n * @see czm_viewportTransformation\n *\n * @example\n * vec4 positionEC = czm_windowToEyeCoordinates(gl_FragCoord);\n */\nvec4 czm_windowToEyeCoordinates(vec4 fragmentCoordinate)\n{\n vec2 screenCoordXY = (fragmentCoordinate.xy - czm_viewport.xy) / czm_viewport.zw;\n return czm_screenToEyeCoordinates(vec4(screenCoordXY, fragmentCoordinate.zw));\n}\n\nvec4 czm_screenToEyeCoordinates(vec2 screenCoordinateXY, float depthOrLogDepth)\n{\n // See reverseLogDepth.glsl. This is separate to re-use the pow.\n#if defined(LOG_DEPTH) || defined(LOG_DEPTH_READ_ONLY)\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 screenCoord = vec4(screenCoordinateXY, far * (1.0 - near / depthFromCamera) / (far - near), 1.0);\n vec4 eyeCoordinate = czm_screenToEyeCoordinates(screenCoord);\n eyeCoordinate.w = 1.0 / depthFromCamera; // Better precision\n return eyeCoordinate;\n#else\n vec4 screenCoord = vec4(screenCoordinateXY, depthOrLogDepth, 1.0);\n vec4 eyeCoordinate = czm_screenToEyeCoordinates(screenCoord);\n#endif\n return eyeCoordinate;\n}\n\n/**\n * Transforms a position given as window x/y and a depth or a log depth from window to eye coordinates.\n * This function produces more accurate results for window positions with log depth than\n * conventionally unpacking the log depth using czm_reverseLogDepth and using the standard version\n * of czm_windowToEyeCoordinates.\n *\n * @name czm_windowToEyeCoordinates\n * @glslFunction\n *\n * @param {vec2} fragmentCoordinateXY The XY position in window coordinates to transform.\n * @param {float} depthOrLogDepth A depth or log depth for the fragment.\n *\n * @see czm_modelToWindowCoordinates\n * @see czm_eyeToWindowCoordinates\n * @see czm_inverseProjection\n * @see czm_viewport\n * @see czm_viewportTransformation\n *\n * @returns {vec4} The transformed position in eye coordinates.\n */\nvec4 czm_windowToEyeCoordinates(vec2 fragmentCoordinateXY, float depthOrLogDepth)\n{\n vec2 screenCoordXY = (fragmentCoordinateXY.xy - czm_viewport.xy) / czm_viewport.zw;\n return czm_screenToEyeCoordinates(screenCoordXY, depthOrLogDepth);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/writeDepthClamp.js
var writeDepthClamp_default = "// emulated noperspective\n#if !defined(LOG_DEPTH)\nin float v_WindowZ;\n#endif\n\n/**\n * Emulates GL_DEPTH_CLAMP. Clamps a fragment to the near and far plane\n * by writing the fragment's depth. See czm_depthClamp for more details.\n *\n * @name czm_writeDepthClamp\n * @glslFunction\n *\n * @example\n * out_FragColor = color;\n * czm_writeDepthClamp();\n *\n * @see czm_depthClamp\n */\nvoid czm_writeDepthClamp()\n{\n#if (!defined(LOG_DEPTH) && (__VERSION__ == 300 || defined(GL_EXT_frag_depth)))\n gl_FragDepth = clamp(v_WindowZ * gl_FragCoord.w, 0.0, 1.0);\n#endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/writeLogDepth.js
var writeLogDepth_default = "#ifdef LOG_DEPTH\nin float v_depthFromNearPlusOne;\n\n#ifdef POLYGON_OFFSET\nuniform vec2 u_polygonOffset;\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n#endif\n\n#endif\n\n/**\n * Writes the fragment depth to the logarithmic depth buffer.\n *
\n * Use this when the vertex shader does not call {@link czm_vertexlogDepth}, for example, when\n * ray-casting geometry using a full screen quad.\n *
\n * @name czm_writeLogDepth\n * @glslFunction\n *\n * @param {float} depth The depth coordinate, where 1.0 is on the near plane and\n * depth increases in eye-space units from there\n *\n * @example\n * czm_writeLogDepth((czm_projection * v_positionEyeCoordinates).w + 1.0);\n */\nvoid czm_writeLogDepth(float depth)\n{\n#if (defined(LOG_DEPTH) && (__VERSION__ == 300 || defined(GL_EXT_frag_depth)))\n // Discard the vertex if it's not between the near and far planes.\n // We allow a bit of epsilon on the near plane comparison because a 1.0\n // from the vertex shader (indicating the vertex should be _on_ the near\n // plane) will not necessarily come here as exactly 1.0.\n if (depth <= 0.9999999 || depth > czm_farDepthFromNearPlusOne) {\n discard;\n }\n\n#ifdef POLYGON_OFFSET\n // Polygon offset: m * factor + r * units\n float factor = u_polygonOffset[0];\n float units = u_polygonOffset[1];\n\n#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n // This factor doesn't work in IE 10\n if (factor != 0.0) {\n // m = sqrt(dZdX^2 + dZdY^2);\n float x = dFdx(depth);\n float y = dFdy(depth);\n float m = sqrt(x * x + y * y);\n\n // Apply the factor before computing the log depth.\n depth += m * factor;\n }\n#endif\n\n#endif\n\n gl_FragDepth = log2(depth) * czm_oneOverLog2FarDepthFromNearPlusOne;\n\n#ifdef POLYGON_OFFSET\n // Apply the units after the log depth.\n gl_FragDepth += czm_epsilon7 * units;\n#endif\n\n#endif\n}\n\n/**\n * Writes the fragment depth to the logarithmic depth buffer.\n *
\n * Use this when the vertex shader calls {@link czm_vertexlogDepth}.\n *
\n *\n * @name czm_writeLogDepth\n * @glslFunction\n */\nvoid czm_writeLogDepth() {\n#ifdef LOG_DEPTH\n czm_writeLogDepth(v_depthFromNearPlusOne);\n#endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/Functions/writeNonPerspective.js
var writeNonPerspective_default = "/**\n * Transforms a value for non-perspective interpolation by multiplying\n * it by w, the value used in the perspective divide. This function is\n * intended to be called in a vertex shader to compute the value of a\n * `varying` that should not be subject to perspective interpolation.\n * For example, screen-space texture coordinates. The fragment shader\n * must call {@link czm_readNonPerspective} to retrieve the final\n * non-perspective value.\n *\n * @name czm_writeNonPerspective\n * @glslFunction\n *\n * @param {float|vec2|vec3|vec4} value The value to be interpolated without accounting for perspective.\n * @param {float} w The perspective divide value. Usually this is the computed `gl_Position.w`.\n * @returns {float|vec2|vec3|vec4} The transformed value, intended to be stored in a `varying` and read in the\n * fragment shader with {@link czm_readNonPerspective}.\n */\nfloat czm_writeNonPerspective(float value, float w) {\n return value * w;\n}\n\nvec2 czm_writeNonPerspective(vec2 value, float w) {\n return value * w;\n}\n\nvec3 czm_writeNonPerspective(vec3 value, float w) {\n return value * w;\n}\n\nvec4 czm_writeNonPerspective(vec4 value, float w) {\n return value * w;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Builtin/CzmBuiltins.js
var CzmBuiltins_default = {
czm_degreesPerRadian: degreesPerRadian_default,
czm_depthRange: depthRange_default,
czm_epsilon1: epsilon1_default,
czm_epsilon2: epsilon2_default,
czm_epsilon3: epsilon3_default,
czm_epsilon4: epsilon4_default,
czm_epsilon5: epsilon5_default,
czm_epsilon6: epsilon6_default,
czm_epsilon7: epsilon7_default,
czm_infinity: infinity_default,
czm_oneOverPi: oneOverPi_default,
czm_oneOverTwoPi: oneOverTwoPi_default,
czm_passCesium3DTile: passCesium3DTile_default,
czm_passCesium3DTileClassification: passCesium3DTileClassification_default,
czm_passCesium3DTileClassificationIgnoreShow: passCesium3DTileClassificationIgnoreShow_default,
czm_passClassification: passClassification_default,
czm_passCompute: passCompute_default,
czm_passEnvironment: passEnvironment_default,
czm_passGlobe: passGlobe_default,
czm_passOpaque: passOpaque_default,
czm_passOverlay: passOverlay_default,
czm_passTerrainClassification: passTerrainClassification_default,
czm_passTranslucent: passTranslucent_default,
czm_passVoxels: passVoxels_default,
czm_pi: pi_default,
czm_piOverFour: piOverFour_default,
czm_piOverSix: piOverSix_default,
czm_piOverThree: piOverThree_default,
czm_piOverTwo: piOverTwo_default,
czm_radiansPerDegree: radiansPerDegree_default,
czm_sceneMode2D: sceneMode2D_default,
czm_sceneMode3D: sceneMode3D_default,
czm_sceneModeColumbusView: sceneModeColumbusView_default,
czm_sceneModeMorphing: sceneModeMorphing_default,
czm_solarRadius: solarRadius_default,
czm_threePiOver2: threePiOver2_default,
czm_twoPi: twoPi_default,
czm_webMercatorMaxLatitude: webMercatorMaxLatitude_default,
czm_depthRangeStruct: depthRangeStruct_default,
czm_material: material_default,
czm_materialInput: materialInput_default,
czm_modelMaterial: modelMaterial_default,
czm_modelVertexOutput: modelVertexOutput_default,
czm_pbrParameters: pbrParameters_default,
czm_ray: ray_default,
czm_raySegment: raySegment_default,
czm_shadowParameters: shadowParameters_default,
czm_HSBToRGB: HSBToRGB_default,
czm_HSLToRGB: HSLToRGB_default,
czm_RGBToHSB: RGBToHSB_default,
czm_RGBToHSL: RGBToHSL_default,
czm_RGBToXYZ: RGBToXYZ_default,
czm_XYZToRGB: XYZToRGB_default,
czm_acesTonemapping: acesTonemapping_default,
czm_alphaWeight: alphaWeight_default,
czm_antialias: antialias_default,
czm_approximateSphericalCoordinates: approximateSphericalCoordinates_default,
czm_backFacing: backFacing_default,
czm_branchFreeTernary: branchFreeTernary_default,
czm_cascadeColor: cascadeColor_default,
czm_cascadeDistance: cascadeDistance_default,
czm_cascadeMatrix: cascadeMatrix_default,
czm_cascadeWeights: cascadeWeights_default,
czm_columbusViewMorph: columbusViewMorph_default,
czm_computePosition: computePosition_default,
czm_cosineAndSine: cosineAndSine_default,
czm_decompressTextureCoordinates: decompressTextureCoordinates_default,
czm_defaultPbrMaterial: defaultPbrMaterial_default,
czm_depthClamp: depthClamp_default,
czm_eastNorthUpToEyeCoordinates: eastNorthUpToEyeCoordinates_default,
czm_ellipsoidContainsPoint: ellipsoidContainsPoint_default,
czm_ellipsoidWgs84TextureCoordinates: ellipsoidWgs84TextureCoordinates_default,
czm_equalsEpsilon: equalsEpsilon_default,
czm_eyeOffset: eyeOffset_default,
czm_eyeToWindowCoordinates: eyeToWindowCoordinates_default,
czm_fastApproximateAtan: fastApproximateAtan_default,
czm_fog: fog_default,
czm_gammaCorrect: gammaCorrect_default,
czm_geodeticSurfaceNormal: geodeticSurfaceNormal_default,
czm_getDefaultMaterial: getDefaultMaterial_default,
czm_getLambertDiffuse: getLambertDiffuse_default,
czm_getSpecular: getSpecular_default,
czm_getWaterNoise: getWaterNoise_default,
czm_hue: hue_default,
czm_inverseGamma: inverseGamma_default,
czm_isEmpty: isEmpty_default,
czm_isFull: isFull_default,
czm_latitudeToWebMercatorFraction: latitudeToWebMercatorFraction_default,
czm_lineDistance: lineDistance_default,
czm_linearToSrgb: linearToSrgb_default,
czm_luminance: luminance_default,
czm_metersPerPixel: metersPerPixel_default,
czm_modelToWindowCoordinates: modelToWindowCoordinates_default,
czm_multiplyWithColorBalance: multiplyWithColorBalance_default,
czm_nearFarScalar: nearFarScalar_default,
czm_octDecode: octDecode_default,
czm_packDepth: packDepth_default,
czm_pbrLighting: pbrLighting_default,
czm_pbrMetallicRoughnessMaterial: pbrMetallicRoughnessMaterial_default,
czm_pbrSpecularGlossinessMaterial: pbrSpecularGlossinessMaterial_default,
czm_phong: phong_default,
czm_planeDistance: planeDistance_default,
czm_pointAlongRay: pointAlongRay_default,
czm_rayEllipsoidIntersectionInterval: rayEllipsoidIntersectionInterval_default,
czm_raySphereIntersectionInterval: raySphereIntersectionInterval_default,
czm_readDepth: readDepth_default,
czm_readNonPerspective: readNonPerspective_default,
czm_reverseLogDepth: reverseLogDepth_default,
czm_round: round_default,
czm_sampleOctahedralProjection: sampleOctahedralProjection_default,
czm_saturation: saturation_default,
czm_shadowDepthCompare: shadowDepthCompare_default,
czm_shadowVisibility: shadowVisibility_default,
czm_signNotZero: signNotZero_default,
czm_sphericalHarmonics: sphericalHarmonics_default,
czm_srgbToLinear: srgbToLinear_default,
czm_tangentToEyeSpaceMatrix: tangentToEyeSpaceMatrix_default,
czm_textureCube: textureCube_default,
czm_transformPlane: transformPlane_default,
czm_translateRelativeToEye: translateRelativeToEye_default,
czm_translucentPhong: translucentPhong_default,
czm_transpose: transpose_default,
czm_unpackDepth: unpackDepth_default,
czm_unpackFloat: unpackFloat_default,
czm_unpackUint: unpackUint_default,
czm_valueTransform: valueTransform_default,
czm_vertexLogDepth: vertexLogDepth_default,
czm_windowToEyeCoordinates: windowToEyeCoordinates_default,
czm_writeDepthClamp: writeDepthClamp_default,
czm_writeLogDepth: writeLogDepth_default,
czm_writeNonPerspective: writeNonPerspective_default
};
// node_modules/@cesium/engine/Source/Renderer/demodernizeShader.js
function demodernizeShader(input, isFragmentShader) {
let output = input;
output = output.replaceAll(`version 300 es`, ``);
output = output.replaceAll(
/(texture\()/g,
`texture2D(`
);
if (isFragmentShader) {
output = output.replaceAll(/(in)\s+(vec\d|mat\d|float)/g, `varying $2`);
if (/out_FragData_(\d+)/.test(output)) {
output = `#extension GL_EXT_draw_buffers : enable
${output}`;
output = output.replaceAll(
/layout\s+\(location\s*=\s*\d+\)\s*out\s+vec4\s+out_FragData_\d+;/g,
``
);
output = output.replaceAll(/out_FragData_(\d+)/g, `gl_FragData[$1]`);
}
output = output.replaceAll(
/layout\s+\(location\s*=\s*0\)\s*out\s+vec4\s+out_FragColor;/g,
``
);
output = output.replaceAll(/out_FragColor/g, `gl_FragColor`);
output = output.replaceAll(/out_FragColor\[(\d+)\]/g, `gl_FragColor[$1]`);
if (/gl_FragDepth/.test(output)) {
output = `#extension GL_EXT_frag_depth : enable
${output}`;
output = output.replaceAll(/gl_FragDepth/g, `gl_FragDepthEXT`);
}
} else {
output = output.replaceAll(/(in)\s+(vec\d|mat\d|float)/g, `attribute $2`);
output = output.replaceAll(
/(out)\s+(vec\d|mat\d|float)\s+([\w]+);/g,
`varying $2 $3;`
);
}
output = `#version 100
${output}`;
return output;
}
var demodernizeShader_default = demodernizeShader;
// node_modules/@cesium/engine/Source/Renderer/ShaderSource.js
function removeComments(source) {
source = source.replace(/\/\/.*/g, "");
return source.replace(/\/\*\*[\s\S]*?\*\//gm, function(match) {
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;
for (let i = 0; i < nodes.length; ++i) {
if (nodes[i].name === name) {
dependencyNode = nodes[i];
}
}
if (!defined_default(dependencyNode)) {
glslSource = removeComments(glslSource);
dependencyNode = {
name,
glslSource,
dependsOn: [],
requiredBy: [],
evaluated: false
};
nodes.push(dependencyNode);
}
return dependencyNode;
}
function generateDependencies(currentNode, dependencyNodes) {
if (currentNode.evaluated) {
return;
}
currentNode.evaluated = true;
let czmMatches = currentNode.glslSource.match(/\bczm_[a-zA-Z0-9_]*/g);
if (defined_default(czmMatches) && czmMatches !== null) {
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);
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) {
const referencedNode = currentNode.dependsOn[i];
const index = referencedNode.requiredBy.indexOf(currentNode);
referencedNode.requiredBy.splice(index, 1);
if (referencedNode.requiredBy.length === 0) {
nodesWithoutIncomingEdges.push(referencedNode);
}
}
}
const badNodes = [];
for (let j = 0; j < allNodes.length; ++j) {
if (allNodes[j].requiredBy.length !== 0) {
badNodes.push(allNodes[j]);
}
}
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}
`;
}
throw new DeveloperError_default(message);
}
}
function getBuiltinsAndAutomaticUniforms(shaderSource) {
const dependencyNodes = [];
const root = getDependencyNode("main", shaderSource, dependencyNodes);
generateDependencies(root, dependencyNodes);
sortDependencies(dependencyNodes);
let builtinsSource = "";
for (let i = dependencyNodes.length - 1; i >= 0; --i) {
builtinsSource = `${builtinsSource + dependencyNodes[i].glslSource}
`;
}
return builtinsSource.replace(root.glslSource, "");
}
function combineShader(shaderSource, isFragmentShader, context) {
let i;
let length3;
let combinedSources = "";
const sources = shaderSource.sources;
if (defined_default(sources)) {
for (i = 0, length3 = sources.length; i < length3; ++i) {
combinedSources += `
#line 0
${sources[i]}`;
}
}
combinedSources = removeComments(combinedSources);
let version2;
combinedSources = combinedSources.replace(/#version\s+(.*?)\n/gm, function(match, group1) {
if (defined_default(version2) && version2 !== group1) {
throw new DeveloperError_default(
`inconsistent versions found: ${version2} and ${group1}`
);
}
version2 = group1;
return "\n";
});
const extensions = [];
combinedSources = combinedSources.replace(/#extension.*\n/gm, function(match) {
extensions.push(match);
return "\n";
});
combinedSources = combinedSources.replace(
/precision\s(lowp|mediump|highp)\s(float|int);/,
""
);
const pickColorQualifier = shaderSource.pickColorQualifier;
if (defined_default(pickColorQualifier)) {
combinedSources = ShaderSource.createPickFragmentShaderSource(
combinedSources,
pickColorQualifier
);
}
let result = "";
const extensionsLength = extensions.length;
for (i = 0; i < extensionsLength; i++) {
result += extensions[i];
}
if (isFragmentShader) {
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";
}
const defines = shaderSource.defines;
if (defined_default(defines)) {
for (i = 0, length3 = defines.length; i < length3; ++i) {
const define2 = defines[i];
if (define2.length !== 0) {
result += `#define ${define2}
`;
}
}
}
if (context.textureFloatLinear) {
result += "#define OES_texture_float_linear\n\n";
}
if (context.floatingPointTexture) {
result += "#define OES_texture_float\n\n";
}
let builtinSources = "";
if (shaderSource.includeBuiltIns) {
builtinSources = getBuiltinsAndAutomaticUniforms(combinedSources);
}
result += "\n#line 0\n";
const combinedShader = builtinSources + combinedSources;
if (context.webgl2 && isFragmentShader && !/layout\s*\(location\s*=\s*0\)\s*out\s+vec4\s+out_FragColor;/g.test(
combinedShader
) && !/czm_out_FragColor/g.test(combinedShader) && /out_FragColor/g.test(combinedShader)) {
result += "layout(location = 0) out vec4 out_FragColor;\n\n";
}
result += builtinSources;
result += combinedSources;
if (!context.webgl2) {
result = demodernizeShader_default(result, isFragmentShader);
} else {
result = `#version 300 es
${result}`;
}
return result;
}
function ShaderSource(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const pickColorQualifier = options.pickColorQualifier;
if (defined_default(pickColorQualifier) && pickColorQualifier !== "uniform" && pickColorQualifier !== "in") {
throw new DeveloperError_default(
"options.pickColorQualifier must be 'uniform' or 'in'."
);
}
this.defines = defined_default(options.defines) ? options.defines.slice(0) : [];
this.sources = defined_default(options.sources) ? options.sources.slice(0) : [];
this.pickColorQualifier = pickColorQualifier;
this.includeBuiltIns = defaultValue_default(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);
};
ShaderSource.prototype.getCacheKey = function() {
const sortedDefines = this.defines.slice().sort();
const definesKey = sortedDefines.join(",");
const pickKey = this.pickColorQualifier;
const builtinsKey = this.includeBuiltIns;
const sourcesKey = this.sources.join("\n");
return `${definesKey}:${pickKey}:${builtinsKey}:${sourcesKey}`;
};
ShaderSource.prototype.createCombinedVertexShader = function(context) {
return combineShader(this, false, context);
};
ShaderSource.prototype.createCombinedFragmentShader = function(context) {
return combineShader(this, true, context);
};
ShaderSource._czmBuiltinsAndUniforms = {};
for (const builtinName in CzmBuiltins_default) {
if (CzmBuiltins_default.hasOwnProperty(builtinName)) {
ShaderSource._czmBuiltinsAndUniforms[builtinName] = CzmBuiltins_default[builtinName];
}
}
for (const uniformName in AutomaticUniforms_default) {
if (AutomaticUniforms_default.hasOwnProperty(uniformName)) {
const uniform = AutomaticUniforms_default[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 = "in vec4 pickColor; \nout vec4 czm_pickColor; \nvoid main() \n{ \n czm_old_main(); \n czm_pickColor = pickColor; \n}";
return `${renamedVS}
${pickMain}`;
};
ShaderSource.createPickFragmentShaderSource = function(fragmentShaderSource, pickColorQualifier) {
const renamedFS = ShaderSource.replaceMain(
fragmentShaderSource,
"czm_old_main"
);
const pickMain = `${pickColorQualifier} vec4 czm_pickColor;
void main()
{
czm_old_main();
if (out_FragColor.a == 0.0) {
discard;
}
out_FragColor = czm_pickColor;
}`;
return `${renamedFS}
${pickMain}`;
};
function containsDefine(shaderSource, define2) {
const defines = shaderSource.defines;
const definesLength = defines.length;
for (let i = 0; i < definesLength; ++i) {
if (defines[i] === define2) {
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 void 0;
}
var normalVaryingNames = ["v_normalEC", "v_normal"];
ShaderSource.findNormalVarying = function(shaderSource) {
if (containsString(shaderSource, "#ifdef HAS_NORMALS")) {
if (containsDefine(shaderSource, "HAS_NORMALS")) {
return "v_normalEC";
}
return void 0;
}
return findFirstString(shaderSource, normalVaryingNames);
};
var positionVaryingNames = ["v_positionEC"];
ShaderSource.findPositionVarying = function(shaderSource) {
return findFirstString(shaderSource, positionVaryingNames);
};
var ShaderSource_default = ShaderSource;
// node_modules/@cesium/engine/Source/Renderer/ShaderCache.js
function ShaderCache(context) {
this._context = context;
this._shaders = {};
this._numberOfShaders = 0;
this._shadersToRelease = {};
}
Object.defineProperties(ShaderCache.prototype, {
numberOfShaders: {
get: function() {
return this._numberOfShaders;
}
}
});
ShaderCache.prototype.replaceShaderProgram = function(options) {
if (defined_default(options.shaderProgram)) {
options.shaderProgram.destroy();
}
return this.getShaderProgram(options);
};
function toSortedJson(dictionary) {
const sortedKeys = Object.keys(dictionary).sort();
return JSON.stringify(dictionary, sortedKeys);
}
ShaderCache.prototype.getShaderProgram = function(options) {
let vertexShaderSource = options.vertexShaderSource;
let fragmentShaderSource = options.fragmentShaderSource;
const attributeLocations8 = options.attributeLocations;
if (typeof vertexShaderSource === "string") {
vertexShaderSource = new ShaderSource_default({
sources: [vertexShaderSource]
});
}
if (typeof fragmentShaderSource === "string") {
fragmentShaderSource = new ShaderSource_default({
sources: [fragmentShaderSource]
});
}
const vertexShaderKey = vertexShaderSource.getCacheKey();
const fragmentShaderKey = fragmentShaderSource.getCacheKey();
const attributeLocationKey = defined_default(attributeLocations8) ? toSortedJson(attributeLocations8) : "";
const keyword = `${vertexShaderKey}:${fragmentShaderKey}:${attributeLocationKey}`;
let cachedShader;
if (defined_default(this._shaders[keyword])) {
cachedShader = this._shaders[keyword];
delete this._shadersToRelease[keyword];
} else {
const context = this._context;
const vertexShaderText = vertexShaderSource.createCombinedVertexShader(
context
);
const fragmentShaderText = fragmentShaderSource.createCombinedFragmentShader(
context
);
const shaderProgram = new ShaderProgram_default({
gl: context._gl,
logShaderCompilation: context.logShaderCompilation,
debugShaders: context.debugShaders,
vertexShaderSource,
vertexShaderText,
fragmentShaderSource,
fragmentShaderText,
attributeLocations: attributeLocations8
});
cachedShader = {
cache: this,
shaderProgram,
keyword,
derivedKeywords: [],
count: 0
};
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_default(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_default(cachedDerivedShader)) {
return void 0;
}
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 attributeLocations8 = options.attributeLocations;
if (typeof vertexShaderSource === "string") {
vertexShaderSource = new ShaderSource_default({
sources: [vertexShaderSource]
});
}
if (typeof fragmentShaderSource === "string") {
fragmentShaderSource = new ShaderSource_default({
sources: [fragmentShaderSource]
});
}
const context = this._context;
const vertexShaderText = vertexShaderSource.createCombinedVertexShader(
context
);
const fragmentShaderText = fragmentShaderSource.createCombinedFragmentShader(
context
);
const derivedShaderProgram = new ShaderProgram_default({
gl: context._gl,
logShaderCompilation: context.logShaderCompilation,
debugShaders: context.debugShaders,
vertexShaderSource,
vertexShaderText,
fragmentShaderSource,
fragmentShaderText,
attributeLocations: attributeLocations8
});
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 length3 = derivedKeywords.length;
for (let i = 0; i < length3; ++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_default(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_default(this);
};
var ShaderCache_default = ShaderCache;
// node_modules/@cesium/engine/Source/Renderer/Texture.js
function Texture(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
const context = options.context;
let width = options.width;
let height = options.height;
const source = options.source;
if (defined_default(source)) {
if (!defined_default(width)) {
width = defaultValue_default(source.videoWidth, source.width);
}
if (!defined_default(height)) {
height = defaultValue_default(source.videoHeight, source.height);
}
}
const pixelFormat = defaultValue_default(options.pixelFormat, PixelFormat_default.RGBA);
const pixelDatatype = defaultValue_default(
options.pixelDatatype,
PixelDatatype_default.UNSIGNED_BYTE
);
const internalFormat = PixelFormat_default.toInternalFormat(
pixelFormat,
pixelDatatype,
context
);
const isCompressed = PixelFormat_default.isCompressedFormat(internalFormat);
if (!defined_default(width) || !defined_default(height)) {
throw new DeveloperError_default(
"options requires a source field to create an initialized texture or width and height fields to create a blank texture."
);
}
Check_default.typeOf.number.greaterThan("width", width, 0);
if (width > ContextLimits_default.maximumTextureSize) {
throw new DeveloperError_default(
`Width must be less than or equal to the maximum texture size (${ContextLimits_default.maximumTextureSize}). Check maximumTextureSize.`
);
}
Check_default.typeOf.number.greaterThan("height", height, 0);
if (height > ContextLimits_default.maximumTextureSize) {
throw new DeveloperError_default(
`Height must be less than or equal to the maximum texture size (${ContextLimits_default.maximumTextureSize}). Check maximumTextureSize.`
);
}
if (!PixelFormat_default.validate(pixelFormat)) {
throw new DeveloperError_default("Invalid options.pixelFormat.");
}
if (!isCompressed && !PixelDatatype_default.validate(pixelDatatype)) {
throw new DeveloperError_default("Invalid options.pixelDatatype.");
}
if (pixelFormat === PixelFormat_default.DEPTH_COMPONENT && pixelDatatype !== PixelDatatype_default.UNSIGNED_SHORT && pixelDatatype !== PixelDatatype_default.UNSIGNED_INT) {
throw new DeveloperError_default(
"When options.pixelFormat is DEPTH_COMPONENT, options.pixelDatatype must be UNSIGNED_SHORT or UNSIGNED_INT."
);
}
if (pixelFormat === PixelFormat_default.DEPTH_STENCIL && pixelDatatype !== PixelDatatype_default.UNSIGNED_INT_24_8) {
throw new DeveloperError_default(
"When options.pixelFormat is DEPTH_STENCIL, options.pixelDatatype must be UNSIGNED_INT_24_8."
);
}
if (pixelDatatype === PixelDatatype_default.FLOAT && !context.floatingPointTexture) {
throw new DeveloperError_default(
"When options.pixelDatatype is FLOAT, this WebGL implementation must support the OES_texture_float extension. Check context.floatingPointTexture."
);
}
if (pixelDatatype === PixelDatatype_default.HALF_FLOAT && !context.halfFloatingPointTexture) {
throw new DeveloperError_default(
"When options.pixelDatatype is HALF_FLOAT, this WebGL implementation must support the OES_texture_half_float extension. Check context.halfFloatingPointTexture."
);
}
if (PixelFormat_default.isDepthFormat(pixelFormat)) {
if (defined_default(source)) {
throw new DeveloperError_default(
"When options.pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, source cannot be provided."
);
}
if (!context.depthTexture) {
throw new DeveloperError_default(
"When options.pixelFormat is DEPTH_COMPONENT or DEPTH_STENCIL, this WebGL implementation must support WEBGL_depth_texture. Check context.depthTexture."
);
}
}
if (isCompressed) {
if (!defined_default(source) || !defined_default(source.arrayBufferView)) {
throw new DeveloperError_default(
"When options.pixelFormat is compressed, options.source.arrayBufferView must be defined."
);
}
if (PixelFormat_default.isDXTFormat(internalFormat) && !context.s3tc) {
throw new DeveloperError_default(
"When options.pixelFormat is S3TC compressed, this WebGL implementation must support the WEBGL_compressed_texture_s3tc extension. Check context.s3tc."
);
} else if (PixelFormat_default.isPVRTCFormat(internalFormat) && !context.pvrtc) {
throw new DeveloperError_default(
"When options.pixelFormat is PVRTC compressed, this WebGL implementation must support the WEBGL_compressed_texture_pvrtc extension. Check context.pvrtc."
);
} else if (PixelFormat_default.isASTCFormat(internalFormat) && !context.astc) {
throw new DeveloperError_default(
"When options.pixelFormat is ASTC compressed, this WebGL implementation must support the WEBGL_compressed_texture_astc extension. Check context.astc."
);
} else if (PixelFormat_default.isETC2Format(internalFormat) && !context.etc) {
throw new DeveloperError_default(
"When options.pixelFormat is ETC2 compressed, this WebGL implementation must support the WEBGL_compressed_texture_etc extension. Check context.etc."
);
} else if (PixelFormat_default.isETC1Format(internalFormat) && !context.etc1) {
throw new DeveloperError_default(
"When options.pixelFormat is ETC1 compressed, this WebGL implementation must support the WEBGL_compressed_texture_etc1 extension. Check context.etc1."
);
} else if (PixelFormat_default.isBC7Format(internalFormat) && !context.bc7) {
throw new DeveloperError_default(
"When options.pixelFormat is BC7 compressed, this WebGL implementation must support the EXT_texture_compression_bptc extension. Check context.bc7."
);
}
if (PixelFormat_default.compressedTextureSizeInBytes(
internalFormat,
width,
height
) !== source.arrayBufferView.byteLength) {
throw new DeveloperError_default(
"The byte length of the array buffer is invalid for the compressed texture with the given width and height."
);
}
}
const preMultiplyAlpha = options.preMultiplyAlpha || pixelFormat === PixelFormat_default.RGB || pixelFormat === PixelFormat_default.LUMINANCE;
const flipY = defaultValue_default(options.flipY, true);
const skipColorSpaceConversion = defaultValue_default(
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_default(source) && defined_default(source.arrayBufferView) && !isCompressed) {
unpackAlignment = PixelFormat_default.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_default(source)) {
if (defined_default(source.arrayBufferView)) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
let arrayBufferView = source.arrayBufferView;
let i, mipWidth, mipHeight;
if (isCompressed) {
gl.compressedTexImage2D(
textureTarget,
0,
internalFormat,
width,
height,
0,
arrayBufferView
);
if (defined_default(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_default.flipY(
arrayBufferView,
pixelFormat,
pixelDatatype,
width,
height
);
}
gl.texImage2D(
textureTarget,
0,
internalFormat,
width,
height,
0,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
arrayBufferView
);
if (defined_default(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_default.toWebGLConstant(pixelDatatype, context),
source.mipLevels[i]
);
}
}
}
} else if (defined_default(source.framebuffer)) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
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 {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
gl.texImage2D(
textureTarget,
0,
internalFormat,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
source
);
}
} else {
gl.texImage2D(
textureTarget,
0,
internalFormat,
width,
height,
0,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
null
);
initialized = false;
}
gl.bindTexture(textureTarget, null);
let sizeInBytes;
if (isCompressed) {
sizeInBytes = PixelFormat_default.compressedTextureSizeInBytes(
pixelFormat,
width,
height
);
} else {
sizeInBytes = PixelFormat_default.textureSizeInBytes(
pixelFormat,
pixelDatatype,
width,
height
);
}
this._id = createGuid_default();
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_default(width, height);
this._hasMipmap = false;
this._sizeInBytes = sizeInBytes;
this._preMultiplyAlpha = preMultiplyAlpha;
this._flipY = flipY;
this._initialized = initialized;
this._sampler = void 0;
this.sampler = defined_default(options.sampler) ? options.sampler : new Sampler_default();
}
Texture.create = function(options) {
return new Texture(options);
};
Texture.fromFramebuffer = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
const context = options.context;
const gl = context._gl;
const pixelFormat = defaultValue_default(options.pixelFormat, PixelFormat_default.RGB);
const framebufferXOffset = defaultValue_default(options.framebufferXOffset, 0);
const framebufferYOffset = defaultValue_default(options.framebufferYOffset, 0);
const width = defaultValue_default(options.width, gl.drawingBufferWidth);
const height = defaultValue_default(options.height, gl.drawingBufferHeight);
const framebuffer = options.framebuffer;
if (!PixelFormat_default.validate(pixelFormat)) {
throw new DeveloperError_default("Invalid pixelFormat.");
}
if (PixelFormat_default.isDepthFormat(pixelFormat) || PixelFormat_default.isCompressedFormat(pixelFormat)) {
throw new DeveloperError_default(
"pixelFormat cannot be DEPTH_COMPONENT, DEPTH_STENCIL or a compressed format."
);
}
Check_default.defined("options.context", options.context);
Check_default.typeOf.number.greaterThanOrEquals(
"framebufferXOffset",
framebufferXOffset,
0
);
Check_default.typeOf.number.greaterThanOrEquals(
"framebufferYOffset",
framebufferYOffset,
0
);
if (framebufferXOffset + width > gl.drawingBufferWidth) {
throw new DeveloperError_default(
"framebufferXOffset + width must be less than or equal to drawingBufferWidth"
);
}
if (framebufferYOffset + height > gl.drawingBufferHeight) {
throw new DeveloperError_default(
"framebufferYOffset + height must be less than or equal to drawingBufferHeight."
);
}
const texture = new Texture({
context,
width,
height,
pixelFormat,
source: {
framebuffer: defined_default(framebuffer) ? framebuffer : context.defaultFramebuffer,
xOffset: framebufferXOffset,
yOffset: framebufferYOffset,
width,
height
}
});
return texture;
};
Object.defineProperties(Texture.prototype, {
id: {
get: function() {
return this._id;
}
},
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_default.NEAREST_MIPMAP_NEAREST || minificationFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_LINEAR || minificationFilter === TextureMinificationFilter_default.LINEAR_MIPMAP_NEAREST || minificationFilter === TextureMinificationFilter_default.LINEAR_MIPMAP_LINEAR;
if (pixelDatatype === PixelDatatype_default.FLOAT && !context.textureFloatLinear || pixelDatatype === PixelDatatype_default.HALF_FLOAT && !context.textureHalfFloatLinear) {
minificationFilter = mipmap ? TextureMinificationFilter_default.NEAREST_MIPMAP_NEAREST : TextureMinificationFilter_default.NEAREST;
magnificationFilter = TextureMagnificationFilter_default.NEAREST;
}
if (context.webgl2) {
if (PixelFormat_default.isDepthFormat(pixelFormat)) {
minificationFilter = TextureMinificationFilter_default.NEAREST;
magnificationFilter = TextureMagnificationFilter_default.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_default(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;
}
}
});
Texture.prototype.copyFrom = function(options) {
Check_default.defined("options", options);
const xOffset = defaultValue_default(options.xOffset, 0);
const yOffset = defaultValue_default(options.yOffset, 0);
Check_default.defined("options.source", options.source);
if (PixelFormat_default.isDepthFormat(this._pixelFormat)) {
throw new DeveloperError_default(
"Cannot call copyFrom when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL."
);
}
if (PixelFormat_default.isCompressedFormat(this._pixelFormat)) {
throw new DeveloperError_default(
"Cannot call copyFrom with a compressed texture pixel format."
);
}
Check_default.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
Check_default.typeOf.number.lessThanOrEquals(
"xOffset + options.source.width",
xOffset + options.source.width,
this._width
);
Check_default.typeOf.number.lessThanOrEquals(
"yOffset + options.source.height",
yOffset + options.source.height,
this._height
);
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_default(
options.skipColorSpaceConversion,
false
);
let unpackAlignment = 4;
if (defined_default(arrayBufferView)) {
unpackAlignment = PixelFormat_default.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) {
if (defined_default(arrayBufferView)) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
if (flipY) {
arrayBufferView = PixelFormat_default.flipY(
arrayBufferView,
pixelFormat,
pixelDatatype,
textureWidth,
textureHeight
);
}
gl.texImage2D(
target,
0,
internalFormat,
textureWidth,
textureHeight,
0,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
arrayBufferView
);
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
gl.texImage2D(
target,
0,
internalFormat,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
source
);
}
uploaded = true;
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
const bufferView = PixelFormat_default.createTypedArray(
pixelFormat,
pixelDatatype,
textureWidth,
textureHeight
);
gl.texImage2D(
target,
0,
internalFormat,
textureWidth,
textureHeight,
0,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
bufferView
);
}
this._initialized = true;
}
if (!uploaded) {
if (defined_default(arrayBufferView)) {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
if (flipY) {
arrayBufferView = PixelFormat_default.flipY(
arrayBufferView,
pixelFormat,
pixelDatatype,
width,
height
);
}
gl.texSubImage2D(
target,
0,
xOffset,
yOffset,
width,
height,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
arrayBufferView
);
} else {
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, preMultiplyAlpha);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY);
gl.texSubImage2D(
target,
0,
xOffset,
yOffset,
pixelFormat,
PixelDatatype_default.toWebGLConstant(pixelDatatype, context),
source
);
}
}
gl.bindTexture(target, null);
};
Texture.prototype.copyFromFramebuffer = function(xOffset, yOffset, framebufferXOffset, framebufferYOffset, width, height) {
xOffset = defaultValue_default(xOffset, 0);
yOffset = defaultValue_default(yOffset, 0);
framebufferXOffset = defaultValue_default(framebufferXOffset, 0);
framebufferYOffset = defaultValue_default(framebufferYOffset, 0);
width = defaultValue_default(width, this._width);
height = defaultValue_default(height, this._height);
if (PixelFormat_default.isDepthFormat(this._pixelFormat)) {
throw new DeveloperError_default(
"Cannot call copyFromFramebuffer when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL."
);
}
if (this._pixelDatatype === PixelDatatype_default.FLOAT) {
throw new DeveloperError_default(
"Cannot call copyFromFramebuffer when the texture pixel data type is FLOAT."
);
}
if (this._pixelDatatype === PixelDatatype_default.HALF_FLOAT) {
throw new DeveloperError_default(
"Cannot call copyFromFramebuffer when the texture pixel data type is HALF_FLOAT."
);
}
if (PixelFormat_default.isCompressedFormat(this._pixelFormat)) {
throw new DeveloperError_default(
"Cannot call copyFrom with a compressed texture pixel format."
);
}
Check_default.typeOf.number.greaterThanOrEquals("xOffset", xOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals("yOffset", yOffset, 0);
Check_default.typeOf.number.greaterThanOrEquals(
"framebufferXOffset",
framebufferXOffset,
0
);
Check_default.typeOf.number.greaterThanOrEquals(
"framebufferYOffset",
framebufferYOffset,
0
);
Check_default.typeOf.number.lessThanOrEquals(
"xOffset + width",
xOffset + width,
this._width
);
Check_default.typeOf.number.lessThanOrEquals(
"yOffset + height",
yOffset + height,
this._height
);
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;
};
Texture.prototype.generateMipmap = function(hint) {
hint = defaultValue_default(hint, MipmapHint_default.DONT_CARE);
if (PixelFormat_default.isDepthFormat(this._pixelFormat)) {
throw new DeveloperError_default(
"Cannot call generateMipmap when the texture pixel format is DEPTH_COMPONENT or DEPTH_STENCIL."
);
}
if (PixelFormat_default.isCompressedFormat(this._pixelFormat)) {
throw new DeveloperError_default(
"Cannot call generateMipmap with a compressed pixel format."
);
}
if (!this._context.webgl2) {
if (this._width > 1 && !Math_default.isPowerOfTwo(this._width)) {
throw new DeveloperError_default(
"width must be a power of two to call generateMipmap() in a WebGL1 context."
);
}
if (this._height > 1 && !Math_default.isPowerOfTwo(this._height)) {
throw new DeveloperError_default(
"height must be a power of two to call generateMipmap() in a WebGL1 context."
);
}
}
if (!MipmapHint_default.validate(hint)) {
throw new DeveloperError_default("hint is invalid.");
}
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_default(this);
};
var Texture_default = Texture;
// node_modules/@cesium/engine/Source/Renderer/TextureCache.js
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_default(cachedTexture)) {
return void 0;
}
delete this._texturesToRelease[keyword];
++cachedTexture.count;
return cachedTexture.texture;
};
TextureCache.prototype.addTexture = function(keyword, texture) {
const cachedTexture = {
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_default(this);
};
var TextureCache_default = TextureCache;
// node_modules/@cesium/engine/Source/Core/EncodedCartesian3.js
function EncodedCartesian3() {
this.high = Cartesian3_default.clone(Cartesian3_default.ZERO);
this.low = Cartesian3_default.clone(Cartesian3_default.ZERO);
}
EncodedCartesian3.encode = function(value, result) {
Check_default.typeOf.number("value", value);
if (!defined_default(result)) {
result = {
high: 0,
low: 0
};
}
let doubleHigh;
if (value >= 0) {
doubleHigh = Math.floor(value / 65536) * 65536;
result.high = doubleHigh;
result.low = value - doubleHigh;
} else {
doubleHigh = Math.floor(-value / 65536) * 65536;
result.high = -doubleHigh;
result.low = value + doubleHigh;
}
return result;
};
var scratchEncode = {
high: 0,
low: 0
};
EncodedCartesian3.fromCartesian = function(cartesian11, result) {
Check_default.typeOf.object("cartesian", cartesian11);
if (!defined_default(result)) {
result = new EncodedCartesian3();
}
const high = result.high;
const low = result.low;
EncodedCartesian3.encode(cartesian11.x, scratchEncode);
high.x = scratchEncode.high;
low.x = scratchEncode.low;
EncodedCartesian3.encode(cartesian11.y, scratchEncode);
high.y = scratchEncode.high;
low.y = scratchEncode.low;
EncodedCartesian3.encode(cartesian11.z, scratchEncode);
high.z = scratchEncode.high;
low.z = scratchEncode.low;
return result;
};
var encodedP = new EncodedCartesian3();
EncodedCartesian3.writeElements = function(cartesian11, cartesianArray, index) {
Check_default.defined("cartesianArray", cartesianArray);
Check_default.typeOf.number("index", index);
Check_default.typeOf.number.greaterThanOrEquals("index", index, 0);
EncodedCartesian3.fromCartesian(cartesian11, 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;
};
var EncodedCartesian3_default = EncodedCartesian3;
// node_modules/@cesium/engine/Source/Core/Plane.js
function Plane(normal2, distance2) {
Check_default.typeOf.object("normal", normal2);
if (!Math_default.equalsEpsilon(
Cartesian3_default.magnitude(normal2),
1,
Math_default.EPSILON6
)) {
throw new DeveloperError_default("normal must be normalized.");
}
Check_default.typeOf.number("distance", distance2);
this.normal = Cartesian3_default.clone(normal2);
this.distance = distance2;
}
Plane.fromPointNormal = function(point, normal2, result) {
Check_default.typeOf.object("point", point);
Check_default.typeOf.object("normal", normal2);
if (!Math_default.equalsEpsilon(
Cartesian3_default.magnitude(normal2),
1,
Math_default.EPSILON6
)) {
throw new DeveloperError_default("normal must be normalized.");
}
const distance2 = -Cartesian3_default.dot(normal2, point);
if (!defined_default(result)) {
return new Plane(normal2, distance2);
}
Cartesian3_default.clone(normal2, result.normal);
result.distance = distance2;
return result;
};
var scratchNormal = new Cartesian3_default();
Plane.fromCartesian4 = function(coefficients, result) {
Check_default.typeOf.object("coefficients", coefficients);
const normal2 = Cartesian3_default.fromCartesian4(coefficients, scratchNormal);
const distance2 = coefficients.w;
if (!Math_default.equalsEpsilon(
Cartesian3_default.magnitude(normal2),
1,
Math_default.EPSILON6
)) {
throw new DeveloperError_default("normal must be normalized.");
}
if (!defined_default(result)) {
return new Plane(normal2, distance2);
}
Cartesian3_default.clone(normal2, result.normal);
result.distance = distance2;
return result;
};
Plane.getPointDistance = function(plane, point) {
Check_default.typeOf.object("plane", plane);
Check_default.typeOf.object("point", point);
return Cartesian3_default.dot(plane.normal, point) + plane.distance;
};
var scratchCartesian = new Cartesian3_default();
Plane.projectPointOntoPlane = function(plane, point, result) {
Check_default.typeOf.object("plane", plane);
Check_default.typeOf.object("point", point);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const pointDistance = Plane.getPointDistance(plane, point);
const scaledNormal = Cartesian3_default.multiplyByScalar(
plane.normal,
pointDistance,
scratchCartesian
);
return Cartesian3_default.subtract(point, scaledNormal, result);
};
var scratchInverseTranspose = new Matrix4_default();
var scratchPlaneCartesian4 = new Cartesian4_default();
var scratchTransformNormal = new Cartesian3_default();
Plane.transform = function(plane, transform3, result) {
Check_default.typeOf.object("plane", plane);
Check_default.typeOf.object("transform", transform3);
const normal2 = plane.normal;
const distance2 = plane.distance;
const inverseTranspose2 = Matrix4_default.inverseTranspose(
transform3,
scratchInverseTranspose
);
let planeAsCartesian4 = Cartesian4_default.fromElements(
normal2.x,
normal2.y,
normal2.z,
distance2,
scratchPlaneCartesian4
);
planeAsCartesian4 = Matrix4_default.multiplyByVector(
inverseTranspose2,
planeAsCartesian4,
planeAsCartesian4
);
const transformedNormal = Cartesian3_default.fromCartesian4(
planeAsCartesian4,
scratchTransformNormal
);
planeAsCartesian4 = Cartesian4_default.divideByScalar(
planeAsCartesian4,
Cartesian3_default.magnitude(transformedNormal),
planeAsCartesian4
);
return Plane.fromCartesian4(planeAsCartesian4, result);
};
Plane.clone = function(plane, result) {
Check_default.typeOf.object("plane", plane);
if (!defined_default(result)) {
return new Plane(plane.normal, plane.distance);
}
Cartesian3_default.clone(plane.normal, result.normal);
result.distance = plane.distance;
return result;
};
Plane.equals = function(left, right) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
return left.distance === right.distance && Cartesian3_default.equals(left.normal, right.normal);
};
Plane.ORIGIN_XY_PLANE = Object.freeze(new Plane(Cartesian3_default.UNIT_Z, 0));
Plane.ORIGIN_YZ_PLANE = Object.freeze(new Plane(Cartesian3_default.UNIT_X, 0));
Plane.ORIGIN_ZX_PLANE = Object.freeze(new Plane(Cartesian3_default.UNIT_Y, 0));
var Plane_default = Plane;
// node_modules/@cesium/engine/Source/Core/CullingVolume.js
function CullingVolume(planes) {
this.planes = defaultValue_default(planes, []);
}
var faces = [new Cartesian3_default(), new Cartesian3_default(), new Cartesian3_default()];
Cartesian3_default.clone(Cartesian3_default.UNIT_X, faces[0]);
Cartesian3_default.clone(Cartesian3_default.UNIT_Y, faces[1]);
Cartesian3_default.clone(Cartesian3_default.UNIT_Z, faces[2]);
var scratchPlaneCenter = new Cartesian3_default();
var scratchPlaneNormal = new Cartesian3_default();
var scratchPlane = new Plane_default(new Cartesian3_default(1, 0, 0), 0);
CullingVolume.fromBoundingSphere = function(boundingSphere, result) {
if (!defined_default(boundingSphere)) {
throw new DeveloperError_default("boundingSphere is required.");
}
if (!defined_default(result)) {
result = new CullingVolume();
}
const length3 = faces.length;
const planes = result.planes;
planes.length = 2 * length3;
const center = boundingSphere.center;
const radius = boundingSphere.radius;
let planeIndex = 0;
for (let i = 0; i < length3; ++i) {
const faceNormal = faces[i];
let plane0 = planes[planeIndex];
let plane1 = planes[planeIndex + 1];
if (!defined_default(plane0)) {
plane0 = planes[planeIndex] = new Cartesian4_default();
}
if (!defined_default(plane1)) {
plane1 = planes[planeIndex + 1] = new Cartesian4_default();
}
Cartesian3_default.multiplyByScalar(faceNormal, -radius, scratchPlaneCenter);
Cartesian3_default.add(center, scratchPlaneCenter, scratchPlaneCenter);
plane0.x = faceNormal.x;
plane0.y = faceNormal.y;
plane0.z = faceNormal.z;
plane0.w = -Cartesian3_default.dot(faceNormal, scratchPlaneCenter);
Cartesian3_default.multiplyByScalar(faceNormal, radius, scratchPlaneCenter);
Cartesian3_default.add(center, scratchPlaneCenter, scratchPlaneCenter);
plane1.x = -faceNormal.x;
plane1.y = -faceNormal.y;
plane1.z = -faceNormal.z;
plane1.w = -Cartesian3_default.dot(
Cartesian3_default.negate(faceNormal, scratchPlaneNormal),
scratchPlaneCenter
);
planeIndex += 2;
}
return result;
};
CullingVolume.prototype.computeVisibility = function(boundingVolume) {
if (!defined_default(boundingVolume)) {
throw new DeveloperError_default("boundingVolume is required.");
}
const planes = this.planes;
let intersecting = false;
for (let k = 0, len = planes.length; k < len; ++k) {
const result = boundingVolume.intersectPlane(
Plane_default.fromCartesian4(planes[k], scratchPlane)
);
if (result === Intersect_default.OUTSIDE) {
return Intersect_default.OUTSIDE;
} else if (result === Intersect_default.INTERSECTING) {
intersecting = true;
}
}
return intersecting ? Intersect_default.INTERSECTING : Intersect_default.INSIDE;
};
CullingVolume.prototype.computeVisibilityWithPlaneMask = function(boundingVolume, parentPlaneMask) {
if (!defined_default(boundingVolume)) {
throw new DeveloperError_default("boundingVolume is required.");
}
if (!defined_default(parentPlaneMask)) {
throw new DeveloperError_default("parentPlaneMask is required.");
}
if (parentPlaneMask === CullingVolume.MASK_OUTSIDE || parentPlaneMask === CullingVolume.MASK_INSIDE) {
return parentPlaneMask;
}
let mask = CullingVolume.MASK_INSIDE;
const planes = this.planes;
for (let k = 0, len = planes.length; k < len; ++k) {
const flag = k < 31 ? 1 << k : 0;
if (k < 31 && (parentPlaneMask & flag) === 0) {
continue;
}
const result = boundingVolume.intersectPlane(
Plane_default.fromCartesian4(planes[k], scratchPlane)
);
if (result === Intersect_default.OUTSIDE) {
return CullingVolume.MASK_OUTSIDE;
} else if (result === Intersect_default.INTERSECTING) {
mask |= flag;
}
}
return mask;
};
CullingVolume.MASK_OUTSIDE = 4294967295;
CullingVolume.MASK_INSIDE = 0;
CullingVolume.MASK_INDETERMINATE = 2147483647;
var CullingVolume_default = CullingVolume;
// node_modules/@cesium/engine/Source/Core/OrthographicOffCenterFrustum.js
function OrthographicOffCenterFrustum(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.left = options.left;
this._left = void 0;
this.right = options.right;
this._right = void 0;
this.top = options.top;
this._top = void 0;
this.bottom = options.bottom;
this._bottom = void 0;
this.near = defaultValue_default(options.near, 1);
this._near = this.near;
this.far = defaultValue_default(options.far, 5e8);
this._far = this.far;
this._cullingVolume = new CullingVolume_default();
this._orthographicMatrix = new Matrix4_default();
}
function update(frustum) {
if (!defined_default(frustum.right) || !defined_default(frustum.left) || !defined_default(frustum.top) || !defined_default(frustum.bottom) || !defined_default(frustum.near) || !defined_default(frustum.far)) {
throw new DeveloperError_default(
"right, left, top, bottom, near, or far parameters are not set."
);
}
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) {
if (frustum.left > frustum.right) {
throw new DeveloperError_default("right must be greater than left.");
}
if (frustum.bottom > frustum.top) {
throw new DeveloperError_default("top must be greater than bottom.");
}
if (frustum.near <= 0 || frustum.near > frustum.far) {
throw new DeveloperError_default(
"near must be greater than zero and less than far."
);
}
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_default.computeOrthographicOffCenter(
frustum.left,
frustum.right,
frustum.bottom,
frustum.top,
frustum.near,
frustum.far,
frustum._orthographicMatrix
);
}
}
Object.defineProperties(OrthographicOffCenterFrustum.prototype, {
projectionMatrix: {
get: function() {
update(this);
return this._orthographicMatrix;
}
}
});
var getPlanesRight = new Cartesian3_default();
var getPlanesNearCenter = new Cartesian3_default();
var getPlanesPoint = new Cartesian3_default();
var negateScratch = new Cartesian3_default();
OrthographicOffCenterFrustum.prototype.computeCullingVolume = function(position, direction2, up) {
if (!defined_default(position)) {
throw new DeveloperError_default("position is required.");
}
if (!defined_default(direction2)) {
throw new DeveloperError_default("direction is required.");
}
if (!defined_default(up)) {
throw new DeveloperError_default("up is required.");
}
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_default.cross(direction2, up, getPlanesRight);
Cartesian3_default.normalize(right, right);
const nearCenter = getPlanesNearCenter;
Cartesian3_default.multiplyByScalar(direction2, n, nearCenter);
Cartesian3_default.add(position, nearCenter, nearCenter);
const point = getPlanesPoint;
Cartesian3_default.multiplyByScalar(right, l, point);
Cartesian3_default.add(nearCenter, point, point);
let plane = planes[0];
if (!defined_default(plane)) {
plane = planes[0] = new Cartesian4_default();
}
plane.x = right.x;
plane.y = right.y;
plane.z = right.z;
plane.w = -Cartesian3_default.dot(right, point);
Cartesian3_default.multiplyByScalar(right, r, point);
Cartesian3_default.add(nearCenter, point, point);
plane = planes[1];
if (!defined_default(plane)) {
plane = planes[1] = new Cartesian4_default();
}
plane.x = -right.x;
plane.y = -right.y;
plane.z = -right.z;
plane.w = -Cartesian3_default.dot(Cartesian3_default.negate(right, negateScratch), point);
Cartesian3_default.multiplyByScalar(up, b, point);
Cartesian3_default.add(nearCenter, point, point);
plane = planes[2];
if (!defined_default(plane)) {
plane = planes[2] = new Cartesian4_default();
}
plane.x = up.x;
plane.y = up.y;
plane.z = up.z;
plane.w = -Cartesian3_default.dot(up, point);
Cartesian3_default.multiplyByScalar(up, t, point);
Cartesian3_default.add(nearCenter, point, point);
plane = planes[3];
if (!defined_default(plane)) {
plane = planes[3] = new Cartesian4_default();
}
plane.x = -up.x;
plane.y = -up.y;
plane.z = -up.z;
plane.w = -Cartesian3_default.dot(Cartesian3_default.negate(up, negateScratch), point);
plane = planes[4];
if (!defined_default(plane)) {
plane = planes[4] = new Cartesian4_default();
}
plane.x = direction2.x;
plane.y = direction2.y;
plane.z = direction2.z;
plane.w = -Cartesian3_default.dot(direction2, nearCenter);
Cartesian3_default.multiplyByScalar(direction2, f, point);
Cartesian3_default.add(position, point, point);
plane = planes[5];
if (!defined_default(plane)) {
plane = planes[5] = new Cartesian4_default();
}
plane.x = -direction2.x;
plane.y = -direction2.y;
plane.z = -direction2.z;
plane.w = -Cartesian3_default.dot(Cartesian3_default.negate(direction2, negateScratch), point);
return this._cullingVolume;
};
OrthographicOffCenterFrustum.prototype.getPixelDimensions = function(drawingBufferWidth, drawingBufferHeight, distance2, pixelRatio, result) {
update(this);
if (!defined_default(drawingBufferWidth) || !defined_default(drawingBufferHeight)) {
throw new DeveloperError_default(
"Both drawingBufferWidth and drawingBufferHeight are required."
);
}
if (drawingBufferWidth <= 0) {
throw new DeveloperError_default("drawingBufferWidth must be greater than zero.");
}
if (drawingBufferHeight <= 0) {
throw new DeveloperError_default("drawingBufferHeight must be greater than zero.");
}
if (!defined_default(distance2)) {
throw new DeveloperError_default("distance is required.");
}
if (!defined_default(pixelRatio)) {
throw new DeveloperError_default("pixelRatio is required.");
}
if (pixelRatio <= 0) {
throw new DeveloperError_default("pixelRatio must be greater than zero.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("A result object is required.");
}
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;
};
OrthographicOffCenterFrustum.prototype.clone = function(result) {
if (!defined_default(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;
result._left = void 0;
result._right = void 0;
result._top = void 0;
result._bottom = void 0;
result._near = void 0;
result._far = void 0;
return result;
};
OrthographicOffCenterFrustum.prototype.equals = function(other) {
return defined_default(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;
};
OrthographicOffCenterFrustum.prototype.equalsEpsilon = function(other, relativeEpsilon, absoluteEpsilon) {
return other === this || defined_default(other) && other instanceof OrthographicOffCenterFrustum && Math_default.equalsEpsilon(
this.right,
other.right,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
this.left,
other.left,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
this.top,
other.top,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
this.bottom,
other.bottom,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
this.near,
other.near,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
this.far,
other.far,
relativeEpsilon,
absoluteEpsilon
);
};
var OrthographicOffCenterFrustum_default = OrthographicOffCenterFrustum;
// node_modules/@cesium/engine/Source/Core/OrthographicFrustum.js
function OrthographicFrustum(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._offCenterFrustum = new OrthographicOffCenterFrustum_default();
this.width = options.width;
this._width = void 0;
this.aspectRatio = options.aspectRatio;
this._aspectRatio = void 0;
this.near = defaultValue_default(options.near, 1);
this._near = this.near;
this.far = defaultValue_default(options.far, 5e8);
this._far = this.far;
}
OrthographicFrustum.packedLength = 4;
OrthographicFrustum.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.width;
array[startingIndex++] = value.aspectRatio;
array[startingIndex++] = value.near;
array[startingIndex] = value.far;
return array;
};
OrthographicFrustum.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new OrthographicFrustum();
}
result.width = array[startingIndex++];
result.aspectRatio = array[startingIndex++];
result.near = array[startingIndex++];
result.far = array[startingIndex];
return result;
};
function update2(frustum) {
if (!defined_default(frustum.width) || !defined_default(frustum.aspectRatio) || !defined_default(frustum.near) || !defined_default(frustum.far)) {
throw new DeveloperError_default(
"width, aspectRatio, near, or far parameters are not set."
);
}
const f = frustum._offCenterFrustum;
if (frustum.width !== frustum._width || frustum.aspectRatio !== frustum._aspectRatio || frustum.near !== frustum._near || frustum.far !== frustum._far) {
if (frustum.aspectRatio < 0) {
throw new DeveloperError_default("aspectRatio must be positive.");
}
if (frustum.near < 0 || frustum.near > frustum.far) {
throw new DeveloperError_default(
"near must be greater than zero and less than far."
);
}
frustum._aspectRatio = frustum.aspectRatio;
frustum._width = frustum.width;
frustum._near = frustum.near;
frustum._far = frustum.far;
const ratio = 1 / 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, {
projectionMatrix: {
get: function() {
update2(this);
return this._offCenterFrustum.projectionMatrix;
}
},
offCenterFrustum: {
get: function() {
update2(this);
return this._offCenterFrustum;
}
}
});
OrthographicFrustum.prototype.computeCullingVolume = function(position, direction2, up) {
update2(this);
return this._offCenterFrustum.computeCullingVolume(position, direction2, up);
};
OrthographicFrustum.prototype.getPixelDimensions = function(drawingBufferWidth, drawingBufferHeight, distance2, pixelRatio, result) {
update2(this);
return this._offCenterFrustum.getPixelDimensions(
drawingBufferWidth,
drawingBufferHeight,
distance2,
pixelRatio,
result
);
};
OrthographicFrustum.prototype.clone = function(result) {
if (!defined_default(result)) {
result = new OrthographicFrustum();
}
result.aspectRatio = this.aspectRatio;
result.width = this.width;
result.near = this.near;
result.far = this.far;
result._aspectRatio = void 0;
result._width = void 0;
result._near = void 0;
result._far = void 0;
this._offCenterFrustum.clone(result._offCenterFrustum);
return result;
};
OrthographicFrustum.prototype.equals = function(other) {
if (!defined_default(other) || !(other instanceof OrthographicFrustum)) {
return false;
}
update2(this);
update2(other);
return this.width === other.width && this.aspectRatio === other.aspectRatio && this._offCenterFrustum.equals(other._offCenterFrustum);
};
OrthographicFrustum.prototype.equalsEpsilon = function(other, relativeEpsilon, absoluteEpsilon) {
if (!defined_default(other) || !(other instanceof OrthographicFrustum)) {
return false;
}
update2(this);
update2(other);
return Math_default.equalsEpsilon(
this.width,
other.width,
relativeEpsilon,
absoluteEpsilon
) && Math_default.equalsEpsilon(
this.aspectRatio,
other.aspectRatio,
relativeEpsilon,
absoluteEpsilon
) && this._offCenterFrustum.equalsEpsilon(
other._offCenterFrustum,
relativeEpsilon,
absoluteEpsilon
);
};
var OrthographicFrustum_default = OrthographicFrustum;
// node_modules/@cesium/engine/Source/Core/Simon1994PlanetaryPositions.js
var Simon1994PlanetaryPositions = {};
function computeTdbMinusTtSpice(daysSinceJ2000InTerrestrialTime) {
const g = 6.239996 + 0.0172019696544 * daysSinceJ2000InTerrestrialTime;
return 1657e-6 * Math.sin(g + 0.01671 * Math.sin(g));
}
var TdtMinusTai = 32.184;
var J2000d = 2451545;
function taiToTdb(date, result) {
result = JulianDate_default.addSeconds(date, TdtMinusTai, result);
const days = JulianDate_default.totalDays(result) - J2000d;
result = JulianDate_default.addSeconds(result, computeTdbMinusTtSpice(days), result);
return result;
}
var epoch = new JulianDate_default(2451545, 0, TimeStandard_default.TAI);
var MetersPerKilometer = 1e3;
var RadiansPerDegree = Math_default.RADIANS_PER_DEGREE;
var RadiansPerArcSecond = Math_default.RADIANS_PER_ARCSECOND;
var MetersPerAstronomicalUnit = 14959787e4;
var perifocalToEquatorial = new Matrix3_default();
function elementsToCartesian(semimajorAxis, eccentricity, inclination, longitudeOfPerigee, longitudeOfNode, meanLongitude, result) {
if (inclination < 0) {
inclination = -inclination;
longitudeOfNode += Math_default.PI;
}
if (inclination < 0 || inclination > Math_default.PI) {
throw new DeveloperError_default(
"The inclination is out of range. Inclination must be greater than or equal to zero and less than or equal to Pi radians."
);
}
const radiusOfPeriapsis = semimajorAxis * (1 - eccentricity);
const argumentOfPeriapsis = longitudeOfPerigee - longitudeOfNode;
const rightAscensionOfAscendingNode = longitudeOfNode;
const trueAnomaly = meanAnomalyToTrueAnomaly(
meanLongitude - longitudeOfPerigee,
eccentricity
);
const type = chooseOrbit(eccentricity, 0);
if (type === "Hyperbolic" && Math.abs(Math_default.negativePiToPi(trueAnomaly)) >= Math.acos(-1 / eccentricity)) {
throw new DeveloperError_default(
"The true anomaly of the hyperbolic orbit lies outside of the bounds of the hyperbola."
);
}
perifocalToCartesianMatrix(
argumentOfPeriapsis,
inclination,
rightAscensionOfAscendingNode,
perifocalToEquatorial
);
const semilatus = radiusOfPeriapsis * (1 + eccentricity);
const costheta = Math.cos(trueAnomaly);
const sintheta = Math.sin(trueAnomaly);
const denom = 1 + eccentricity * costheta;
if (denom <= Math_default.Epsilon10) {
throw new DeveloperError_default("elements cannot be converted to cartesian");
}
const radius = semilatus / denom;
if (!defined_default(result)) {
result = new Cartesian3_default(radius * costheta, radius * sintheta, 0);
} else {
result.x = radius * costheta;
result.y = radius * sintheta;
result.z = 0;
}
return Matrix3_default.multiplyByVector(perifocalToEquatorial, result, result);
}
function chooseOrbit(eccentricity, tolerance) {
if (eccentricity < 0) {
throw new DeveloperError_default("eccentricity cannot be negative.");
}
if (eccentricity <= tolerance) {
return "Circular";
} else if (eccentricity < 1 - tolerance) {
return "Elliptical";
} else if (eccentricity <= 1 + tolerance) {
return "Parabolic";
}
return "Hyperbolic";
}
function meanAnomalyToTrueAnomaly(meanAnomaly, eccentricity) {
if (eccentricity < 0 || eccentricity >= 1) {
throw new DeveloperError_default("eccentricity out of range.");
}
const eccentricAnomaly = meanAnomalyToEccentricAnomaly(
meanAnomaly,
eccentricity
);
return eccentricAnomalyToTrueAnomaly(eccentricAnomaly, eccentricity);
}
var maxIterationCount = 50;
var keplerEqConvergence = Math_default.EPSILON8;
function meanAnomalyToEccentricAnomaly(meanAnomaly, eccentricity) {
if (eccentricity < 0 || eccentricity >= 1) {
throw new DeveloperError_default("eccentricity out of range.");
}
const revs = Math.floor(meanAnomaly / Math_default.TWO_PI);
meanAnomaly -= revs * Math_default.TWO_PI;
let iterationValue = meanAnomaly + eccentricity * Math.sin(meanAnomaly) / (1 - Math.sin(meanAnomaly + eccentricity) + Math.sin(meanAnomaly));
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;
}
if (count >= maxIterationCount) {
throw new DeveloperError_default("Kepler equation did not converge");
}
eccentricAnomaly = iterationValue + revs * Math_default.TWO_PI;
return eccentricAnomaly;
}
function eccentricAnomalyToTrueAnomaly(eccentricAnomaly, eccentricity) {
if (eccentricity < 0 || eccentricity >= 1) {
throw new DeveloperError_default("eccentricity out of range.");
}
const revs = Math.floor(eccentricAnomaly / Math_default.TWO_PI);
eccentricAnomaly -= revs * Math_default.TWO_PI;
const trueAnomalyX = Math.cos(eccentricAnomaly) - eccentricity;
const trueAnomalyY = Math.sin(eccentricAnomaly) * Math.sqrt(1 - eccentricity * eccentricity);
let trueAnomaly = Math.atan2(trueAnomalyY, trueAnomalyX);
trueAnomaly = Math_default.zeroToTwoPi(trueAnomaly);
if (eccentricAnomaly < 0) {
trueAnomaly -= Math_default.TWO_PI;
}
trueAnomaly += revs * Math_default.TWO_PI;
return trueAnomaly;
}
function perifocalToCartesianMatrix(argumentOfPeriapsis, inclination, rightAscension, result) {
if (inclination < 0 || inclination > Math_default.PI) {
throw new DeveloperError_default("inclination out of range");
}
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_default(result)) {
result = new Matrix3_default(
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;
}
var semiMajorAxis0 = 1.0000010178 * MetersPerAstronomicalUnit;
var meanLongitude0 = 100.46645683 * RadiansPerDegree;
var meanLongitude1 = 129597742283429e-5 * RadiansPerArcSecond;
var p1u = 16002;
var p2u = 21863;
var p3u = 32004;
var p4u = 10931;
var p5u = 14529;
var p6u = 16368;
var p7u = 15318;
var p8u = 32794;
var Ca1 = 64 * 1e-7 * MetersPerAstronomicalUnit;
var Ca2 = -152 * 1e-7 * MetersPerAstronomicalUnit;
var Ca3 = 62 * 1e-7 * MetersPerAstronomicalUnit;
var Ca4 = -8 * 1e-7 * MetersPerAstronomicalUnit;
var Ca5 = 32 * 1e-7 * MetersPerAstronomicalUnit;
var Ca6 = -41 * 1e-7 * MetersPerAstronomicalUnit;
var Ca7 = 19 * 1e-7 * MetersPerAstronomicalUnit;
var Ca8 = -11 * 1e-7 * MetersPerAstronomicalUnit;
var Sa1 = -150 * 1e-7 * MetersPerAstronomicalUnit;
var Sa2 = -46 * 1e-7 * MetersPerAstronomicalUnit;
var Sa3 = 68 * 1e-7 * MetersPerAstronomicalUnit;
var Sa4 = 54 * 1e-7 * MetersPerAstronomicalUnit;
var Sa5 = 14 * 1e-7 * MetersPerAstronomicalUnit;
var Sa6 = 24 * 1e-7 * MetersPerAstronomicalUnit;
var Sa7 = -28 * 1e-7 * MetersPerAstronomicalUnit;
var Sa8 = 22 * 1e-7 * MetersPerAstronomicalUnit;
var q1u = 10;
var q2u = 16002;
var q3u = 21863;
var q4u = 10931;
var q5u = 1473;
var q6u = 32004;
var q7u = 4387;
var q8u = 73;
var Cl1 = -325 * 1e-7;
var Cl2 = -322 * 1e-7;
var Cl3 = -79 * 1e-7;
var Cl4 = 232 * 1e-7;
var Cl5 = -52 * 1e-7;
var Cl6 = 97 * 1e-7;
var Cl7 = 55 * 1e-7;
var Cl8 = -41 * 1e-7;
var Sl1 = -105 * 1e-7;
var Sl2 = -137 * 1e-7;
var Sl3 = 258 * 1e-7;
var Sl4 = 35 * 1e-7;
var Sl5 = -116 * 1e-7;
var Sl6 = -88 * 1e-7;
var Sl7 = -112 * 1e-7;
var Sl8 = -80 * 1e-7;
var scratchDate = new JulianDate_default(0, 0, TimeStandard_default.TAI);
function computeSimonEarthMoonBarycenter(date, result) {
taiToTdb(date, scratchDate);
const x = scratchDate.dayNumber - epoch.dayNumber + (scratchDate.secondsOfDay - epoch.secondsOfDay) / TimeConstants_default.SECONDS_PER_DAY;
const t = x / (TimeConstants_default.DAYS_PER_JULIAN_CENTURY * 10);
const u3 = 0.3595362 * t;
const semimajorAxis = semiMajorAxis0 + Ca1 * Math.cos(p1u * u3) + Sa1 * Math.sin(p1u * u3) + Ca2 * Math.cos(p2u * u3) + Sa2 * Math.sin(p2u * u3) + Ca3 * Math.cos(p3u * u3) + Sa3 * Math.sin(p3u * u3) + Ca4 * Math.cos(p4u * u3) + Sa4 * Math.sin(p4u * u3) + Ca5 * Math.cos(p5u * u3) + Sa5 * Math.sin(p5u * u3) + Ca6 * Math.cos(p6u * u3) + Sa6 * Math.sin(p6u * u3) + Ca7 * Math.cos(p7u * u3) + Sa7 * Math.sin(p7u * u3) + Ca8 * Math.cos(p8u * u3) + Sa8 * Math.sin(p8u * u3);
const meanLongitude = meanLongitude0 + meanLongitude1 * t + Cl1 * Math.cos(q1u * u3) + Sl1 * Math.sin(q1u * u3) + Cl2 * Math.cos(q2u * u3) + Sl2 * Math.sin(q2u * u3) + Cl3 * Math.cos(q3u * u3) + Sl3 * Math.sin(q3u * u3) + Cl4 * Math.cos(q4u * u3) + Sl4 * Math.sin(q4u * u3) + Cl5 * Math.cos(q5u * u3) + Sl5 * Math.sin(q5u * u3) + Cl6 * Math.cos(q6u * u3) + Sl6 * Math.sin(q6u * u3) + Cl7 * Math.cos(q7u * u3) + Sl7 * Math.sin(q7u * u3) + Cl8 * Math.cos(q8u * u3) + Sl8 * Math.sin(q8u * u3);
const eccentricity = 0.0167086342 - 4203654e-10 * 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
);
}
function computeSimonMoon(date, result) {
taiToTdb(date, scratchDate);
const x = scratchDate.dayNumber - epoch.dayNumber + (scratchDate.secondsOfDay - epoch.secondsOfDay) / TimeConstants_default.SECONDS_PER_DAY;
const t = x / TimeConstants_default.DAYS_PER_JULIAN_CENTURY;
const t2 = t * t;
const t3 = t2 * t;
const t4 = t3 * t;
let semimajorAxis = 383397.7725 + 4e-3 * t;
let eccentricity = 0.055545526 - 16e-9 * t;
const inclinationConstant = 5.15668983 * RadiansPerDegree;
let inclinationSecPart = -8e-5 * t + 0.02966 * t2 - 42e-6 * t3 - 13e-8 * t4;
const longitudeOfPerigeeConstant = 83.35324312 * RadiansPerDegree;
let longitudeOfPerigeeSecPart = 146434202669e-4 * t - 38.2702 * t2 - 0.045047 * t3 + 21301e-8 * t4;
const longitudeOfNodeConstant = 125.04455501 * RadiansPerDegree;
let longitudeOfNodeSecPart = -69679193631e-4 * t + 6.3602 * t2 + 7625e-6 * t3 - 3586e-8 * t4;
const meanLongitudeConstant = 218.31664563 * RadiansPerDegree;
let meanLongitudeSecPart = 17325593434847e-4 * t - 6.391 * t2 + 6588e-6 * t3 - 3169e-8 * t4;
const D = 297.85019547 * RadiansPerDegree + RadiansPerArcSecond * (1602961601209e-3 * t - 6.3706 * t2 + 6593e-6 * t3 - 3169e-8 * t4);
const F = 93.27209062 * RadiansPerDegree + RadiansPerArcSecond * (17395272628478e-4 * t - 12.7512 * t2 - 1037e-6 * t3 + 417e-8 * t4);
const l = 134.96340251 * RadiansPerDegree + RadiansPerArcSecond * (17179159232178e-4 * t + 31.8792 * t2 + 0.051635 * t3 - 2447e-7 * t4);
const lprime = 357.52910918 * RadiansPerDegree + RadiansPerArcSecond * (1295965810481e-4 * t - 0.5532 * t2 + 136e-6 * t3 - 1149e-8 * t4);
const psi = 310.17137918 * RadiansPerDegree - RadiansPerArcSecond * (6967051436e-3 * t + 6.2068 * t2 + 7618e-6 * t3 - 3219e-8 * t4);
const twoD = 2 * D;
const fourD = 4 * D;
const sixD = 6 * D;
const twol = 2 * l;
const threel = 3 * l;
const fourl = 4 * l;
const twoF = 2 * 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 * Math.cos(twoD + l);
eccentricity += 0.014216 * Math.cos(twoD - l) + 8551e-6 * Math.cos(twoD - twol) - 1383e-6 * Math.cos(l) + 1356e-6 * Math.cos(twoD + l) - 1147e-6 * Math.cos(fourD - threel) - 914e-6 * Math.cos(fourD - twol) + 869e-6 * Math.cos(twoD - lprime - l) - 627e-6 * Math.cos(twoD) - 394e-6 * Math.cos(fourD - fourl) + 282e-6 * Math.cos(twoD - lprime - twol) - 279e-6 * Math.cos(D - l) - 236e-6 * Math.cos(twol) + 231e-6 * Math.cos(fourD) + 229e-6 * Math.cos(sixD - fourl) - 201e-6 * 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 * 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 * Math.sin(twoD - lprime);
const twoPsi = 2 * psi;
const threePsi = 3 * 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 + 12e-4 * Math.cos(twoD - twoF + twoPsi) * t2 - 16e-5 * Math.cos(psi) * t3 + 4e-5 * Math.cos(threePsi) * t3 + 4e-5 * Math.cos(twoPsi) * t3;
const perigeeAndMean = 2.116 * Math.sin(psi) * t - 0.111 * Math.sin(twoD - twoF - psi) * t - 15e-4 * 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 + 14e-4 * Math.sin(psi) * t3 - 11e-4 * Math.sin(threePsi) * t3 - 9e-4 * Math.sin(twoPsi) * t3;
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
);
}
var moonEarthMassRatio = 0.012300034;
var factor = moonEarthMassRatio / (moonEarthMassRatio + 1) * -1;
function computeSimonEarth(date, result) {
result = computeSimonMoon(date, result);
return Cartesian3_default.multiplyByScalar(result, factor, result);
}
var axesTransformation = new Matrix3_default(
1.0000000000000002,
5619723173785822e-31,
4690511510146299e-34,
-5154129427414611e-31,
0.9174820620691819,
-0.39777715593191376,
-223970096136568e-30,
0.39777715593191376,
0.9174820620691819
);
var translation = new Cartesian3_default();
Simon1994PlanetaryPositions.computeSunPositionInEarthInertialFrame = function(julianDate, result) {
if (!defined_default(julianDate)) {
julianDate = JulianDate_default.now();
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
translation = computeSimonEarthMoonBarycenter(julianDate, translation);
result = Cartesian3_default.negate(translation, result);
computeSimonEarth(julianDate, translation);
Cartesian3_default.subtract(result, translation, result);
Matrix3_default.multiplyByVector(axesTransformation, result, result);
return result;
};
Simon1994PlanetaryPositions.computeMoonPositionInEarthInertialFrame = function(julianDate, result) {
if (!defined_default(julianDate)) {
julianDate = JulianDate_default.now();
}
result = computeSimonMoon(julianDate, result);
Matrix3_default.multiplyByVector(axesTransformation, result, result);
return result;
};
var Simon1994PlanetaryPositions_default = Simon1994PlanetaryPositions;
// node_modules/@cesium/engine/Source/Scene/SceneMode.js
var SceneMode = {
MORPHING: 0,
COLUMBUS_VIEW: 1,
SCENE2D: 2,
SCENE3D: 3
};
SceneMode.getMorphTime = function(value) {
if (value === SceneMode.SCENE3D) {
return 1;
} else if (value === SceneMode.MORPHING) {
return void 0;
}
return 0;
};
var SceneMode_default = Object.freeze(SceneMode);
// node_modules/@cesium/engine/Source/Scene/SunLight.js
function SunLight(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.color = Color_default.clone(defaultValue_default(options.color, Color_default.WHITE));
this.intensity = defaultValue_default(options.intensity, 2);
}
var SunLight_default = SunLight;
// node_modules/@cesium/engine/Source/Renderer/UniformState.js
function UniformState() {
this.globeDepthTexture = void 0;
this.gamma = void 0;
this._viewport = new BoundingRectangle_default();
this._viewportCartesian4 = new Cartesian4_default();
this._viewportDirty = false;
this._viewportOrthographicMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._viewportTransformation = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._model = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._view = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._inverseView = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._projection = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._infiniteProjection = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._entireFrustum = new Cartesian2_default();
this._currentFrustum = new Cartesian2_default();
this._frustumPlanes = new Cartesian4_default();
this._farDepthFromNearPlusOne = void 0;
this._log2FarDepthFromNearPlusOne = void 0;
this._oneOverLog2FarDepthFromNearPlusOne = void 0;
this._frameState = void 0;
this._temeToPseudoFixed = Matrix3_default.clone(Matrix4_default.IDENTITY);
this._view3DDirty = true;
this._view3D = new Matrix4_default();
this._inverseView3DDirty = true;
this._inverseView3D = new Matrix4_default();
this._inverseModelDirty = true;
this._inverseModel = new Matrix4_default();
this._inverseTransposeModelDirty = true;
this._inverseTransposeModel = new Matrix3_default();
this._viewRotation = new Matrix3_default();
this._inverseViewRotation = new Matrix3_default();
this._viewRotation3D = new Matrix3_default();
this._inverseViewRotation3D = new Matrix3_default();
this._inverseProjectionDirty = true;
this._inverseProjection = new Matrix4_default();
this._modelViewDirty = true;
this._modelView = new Matrix4_default();
this._modelView3DDirty = true;
this._modelView3D = new Matrix4_default();
this._modelViewRelativeToEyeDirty = true;
this._modelViewRelativeToEye = new Matrix4_default();
this._inverseModelViewDirty = true;
this._inverseModelView = new Matrix4_default();
this._inverseModelView3DDirty = true;
this._inverseModelView3D = new Matrix4_default();
this._viewProjectionDirty = true;
this._viewProjection = new Matrix4_default();
this._inverseViewProjectionDirty = true;
this._inverseViewProjection = new Matrix4_default();
this._modelViewProjectionDirty = true;
this._modelViewProjection = new Matrix4_default();
this._inverseModelViewProjectionDirty = true;
this._inverseModelViewProjection = new Matrix4_default();
this._modelViewProjectionRelativeToEyeDirty = true;
this._modelViewProjectionRelativeToEye = new Matrix4_default();
this._modelViewInfiniteProjectionDirty = true;
this._modelViewInfiniteProjection = new Matrix4_default();
this._normalDirty = true;
this._normal = new Matrix3_default();
this._normal3DDirty = true;
this._normal3D = new Matrix3_default();
this._inverseNormalDirty = true;
this._inverseNormal = new Matrix3_default();
this._inverseNormal3DDirty = true;
this._inverseNormal3D = new Matrix3_default();
this._encodedCameraPositionMCDirty = true;
this._encodedCameraPositionMC = new EncodedCartesian3_default();
this._cameraPosition = new Cartesian3_default();
this._sunPositionWC = new Cartesian3_default();
this._sunPositionColumbusView = new Cartesian3_default();
this._sunDirectionWC = new Cartesian3_default();
this._sunDirectionEC = new Cartesian3_default();
this._moonDirectionEC = new Cartesian3_default();
this._lightDirectionWC = new Cartesian3_default();
this._lightDirectionEC = new Cartesian3_default();
this._lightColor = new Cartesian3_default();
this._lightColorHdr = new Cartesian3_default();
this._pass = void 0;
this._mode = void 0;
this._mapProjection = void 0;
this._ellipsoid = void 0;
this._cameraDirection = new Cartesian3_default();
this._cameraRight = new Cartesian3_default();
this._cameraUp = new Cartesian3_default();
this._frustum2DWidth = 0;
this._eyeHeight = 0;
this._eyeHeight2D = new Cartesian2_default();
this._pixelRatio = 1;
this._orthographicIn3D = false;
this._backgroundColor = new Color_default();
this._brdfLut = void 0;
this._environmentMap = void 0;
this._sphericalHarmonicCoefficients = void 0;
this._specularEnvironmentMaps = void 0;
this._specularEnvironmentMapsDimensions = new Cartesian2_default();
this._specularEnvironmentMapsMaximumLOD = void 0;
this._fogDensity = void 0;
this._invertClassificationColor = void 0;
this._splitPosition = 0;
this._pixelSizePerMeter = void 0;
this._geometricToleranceOverMeter = void 0;
this._minimumDisableDepthTestDistance = void 0;
}
Object.defineProperties(UniformState.prototype, {
frameState: {
get: function() {
return this._frameState;
}
},
viewport: {
get: function() {
return this._viewport;
},
set: function(viewport) {
if (!BoundingRectangle_default.equals(viewport, this._viewport)) {
BoundingRectangle_default.clone(viewport, this._viewport);
const v7 = this._viewport;
const vc = this._viewportCartesian4;
vc.x = v7.x;
vc.y = v7.y;
vc.z = v7.width;
vc.w = v7.height;
this._viewportDirty = true;
}
}
},
viewportCartesian4: {
get: function() {
return this._viewportCartesian4;
}
},
viewportOrthographic: {
get: function() {
cleanViewport(this);
return this._viewportOrthographicMatrix;
}
},
viewportTransformation: {
get: function() {
cleanViewport(this);
return this._viewportTransformation;
}
},
model: {
get: function() {
return this._model;
},
set: function(matrix) {
Matrix4_default.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;
}
},
inverseModel: {
get: function() {
if (this._inverseModelDirty) {
this._inverseModelDirty = false;
Matrix4_default.inverse(this._model, this._inverseModel);
}
return this._inverseModel;
}
},
inverseTransposeModel: {
get: function() {
const m = this._inverseTransposeModel;
if (this._inverseTransposeModelDirty) {
this._inverseTransposeModelDirty = false;
Matrix4_default.getMatrix3(this.inverseModel, m);
Matrix3_default.transpose(m, m);
}
return m;
}
},
view: {
get: function() {
return this._view;
}
},
view3D: {
get: function() {
updateView3D(this);
return this._view3D;
}
},
viewRotation: {
get: function() {
updateView3D(this);
return this._viewRotation;
}
},
viewRotation3D: {
get: function() {
updateView3D(this);
return this._viewRotation3D;
}
},
inverseView: {
get: function() {
return this._inverseView;
}
},
inverseView3D: {
get: function() {
updateInverseView3D(this);
return this._inverseView3D;
}
},
inverseViewRotation: {
get: function() {
return this._inverseViewRotation;
}
},
inverseViewRotation3D: {
get: function() {
updateInverseView3D(this);
return this._inverseViewRotation3D;
}
},
projection: {
get: function() {
return this._projection;
}
},
inverseProjection: {
get: function() {
cleanInverseProjection(this);
return this._inverseProjection;
}
},
infiniteProjection: {
get: function() {
return this._infiniteProjection;
}
},
modelView: {
get: function() {
cleanModelView(this);
return this._modelView;
}
},
modelView3D: {
get: function() {
cleanModelView3D(this);
return this._modelView3D;
}
},
modelViewRelativeToEye: {
get: function() {
cleanModelViewRelativeToEye(this);
return this._modelViewRelativeToEye;
}
},
inverseModelView: {
get: function() {
cleanInverseModelView(this);
return this._inverseModelView;
}
},
inverseModelView3D: {
get: function() {
cleanInverseModelView3D(this);
return this._inverseModelView3D;
}
},
viewProjection: {
get: function() {
cleanViewProjection(this);
return this._viewProjection;
}
},
inverseViewProjection: {
get: function() {
cleanInverseViewProjection(this);
return this._inverseViewProjection;
}
},
modelViewProjection: {
get: function() {
cleanModelViewProjection(this);
return this._modelViewProjection;
}
},
inverseModelViewProjection: {
get: function() {
cleanInverseModelViewProjection(this);
return this._inverseModelViewProjection;
}
},
modelViewProjectionRelativeToEye: {
get: function() {
cleanModelViewProjectionRelativeToEye(this);
return this._modelViewProjectionRelativeToEye;
}
},
modelViewInfiniteProjection: {
get: function() {
cleanModelViewInfiniteProjection(this);
return this._modelViewInfiniteProjection;
}
},
normal: {
get: function() {
cleanNormal(this);
return this._normal;
}
},
normal3D: {
get: function() {
cleanNormal3D(this);
return this._normal3D;
}
},
inverseNormal: {
get: function() {
cleanInverseNormal(this);
return this._inverseNormal;
}
},
inverseNormal3D: {
get: function() {
cleanInverseNormal3D(this);
return this._inverseNormal3D;
}
},
entireFrustum: {
get: function() {
return this._entireFrustum;
}
},
currentFrustum: {
get: function() {
return this._currentFrustum;
}
},
frustumPlanes: {
get: function() {
return this._frustumPlanes;
}
},
farDepthFromNearPlusOne: {
get: function() {
return this._farDepthFromNearPlusOne;
}
},
log2FarDepthFromNearPlusOne: {
get: function() {
return this._log2FarDepthFromNearPlusOne;
}
},
oneOverLog2FarDepthFromNearPlusOne: {
get: function() {
return this._oneOverLog2FarDepthFromNearPlusOne;
}
},
eyeHeight: {
get: function() {
return this._eyeHeight;
}
},
eyeHeight2D: {
get: function() {
return this._eyeHeight2D;
}
},
sunPositionWC: {
get: function() {
return this._sunPositionWC;
}
},
sunPositionColumbusView: {
get: function() {
return this._sunPositionColumbusView;
}
},
sunDirectionWC: {
get: function() {
return this._sunDirectionWC;
}
},
sunDirectionEC: {
get: function() {
return this._sunDirectionEC;
}
},
moonDirectionEC: {
get: function() {
return this._moonDirectionEC;
}
},
lightDirectionWC: {
get: function() {
return this._lightDirectionWC;
}
},
lightDirectionEC: {
get: function() {
return this._lightDirectionEC;
}
},
lightColor: {
get: function() {
return this._lightColor;
}
},
lightColorHdr: {
get: function() {
return this._lightColorHdr;
}
},
encodedCameraPositionMCHigh: {
get: function() {
cleanEncodedCameraPositionMC(this);
return this._encodedCameraPositionMC.high;
}
},
encodedCameraPositionMCLow: {
get: function() {
cleanEncodedCameraPositionMC(this);
return this._encodedCameraPositionMC.low;
}
},
temeToPseudoFixedMatrix: {
get: function() {
return this._temeToPseudoFixed;
}
},
pixelRatio: {
get: function() {
return this._pixelRatio;
}
},
fogDensity: {
get: function() {
return this._fogDensity;
}
},
geometricToleranceOverMeter: {
get: function() {
return this._geometricToleranceOverMeter;
}
},
pass: {
get: function() {
return this._pass;
}
},
backgroundColor: {
get: function() {
return this._backgroundColor;
}
},
brdfLut: {
get: function() {
return this._brdfLut;
}
},
environmentMap: {
get: function() {
return this._environmentMap;
}
},
sphericalHarmonicCoefficients: {
get: function() {
return this._sphericalHarmonicCoefficients;
}
},
specularEnvironmentMaps: {
get: function() {
return this._specularEnvironmentMaps;
}
},
specularEnvironmentMapsDimensions: {
get: function() {
return this._specularEnvironmentMapsDimensions;
}
},
specularEnvironmentMapsMaximumLOD: {
get: function() {
return this._specularEnvironmentMapsMaximumLOD;
}
},
splitPosition: {
get: function() {
return this._splitPosition;
}
},
minimumDisableDepthTestDistance: {
get: function() {
return this._minimumDisableDepthTestDistance;
}
},
invertClassificationColor: {
get: function() {
return this._invertClassificationColor;
}
},
orthographicIn3D: {
get: function() {
return this._orthographicIn3D;
}
},
ellipsoid: {
get: function() {
return defaultValue_default(this._ellipsoid, Ellipsoid_default.WGS84);
}
}
});
function setView(uniformState, matrix) {
Matrix4_default.clone(matrix, uniformState._view);
Matrix4_default.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_default.clone(matrix, uniformState._inverseView);
Matrix4_default.getMatrix3(matrix, uniformState._inverseViewRotation);
}
function setProjection(uniformState, matrix) {
Matrix4_default.clone(matrix, uniformState._projection);
uniformState._inverseProjectionDirty = true;
uniformState._viewProjectionDirty = true;
uniformState._inverseViewProjectionDirty = true;
uniformState._modelViewProjectionDirty = true;
uniformState._modelViewProjectionRelativeToEyeDirty = true;
}
function setInfiniteProjection(uniformState, matrix) {
Matrix4_default.clone(matrix, uniformState._infiniteProjection);
uniformState._modelViewInfiniteProjectionDirty = true;
}
function setCamera(uniformState, camera) {
Cartesian3_default.clone(camera.positionWC, uniformState._cameraPosition);
Cartesian3_default.clone(camera.directionWC, uniformState._cameraDirection);
Cartesian3_default.clone(camera.rightWC, uniformState._cameraRight);
Cartesian3_default.clone(camera.upWC, uniformState._cameraUp);
const positionCartographic = camera.positionCartographic;
if (!defined_default(positionCartographic)) {
uniformState._eyeHeight = -uniformState._ellipsoid.maximumRadius;
} else {
uniformState._eyeHeight = positionCartographic.height;
}
uniformState._encodedCameraPositionMCDirty = true;
}
var transformMatrix = new Matrix3_default();
var sunCartographicScratch = new Cartographic_default();
function setSunAndMoonDirections(uniformState, frameState) {
if (!defined_default(
Transforms_default.computeIcrfToFixedMatrix(frameState.time, transformMatrix)
)) {
transformMatrix = Transforms_default.computeTemeToPseudoFixedMatrix(
frameState.time,
transformMatrix
);
}
let position = Simon1994PlanetaryPositions_default.computeSunPositionInEarthInertialFrame(
frameState.time,
uniformState._sunPositionWC
);
Matrix3_default.multiplyByVector(transformMatrix, position, position);
Cartesian3_default.normalize(position, uniformState._sunDirectionWC);
position = Matrix3_default.multiplyByVector(
uniformState.viewRotation3D,
position,
uniformState._sunDirectionEC
);
Cartesian3_default.normalize(position, position);
position = Simon1994PlanetaryPositions_default.computeMoonPositionInEarthInertialFrame(
frameState.time,
uniformState._moonDirectionEC
);
Matrix3_default.multiplyByVector(transformMatrix, position, position);
Matrix3_default.multiplyByVector(uniformState.viewRotation3D, position, position);
Cartesian3_default.normalize(position, position);
const projection = frameState.mapProjection;
const ellipsoid = projection.ellipsoid;
const sunCartographic = ellipsoid.cartesianToCartographic(
uniformState._sunPositionWC,
sunCartographicScratch
);
projection.project(sunCartographic, uniformState._sunPositionColumbusView);
}
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_default.SCENE2D && camera.frustum instanceof OrthographicFrustum_default;
};
UniformState.prototype.updateFrustum = function(frustum) {
setProjection(this, frustum.projectionMatrix);
if (defined_default(frustum.infiniteProjectionMatrix)) {
setInfiniteProjection(this, frustum.infiniteProjectionMatrix);
}
this._currentFrustum.x = frustum.near;
this._currentFrustum.y = frustum.far;
this._farDepthFromNearPlusOne = frustum.far - frustum.near + 1;
this._log2FarDepthFromNearPlusOne = Math_default.log2(
this._farDepthFromNearPlusOne
);
this._oneOverLog2FarDepthFromNearPlusOne = 1 / this._log2FarDepthFromNearPlusOne;
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
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;
};
var EMPTY_ARRAY = [];
var defaultLight = new SunLight_default();
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_default.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;
this._eyeHeight2D.x = 0;
this._eyeHeight2D.y = 0;
}
setSunAndMoonDirections(this, frameState);
const light = defaultValue_default(frameState.light, defaultLight);
if (light instanceof SunLight_default) {
this._lightDirectionWC = Cartesian3_default.clone(
this._sunDirectionWC,
this._lightDirectionWC
);
this._lightDirectionEC = Cartesian3_default.clone(
this._sunDirectionEC,
this._lightDirectionEC
);
} else {
this._lightDirectionWC = Cartesian3_default.normalize(
Cartesian3_default.negate(light.direction, this._lightDirectionWC),
this._lightDirectionWC
);
this._lightDirectionEC = Matrix3_default.multiplyByVector(
this.viewRotation3D,
this._lightDirectionWC,
this._lightDirectionEC
);
}
const lightColor = light.color;
let lightColorHdr = Cartesian3_default.fromElements(
lightColor.red,
lightColor.green,
lightColor.blue,
this._lightColorHdr
);
lightColorHdr = Cartesian3_default.multiplyByScalar(
lightColorHdr,
light.intensity,
lightColorHdr
);
const maximumComponent = Cartesian3_default.maximumComponent(lightColorHdr);
if (maximumComponent > 1) {
Cartesian3_default.divideByScalar(
lightColorHdr,
maximumComponent,
this._lightColor
);
} else {
Cartesian3_default.clone(lightColorHdr, this._lightColor);
}
const brdfLutGenerator = frameState.brdfLutGenerator;
const brdfLut = defined_default(brdfLutGenerator) ? brdfLutGenerator.colorTexture : void 0;
this._brdfLut = brdfLut;
this._environmentMap = defaultValue_default(
frameState.environmentMap,
frameState.context.defaultCubeMap
);
this._sphericalHarmonicCoefficients = defaultValue_default(
frameState.sphericalHarmonicCoefficients,
EMPTY_ARRAY
);
this._specularEnvironmentMaps = frameState.specularEnvironmentMaps;
this._specularEnvironmentMapsMaximumLOD = frameState.specularEnvironmentMapsMaximumLOD;
if (defined_default(this._specularEnvironmentMaps)) {
Cartesian2_default.clone(
this._specularEnvironmentMaps.dimensions,
this._specularEnvironmentMapsDimensions
);
}
this._fogDensity = frameState.fog.density;
this._invertClassificationColor = frameState.invertClassificationColor;
this._frameState = frameState;
this._temeToPseudoFixed = Transforms_default.computeTemeToPseudoFixedMatrix(
frameState.time,
this._temeToPseudoFixed
);
this._splitPosition = frameState.splitPosition * frameState.context.drawingBufferWidth;
const fov = camera.frustum.fov;
const viewport = this._viewport;
let pixelSizePerMeter;
if (defined_default(fov)) {
if (viewport.height > viewport.width) {
pixelSizePerMeter = Math.tan(0.5 * fov) * 2 / viewport.height;
} else {
pixelSizePerMeter = Math.tan(0.5 * fov) * 2 / viewport.width;
}
} else {
pixelSizePerMeter = 1 / Math.max(viewport.width, viewport.height);
}
this._geometricToleranceOverMeter = pixelSizePerMeter * frameState.maximumScreenSpaceError;
Color_default.clone(frameState.backgroundColor, this._backgroundColor);
this._minimumDisableDepthTestDistance = frameState.minimumDisableDepthTestDistance;
this._minimumDisableDepthTestDistance *= this._minimumDisableDepthTestDistance;
if (this._minimumDisableDepthTestDistance === Number.POSITIVE_INFINITY) {
this._minimumDisableDepthTestDistance = -1;
}
};
function cleanViewport(uniformState) {
if (uniformState._viewportDirty) {
const v7 = uniformState._viewport;
Matrix4_default.computeOrthographicOffCenter(
v7.x,
v7.x + v7.width,
v7.y,
v7.y + v7.height,
0,
1,
uniformState._viewportOrthographicMatrix
);
Matrix4_default.computeViewportTransformation(
v7,
0,
1,
uniformState._viewportTransformation
);
uniformState._viewportDirty = false;
}
}
function cleanInverseProjection(uniformState) {
if (uniformState._inverseProjectionDirty) {
uniformState._inverseProjectionDirty = false;
if (uniformState._mode !== SceneMode_default.SCENE2D && uniformState._mode !== SceneMode_default.MORPHING && !uniformState._orthographicIn3D) {
Matrix4_default.inverse(
uniformState._projection,
uniformState._inverseProjection
);
} else {
Matrix4_default.clone(Matrix4_default.ZERO, uniformState._inverseProjection);
}
}
}
function cleanModelView(uniformState) {
if (uniformState._modelViewDirty) {
uniformState._modelViewDirty = false;
Matrix4_default.multiplyTransformation(
uniformState._view,
uniformState._model,
uniformState._modelView
);
}
}
function cleanModelView3D(uniformState) {
if (uniformState._modelView3DDirty) {
uniformState._modelView3DDirty = false;
Matrix4_default.multiplyTransformation(
uniformState.view3D,
uniformState._model,
uniformState._modelView3D
);
}
}
function cleanInverseModelView(uniformState) {
if (uniformState._inverseModelViewDirty) {
uniformState._inverseModelViewDirty = false;
Matrix4_default.inverse(uniformState.modelView, uniformState._inverseModelView);
}
}
function cleanInverseModelView3D(uniformState) {
if (uniformState._inverseModelView3DDirty) {
uniformState._inverseModelView3DDirty = false;
Matrix4_default.inverse(uniformState.modelView3D, uniformState._inverseModelView3D);
}
}
function cleanViewProjection(uniformState) {
if (uniformState._viewProjectionDirty) {
uniformState._viewProjectionDirty = false;
Matrix4_default.multiply(
uniformState._projection,
uniformState._view,
uniformState._viewProjection
);
}
}
function cleanInverseViewProjection(uniformState) {
if (uniformState._inverseViewProjectionDirty) {
uniformState._inverseViewProjectionDirty = false;
Matrix4_default.inverse(
uniformState.viewProjection,
uniformState._inverseViewProjection
);
}
}
function cleanModelViewProjection(uniformState) {
if (uniformState._modelViewProjectionDirty) {
uniformState._modelViewProjectionDirty = false;
Matrix4_default.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;
mvRte[13] = 0;
mvRte[14] = 0;
mvRte[15] = mv[15];
}
}
function cleanInverseModelViewProjection(uniformState) {
if (uniformState._inverseModelViewProjectionDirty) {
uniformState._inverseModelViewProjectionDirty = false;
Matrix4_default.inverse(
uniformState.modelViewProjection,
uniformState._inverseModelViewProjection
);
}
}
function cleanModelViewProjectionRelativeToEye(uniformState) {
if (uniformState._modelViewProjectionRelativeToEyeDirty) {
uniformState._modelViewProjectionRelativeToEyeDirty = false;
Matrix4_default.multiply(
uniformState._projection,
uniformState.modelViewRelativeToEye,
uniformState._modelViewProjectionRelativeToEye
);
}
}
function cleanModelViewInfiniteProjection(uniformState) {
if (uniformState._modelViewInfiniteProjectionDirty) {
uniformState._modelViewInfiniteProjectionDirty = false;
Matrix4_default.multiply(
uniformState._infiniteProjection,
uniformState.modelView,
uniformState._modelViewInfiniteProjection
);
}
}
function cleanNormal(uniformState) {
if (uniformState._normalDirty) {
uniformState._normalDirty = false;
const m = uniformState._normal;
Matrix4_default.getMatrix3(uniformState.inverseModelView, m);
Matrix3_default.getRotation(m, m);
Matrix3_default.transpose(m, m);
}
}
function cleanNormal3D(uniformState) {
if (uniformState._normal3DDirty) {
uniformState._normal3DDirty = false;
const m = uniformState._normal3D;
Matrix4_default.getMatrix3(uniformState.inverseModelView3D, m);
Matrix3_default.getRotation(m, m);
Matrix3_default.transpose(m, m);
}
}
function cleanInverseNormal(uniformState) {
if (uniformState._inverseNormalDirty) {
uniformState._inverseNormalDirty = false;
Matrix4_default.getMatrix3(
uniformState.inverseModelView,
uniformState._inverseNormal
);
Matrix3_default.getRotation(
uniformState._inverseNormal,
uniformState._inverseNormal
);
}
}
function cleanInverseNormal3D(uniformState) {
if (uniformState._inverseNormal3DDirty) {
uniformState._inverseNormal3DDirty = false;
Matrix4_default.getMatrix3(
uniformState.inverseModelView3D,
uniformState._inverseNormal3D
);
Matrix3_default.getRotation(
uniformState._inverseNormal3D,
uniformState._inverseNormal3D
);
}
}
var cameraPositionMC = new Cartesian3_default();
function cleanEncodedCameraPositionMC(uniformState) {
if (uniformState._encodedCameraPositionMCDirty) {
uniformState._encodedCameraPositionMCDirty = false;
Matrix4_default.multiplyByPoint(
uniformState.inverseModel,
uniformState._cameraPosition,
cameraPositionMC
);
EncodedCartesian3_default.fromCartesian(
cameraPositionMC,
uniformState._encodedCameraPositionMC
);
}
}
var view2Dto3DPScratch = new Cartesian3_default();
var view2Dto3DRScratch = new Cartesian3_default();
var view2Dto3DUScratch = new Cartesian3_default();
var view2Dto3DDScratch = new Cartesian3_default();
var view2Dto3DCartographicScratch = new Cartographic_default();
var view2Dto3DCartesian3Scratch = new Cartesian3_default();
var view2Dto3DMatrix4Scratch = new Matrix4_default();
function view2Dto3D(position2D, direction2D, right2D, up2D, frustum2DWidth, mode2, projection, result) {
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 u3 = view2Dto3DUScratch;
u3.x = up2D.y;
u3.y = up2D.z;
u3.z = up2D.x;
const d = view2Dto3DDScratch;
d.x = direction2D.y;
d.y = direction2D.z;
d.z = direction2D.x;
if (mode2 === SceneMode_default.SCENE2D) {
p.z = frustum2DWidth * 0.5;
}
const cartographic2 = projection.unproject(p, view2Dto3DCartographicScratch);
cartographic2.longitude = Math_default.clamp(
cartographic2.longitude,
-Math.PI,
Math.PI
);
cartographic2.latitude = Math_default.clamp(
cartographic2.latitude,
-Math_default.PI_OVER_TWO,
Math_default.PI_OVER_TWO
);
const ellipsoid = projection.ellipsoid;
const position3D = ellipsoid.cartographicToCartesian(
cartographic2,
view2Dto3DCartesian3Scratch
);
const enuToFixed = Transforms_default.eastNorthUpToFixedFrame(
position3D,
ellipsoid,
view2Dto3DMatrix4Scratch
);
Matrix4_default.multiplyByPointAsVector(enuToFixed, r, r);
Matrix4_default.multiplyByPointAsVector(enuToFixed, u3, u3);
Matrix4_default.multiplyByPointAsVector(enuToFixed, d, d);
if (!defined_default(result)) {
result = new Matrix4_default();
}
result[0] = r.x;
result[1] = u3.x;
result[2] = -d.x;
result[3] = 0;
result[4] = r.y;
result[5] = u3.y;
result[6] = -d.y;
result[7] = 0;
result[8] = r.z;
result[9] = u3.z;
result[10] = -d.z;
result[11] = 0;
result[12] = -Cartesian3_default.dot(r, position3D);
result[13] = -Cartesian3_default.dot(u3, position3D);
result[14] = Cartesian3_default.dot(d, position3D);
result[15] = 1;
return result;
}
function updateView3D(that) {
if (that._view3DDirty) {
if (that._mode === SceneMode_default.SCENE3D) {
Matrix4_default.clone(that._view, that._view3D);
} else {
view2Dto3D(
that._cameraPosition,
that._cameraDirection,
that._cameraRight,
that._cameraUp,
that._frustum2DWidth,
that._mode,
that._mapProjection,
that._view3D
);
}
Matrix4_default.getMatrix3(that._view3D, that._viewRotation3D);
that._view3DDirty = false;
}
}
function updateInverseView3D(that) {
if (that._inverseView3DDirty) {
Matrix4_default.inverseTransformation(that.view3D, that._inverseView3D);
Matrix4_default.getMatrix3(that._inverseView3D, that._inverseViewRotation3D);
that._inverseView3DDirty = false;
}
}
var UniformState_default = UniformState;
// node_modules/@cesium/engine/Source/Renderer/VertexArray.js
function addAttribute(attributes, attribute, index, context) {
const hasVertexBuffer = defined_default(attribute.vertexBuffer);
const hasValue = defined_default(attribute.value);
const componentsPerAttribute = attribute.value ? attribute.value.length : attribute.componentsPerAttribute;
if (!hasVertexBuffer && !hasValue) {
throw new DeveloperError_default("attribute must have a vertexBuffer or a value.");
}
if (hasVertexBuffer && hasValue) {
throw new DeveloperError_default(
"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_default(
"attribute.value.length must be in the range [1, 4]."
);
}
throw new DeveloperError_default(
"attribute.componentsPerAttribute must be in the range [1, 4]."
);
}
if (defined_default(attribute.componentDatatype) && !ComponentDatatype_default.validate(attribute.componentDatatype)) {
throw new DeveloperError_default(
"attribute must have a valid componentDatatype or not specify it."
);
}
if (defined_default(attribute.strideInBytes) && attribute.strideInBytes > 255) {
throw new DeveloperError_default(
"attribute must have a strideInBytes less than or equal to 255 or not specify it."
);
}
if (defined_default(attribute.instanceDivisor) && attribute.instanceDivisor > 0 && !context.instancedArrays) {
throw new DeveloperError_default("instanced arrays is not supported");
}
if (defined_default(attribute.instanceDivisor) && attribute.instanceDivisor < 0) {
throw new DeveloperError_default(
"attribute must have an instanceDivisor greater than or equal to zero"
);
}
if (defined_default(attribute.instanceDivisor) && hasValue) {
throw new DeveloperError_default(
"attribute cannot have have an instanceDivisor if it is not backed by a buffer"
);
}
if (defined_default(attribute.instanceDivisor) && attribute.instanceDivisor > 0 && attribute.index === 0) {
throw new DeveloperError_default(
"attribute zero cannot have an instanceDivisor greater than 0"
);
}
const attr = {
index: defaultValue_default(attribute.index, index),
enabled: defaultValue_default(attribute.enabled, true),
vertexBuffer: attribute.vertexBuffer,
value: hasValue ? attribute.value.slice(0) : void 0,
componentsPerAttribute,
componentDatatype: defaultValue_default(
attribute.componentDatatype,
ComponentDatatype_default.FLOAT
),
normalize: defaultValue_default(attribute.normalize, false),
offsetInBytes: defaultValue_default(attribute.offsetInBytes, 0),
strideInBytes: defaultValue_default(attribute.strideInBytes, 0),
instanceDivisor: defaultValue_default(attribute.instanceDivisor, 0)
};
if (hasVertexBuffer) {
attr.vertexAttrib = function(gl) {
const index2 = this.index;
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer._getBuffer());
gl.vertexAttribPointer(
index2,
this.componentsPerAttribute,
this.componentDatatype,
this.normalize,
this.strideInBytes,
this.offsetInBytes
);
gl.enableVertexAttribArray(index2);
if (this.instanceDivisor > 0) {
context.glVertexAttribDivisor(index2, this.instanceDivisor);
context._vertexAttribDivisors[index2] = this.instanceDivisor;
context._previousDrawInstanced = true;
}
};
attr.disableVertexAttribArray = function(gl) {
gl.disableVertexAttribArray(this.index);
if (this.instanceDivisor > 0) {
context.glVertexAttribDivisor(index, 0);
}
};
} else {
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_default(indexBuffer)) {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer._getBuffer());
}
}
function VertexArray(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
Check_default.defined("options.attributes", options.attributes);
const context = options.context;
const gl = context._gl;
const attributes = options.attributes;
const indexBuffer = options.indexBuffer;
let i;
const vaAttributes = [];
let numberOfVertices = 1;
let hasInstancedAttributes = false;
let hasConstantAttributes = false;
let length3 = attributes.length;
for (i = 0; i < length3; ++i) {
addAttribute(vaAttributes, attributes[i], i, context);
}
length3 = vaAttributes.length;
for (i = 0; i < length3; ++i) {
const attribute = vaAttributes[i];
if (defined_default(attribute.vertexBuffer) && attribute.instanceDivisor === 0) {
const bytes = attribute.strideInBytes || attribute.componentsPerAttribute * ComponentDatatype_default.getSizeInBytes(attribute.componentDatatype);
numberOfVertices = attribute.vertexBuffer.sizeInBytes / bytes;
break;
}
}
for (i = 0; i < length3; ++i) {
if (vaAttributes[i].instanceDivisor > 0) {
hasInstancedAttributes = true;
}
if (defined_default(vaAttributes[i].value)) {
hasConstantAttributes = true;
}
}
const uniqueIndices = {};
for (i = 0; i < length3; ++i) {
const index = vaAttributes[i].index;
if (uniqueIndices[index]) {
throw new DeveloperError_default(
`Index ${index} is used by more than one attribute.`
);
}
uniqueIndices[index] = true;
}
let vao;
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_default.getSizeInBytes(attribute.componentDatatype) * attribute.componentsPerAttribute;
}
function interleaveAttributes(attributes) {
let j;
let name;
let attribute;
const names = [];
for (name in attributes) {
if (attributes.hasOwnProperty(name) && defined_default(attributes[name]) && defined_default(attributes[name].values)) {
names.push(name);
if (attributes[name].componentDatatype === ComponentDatatype_default.DOUBLE) {
attributes[name].componentDatatype = ComponentDatatype_default.FLOAT;
attributes[name].values = ComponentDatatype_default.createTypedArray(
ComponentDatatype_default.FLOAT,
attributes[name].values
);
}
}
}
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_default(
`${"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()}).`
);
}
}
}
names.sort(function(left, right) {
return ComponentDatatype_default.getSizeInBytes(attributes[right].componentDatatype) - ComponentDatatype_default.getSizeInBytes(attributes[left].componentDatatype);
});
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) {
const maxComponentSizeInBytes = ComponentDatatype_default.getSizeInBytes(
attributes[names[0]].componentDatatype
);
const remainder = vertexSizeInBytes % maxComponentSizeInBytes;
if (remainder !== 0) {
vertexSizeInBytes += maxComponentSizeInBytes - remainder;
}
const vertexBufferSizeInBytes = numberOfVertices * vertexSizeInBytes;
const buffer = new ArrayBuffer(vertexBufferSizeInBytes);
const views = {};
for (j = 0; j < namesLength; ++j) {
name = names[j];
const sizeInBytes = ComponentDatatype_default.getSizeInBytes(
attributes[name].componentDatatype
);
views[name] = {
pointer: ComponentDatatype_default.createTypedArray(
attributes[name].componentDatatype,
buffer
),
index: offsetsInBytes[name] / sizeInBytes,
strideInComponentType: vertexSizeInBytes / sizeInBytes
};
}
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,
offsetsInBytes,
vertexSizeInBytes
};
}
return void 0;
}
VertexArray.fromGeometry = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
const context = options.context;
const geometry = defaultValue_default(options.geometry, defaultValue_default.EMPTY_OBJECT);
const bufferUsage = defaultValue_default(
options.bufferUsage,
BufferUsage_default.DYNAMIC_DRAW
);
const attributeLocations8 = defaultValue_default(
options.attributeLocations,
defaultValue_default.EMPTY_OBJECT
);
const interleave = defaultValue_default(options.interleave, false);
const createdVAAttributes = options.vertexArrayAttributes;
let name;
let attribute;
let vertexBuffer;
const vaAttributes = defined_default(createdVAAttributes) ? createdVAAttributes : [];
const attributes = geometry.attributes;
if (interleave) {
const interleavedAttributes = interleaveAttributes(attributes);
if (defined_default(interleavedAttributes)) {
vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: interleavedAttributes.buffer,
usage: bufferUsage
});
const offsetsInBytes = interleavedAttributes.offsetsInBytes;
const strideInBytes = interleavedAttributes.vertexSizeInBytes;
for (name in attributes) {
if (attributes.hasOwnProperty(name) && defined_default(attributes[name])) {
attribute = attributes[name];
if (defined_default(attribute.values)) {
vaAttributes.push({
index: attributeLocations8[name],
vertexBuffer,
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
offsetInBytes: offsetsInBytes[name],
strideInBytes
});
} else {
vaAttributes.push({
index: attributeLocations8[name],
value: attribute.value,
componentDatatype: attribute.componentDatatype,
normalize: attribute.normalize
});
}
}
}
}
} else {
for (name in attributes) {
if (attributes.hasOwnProperty(name) && defined_default(attributes[name])) {
attribute = attributes[name];
let componentDatatype = attribute.componentDatatype;
if (componentDatatype === ComponentDatatype_default.DOUBLE) {
componentDatatype = ComponentDatatype_default.FLOAT;
}
vertexBuffer = void 0;
if (defined_default(attribute.values)) {
vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: ComponentDatatype_default.createTypedArray(
componentDatatype,
attribute.values
),
usage: bufferUsage
});
}
vaAttributes.push({
index: attributeLocations8[name],
vertexBuffer,
value: attribute.value,
componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize
});
}
}
}
let indexBuffer;
const indices2 = geometry.indices;
if (defined_default(indices2)) {
if (Geometry_default.computeNumberOfVertices(geometry) >= Math_default.SIXTY_FOUR_KILOBYTES && context.elementIndexUint) {
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: new Uint32Array(indices2),
usage: bufferUsage,
indexDatatype: IndexDatatype_default.UNSIGNED_INT
});
} else {
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: new Uint16Array(indices2),
usage: bufferUsage,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
}
}
return new VertexArray({
context,
attributes: vaAttributes,
indexBuffer
});
};
Object.defineProperties(VertexArray.prototype, {
numberOfAttributes: {
get: function() {
return this._attributes.length;
}
},
numberOfVertices: {
get: function() {
return this._numberOfVertices;
}
},
indexBuffer: {
get: function() {
return this._indexBuffer;
}
}
});
VertexArray.prototype.getAttribute = function(index) {
Check_default.defined("index", index);
return this._attributes[index];
};
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_default.maximumVertexAttributes;
let i;
if (hasInstancedAttributes) {
const length3 = attributes.length;
for (i = 0; i < length3; ++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;
}
}
}
}
function setConstantAttributes(vertexArray, gl) {
const attributes = vertexArray._attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; ++i) {
const attribute = attributes[i];
if (attribute.enabled && defined_default(attribute.value)) {
attribute.vertexAttrib(gl);
}
}
}
VertexArray.prototype._bind = function() {
if (defined_default(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_default(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_default(vertexBuffer) && !vertexBuffer.isDestroyed() && vertexBuffer.vertexArrayDestroyable) {
vertexBuffer.destroy();
}
}
const indexBuffer = this._indexBuffer;
if (defined_default(indexBuffer) && !indexBuffer.isDestroyed() && indexBuffer.vertexArrayDestroyable) {
indexBuffer.destroy();
}
if (defined_default(this._vao)) {
this._context.glDeleteVertexArray(this._vao);
}
return destroyObject_default(this);
};
var VertexArray_default = VertexArray;
// node_modules/@cesium/engine/Source/Renderer/Context.js
function Context(canvas, options) {
Check_default.defined("canvas", canvas);
const {
getWebGLStub,
requestWebgl1,
webgl: webglOptions = {},
allowTextureFilterAnisotropic = true
} = defaultValue_default(options, {});
webglOptions.alpha = defaultValue_default(webglOptions.alpha, false);
webglOptions.stencil = defaultValue_default(webglOptions.stencil, true);
webglOptions.powerPreference = defaultValue_default(
webglOptions.powerPreference,
"high-performance"
);
const glContext = defined_default(getWebGLStub) ? getWebGLStub(canvas, webglOptions) : getWebGLContext(canvas, webglOptions, requestWebgl1);
const webgl2Supported = typeof WebGL2RenderingContext !== "undefined";
const webgl2 = webgl2Supported && glContext instanceof WebGL2RenderingContext;
this._canvas = canvas;
this._originalGLContext = glContext;
this._gl = glContext;
this._webgl2 = webgl2;
this._id = createGuid_default();
this.validateFramebuffer = false;
this.validateShaderProgram = false;
this.logShaderCompilation = false;
this._throwOnWebGLError = false;
this._shaderCache = new ShaderCache_default(this);
this._textureCache = new TextureCache_default();
const gl = glContext;
this._stencilBits = gl.getParameter(gl.STENCIL_BITS);
ContextLimits_default._maximumCombinedTextureImageUnits = gl.getParameter(
gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS
);
ContextLimits_default._maximumCubeMapSize = gl.getParameter(
gl.MAX_CUBE_MAP_TEXTURE_SIZE
);
ContextLimits_default._maximumFragmentUniformVectors = gl.getParameter(
gl.MAX_FRAGMENT_UNIFORM_VECTORS
);
ContextLimits_default._maximumTextureImageUnits = gl.getParameter(
gl.MAX_TEXTURE_IMAGE_UNITS
);
ContextLimits_default._maximumRenderbufferSize = gl.getParameter(
gl.MAX_RENDERBUFFER_SIZE
);
ContextLimits_default._maximumTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
ContextLimits_default._maximumVaryingVectors = gl.getParameter(
gl.MAX_VARYING_VECTORS
);
ContextLimits_default._maximumVertexAttributes = gl.getParameter(
gl.MAX_VERTEX_ATTRIBS
);
ContextLimits_default._maximumVertexTextureImageUnits = gl.getParameter(
gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS
);
ContextLimits_default._maximumVertexUniformVectors = gl.getParameter(
gl.MAX_VERTEX_UNIFORM_VECTORS
);
ContextLimits_default._maximumSamples = this._webgl2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
const aliasedLineWidthRange = gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE);
ContextLimits_default._minimumAliasedLineWidth = aliasedLineWidthRange[0];
ContextLimits_default._maximumAliasedLineWidth = aliasedLineWidthRange[1];
const aliasedPointSizeRange = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE);
ContextLimits_default._minimumAliasedPointSize = aliasedPointSizeRange[0];
ContextLimits_default._maximumAliasedPointSize = aliasedPointSizeRange[1];
const maximumViewportDimensions = gl.getParameter(gl.MAX_VIEWPORT_DIMS);
ContextLimits_default._maximumViewportWidth = maximumViewportDimensions[0];
ContextLimits_default._maximumViewportHeight = maximumViewportDimensions[1];
const highpFloat = gl.getShaderPrecisionFormat(
gl.FRAGMENT_SHADER,
gl.HIGH_FLOAT
);
ContextLimits_default._highpFloatSupported = highpFloat.precision !== 0;
const highpInt = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT);
ContextLimits_default._highpIntSupported = highpInt.rangeMax !== 0;
this._antialias = gl.getContextAttributes().antialias;
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"]);
loadKTX2_default.setKTX2SupportedFormats(
this._s3tc,
this._pvrtc,
this._astc,
this._etc,
this._etc1,
this._bc7
);
const textureFilterAnisotropic = allowTextureFilterAnisotropic ? getExtension(gl, [
"EXT_texture_filter_anisotropic",
"WEBKIT_EXT_texture_filter_anisotropic"
]) : void 0;
this._textureFilterAnisotropic = textureFilterAnisotropic;
ContextLimits_default._maximumTextureFilterAnisotropy = defined_default(
textureFilterAnisotropic
) ? gl.getParameter(textureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 1;
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(mode2, count, type, offset2, instanceCount) {
gl.drawElementsInstanced(mode2, count, type, offset2, instanceCount);
};
glDrawArraysInstanced = function(mode2, first, count, instanceCount) {
gl.drawArraysInstanced(mode2, 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_default(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_default(instancedArrays)) {
glDrawElementsInstanced = function(mode2, count, type, offset2, instanceCount) {
instancedArrays.drawElementsInstancedANGLE(
mode2,
count,
type,
offset2,
instanceCount
);
};
glDrawArraysInstanced = function(mode2, first, count, instanceCount) {
instancedArrays.drawArraysInstancedANGLE(
mode2,
first,
count,
instanceCount
);
};
glVertexAttribDivisor = function(index, divisor) {
instancedArrays.vertexAttribDivisorANGLE(index, divisor);
};
}
drawBuffers = getExtension(gl, ["WEBGL_draw_buffers"]);
if (defined_default(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_default._maximumDrawBuffers = this.drawBuffers ? gl.getParameter(WebGLConstants_default.MAX_DRAW_BUFFERS) : 1;
ContextLimits_default._maximumColorAttachments = this.drawBuffers ? gl.getParameter(WebGLConstants_default.MAX_COLOR_ATTACHMENTS) : 1;
this._clearColor = new Color_default(0, 0, 0, 0);
this._clearDepth = 1;
this._clearStencil = 0;
const us = new UniformState_default();
const ps = new PassState_default(this);
const rs = RenderState_default.fromCache();
this._defaultPassState = ps;
this._defaultRenderState = rs;
this._defaultTexture = void 0;
this._defaultEmissiveTexture = void 0;
this._defaultNormalTexture = void 0;
this._defaultCubeMap = void 0;
this._us = us;
this._currentRenderState = rs;
this._currentPassState = ps;
this._currentFramebuffer = void 0;
this._maxFrameTextureUnitIndex = 0;
this._vertexAttribDivisors = [];
this._previousDrawInstanced = false;
for (let i = 0; i < ContextLimits_default._maximumVertexAttributes; i++) {
this._vertexAttribDivisors.push(0);
}
this._pickObjects = {};
this._nextPickColor = new Uint32Array(1);
this.options = {
getWebGLStub,
requestWebgl1,
webgl: webglOptions,
allowTextureFilterAnisotropic
};
this.cache = {};
RenderState_default.apply(gl, rs, ps);
}
function getWebGLContext(canvas, webglOptions, requestWebgl1) {
if (typeof WebGLRenderingContext === "undefined") {
throw new RuntimeError_default(
"The browser does not support WebGL. Visit http://get.webgl.org."
);
}
const webgl2Supported = typeof WebGL2RenderingContext !== "undefined";
if (!requestWebgl1 && !webgl2Supported) {
requestWebgl1 = true;
}
const contextType = requestWebgl1 ? "webgl" : "webgl2";
const glContext = canvas.getContext(contextType, webglOptions);
if (!defined_default(glContext)) {
throw new RuntimeError_default(
"The browser supports WebGL, but initialization failed."
);
}
return glContext;
}
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_default(
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_default(logFunction)) {
return gl;
}
function wrapFunction2(property) {
return function() {
const result = property.apply(gl, arguments);
logFunction(gl, property, arguments);
return result;
};
}
const glWrapper = {};
for (const propertyName in gl) {
const property = gl[propertyName];
if (property instanceof Function) {
glWrapper[propertyName] = wrapFunction2(property);
} else {
Object.defineProperty(
glWrapper,
propertyName,
makeGetterSetter(gl, propertyName, logFunction)
);
}
}
return glWrapper;
}
function getExtension(gl, names) {
const length3 = names.length;
for (let i = 0; i < length3; ++i) {
const extension = gl.getExtension(names[i]);
if (extension) {
return extension;
}
}
return void 0;
}
var 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;
}
},
stencilBits: {
get: function() {
return this._stencilBits;
}
},
stencilBuffer: {
get: function() {
return this._stencilBits >= 8;
}
},
antialias: {
get: function() {
return this._antialias;
}
},
msaa: {
get: function() {
return this._webgl2;
}
},
standardDerivatives: {
get: function() {
return this._standardDerivatives || this._webgl2;
}
},
floatBlend: {
get: function() {
return this._floatBlend;
}
},
blendMinmax: {
get: function() {
return this._blendMinmax || this._webgl2;
}
},
elementIndexUint: {
get: function() {
return this._elementIndexUint || this._webgl2;
}
},
depthTexture: {
get: function() {
return this._depthTexture || this._webgl2;
}
},
floatingPointTexture: {
get: function() {
return this._webgl2 || this._textureFloat;
}
},
halfFloatingPointTexture: {
get: function() {
return this._webgl2 || this._textureHalfFloat;
}
},
textureFloatLinear: {
get: function() {
return this._textureFloatLinear;
}
},
textureHalfFloatLinear: {
get: function() {
return this._webgl2 && this._textureFloatLinear || !this._webgl2 && this._textureHalfFloatLinear;
}
},
textureFilterAnisotropic: {
get: function() {
return !!this._textureFilterAnisotropic;
}
},
s3tc: {
get: function() {
return this._s3tc;
}
},
pvrtc: {
get: function() {
return this._pvrtc;
}
},
astc: {
get: function() {
return this._astc;
}
},
etc: {
get: function() {
return this._etc;
}
},
etc1: {
get: function() {
return this._etc1;
}
},
bc7: {
get: function() {
return this._bc7;
}
},
supportsBasis: {
get: function() {
return this._s3tc || this._pvrtc || this._astc || this._etc || this._etc1 || this._bc7;
}
},
vertexArrayObject: {
get: function() {
return this._vertexArrayObject || this._webgl2;
}
},
fragmentDepth: {
get: function() {
return this._fragDepth || this._webgl2;
}
},
instancedArrays: {
get: function() {
return this._instancedArrays || this._webgl2;
}
},
colorBufferFloat: {
get: function() {
return this._colorBufferFloat;
}
},
colorBufferHalfFloat: {
get: function() {
return this._webgl2 && this._colorBufferFloat || !this._webgl2 && this._colorBufferHalfFloat;
}
},
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 : void 0
);
}
},
defaultTexture: {
get: function() {
if (this._defaultTexture === void 0) {
this._defaultTexture = new Texture_default({
context: this,
source: {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([255, 255, 255, 255])
},
flipY: false
});
}
return this._defaultTexture;
}
},
defaultEmissiveTexture: {
get: function() {
if (this._defaultEmissiveTexture === void 0) {
this._defaultEmissiveTexture = new Texture_default({
context: this,
pixelFormat: PixelFormat_default.RGB,
source: {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([0, 0, 0])
},
flipY: false
});
}
return this._defaultEmissiveTexture;
}
},
defaultNormalTexture: {
get: function() {
if (this._defaultNormalTexture === void 0) {
this._defaultNormalTexture = new Texture_default({
context: this,
pixelFormat: PixelFormat_default.RGB,
source: {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([128, 128, 255])
},
flipY: false
});
}
return this._defaultNormalTexture;
}
},
defaultCubeMap: {
get: function() {
if (this._defaultCubeMap === void 0) {
const face = {
width: 1,
height: 1,
arrayBufferView: new Uint8Array([255, 255, 255, 255])
};
this._defaultCubeMap = new CubeMap_default({
context: this,
source: {
positiveX: face,
negativeX: face,
positiveY: face,
negativeY: face,
positiveZ: face,
negativeZ: face
},
flipY: false
});
}
return this._defaultCubeMap;
}
},
drawingBufferHeight: {
get: function() {
return this._gl.drawingBufferHeight;
}
},
drawingBufferWidth: {
get: function() {
return this._gl.drawingBufferWidth;
}
},
defaultFramebuffer: {
get: function() {
return defaultFramebufferMarker;
}
}
});
function validateFramebuffer(context) {
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_default(message);
}
}
}
function applyRenderState(context, renderState, passState, clear2) {
const previousRenderState = context._currentRenderState;
const previousPassState = context._currentPassState;
context._currentRenderState = renderState;
context._currentPassState = passState;
RenderState_default.partialApply(
context._gl,
previousRenderState,
renderState,
previousPassState,
passState,
clear2
);
}
var scratchBackBufferArray;
if (typeof WebGLRenderingContext !== "undefined") {
scratchBackBufferArray = [WebGLConstants_default.BACK];
}
function bindFramebuffer(context, framebuffer) {
if (framebuffer !== context._currentFramebuffer) {
context._currentFramebuffer = framebuffer;
let buffers = scratchBackBufferArray;
if (defined_default(framebuffer)) {
framebuffer._bind();
validateFramebuffer(context);
buffers = framebuffer._getActiveColorAttachments();
} else {
const gl = context._gl;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
if (context.drawBuffers) {
context.glDrawBuffers(buffers);
}
}
}
var defaultClearCommand = new ClearCommand_default();
Context.prototype.clear = function(clearCommand, passState) {
clearCommand = defaultValue_default(clearCommand, defaultClearCommand);
passState = defaultValue_default(passState, this._defaultPassState);
const gl = this._gl;
let bitmask = 0;
const c = clearCommand.color;
const d = clearCommand.depth;
const s = clearCommand.stencil;
if (defined_default(c)) {
if (!Color_default.equals(this._clearColor, c)) {
Color_default.clone(c, this._clearColor);
gl.clearColor(c.red, c.green, c.blue, c.alpha);
}
bitmask |= gl.COLOR_BUFFER_BIT;
}
if (defined_default(d)) {
if (d !== this._clearDepth) {
this._clearDepth = d;
gl.clearDepth(d);
}
bitmask |= gl.DEPTH_BUFFER_BIT;
}
if (defined_default(s)) {
if (s !== this._clearStencil) {
this._clearStencil = s;
gl.clearStencil(s);
}
bitmask |= gl.STENCIL_BUFFER_BIT;
}
const rs = defaultValue_default(clearCommand.renderState, this._defaultRenderState);
applyRenderState(this, rs, passState, true);
const framebuffer = defaultValue_default(
clearCommand.framebuffer,
passState.framebuffer
);
bindFramebuffer(this, framebuffer);
gl.clear(bitmask);
};
function beginDraw(context, framebuffer, passState, shaderProgram, renderState) {
if (defined_default(framebuffer) && renderState.depthTest) {
if (renderState.depthTest.enabled && !framebuffer.hasDepthAttachment) {
throw new DeveloperError_default(
"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."
);
}
}
bindFramebuffer(context, framebuffer);
applyRenderState(context, renderState, passState, false);
shaderProgram._bind();
context._maxFrameTextureUnitIndex = Math.max(
context._maxFrameTextureUnitIndex,
shaderProgram.maximumTextureUnitIndex
);
}
function continueDraw(context, drawCommand, shaderProgram, uniformMap2) {
const primitiveType = drawCommand._primitiveType;
const va = drawCommand._vertexArray;
let offset2 = drawCommand._offset;
let count = drawCommand._count;
const instanceCount = drawCommand.instanceCount;
if (!PrimitiveType_default.validate(primitiveType)) {
throw new DeveloperError_default(
"drawCommand.primitiveType is required and must be valid."
);
}
Check_default.defined("drawCommand.vertexArray", va);
Check_default.typeOf.number.greaterThanOrEquals("drawCommand.offset", offset2, 0);
if (defined_default(count)) {
Check_default.typeOf.number.greaterThanOrEquals("drawCommand.count", count, 0);
}
Check_default.typeOf.number.greaterThanOrEquals(
"drawCommand.instanceCount",
instanceCount,
0
);
if (instanceCount > 0 && !context.instancedArrays) {
throw new DeveloperError_default("Instanced arrays extension is not supported");
}
context._us.model = defaultValue_default(drawCommand._modelMatrix, Matrix4_default.IDENTITY);
shaderProgram._setUniforms(
uniformMap2,
context._us,
context.validateShaderProgram
);
va._bind();
const indexBuffer = va.indexBuffer;
if (defined_default(indexBuffer)) {
offset2 = offset2 * indexBuffer.bytesPerIndex;
count = defaultValue_default(count, indexBuffer.numberOfIndices);
if (instanceCount === 0) {
context._gl.drawElements(
primitiveType,
count,
indexBuffer.indexDatatype,
offset2
);
} else {
context.glDrawElementsInstanced(
primitiveType,
count,
indexBuffer.indexDatatype,
offset2,
instanceCount
);
}
} else {
count = defaultValue_default(count, va.numberOfVertices);
if (instanceCount === 0) {
context._gl.drawArrays(primitiveType, offset2, count);
} else {
context.glDrawArraysInstanced(
primitiveType,
offset2,
count,
instanceCount
);
}
}
va._unBind();
}
Context.prototype.draw = function(drawCommand, passState, shaderProgram, uniformMap2) {
Check_default.defined("drawCommand", drawCommand);
Check_default.defined("drawCommand.shaderProgram", drawCommand._shaderProgram);
passState = defaultValue_default(passState, this._defaultPassState);
const framebuffer = defaultValue_default(
drawCommand._framebuffer,
passState.framebuffer
);
const renderState = defaultValue_default(
drawCommand._renderState,
this._defaultRenderState
);
shaderProgram = defaultValue_default(shaderProgram, drawCommand._shaderProgram);
uniformMap2 = defaultValue_default(uniformMap2, drawCommand._uniformMap);
beginDraw(this, framebuffer, passState, shaderProgram, renderState);
continueDraw(this, drawCommand, shaderProgram, uniformMap2);
};
Context.prototype.endFrame = function() {
const gl = this._gl;
gl.useProgram(null);
this._currentFramebuffer = void 0;
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
const buffers = scratchBackBufferArray;
if (this.drawBuffers) {
this.glDrawBuffers(buffers);
}
const length3 = this._maxFrameTextureUnitIndex;
this._maxFrameTextureUnitIndex = 0;
for (let i = 0; i < length3; ++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_default(readState, defaultValue_default.EMPTY_OBJECT);
const x = Math.max(defaultValue_default(readState.x, 0), 0);
const y = Math.max(defaultValue_default(readState.y, 0), 0);
const width = defaultValue_default(readState.width, gl.drawingBufferWidth);
const height = defaultValue_default(readState.height, gl.drawingBufferHeight);
const framebuffer = readState.framebuffer;
Check_default.typeOf.number.greaterThan("readState.width", width, 0);
Check_default.typeOf.number.greaterThan("readState.height", height, 0);
let pixelDatatype = PixelDatatype_default.UNSIGNED_BYTE;
if (defined_default(framebuffer) && framebuffer.numberOfColorAttachments > 0) {
pixelDatatype = framebuffer.getColorTexture(0).pixelDatatype;
}
const pixels = PixelFormat_default.createTypedArray(
PixelFormat_default.RGBA,
pixelDatatype,
width,
height
);
bindFramebuffer(this, framebuffer);
gl.readPixels(
x,
y,
width,
height,
PixelFormat_default.RGBA,
PixelDatatype_default.toWebGLConstant(pixelDatatype, this),
pixels
);
return pixels;
};
var viewportQuadAttributeLocations = {
position: 0,
textureCoordinates: 1
};
Context.prototype.getViewportQuadVertexArray = function() {
let vertexArray = this.cache.viewportQuad_vertexArray;
if (!defined_default(vertexArray)) {
const geometry = new Geometry_default({
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: [-1, -1, 1, -1, 1, 1, -1, 1]
}),
textureCoordinates: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: [0, 0, 1, 0, 1, 1, 0, 1]
})
},
indices: new Uint16Array([0, 1, 2, 0, 2, 3]),
primitiveType: PrimitiveType_default.TRIANGLES
});
vertexArray = VertexArray_default.fromGeometry({
context: this,
geometry,
attributeLocations: viewportQuadAttributeLocations,
bufferUsage: BufferUsage_default.STATIC_DRAW,
interleave: true
});
this.cache.viewportQuad_vertexArray = vertexArray;
}
return vertexArray;
};
Context.prototype.createViewportQuadCommand = function(fragmentShaderSource, overrides) {
overrides = defaultValue_default(overrides, defaultValue_default.EMPTY_OBJECT);
return new DrawCommand_default({
vertexArray: this.getViewportQuadVertexArray(),
primitiveType: PrimitiveType_default.TRIANGLES,
renderState: overrides.renderState,
shaderProgram: ShaderProgram_default.fromCache({
context: this,
vertexShaderSource: ViewportQuadVS_default,
fragmentShaderSource,
attributeLocations: viewportQuadAttributeLocations
}),
uniformMap: overrides.uniformMap,
owner: overrides.owner,
framebuffer: overrides.framebuffer,
pass: overrides.pass
});
};
Context.prototype.getObjectByPickColor = function(pickColor) {
Check_default.defined("pickColor", pickColor);
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 void 0;
};
Context.prototype.createPickId = function(object) {
Check_default.defined("object", object);
++this._nextPickColor[0];
const key = this._nextPickColor[0];
if (key === 0) {
throw new RuntimeError_default("Out of unique Pick IDs.");
}
this._pickObjects[key] = object;
return new PickId(this._pickObjects, key, Color_default.fromRgba(key));
};
Context.prototype.isDestroyed = function() {
return false;
};
Context.prototype.destroy = function() {
const cache = this.cache;
for (const property in cache) {
if (cache.hasOwnProperty(property)) {
const propertyValue = cache[property];
if (defined_default(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_default(this);
};
Context._deprecationWarning = deprecationWarning_default;
var Context_default = Context;
// node_modules/@cesium/engine/Source/Renderer/MultisampleFramebuffer.js
function MultisampleFramebuffer(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const context = options.context;
const width = options.width;
const height = options.height;
Check_default.defined("options.context", context);
Check_default.defined("options.width", width);
Check_default.defined("options.height", height);
this._width = width;
this._height = height;
const colorRenderbuffers = options.colorRenderbuffers;
const colorTextures = options.colorTextures;
if (defined_default(colorRenderbuffers) !== defined_default(colorTextures)) {
throw new DeveloperError_default(
"Both color renderbuffer and texture attachments must be provided."
);
}
const depthStencilRenderbuffer = options.depthStencilRenderbuffer;
const depthStencilTexture = options.depthStencilTexture;
if (defined_default(depthStencilRenderbuffer) !== defined_default(depthStencilTexture)) {
throw new DeveloperError_default(
"Both depth-stencil renderbuffer and texture attachments must be provided."
);
}
this._renderFramebuffer = new Framebuffer_default({
context,
colorRenderbuffers,
depthStencilRenderbuffer,
destroyAttachments: options.destroyAttachments
});
this._colorFramebuffer = new Framebuffer_default({
context,
colorTextures,
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_default(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_default(this);
};
var MultisampleFramebuffer_default = MultisampleFramebuffer;
// node_modules/@cesium/engine/Source/Renderer/RenderbufferFormat.js
var RenderbufferFormat = {
RGBA4: WebGLConstants_default.RGBA4,
RGBA8: WebGLConstants_default.RGBA8,
RGBA16F: WebGLConstants_default.RGBA16F,
RGBA32F: WebGLConstants_default.RGBA32F,
RGB5_A1: WebGLConstants_default.RGB5_A1,
RGB565: WebGLConstants_default.RGB565,
DEPTH_COMPONENT16: WebGLConstants_default.DEPTH_COMPONENT16,
STENCIL_INDEX8: WebGLConstants_default.STENCIL_INDEX8,
DEPTH_STENCIL: WebGLConstants_default.DEPTH_STENCIL,
DEPTH24_STENCIL8: WebGLConstants_default.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_default.FLOAT) {
return RenderbufferFormat.RGBA32F;
} else if (datatype === WebGLConstants_default.HALF_FLOAT_OES) {
return RenderbufferFormat.RGBA16F;
}
return RenderbufferFormat.RGBA8;
}
};
var RenderbufferFormat_default = Object.freeze(RenderbufferFormat);
// node_modules/@cesium/engine/Source/Renderer/Renderbuffer.js
function Renderbuffer(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.context", options.context);
const context = options.context;
const gl = context._gl;
const maximumRenderbufferSize = ContextLimits_default.maximumRenderbufferSize;
const format = defaultValue_default(options.format, RenderbufferFormat_default.RGBA4);
const width = defined_default(options.width) ? options.width : gl.drawingBufferWidth;
const height = defined_default(options.height) ? options.height : gl.drawingBufferHeight;
const numSamples = defaultValue_default(options.numSamples, 1);
if (!RenderbufferFormat_default.validate(format)) {
throw new DeveloperError_default("Invalid format.");
}
Check_default.typeOf.number.greaterThan("width", width, 0);
if (width > maximumRenderbufferSize) {
throw new DeveloperError_default(
`Width must be less than or equal to the maximum renderbuffer size (${maximumRenderbufferSize}). Check maximumRenderbufferSize.`
);
}
Check_default.typeOf.number.greaterThan("height", height, 0);
if (height > maximumRenderbufferSize) {
throw new DeveloperError_default(
`Height must be less than or equal to the maximum renderbuffer size (${maximumRenderbufferSize}). Check maximumRenderbufferSize.`
);
}
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_default(this);
};
var Renderbuffer_default = Renderbuffer;
// node_modules/@cesium/engine/Source/Renderer/FramebufferManager.js
function FramebufferManager(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._numSamples = defaultValue_default(options.numSamples, 1);
this._colorAttachmentsLength = defaultValue_default(
options.colorAttachmentsLength,
1
);
this._color = defaultValue_default(options.color, true);
this._depth = defaultValue_default(options.depth, false);
this._depthStencil = defaultValue_default(options.depthStencil, false);
this._supportsDepthTexture = defaultValue_default(
options.supportsDepthTexture,
false
);
if (!this._color && !this._depth && !this._depthStencil) {
throw new DeveloperError_default(
"Must enable at least one type of framebuffer attachment."
);
}
if (this._depth && this._depthStencil) {
throw new DeveloperError_default(
"Cannot have both a depth and depth-stencil attachment."
);
}
this._createColorAttachments = defaultValue_default(
options.createColorAttachments,
true
);
this._createDepthAttachments = defaultValue_default(
options.createDepthAttachments,
true
);
this._pixelDatatype = options.pixelDatatype;
this._pixelFormat = options.pixelFormat;
this._width = void 0;
this._height = void 0;
this._framebuffer = void 0;
this._multisampleFramebuffer = void 0;
this._colorTextures = void 0;
if (this._color) {
this._colorTextures = new Array(this._colorAttachmentsLength);
this._colorRenderbuffers = new Array(this._colorAttachmentsLength);
}
this._colorRenderbuffer = void 0;
this._depthStencilRenderbuffer = void 0;
this._depthStencilTexture = void 0;
this._depthRenderbuffer = void 0;
this._depthTexture = void 0;
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_default(numSamples, 1);
const dimensionChanged = this._width !== width || this._height !== height;
const samplesChanged = this._numSamples !== numSamples;
const pixelChanged = defined_default(pixelDatatype) && this._pixelDatatype !== pixelDatatype || defined_default(pixelFormat) && this._pixelFormat !== pixelFormat;
const framebufferDefined = numSamples === 1 ? defined_default(this._framebuffer) : defined_default(this._multisampleFramebuffer);
return this._attachmentsDirty || dimensionChanged || samplesChanged || pixelChanged || !framebufferDefined || this._color && !defined_default(this._colorTextures[0]);
};
FramebufferManager.prototype.update = function(context, width, height, numSamples, pixelDatatype, pixelFormat) {
if (!defined_default(width) || !defined_default(height)) {
throw new DeveloperError_default("width and height must be defined.");
}
numSamples = context.msaa ? defaultValue_default(numSamples, 1) : 1;
pixelDatatype = defaultValue_default(
pixelDatatype,
this._color ? defaultValue_default(this._pixelDatatype, PixelDatatype_default.UNSIGNED_BYTE) : void 0
);
pixelFormat = defaultValue_default(
pixelFormat,
this._color ? defaultValue_default(this._pixelFormat, PixelFormat_default.RGBA) : void 0
);
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;
if (this._color && this._createColorAttachments) {
for (let i = 0; i < this._colorAttachmentsLength; ++i) {
this._colorTextures[i] = new Texture_default({
context,
width,
height,
pixelFormat,
pixelDatatype,
sampler: Sampler_default.NEAREST
});
if (this._numSamples > 1) {
const format = RenderbufferFormat_default.getColorFormat(pixelDatatype);
this._colorRenderbuffers[i] = new Renderbuffer_default({
context,
width,
height,
format,
numSamples: this._numSamples
});
}
}
}
if (this._depthStencil && this._createDepthAttachments) {
if (this._supportsDepthTexture && context.depthTexture) {
this._depthStencilTexture = new Texture_default({
context,
width,
height,
pixelFormat: PixelFormat_default.DEPTH_STENCIL,
pixelDatatype: PixelDatatype_default.UNSIGNED_INT_24_8,
sampler: Sampler_default.NEAREST
});
if (this._numSamples > 1) {
this._depthStencilRenderbuffer = new Renderbuffer_default({
context,
width,
height,
format: RenderbufferFormat_default.DEPTH24_STENCIL8,
numSamples: this._numSamples
});
}
} else {
this._depthStencilRenderbuffer = new Renderbuffer_default({
context,
width,
height,
format: RenderbufferFormat_default.DEPTH_STENCIL
});
}
}
if (this._depth && this._createDepthAttachments) {
if (this._supportsDepthTexture && context.depthTexture) {
this._depthTexture = new Texture_default({
context,
width,
height,
pixelFormat: PixelFormat_default.DEPTH_COMPONENT,
pixelDatatype: PixelDatatype_default.UNSIGNED_INT,
sampler: Sampler_default.NEAREST
});
} else {
this._depthRenderbuffer = new Renderbuffer_default({
context,
width,
height,
format: RenderbufferFormat_default.DEPTH_COMPONENT16
});
}
}
if (this._numSamples > 1) {
this._multisampleFramebuffer = new MultisampleFramebuffer_default({
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_default({
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_default(index, 0);
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
return this._colorTextures[index];
};
FramebufferManager.prototype.setColorTexture = function(texture, index) {
index = defaultValue_default(index, 0);
if (this._createColorAttachments) {
throw new DeveloperError_default(
"createColorAttachments must be false if setColorTexture is called."
);
}
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
this._attachmentsDirty = texture !== this._colorTextures[index];
this._colorTextures[index] = texture;
};
FramebufferManager.prototype.getColorRenderbuffer = function(index) {
index = defaultValue_default(index, 0);
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
return this._colorRenderbuffers[index];
};
FramebufferManager.prototype.setColorRenderbuffer = function(renderbuffer, index) {
index = defaultValue_default(index, 0);
if (this._createColorAttachments) {
throw new DeveloperError_default(
"createColorAttachments must be false if setColorRenderbuffer is called."
);
}
if (index >= this._colorAttachmentsLength) {
throw new DeveloperError_default(
"index must be smaller than total number of color attachments."
);
}
this._attachmentsDirty = renderbuffer !== this._colorRenderbuffers[index];
this._colorRenderbuffers[index] = renderbuffer;
};
FramebufferManager.prototype.getDepthRenderbuffer = function() {
return this._depthRenderbuffer;
};
FramebufferManager.prototype.setDepthRenderbuffer = function(renderbuffer) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthRenderbuffer is called."
);
}
this._attachmentsDirty = renderbuffer !== this._depthRenderbuffer;
this._depthRenderbuffer = renderbuffer;
};
FramebufferManager.prototype.getDepthTexture = function() {
return this._depthTexture;
};
FramebufferManager.prototype.setDepthTexture = function(texture) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthTexture is called."
);
}
this._attachmentsDirty = texture !== this._depthTexture;
this._depthTexture = texture;
};
FramebufferManager.prototype.getDepthStencilRenderbuffer = function() {
return this._depthStencilRenderbuffer;
};
FramebufferManager.prototype.setDepthStencilRenderbuffer = function(renderbuffer) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthStencilRenderbuffer is called."
);
}
this._attachmentsDirty = renderbuffer !== this._depthStencilRenderbuffer;
this._depthStencilRenderbuffer = renderbuffer;
};
FramebufferManager.prototype.getDepthStencilTexture = function() {
return this._depthStencilTexture;
};
FramebufferManager.prototype.setDepthStencilTexture = function(texture) {
if (this._createDepthAttachments) {
throw new DeveloperError_default(
"createDepthAttachments must be false if setDepthStencilTexture is called."
);
}
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 length3 = this._colorTextures.length;
for (i = 0; i < length3; ++i) {
const texture = this._colorTextures[i];
if (this._createColorAttachments) {
if (defined_default(texture) && !texture.isDestroyed()) {
this._colorTextures[i].destroy();
this._colorTextures[i] = void 0;
}
}
if (defined_default(texture) && texture.isDestroyed()) {
this._colorTextures[i] = void 0;
}
const renderbuffer = this._colorRenderbuffers[i];
if (this._createColorAttachments) {
if (defined_default(renderbuffer) && !renderbuffer.isDestroyed()) {
this._colorRenderbuffers[i].destroy();
this._colorRenderbuffers[i] = void 0;
}
}
if (defined_default(renderbuffer) && renderbuffer.isDestroyed()) {
this._colorRenderbuffers[i] = void 0;
}
}
}
if (this._depthStencil) {
if (this._createDepthAttachments) {
this._depthStencilTexture = this._depthStencilTexture && this._depthStencilTexture.destroy();
this._depthStencilRenderbuffer = this._depthStencilRenderbuffer && this._depthStencilRenderbuffer.destroy();
}
if (defined_default(this._depthStencilTexture) && this._depthStencilTexture.isDestroyed()) {
this._depthStencilTexture = void 0;
}
if (defined_default(this._depthStencilRenderbuffer) && this._depthStencilRenderbuffer.isDestroyed()) {
this._depthStencilRenderbuffer = void 0;
}
}
if (this._depth) {
if (this._createDepthAttachments) {
this._depthTexture = this._depthTexture && this._depthTexture.destroy();
this._depthRenderbuffer = this._depthRenderbuffer && this._depthRenderbuffer.destroy();
}
if (defined_default(this._depthTexture) && this._depthTexture.isDestroyed()) {
this._depthTexture = void 0;
}
if (defined_default(this._depthRenderbuffer) && this._depthRenderbuffer.isDestroyed()) {
this._depthRenderbuffer = void 0;
}
}
this.destroyFramebuffer();
};
var FramebufferManager_default = FramebufferManager;
// node_modules/@cesium/engine/Source/Renderer/ShaderDestination.js
var ShaderDestination = {
VERTEX: 0,
FRAGMENT: 1,
BOTH: 2
};
ShaderDestination.includesVertexShader = function(destination) {
Check_default.typeOf.number("destination", destination);
return destination === ShaderDestination.VERTEX || destination === ShaderDestination.BOTH;
};
ShaderDestination.includesFragmentShader = function(destination) {
Check_default.typeOf.number("destination", destination);
return destination === ShaderDestination.FRAGMENT || destination === ShaderDestination.BOTH;
};
var ShaderDestination_default = Object.freeze(ShaderDestination);
// node_modules/@cesium/engine/Source/Renderer/ShaderStruct.js
function ShaderStruct(name) {
this.name = name;
this.fields = [];
}
ShaderStruct.prototype.addField = function(type, identifier) {
const field = ` ${type} ${identifier};`;
this.fields.push(field);
};
ShaderStruct.prototype.generateGlslLines = function() {
let fields = this.fields;
if (fields.length === 0) {
fields = [" float _empty;"];
}
return [].concat(`struct ${this.name}`, "{", fields, "};");
};
var ShaderStruct_default = ShaderStruct;
// node_modules/@cesium/engine/Source/Renderer/ShaderFunction.js
function ShaderFunction(signature) {
this.signature = signature;
this.body = [];
}
ShaderFunction.prototype.addLines = function(lines) {
if (typeof lines !== "string" && !Array.isArray(lines)) {
throw new DeveloperError_default(
`Expected lines to be a string or an array of strings, actual value was ${lines}`
);
}
const body = this.body;
if (Array.isArray(lines)) {
const length3 = lines.length;
for (let i = 0; i < length3; i++) {
body.push(` ${lines[i]}`);
}
} else {
body.push(` ${lines}`);
}
};
ShaderFunction.prototype.generateGlslLines = function() {
return [].concat(this.signature, "{", this.body, "}");
};
var ShaderFunction_default = ShaderFunction;
// node_modules/@cesium/engine/Source/Renderer/ShaderBuilder.js
function ShaderBuilder() {
this._positionAttributeLine = void 0;
this._nextAttributeLocation = 1;
this._attributeLocations = {};
this._attributeLines = [];
this._structs = {};
this._functions = {};
this._vertexShaderParts = {
defineLines: [],
uniformLines: [],
shaderLines: [],
varyingLines: [],
structIds: [],
functionIds: []
};
this._fragmentShaderParts = {
defineLines: [],
uniformLines: [],
shaderLines: [],
varyingLines: [],
structIds: [],
functionIds: []
};
}
Object.defineProperties(ShaderBuilder.prototype, {
attributeLocations: {
get: function() {
return this._attributeLocations;
}
}
});
ShaderBuilder.prototype.addDefine = function(identifier, value, destination) {
Check_default.typeOf.string("identifier", identifier);
destination = defaultValue_default(destination, ShaderDestination_default.BOTH);
let line = identifier;
if (defined_default(value)) {
line += ` ${value.toString()}`;
}
if (ShaderDestination_default.includesVertexShader(destination)) {
this._vertexShaderParts.defineLines.push(line);
}
if (ShaderDestination_default.includesFragmentShader(destination)) {
this._fragmentShaderParts.defineLines.push(line);
}
};
ShaderBuilder.prototype.addStruct = function(structId, structName, destination) {
Check_default.typeOf.string("structId", structId);
Check_default.typeOf.string("structName", structName);
Check_default.typeOf.number("destination", destination);
this._structs[structId] = new ShaderStruct_default(structName);
if (ShaderDestination_default.includesVertexShader(destination)) {
this._vertexShaderParts.structIds.push(structId);
}
if (ShaderDestination_default.includesFragmentShader(destination)) {
this._fragmentShaderParts.structIds.push(structId);
}
};
ShaderBuilder.prototype.addStructField = function(structId, type, identifier) {
Check_default.typeOf.string("structId", structId);
Check_default.typeOf.string("type", type);
Check_default.typeOf.string("identifier", identifier);
this._structs[structId].addField(type, identifier);
};
ShaderBuilder.prototype.addFunction = function(functionName, signature, destination) {
Check_default.typeOf.string("functionName", functionName);
Check_default.typeOf.string("signature", signature);
Check_default.typeOf.number("destination", destination);
this._functions[functionName] = new ShaderFunction_default(signature);
if (ShaderDestination_default.includesVertexShader(destination)) {
this._vertexShaderParts.functionIds.push(functionName);
}
if (ShaderDestination_default.includesFragmentShader(destination)) {
this._fragmentShaderParts.functionIds.push(functionName);
}
};
ShaderBuilder.prototype.addFunctionLines = function(functionName, lines) {
Check_default.typeOf.string("functionName", functionName);
if (typeof lines !== "string" && !Array.isArray(lines)) {
throw new DeveloperError_default(
`Expected lines to be a string or an array of strings, actual value was ${lines}`
);
}
this._functions[functionName].addLines(lines);
};
ShaderBuilder.prototype.addUniform = function(type, identifier, destination) {
Check_default.typeOf.string("type", type);
Check_default.typeOf.string("identifier", identifier);
destination = defaultValue_default(destination, ShaderDestination_default.BOTH);
const line = `uniform ${type} ${identifier};`;
if (ShaderDestination_default.includesVertexShader(destination)) {
this._vertexShaderParts.uniformLines.push(line);
}
if (ShaderDestination_default.includesFragmentShader(destination)) {
this._fragmentShaderParts.uniformLines.push(line);
}
};
ShaderBuilder.prototype.setPositionAttribute = function(type, identifier) {
Check_default.typeOf.string("type", type);
Check_default.typeOf.string("identifier", identifier);
if (defined_default(this._positionAttributeLine)) {
throw new DeveloperError_default(
"setPositionAttribute() must be called exactly once for the attribute used for gl_Position. For other attributes, use addAttribute()"
);
}
this._positionAttributeLine = `in ${type} ${identifier};`;
this._attributeLocations[identifier] = 0;
return 0;
};
ShaderBuilder.prototype.addAttribute = function(type, identifier) {
Check_default.typeOf.string("type", type);
Check_default.typeOf.string("identifier", identifier);
const line = `in ${type} ${identifier};`;
this._attributeLines.push(line);
const location2 = this._nextAttributeLocation;
this._attributeLocations[identifier] = location2;
this._nextAttributeLocation += getAttributeLocationCount(type);
return location2;
};
ShaderBuilder.prototype.addVarying = function(type, identifier) {
Check_default.typeOf.string("type", type);
Check_default.typeOf.string("identifier", identifier);
const line = `${type} ${identifier};`;
this._vertexShaderParts.varyingLines.push(`out ${line}`);
this._fragmentShaderParts.varyingLines.push(`in ${line}`);
};
ShaderBuilder.prototype.addVertexLines = function(lines) {
if (typeof lines !== "string" && !Array.isArray(lines)) {
throw new DeveloperError_default(
`Expected lines to be a string or an array of strings, actual value was ${lines}`
);
}
const vertexLines = this._vertexShaderParts.shaderLines;
if (Array.isArray(lines)) {
vertexLines.push.apply(vertexLines, lines);
} else {
vertexLines.push(lines);
}
};
ShaderBuilder.prototype.addFragmentLines = function(lines) {
if (typeof lines !== "string" && !Array.isArray(lines)) {
throw new DeveloperError_default(
`Expected lines to be a string or an array of strings, actual value was ${lines}`
);
}
const fragmentLines = this._fragmentShaderParts.shaderLines;
if (Array.isArray(lines)) {
fragmentLines.push.apply(fragmentLines, lines);
} else {
fragmentLines.push(lines);
}
};
ShaderBuilder.prototype.buildShaderProgram = function(context) {
Check_default.typeOf.object("context", context);
const positionAttribute = defined_default(this._positionAttributeLine) ? [this._positionAttributeLine] : [];
const structLines = generateStructLines(this);
const functionLines = generateFunctionLines(this);
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_default({
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_default({
defines: this._fragmentShaderParts.defineLines,
sources: [fragmentLines]
});
return ShaderProgram_default.fromCache({
context,
vertexShaderSource,
fragmentShaderSource,
attributeLocations: this._attributeLocations
});
};
ShaderBuilder.prototype.clone = function() {
return clone_default(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,
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,
fragmentLines
};
}
var ShaderBuilder_default = ShaderBuilder;
// node_modules/@cesium/engine/Source/Renderer/VertexArrayFacade.js
function VertexArrayFacade(context, attributes, sizeInVertices, instanced) {
Check_default.defined("context", context);
if (!attributes || attributes.length === 0) {
throw new DeveloperError_default("At least one attribute is required.");
}
const attrs = VertexArrayFacade._verifyAttributes(attributes);
sizeInVertices = defaultValue_default(sizeInVertices, 0);
const precreatedAttributes = [];
const attributesByUsage = {};
let attributesForUsage;
let usage;
const length3 = attrs.length;
for (let i = 0; i < length3; ++i) {
const attribute = attrs[i];
if (attribute.vertexBuffer) {
precreatedAttributes.push(attribute);
continue;
}
usage = attribute.usage;
attributesForUsage = attributesByUsage[usage];
if (!defined_default(attributesForUsage)) {
attributesForUsage = attributesByUsage[usage] = [];
}
attributesForUsage.push(attribute);
}
function compare(left, right) {
return ComponentDatatype_default.getSizeInBytes(right.componentDatatype) - ComponentDatatype_default.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,
vertexBuffer: void 0,
usage: bufferUsage,
needsCommit: false,
arrayBuffer: void 0,
arrayViews: VertexArrayFacade._createArrayViews(
attributesForUsage,
vertexSizeInBytes
)
};
this._allBuffers.push(buffer);
}
}
this._size = 0;
this._instanced = defaultValue_default(instanced, false);
this._precreated = precreatedAttributes;
this._context = context;
this.writers = void 0;
this.va = void 0;
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_default(attribute.index, i),
enabled: defaultValue_default(attribute.enabled, true),
componentsPerAttribute: attribute.componentsPerAttribute,
componentDatatype: defaultValue_default(
attribute.componentDatatype,
ComponentDatatype_default.FLOAT
),
normalize: defaultValue_default(attribute.normalize, false),
vertexBuffer: attribute.vertexBuffer,
usage: defaultValue_default(attribute.usage, BufferUsage_default.STATIC_DRAW)
};
attrs.push(attr);
if (attr.componentsPerAttribute !== 1 && attr.componentsPerAttribute !== 2 && attr.componentsPerAttribute !== 3 && attr.componentsPerAttribute !== 4) {
throw new DeveloperError_default(
"attribute.componentsPerAttribute must be in the range [1, 4]."
);
}
const datatype = attr.componentDatatype;
if (!ComponentDatatype_default.validate(datatype)) {
throw new DeveloperError_default(
"Attribute must have a valid componentDatatype or not specify it."
);
}
if (!BufferUsage_default.validate(attr.usage)) {
throw new DeveloperError_default(
"Attribute must have a valid usage or not specify it."
);
}
}
const uniqueIndices = new Array(attrs.length);
for (let j = 0; j < attrs.length; ++j) {
const currentAttr = attrs[j];
const index = currentAttr.index;
if (uniqueIndices[index]) {
throw new DeveloperError_default(
`Index ${index} is used by more than one attribute.`
);
}
uniqueIndices[index] = true;
}
return attrs;
};
VertexArrayFacade._vertexSizeInBytes = function(attributes) {
let sizeInBytes = 0;
const length3 = attributes.length;
for (let i = 0; i < length3; ++i) {
const attribute = attributes[i];
sizeInBytes += attribute.componentsPerAttribute * ComponentDatatype_default.getSizeInBytes(attribute.componentDatatype);
}
const maxComponentSizeInBytes = length3 > 0 ? ComponentDatatype_default.getSizeInBytes(attributes[0].componentDatatype) : 0;
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 length3 = attributes.length;
for (let i = 0; i < length3; ++i) {
const attribute = attributes[i];
const componentDatatype = attribute.componentDatatype;
views.push({
index: attribute.index,
enabled: attribute.enabled,
componentsPerAttribute: attribute.componentsPerAttribute,
componentDatatype,
normalize: attribute.normalize,
offsetInBytes,
vertexSizeInComponentType: vertexSizeInBytes / ComponentDatatype_default.getSizeInBytes(componentDatatype),
view: void 0
});
offsetInBytes += attribute.componentsPerAttribute * ComponentDatatype_default.getSizeInBytes(componentDatatype);
}
return views;
};
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);
VertexArrayFacade._appendWriters(this.writers, buffer);
}
destroyVA(this);
};
VertexArrayFacade._resize = function(buffer, size) {
if (buffer.vertexSizeInBytes > 0) {
const arrayBuffer = new ArrayBuffer(size * buffer.vertexSizeInBytes);
if (defined_default(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];
}
}
const views = buffer.arrayViews;
const length3 = views.length;
for (let i = 0; i < length3; ++i) {
const view = views[i];
view.view = ComponentDatatype_default.createArrayBufferView(
view.componentDatatype,
arrayBuffer,
view.offsetInBytes
);
}
buffer.arrayBuffer = arrayBuffer;
}
};
var createWriters = [
function(buffer, view, vertexSizeInComponentType) {
return function(index, attribute) {
view[index * vertexSizeInComponentType] = attribute;
buffer.needsCommit = true;
};
},
function(buffer, view, vertexSizeInComponentType) {
return function(index, component0, component1) {
const i = index * vertexSizeInComponentType;
view[i] = component0;
view[i + 1] = component1;
buffer.needsCommit = true;
};
},
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;
};
},
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 length3 = arrayViews.length;
for (let i = 0; i < length3; ++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 length3;
for (i = 0, length3 = allBuffers.length; i < length3; ++i) {
buffer = allBuffers[i];
recreateVA = commit(this, buffer) || recreateVA;
}
if (recreateVA || !defined_default(this.va)) {
destroyVA(this);
const va = this.va = [];
const chunkSize = Math_default.SIXTY_FOUR_KILOBYTES - 4;
const numberOfVertexArrays = defined_default(indexBuffer) && !this._instanced ? Math.ceil(this._size / chunkSize) : 1;
for (let k = 0; k < numberOfVertexArrays; ++k) {
let attributes = [];
for (i = 0, length3 = allBuffers.length; i < length3; ++i) {
buffer = allBuffers[i];
const offset2 = k * (buffer.vertexSizeInBytes * chunkSize);
VertexArrayFacade._appendAttributes(
attributes,
buffer,
offset2,
this._instanced
);
}
attributes = attributes.concat(this._precreated);
va.push({
va: new VertexArray_default({
context: this._context,
attributes,
indexBuffer
}),
indicesCount: 1.5 * (k !== numberOfVertexArrays - 1 ? chunkSize : this._size % chunkSize)
});
}
}
};
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_default(vertexBuffer);
if (!vertexBufferDefined || vertexBuffer.sizeInBytes < vertexBufferSizeInBytes) {
if (vertexBufferDefined) {
vertexBuffer.destroy();
}
buffer.vertexBuffer = Buffer_default.createVertexBuffer({
context: vertexArrayFacade._context,
typedArray: buffer.arrayBuffer,
usage: buffer.usage
});
buffer.vertexBuffer.vertexArrayDestroyable = false;
return true;
}
buffer.vertexBuffer.copyFromArrayView(buffer.arrayBuffer);
}
return false;
}
VertexArrayFacade._appendAttributes = function(attributes, buffer, vertexBufferOffset, instanced) {
const arrayViews = buffer.arrayViews;
const length3 = arrayViews.length;
for (let i = 0; i < length3; ++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) {
if (offsetInVertices < 0 || offsetInVertices >= this._size) {
throw new DeveloperError_default(
"offsetInVertices must be greater than or equal to zero and less than the vertex array size."
);
}
if (offsetInVertices + lengthInVertices > this._size) {
throw new DeveloperError_default(
"offsetInVertices + lengthInVertices cannot exceed the vertex array size."
);
}
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;
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_default(va)) {
return;
}
const length3 = va.length;
for (let i = 0; i < length3; ++i) {
va[i].va.destroy();
}
vertexArrayFacade.va = void 0;
}
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_default(this);
};
var VertexArrayFacade_default = VertexArrayFacade;
// node_modules/@cesium/engine/Source/Renderer/loadCubeMap.js
function loadCubeMap(context, urls, skipColorSpaceConversion) {
Check_default.defined("context", context);
if (!defined_default(urls) || !defined_default(urls.positiveX) || !defined_default(urls.negativeX) || !defined_default(urls.positiveY) || !defined_default(urls.negativeY) || !defined_default(urls.positiveZ) || !defined_default(urls.negativeZ)) {
throw new DeveloperError_default(
"urls is required and must have positiveX, negativeX, positiveY, negativeY, positiveZ, and negativeZ properties."
);
}
const flipOptions = {
flipY: true,
skipColorSpaceConversion,
preferImageBitmap: true
};
const facePromises = [
Resource_default.createIfNeeded(urls.positiveX).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.negativeX).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.positiveY).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.negativeY).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.positiveZ).fetchImage(flipOptions),
Resource_default.createIfNeeded(urls.negativeZ).fetchImage(flipOptions)
];
return Promise.all(facePromises).then(function(images) {
return new CubeMap_default({
context,
source: {
positiveX: images[0],
negativeX: images[1],
positiveY: images[2],
negativeY: images[3],
positiveZ: images[4],
negativeZ: images[5]
}
});
});
}
var loadCubeMap_default = loadCubeMap;
// node_modules/@cesium/engine/Source/DataSources/ConstantProperty.js
function ConstantProperty(value) {
this._value = void 0;
this._hasClone = false;
this._hasEquals = false;
this._definitionChanged = new Event_default();
this.setValue(value);
}
Object.defineProperties(ConstantProperty.prototype, {
isConstant: {
value: true
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
}
});
ConstantProperty.prototype.getValue = function(time, result) {
return this._hasClone ? this._value.clone(result) : this._value;
};
ConstantProperty.prototype.setValue = function(value) {
const oldValue2 = this._value;
if (oldValue2 !== value) {
const isDefined = defined_default(value);
const hasClone = isDefined && typeof value.clone === "function";
const hasEquals = isDefined && typeof value.equals === "function";
const changed = !hasEquals || !value.equals(oldValue2);
if (changed) {
this._hasClone = hasClone;
this._hasEquals = hasEquals;
this._value = !hasClone ? value : value.clone(this._value);
this._definitionChanged.raiseEvent(this);
}
}
};
ConstantProperty.prototype.equals = function(other) {
return this === other || other instanceof ConstantProperty && (!this._hasEquals && this._value === other._value || this._hasEquals && this._value.equals(other._value));
};
ConstantProperty.prototype.valueOf = function() {
return this._value;
};
ConstantProperty.prototype.toString = function() {
return String(this._value);
};
var ConstantProperty_default = ConstantProperty;
// node_modules/@cesium/engine/Source/DataSources/createPropertyDescriptor.js
function createProperty(name, privateName, subscriptionName, configurable, createPropertyCallback) {
return {
configurable,
get: function() {
return this[privateName];
},
set: function(value) {
const oldValue2 = this[privateName];
const subscription = this[subscriptionName];
if (defined_default(subscription)) {
subscription();
this[subscriptionName] = void 0;
}
const hasValue = value !== void 0;
if (hasValue && (!defined_default(value) || !defined_default(value.getValue)) && defined_default(createPropertyCallback)) {
value = createPropertyCallback(value);
}
if (oldValue2 !== value) {
this[privateName] = value;
this._definitionChanged.raiseEvent(this, name, value, oldValue2);
}
if (defined_default(value) && defined_default(value.definitionChanged)) {
this[subscriptionName] = value.definitionChanged.addEventListener(
function() {
this._definitionChanged.raiseEvent(this, name, value, value);
},
this
);
}
}
};
}
function createConstantProperty(value) {
return new ConstantProperty_default(value);
}
function createPropertyDescriptor(name, configurable, createPropertyCallback) {
return createProperty(
name,
`_${name.toString()}`,
`_${name.toString()}Subscription`,
defaultValue_default(configurable, false),
defaultValue_default(createPropertyCallback, createConstantProperty)
);
}
var createPropertyDescriptor_default = createPropertyDescriptor;
// node_modules/@cesium/engine/Source/DataSources/BillboardGraphics.js
function BillboardGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._image = void 0;
this._imageSubscription = void 0;
this._scale = void 0;
this._scaleSubscription = void 0;
this._pixelOffset = void 0;
this._pixelOffsetSubscription = void 0;
this._eyeOffset = void 0;
this._eyeOffsetSubscription = void 0;
this._horizontalOrigin = void 0;
this._horizontalOriginSubscription = void 0;
this._verticalOrigin = void 0;
this._verticalOriginSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._color = void 0;
this._colorSubscription = void 0;
this._rotation = void 0;
this._rotationSubscription = void 0;
this._alignedAxis = void 0;
this._alignedAxisSubscription = void 0;
this._sizeInMeters = void 0;
this._sizeInMetersSubscription = void 0;
this._width = void 0;
this._widthSubscription = void 0;
this._height = void 0;
this._heightSubscription = void 0;
this._scaleByDistance = void 0;
this._scaleByDistanceSubscription = void 0;
this._translucencyByDistance = void 0;
this._translucencyByDistanceSubscription = void 0;
this._pixelOffsetScaleByDistance = void 0;
this._pixelOffsetScaleByDistanceSubscription = void 0;
this._imageSubRegion = void 0;
this._imageSubRegionSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._disableDepthTestDistance = void 0;
this._disableDepthTestDistanceSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(BillboardGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
image: createPropertyDescriptor_default("image"),
scale: createPropertyDescriptor_default("scale"),
pixelOffset: createPropertyDescriptor_default("pixelOffset"),
eyeOffset: createPropertyDescriptor_default("eyeOffset"),
horizontalOrigin: createPropertyDescriptor_default("horizontalOrigin"),
verticalOrigin: createPropertyDescriptor_default("verticalOrigin"),
heightReference: createPropertyDescriptor_default("heightReference"),
color: createPropertyDescriptor_default("color"),
rotation: createPropertyDescriptor_default("rotation"),
alignedAxis: createPropertyDescriptor_default("alignedAxis"),
sizeInMeters: createPropertyDescriptor_default("sizeInMeters"),
width: createPropertyDescriptor_default("width"),
height: createPropertyDescriptor_default("height"),
scaleByDistance: createPropertyDescriptor_default("scaleByDistance"),
translucencyByDistance: createPropertyDescriptor_default("translucencyByDistance"),
pixelOffsetScaleByDistance: createPropertyDescriptor_default(
"pixelOffsetScaleByDistance"
),
imageSubRegion: createPropertyDescriptor_default("imageSubRegion"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
disableDepthTestDistance: createPropertyDescriptor_default(
"disableDepthTestDistance"
)
});
BillboardGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
BillboardGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this._show, source.show);
this.image = defaultValue_default(this._image, source.image);
this.scale = defaultValue_default(this._scale, source.scale);
this.pixelOffset = defaultValue_default(this._pixelOffset, source.pixelOffset);
this.eyeOffset = defaultValue_default(this._eyeOffset, source.eyeOffset);
this.horizontalOrigin = defaultValue_default(
this._horizontalOrigin,
source.horizontalOrigin
);
this.verticalOrigin = defaultValue_default(
this._verticalOrigin,
source.verticalOrigin
);
this.heightReference = defaultValue_default(
this._heightReference,
source.heightReference
);
this.color = defaultValue_default(this._color, source.color);
this.rotation = defaultValue_default(this._rotation, source.rotation);
this.alignedAxis = defaultValue_default(this._alignedAxis, source.alignedAxis);
this.sizeInMeters = defaultValue_default(this._sizeInMeters, source.sizeInMeters);
this.width = defaultValue_default(this._width, source.width);
this.height = defaultValue_default(this._height, source.height);
this.scaleByDistance = defaultValue_default(
this._scaleByDistance,
source.scaleByDistance
);
this.translucencyByDistance = defaultValue_default(
this._translucencyByDistance,
source.translucencyByDistance
);
this.pixelOffsetScaleByDistance = defaultValue_default(
this._pixelOffsetScaleByDistance,
source.pixelOffsetScaleByDistance
);
this.imageSubRegion = defaultValue_default(
this._imageSubRegion,
source.imageSubRegion
);
this.distanceDisplayCondition = defaultValue_default(
this._distanceDisplayCondition,
source.distanceDisplayCondition
);
this.disableDepthTestDistance = defaultValue_default(
this._disableDepthTestDistance,
source.disableDepthTestDistance
);
};
var BillboardGraphics_default = BillboardGraphics;
// node_modules/@cesium/engine/Source/Core/AssociativeArray.js
function AssociativeArray() {
this._array = [];
this._hash = {};
}
Object.defineProperties(AssociativeArray.prototype, {
length: {
get: function() {
return this._array.length;
}
},
values: {
get: function() {
return this._array;
}
}
});
AssociativeArray.prototype.contains = function(key) {
if (typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
return defined_default(this._hash[key]);
};
AssociativeArray.prototype.set = function(key, value) {
if (typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
const oldValue2 = this._hash[key];
if (value !== oldValue2) {
this.remove(key);
this._hash[key] = value;
this._array.push(value);
}
};
AssociativeArray.prototype.get = function(key) {
if (typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
return this._hash[key];
};
AssociativeArray.prototype.remove = function(key) {
if (defined_default(key) && typeof key !== "string" && typeof key !== "number") {
throw new DeveloperError_default("key is required to be a string or number.");
}
const value = this._hash[key];
const hasValue = defined_default(value);
if (hasValue) {
const array = this._array;
array.splice(array.indexOf(value), 1);
delete this._hash[key];
}
return hasValue;
};
AssociativeArray.prototype.removeAll = function() {
const array = this._array;
if (array.length > 0) {
this._hash = {};
array.length = 0;
}
};
var AssociativeArray_default = AssociativeArray;
// node_modules/@cesium/engine/Source/Core/DistanceDisplayCondition.js
function DistanceDisplayCondition(near, far) {
near = defaultValue_default(near, 0);
this._near = near;
far = defaultValue_default(far, Number.MAX_VALUE);
this._far = far;
}
Object.defineProperties(DistanceDisplayCondition.prototype, {
near: {
get: function() {
return this._near;
},
set: function(value) {
this._near = value;
}
},
far: {
get: function() {
return this._far;
},
set: function(value) {
this._far = value;
}
}
});
DistanceDisplayCondition.packedLength = 2;
DistanceDisplayCondition.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.near;
array[startingIndex] = value.far;
return array;
};
DistanceDisplayCondition.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new DistanceDisplayCondition();
}
result.near = array[startingIndex++];
result.far = array[startingIndex];
return result;
};
DistanceDisplayCondition.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.near === right.near && left.far === right.far;
};
DistanceDisplayCondition.clone = function(value, result) {
if (!defined_default(value)) {
return void 0;
}
if (!defined_default(result)) {
result = new DistanceDisplayCondition();
}
result.near = value.near;
result.far = value.far;
return result;
};
DistanceDisplayCondition.prototype.clone = function(result) {
return DistanceDisplayCondition.clone(this, result);
};
DistanceDisplayCondition.prototype.equals = function(other) {
return DistanceDisplayCondition.equals(this, other);
};
var DistanceDisplayCondition_default = DistanceDisplayCondition;
// node_modules/@cesium/engine/Source/Core/NearFarScalar.js
function NearFarScalar(near, nearValue, far, farValue) {
this.near = defaultValue_default(near, 0);
this.nearValue = defaultValue_default(nearValue, 0);
this.far = defaultValue_default(far, 1);
this.farValue = defaultValue_default(farValue, 0);
}
NearFarScalar.clone = function(nearFarScalar, result) {
if (!defined_default(nearFarScalar)) {
return void 0;
}
if (!defined_default(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;
};
NearFarScalar.packedLength = 4;
NearFarScalar.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.near;
array[startingIndex++] = value.nearValue;
array[startingIndex++] = value.far;
array[startingIndex] = value.farValue;
return array;
};
NearFarScalar.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new NearFarScalar();
}
result.near = array[startingIndex++];
result.nearValue = array[startingIndex++];
result.far = array[startingIndex++];
result.farValue = array[startingIndex];
return result;
};
NearFarScalar.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.near === right.near && left.nearValue === right.nearValue && left.far === right.far && left.farValue === right.farValue;
};
NearFarScalar.prototype.clone = function(result) {
return NearFarScalar.clone(this, result);
};
NearFarScalar.prototype.equals = function(right) {
return NearFarScalar.equals(this, right);
};
var NearFarScalar_default = NearFarScalar;
// node_modules/@cesium/engine/Source/Scene/HeightReference.js
var HeightReference = {
NONE: 0,
CLAMP_TO_GROUND: 1,
RELATIVE_TO_GROUND: 2
};
var HeightReference_default = Object.freeze(HeightReference);
// node_modules/@cesium/engine/Source/Scene/HorizontalOrigin.js
var HorizontalOrigin = {
CENTER: 0,
LEFT: 1,
RIGHT: -1
};
var HorizontalOrigin_default = Object.freeze(HorizontalOrigin);
// node_modules/@cesium/engine/Source/Scene/VerticalOrigin.js
var VerticalOrigin = {
CENTER: 0,
BOTTOM: 1,
BASELINE: 2,
TOP: -1
};
var VerticalOrigin_default = Object.freeze(VerticalOrigin);
// node_modules/@cesium/engine/Source/DataSources/BoundingSphereState.js
var BoundingSphereState = {
DONE: 0,
PENDING: 1,
FAILED: 2
};
var BoundingSphereState_default = Object.freeze(BoundingSphereState);
// node_modules/@cesium/engine/Source/DataSources/Property.js
function Property() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(Property.prototype, {
isConstant: {
get: DeveloperError_default.throwInstantiationError
},
definitionChanged: {
get: DeveloperError_default.throwInstantiationError
}
});
Property.prototype.getValue = DeveloperError_default.throwInstantiationError;
Property.prototype.equals = DeveloperError_default.throwInstantiationError;
Property.equals = function(left, right) {
return left === right || defined_default(left) && left.equals(right);
};
Property.arrayEquals = function(left, right) {
if (left === right) {
return true;
}
if (!defined_default(left) || !defined_default(right) || left.length !== right.length) {
return false;
}
const length3 = left.length;
for (let i = 0; i < length3; i++) {
if (!Property.equals(left[i], right[i])) {
return false;
}
}
return true;
};
Property.isConstant = function(property) {
return !defined_default(property) || property.isConstant;
};
Property.getValueOrUndefined = function(property, time, result) {
return defined_default(property) ? property.getValue(time, result) : void 0;
};
Property.getValueOrDefault = function(property, time, valueDefault, result) {
return defined_default(property) ? defaultValue_default(property.getValue(time, result), valueDefault) : valueDefault;
};
Property.getValueOrClonedDefault = function(property, time, valueDefault, result) {
let value;
if (defined_default(property)) {
value = property.getValue(time, result);
}
if (!defined_default(value)) {
value = valueDefault.clone(value);
}
return value;
};
var Property_default = Property;
// node_modules/@cesium/engine/Source/DataSources/BillboardVisualizer.js
var defaultColor = Color_default.WHITE;
var defaultEyeOffset = Cartesian3_default.ZERO;
var defaultHeightReference = HeightReference_default.NONE;
var defaultPixelOffset = Cartesian2_default.ZERO;
var defaultScale = 1;
var defaultRotation = 0;
var defaultAlignedAxis = Cartesian3_default.ZERO;
var defaultHorizontalOrigin = HorizontalOrigin_default.CENTER;
var defaultVerticalOrigin = VerticalOrigin_default.CENTER;
var defaultSizeInMeters = false;
var positionScratch = new Cartesian3_default();
var colorScratch = new Color_default();
var eyeOffsetScratch = new Cartesian3_default();
var pixelOffsetScratch = new Cartesian2_default();
var scaleByDistanceScratch = new NearFarScalar_default();
var translucencyByDistanceScratch = new NearFarScalar_default();
var pixelOffsetScaleByDistanceScratch = new NearFarScalar_default();
var boundingRectangleScratch = new BoundingRectangle_default();
var distanceDisplayConditionScratch = new DistanceDisplayCondition_default();
function EntityData(entity) {
this.entity = entity;
this.billboard = void 0;
this.textureValue = void 0;
}
function BillboardVisualizer(entityCluster, entityCollection) {
if (!defined_default(entityCluster)) {
throw new DeveloperError_default("entityCluster is required.");
}
if (!defined_default(entityCollection)) {
throw new DeveloperError_default("entityCollection is required.");
}
entityCollection.collectionChanged.addEventListener(
BillboardVisualizer.prototype._onCollectionChanged,
this
);
this._cluster = entityCluster;
this._entityCollection = entityCollection;
this._items = new AssociativeArray_default();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
BillboardVisualizer.prototype.update = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
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_default.getValueOrDefault(billboardGraphics._show, time, true);
let position;
if (show) {
position = Property_default.getValueOrUndefined(
entity._position,
time,
positionScratch
);
textureValue = Property_default.getValueOrUndefined(
billboardGraphics._image,
time
);
show = defined_default(position) && defined_default(textureValue);
}
if (!show) {
returnPrimitive(item, entity, cluster);
continue;
}
if (!Property_default.isConstant(entity._position)) {
cluster._clusterDirty = true;
}
if (!defined_default(billboard)) {
billboard = cluster.getBillboard(entity);
billboard.id = entity;
billboard.image = void 0;
item.billboard = billboard;
}
billboard.show = show;
if (!defined_default(billboard.image) || item.textureValue !== textureValue) {
billboard.image = textureValue;
item.textureValue = textureValue;
}
billboard.position = position;
billboard.color = Property_default.getValueOrDefault(
billboardGraphics._color,
time,
defaultColor,
colorScratch
);
billboard.eyeOffset = Property_default.getValueOrDefault(
billboardGraphics._eyeOffset,
time,
defaultEyeOffset,
eyeOffsetScratch
);
billboard.heightReference = Property_default.getValueOrDefault(
billboardGraphics._heightReference,
time,
defaultHeightReference
);
billboard.pixelOffset = Property_default.getValueOrDefault(
billboardGraphics._pixelOffset,
time,
defaultPixelOffset,
pixelOffsetScratch
);
billboard.scale = Property_default.getValueOrDefault(
billboardGraphics._scale,
time,
defaultScale
);
billboard.rotation = Property_default.getValueOrDefault(
billboardGraphics._rotation,
time,
defaultRotation
);
billboard.alignedAxis = Property_default.getValueOrDefault(
billboardGraphics._alignedAxis,
time,
defaultAlignedAxis
);
billboard.horizontalOrigin = Property_default.getValueOrDefault(
billboardGraphics._horizontalOrigin,
time,
defaultHorizontalOrigin
);
billboard.verticalOrigin = Property_default.getValueOrDefault(
billboardGraphics._verticalOrigin,
time,
defaultVerticalOrigin
);
billboard.width = Property_default.getValueOrUndefined(
billboardGraphics._width,
time
);
billboard.height = Property_default.getValueOrUndefined(
billboardGraphics._height,
time
);
billboard.scaleByDistance = Property_default.getValueOrUndefined(
billboardGraphics._scaleByDistance,
time,
scaleByDistanceScratch
);
billboard.translucencyByDistance = Property_default.getValueOrUndefined(
billboardGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch
);
billboard.pixelOffsetScaleByDistance = Property_default.getValueOrUndefined(
billboardGraphics._pixelOffsetScaleByDistance,
time,
pixelOffsetScaleByDistanceScratch
);
billboard.sizeInMeters = Property_default.getValueOrDefault(
billboardGraphics._sizeInMeters,
time,
defaultSizeInMeters
);
billboard.distanceDisplayCondition = Property_default.getValueOrUndefined(
billboardGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch
);
billboard.disableDepthTestDistance = Property_default.getValueOrUndefined(
billboardGraphics._disableDepthTestDistance,
time
);
const subRegion = Property_default.getValueOrUndefined(
billboardGraphics._imageSubRegion,
time,
boundingRectangleScratch
);
if (defined_default(subRegion)) {
billboard.setImageSubRegion(billboard._imageId, subRegion);
}
}
return true;
};
BillboardVisualizer.prototype.getBoundingSphere = function(entity, result) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const item = this._items.get(entity.id);
if (!defined_default(item) || !defined_default(item.billboard)) {
return BoundingSphereState_default.FAILED;
}
const billboard = item.billboard;
if (billboard.heightReference === HeightReference_default.NONE) {
result.center = Cartesian3_default.clone(billboard.position, result.center);
} else {
if (!defined_default(billboard._clampedPosition)) {
return BoundingSphereState_default.PENDING;
}
result.center = Cartesian3_default.clone(billboard._clampedPosition, result.center);
}
result.radius = 0;
return BoundingSphereState_default.DONE;
};
BillboardVisualizer.prototype.isDestroyed = function() {
return false;
};
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_default(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_default(entity._billboard) && defined_default(entity._position)) {
items.set(entity.id, new EntityData(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined_default(entity._billboard) && defined_default(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_default(item)) {
item.billboard = void 0;
cluster.removeBillboard(entity);
}
}
var BillboardVisualizer_default = BillboardVisualizer;
// node_modules/@cesium/engine/Source/Core/Interval.js
function Interval(start, stop2) {
this.start = defaultValue_default(start, 0);
this.stop = defaultValue_default(stop2, 0);
}
var Interval_default = Interval;
// node_modules/@cesium/engine/Source/Core/BoundingSphere.js
function BoundingSphere(center, radius) {
this.center = Cartesian3_default.clone(defaultValue_default(center, Cartesian3_default.ZERO));
this.radius = defaultValue_default(radius, 0);
}
var fromPointsXMin = new Cartesian3_default();
var fromPointsYMin = new Cartesian3_default();
var fromPointsZMin = new Cartesian3_default();
var fromPointsXMax = new Cartesian3_default();
var fromPointsYMax = new Cartesian3_default();
var fromPointsZMax = new Cartesian3_default();
var fromPointsCurrentPos = new Cartesian3_default();
var fromPointsScratch = new Cartesian3_default();
var fromPointsRitterCenter = new Cartesian3_default();
var fromPointsMinBoxPt = new Cartesian3_default();
var fromPointsMaxBoxPt = new Cartesian3_default();
var fromPointsNaiveCenterScratch = new Cartesian3_default();
var volumeConstant = 4 / 3 * Math_default.PI;
BoundingSphere.fromPoints = function(positions, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(positions) || positions.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
const currentPos = Cartesian3_default.clone(positions[0], fromPointsCurrentPos);
const xMin = Cartesian3_default.clone(currentPos, fromPointsXMin);
const yMin = Cartesian3_default.clone(currentPos, fromPointsYMin);
const zMin = Cartesian3_default.clone(currentPos, fromPointsZMin);
const xMax = Cartesian3_default.clone(currentPos, fromPointsXMax);
const yMax = Cartesian3_default.clone(currentPos, fromPointsYMax);
const zMax = Cartesian3_default.clone(currentPos, fromPointsZMax);
const numPositions = positions.length;
let i;
for (i = 1; i < numPositions; i++) {
Cartesian3_default.clone(positions[i], currentPos);
const x = currentPos.x;
const y = currentPos.y;
const z = currentPos.z;
if (x < xMin.x) {
Cartesian3_default.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3_default.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3_default.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3_default.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3_default.clone(currentPos, zMax);
}
}
const xSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(zMax, zMin, fromPointsScratch)
);
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;
}
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;
let radiusSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
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_default.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
let naiveRadius = 0;
for (i = 0; i < numPositions; i++) {
Cartesian3_default.clone(positions[i], currentPos);
const r = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
const oldCenterToPointSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
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_default.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3_default.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
var defaultProjection2 = new GeographicProjection_default();
var fromRectangle2DLowerLeft = new Cartesian3_default();
var fromRectangle2DUpperRight = new Cartesian3_default();
var fromRectangle2DSouthwest = new Cartographic_default();
var fromRectangle2DNortheast = new Cartographic_default();
BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
return BoundingSphere.fromRectangleWithHeights2D(
rectangle,
projection,
0,
0,
result
);
};
BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(rectangle)) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
projection = defaultValue_default(projection, defaultProjection2);
Rectangle_default.southwest(rectangle, fromRectangle2DSouthwest);
fromRectangle2DSouthwest.height = minimumHeight;
Rectangle_default.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;
};
var fromRectangle3DScratch = [];
BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
surfaceHeight = defaultValue_default(surfaceHeight, 0);
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(rectangle)) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
const positions = Rectangle_default.subsample(
rectangle,
ellipsoid,
surfaceHeight,
fromRectangle3DScratch
);
return BoundingSphere.fromPoints(positions, result);
};
BoundingSphere.fromVertices = function(positions, center, stride, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(positions) || positions.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
center = defaultValue_default(center, Cartesian3_default.ZERO);
stride = defaultValue_default(stride, 3);
Check_default.typeOf.number.greaterThanOrEquals("stride", stride, 3);
const currentPos = fromPointsCurrentPos;
currentPos.x = positions[0] + center.x;
currentPos.y = positions[1] + center.y;
currentPos.z = positions[2] + center.z;
const xMin = Cartesian3_default.clone(currentPos, fromPointsXMin);
const yMin = Cartesian3_default.clone(currentPos, fromPointsYMin);
const zMin = Cartesian3_default.clone(currentPos, fromPointsZMin);
const xMax = Cartesian3_default.clone(currentPos, fromPointsXMax);
const yMax = Cartesian3_default.clone(currentPos, fromPointsYMax);
const zMax = Cartesian3_default.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;
if (x < xMin.x) {
Cartesian3_default.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3_default.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3_default.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3_default.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3_default.clone(currentPos, zMax);
}
}
const xSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(zMax, zMin, fromPointsScratch)
);
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;
}
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;
let radiusSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
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_default.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
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;
const r = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
const oldCenterToPointSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
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_default.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3_default.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(positionsHigh) || !defined_default(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 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_default.clone(currentPos, fromPointsXMin);
const yMin = Cartesian3_default.clone(currentPos, fromPointsYMin);
const zMin = Cartesian3_default.clone(currentPos, fromPointsZMin);
const xMax = Cartesian3_default.clone(currentPos, fromPointsXMax);
const yMax = Cartesian3_default.clone(currentPos, fromPointsYMax);
const zMax = Cartesian3_default.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;
if (x < xMin.x) {
Cartesian3_default.clone(currentPos, xMin);
}
if (x > xMax.x) {
Cartesian3_default.clone(currentPos, xMax);
}
if (y < yMin.y) {
Cartesian3_default.clone(currentPos, yMin);
}
if (y > yMax.y) {
Cartesian3_default.clone(currentPos, yMax);
}
if (z < zMin.z) {
Cartesian3_default.clone(currentPos, zMin);
}
if (z > zMax.z) {
Cartesian3_default.clone(currentPos, zMax);
}
}
const xSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(zMax, zMin, fromPointsScratch)
);
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;
}
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;
let radiusSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
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_default.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
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];
const r = Cartesian3_default.magnitude(
Cartesian3_default.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
const oldCenterToPointSquared = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
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_default.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Cartesian3_default.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
Check_default.typeOf.object("corner", corner);
Check_default.typeOf.object("oppositeCorner", oppositeCorner);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const center = Cartesian3_default.midpoint(corner, oppositeCorner, result.center);
result.radius = Cartesian3_default.distance(center, oppositeCorner);
return result;
};
BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
Check_default.typeOf.object("ellipsoid", ellipsoid);
if (!defined_default(result)) {
result = new BoundingSphere();
}
Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = ellipsoid.maximumRadius;
return result;
};
var fromBoundingSpheresScratch = new Cartesian3_default();
BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
if (!defined_default(result)) {
result = new BoundingSphere();
}
if (!defined_default(boundingSpheres) || boundingSpheres.length === 0) {
result.center = Cartesian3_default.clone(Cartesian3_default.ZERO, result.center);
result.radius = 0;
return result;
}
const length3 = boundingSpheres.length;
if (length3 === 1) {
return BoundingSphere.clone(boundingSpheres[0], result);
}
if (length3 === 2) {
return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
}
const positions = [];
let i;
for (i = 0; i < length3; i++) {
positions.push(boundingSpheres[i].center);
}
result = BoundingSphere.fromPoints(positions, result);
const center = result.center;
let radius = result.radius;
for (i = 0; i < length3; i++) {
const tmp2 = boundingSpheres[i];
radius = Math.max(
radius,
Cartesian3_default.distance(center, tmp2.center, fromBoundingSpheresScratch) + tmp2.radius
);
}
result.radius = radius;
return result;
};
var fromOrientedBoundingBoxScratchU = new Cartesian3_default();
var fromOrientedBoundingBoxScratchV = new Cartesian3_default();
var fromOrientedBoundingBoxScratchW = new Cartesian3_default();
BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
Check_default.defined("orientedBoundingBox", orientedBoundingBox);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const halfAxes = orientedBoundingBox.halfAxes;
const u3 = Matrix3_default.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
const v7 = Matrix3_default.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
const w = Matrix3_default.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
Cartesian3_default.add(u3, v7, u3);
Cartesian3_default.add(u3, w, u3);
result.center = Cartesian3_default.clone(orientedBoundingBox.center, result.center);
result.radius = Cartesian3_default.magnitude(u3);
return result;
};
var scratchFromTransformationCenter = new Cartesian3_default();
var scratchFromTransformationScale = new Cartesian3_default();
BoundingSphere.fromTransformation = function(transformation, result) {
Check_default.typeOf.object("transformation", transformation);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const center = Matrix4_default.getTranslation(
transformation,
scratchFromTransformationCenter
);
const scale = Matrix4_default.getScale(
transformation,
scratchFromTransformationScale
);
const radius = 0.5 * Cartesian3_default.magnitude(scale);
result.center = Cartesian3_default.clone(center, result.center);
result.radius = radius;
return result;
};
BoundingSphere.clone = function(sphere, result) {
if (!defined_default(sphere)) {
return void 0;
}
if (!defined_default(result)) {
return new BoundingSphere(sphere.center, sphere.radius);
}
result.center = Cartesian3_default.clone(sphere.center, result.center);
result.radius = sphere.radius;
return result;
};
BoundingSphere.packedLength = 4;
BoundingSphere.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const center = value.center;
array[startingIndex++] = center.x;
array[startingIndex++] = center.y;
array[startingIndex++] = center.z;
array[startingIndex] = value.radius;
return array;
};
BoundingSphere.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(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;
};
var unionScratch = new Cartesian3_default();
var unionScratchCenter = new Cartesian3_default();
BoundingSphere.union = function(left, right, result) {
Check_default.typeOf.object("left", left);
Check_default.typeOf.object("right", right);
if (!defined_default(result)) {
result = new BoundingSphere();
}
const leftCenter = left.center;
const leftRadius = left.radius;
const rightCenter = right.center;
const rightRadius = right.radius;
const toRightCenter = Cartesian3_default.subtract(
rightCenter,
leftCenter,
unionScratch
);
const centerSeparation = Cartesian3_default.magnitude(toRightCenter);
if (leftRadius >= centerSeparation + rightRadius) {
left.clone(result);
return result;
}
if (rightRadius >= centerSeparation + leftRadius) {
right.clone(result);
return result;
}
const halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
const center = Cartesian3_default.multiplyByScalar(
toRightCenter,
(-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
unionScratchCenter
);
Cartesian3_default.add(center, leftCenter, center);
Cartesian3_default.clone(center, result.center);
result.radius = halfDistanceBetweenTangentPoints;
return result;
};
var expandScratch = new Cartesian3_default();
BoundingSphere.expand = function(sphere, point, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("point", point);
result = BoundingSphere.clone(sphere, result);
const radius = Cartesian3_default.magnitude(
Cartesian3_default.subtract(point, result.center, expandScratch)
);
if (radius > result.radius) {
result.radius = radius;
}
return result;
};
BoundingSphere.intersectPlane = function(sphere, plane) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("plane", plane);
const center = sphere.center;
const radius = sphere.radius;
const normal2 = plane.normal;
const distanceToPlane = Cartesian3_default.dot(normal2, center) + plane.distance;
if (distanceToPlane < -radius) {
return Intersect_default.OUTSIDE;
} else if (distanceToPlane < radius) {
return Intersect_default.INTERSECTING;
}
return Intersect_default.INSIDE;
};
BoundingSphere.transform = function(sphere, transform3, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("transform", transform3);
if (!defined_default(result)) {
result = new BoundingSphere();
}
result.center = Matrix4_default.multiplyByPoint(
transform3,
sphere.center,
result.center
);
result.radius = Matrix4_default.getMaximumScale(transform3) * sphere.radius;
return result;
};
var distanceSquaredToScratch = new Cartesian3_default();
BoundingSphere.distanceSquaredTo = function(sphere, cartesian11) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("cartesian", cartesian11);
const diff = Cartesian3_default.subtract(
sphere.center,
cartesian11,
distanceSquaredToScratch
);
const distance2 = Cartesian3_default.magnitude(diff) - sphere.radius;
if (distance2 <= 0) {
return 0;
}
return distance2 * distance2;
};
BoundingSphere.transformWithoutScale = function(sphere, transform3, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("transform", transform3);
if (!defined_default(result)) {
result = new BoundingSphere();
}
result.center = Matrix4_default.multiplyByPoint(
transform3,
sphere.center,
result.center
);
result.radius = sphere.radius;
return result;
};
var scratchCartesian3 = new Cartesian3_default();
BoundingSphere.computePlaneDistances = function(sphere, position, direction2, result) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("position", position);
Check_default.typeOf.object("direction", direction2);
if (!defined_default(result)) {
result = new Interval_default();
}
const toCenter = Cartesian3_default.subtract(
sphere.center,
position,
scratchCartesian3
);
const mag = Cartesian3_default.dot(direction2, toCenter);
result.start = mag - sphere.radius;
result.stop = mag + sphere.radius;
return result;
};
var projectTo2DNormalScratch = new Cartesian3_default();
var projectTo2DEastScratch = new Cartesian3_default();
var projectTo2DNorthScratch = new Cartesian3_default();
var projectTo2DWestScratch = new Cartesian3_default();
var projectTo2DSouthScratch = new Cartesian3_default();
var projectTo2DCartographicScratch = new Cartographic_default();
var projectTo2DPositionsScratch = new Array(8);
for (let n = 0; n < 8; ++n) {
projectTo2DPositionsScratch[n] = new Cartesian3_default();
}
var projectTo2DProjection = new GeographicProjection_default();
BoundingSphere.projectTo2D = function(sphere, projection, result) {
Check_default.typeOf.object("sphere", sphere);
projection = defaultValue_default(projection, projectTo2DProjection);
const ellipsoid = projection.ellipsoid;
let center = sphere.center;
const radius = sphere.radius;
let normal2;
if (Cartesian3_default.equals(center, Cartesian3_default.ZERO)) {
normal2 = Cartesian3_default.clone(Cartesian3_default.UNIT_X, projectTo2DNormalScratch);
} else {
normal2 = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
}
const east = Cartesian3_default.cross(
Cartesian3_default.UNIT_Z,
normal2,
projectTo2DEastScratch
);
Cartesian3_default.normalize(east, east);
const north = Cartesian3_default.cross(normal2, east, projectTo2DNorthScratch);
Cartesian3_default.normalize(north, north);
Cartesian3_default.multiplyByScalar(normal2, radius, normal2);
Cartesian3_default.multiplyByScalar(north, radius, north);
Cartesian3_default.multiplyByScalar(east, radius, east);
const south = Cartesian3_default.negate(north, projectTo2DSouthScratch);
const west = Cartesian3_default.negate(east, projectTo2DWestScratch);
const positions = projectTo2DPositionsScratch;
let corner = positions[0];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, east, corner);
corner = positions[1];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[2];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[3];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, east, corner);
Cartesian3_default.negate(normal2, normal2);
corner = positions[4];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, east, corner);
corner = positions[5];
Cartesian3_default.add(normal2, north, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[6];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, west, corner);
corner = positions[7];
Cartesian3_default.add(normal2, south, corner);
Cartesian3_default.add(corner, east, corner);
const length3 = positions.length;
for (let i = 0; i < length3; ++i) {
const position = positions[i];
Cartesian3_default.add(center, position, position);
const cartographic2 = ellipsoid.cartesianToCartographic(
position,
projectTo2DCartographicScratch
);
projection.project(cartographic2, position);
}
result = BoundingSphere.fromPoints(positions, result);
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;
};
BoundingSphere.isOccluded = function(sphere, occluder) {
Check_default.typeOf.object("sphere", sphere);
Check_default.typeOf.object("occluder", occluder);
return !occluder.isBoundingSphereVisible(sphere);
};
BoundingSphere.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && Cartesian3_default.equals(left.center, right.center) && left.radius === right.radius;
};
BoundingSphere.prototype.intersectPlane = function(plane) {
return BoundingSphere.intersectPlane(this, plane);
};
BoundingSphere.prototype.distanceSquaredTo = function(cartesian11) {
return BoundingSphere.distanceSquaredTo(this, cartesian11);
};
BoundingSphere.prototype.computePlaneDistances = function(position, direction2, result) {
return BoundingSphere.computePlaneDistances(
this,
position,
direction2,
result
);
};
BoundingSphere.prototype.isOccluded = function(occluder) {
return BoundingSphere.isOccluded(this, occluder);
};
BoundingSphere.prototype.equals = function(right) {
return BoundingSphere.equals(this, right);
};
BoundingSphere.prototype.clone = function(result) {
return BoundingSphere.clone(this, result);
};
BoundingSphere.prototype.volume = function() {
const radius = this.radius;
return volumeConstant * radius * radius * radius;
};
var BoundingSphere_default = BoundingSphere;
// node_modules/@cesium/engine/Source/Core/GeometryAttributes.js
function GeometryAttributes(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.position = options.position;
this.normal = options.normal;
this.st = options.st;
this.bitangent = options.bitangent;
this.tangent = options.tangent;
this.color = options.color;
}
var GeometryAttributes_default = GeometryAttributes;
// node_modules/@cesium/engine/Source/Core/GeometryOffsetAttribute.js
var GeometryOffsetAttribute = {
NONE: 0,
TOP: 1,
ALL: 2
};
var GeometryOffsetAttribute_default = Object.freeze(GeometryOffsetAttribute);
// node_modules/@cesium/engine/Source/Core/VertexFormat.js
function VertexFormat(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.position = defaultValue_default(options.position, false);
this.normal = defaultValue_default(options.normal, false);
this.st = defaultValue_default(options.st, false);
this.bitangent = defaultValue_default(options.bitangent, false);
this.tangent = defaultValue_default(options.tangent, false);
this.color = defaultValue_default(options.color, false);
}
VertexFormat.POSITION_ONLY = Object.freeze(
new VertexFormat({
position: true
})
);
VertexFormat.POSITION_AND_NORMAL = Object.freeze(
new VertexFormat({
position: true,
normal: true
})
);
VertexFormat.POSITION_NORMAL_AND_ST = Object.freeze(
new VertexFormat({
position: true,
normal: true,
st: true
})
);
VertexFormat.POSITION_AND_ST = Object.freeze(
new VertexFormat({
position: true,
st: true
})
);
VertexFormat.POSITION_AND_COLOR = Object.freeze(
new VertexFormat({
position: true,
color: true
})
);
VertexFormat.ALL = Object.freeze(
new VertexFormat({
position: true,
normal: true,
st: true,
tangent: true,
bitangent: true
})
);
VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;
VertexFormat.packedLength = 6;
VertexFormat.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex++] = value.position ? 1 : 0;
array[startingIndex++] = value.normal ? 1 : 0;
array[startingIndex++] = value.st ? 1 : 0;
array[startingIndex++] = value.tangent ? 1 : 0;
array[startingIndex++] = value.bitangent ? 1 : 0;
array[startingIndex] = value.color ? 1 : 0;
return array;
};
VertexFormat.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new VertexFormat();
}
result.position = array[startingIndex++] === 1;
result.normal = array[startingIndex++] === 1;
result.st = array[startingIndex++] === 1;
result.tangent = array[startingIndex++] === 1;
result.bitangent = array[startingIndex++] === 1;
result.color = array[startingIndex] === 1;
return result;
};
VertexFormat.clone = function(vertexFormat, result) {
if (!defined_default(vertexFormat)) {
return void 0;
}
if (!defined_default(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;
};
var VertexFormat_default = VertexFormat;
// node_modules/@cesium/engine/Source/Core/BoxGeometry.js
var diffScratch = new Cartesian3_default();
function BoxGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const min3 = options.minimum;
const max3 = options.maximum;
Check_default.typeOf.object("min", min3);
Check_default.typeOf.object("max", max3);
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
this._minimum = Cartesian3_default.clone(min3);
this._maximum = Cartesian3_default.clone(max3);
this._vertexFormat = vertexFormat;
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createBoxGeometry";
}
BoxGeometry.fromDimensions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const dimensions = options.dimensions;
Check_default.typeOf.object("dimensions", dimensions);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0);
const corner = Cartesian3_default.multiplyByScalar(dimensions, 0.5, new Cartesian3_default());
return new BoxGeometry({
minimum: Cartesian3_default.negate(corner, new Cartesian3_default()),
maximum: corner,
vertexFormat: options.vertexFormat,
offsetAttribute: options.offsetAttribute
});
};
BoxGeometry.fromAxisAlignedBoundingBox = function(boundingBox) {
Check_default.typeOf.object("boundingBox", boundingBox);
return new BoxGeometry({
minimum: boundingBox.minimum,
maximum: boundingBox.maximum
});
};
BoxGeometry.packedLength = 2 * Cartesian3_default.packedLength + VertexFormat_default.packedLength + 1;
BoxGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._minimum, array, startingIndex);
Cartesian3_default.pack(
value._maximum,
array,
startingIndex + Cartesian3_default.packedLength
);
VertexFormat_default.pack(
value._vertexFormat,
array,
startingIndex + 2 * Cartesian3_default.packedLength
);
array[startingIndex + 2 * Cartesian3_default.packedLength + VertexFormat_default.packedLength] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchMin = new Cartesian3_default();
var scratchMax = new Cartesian3_default();
var scratchVertexFormat = new VertexFormat_default();
var scratchOptions = {
minimum: scratchMin,
maximum: scratchMax,
vertexFormat: scratchVertexFormat,
offsetAttribute: void 0
};
BoxGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const min3 = Cartesian3_default.unpack(array, startingIndex, scratchMin);
const max3 = Cartesian3_default.unpack(
array,
startingIndex + Cartesian3_default.packedLength,
scratchMax
);
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex + 2 * Cartesian3_default.packedLength,
scratchVertexFormat
);
const offsetAttribute = array[startingIndex + 2 * Cartesian3_default.packedLength + VertexFormat_default.packedLength];
if (!defined_default(result)) {
scratchOptions.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new BoxGeometry(scratchOptions);
}
result._minimum = Cartesian3_default.clone(min3, result._minimum);
result._maximum = Cartesian3_default.clone(max3, result._maximum);
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
BoxGeometry.createGeometry = function(boxGeometry) {
const min3 = boxGeometry._minimum;
const max3 = boxGeometry._maximum;
const vertexFormat = boxGeometry._vertexFormat;
if (Cartesian3_default.equals(min3, max3)) {
return;
}
const attributes = new GeometryAttributes_default();
let indices2;
let positions;
if (vertexFormat.position && (vertexFormat.st || vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent)) {
if (vertexFormat.position) {
positions = new Float64Array(6 * 4 * 3);
positions[0] = min3.x;
positions[1] = min3.y;
positions[2] = max3.z;
positions[3] = max3.x;
positions[4] = min3.y;
positions[5] = max3.z;
positions[6] = max3.x;
positions[7] = max3.y;
positions[8] = max3.z;
positions[9] = min3.x;
positions[10] = max3.y;
positions[11] = max3.z;
positions[12] = min3.x;
positions[13] = min3.y;
positions[14] = min3.z;
positions[15] = max3.x;
positions[16] = min3.y;
positions[17] = min3.z;
positions[18] = max3.x;
positions[19] = max3.y;
positions[20] = min3.z;
positions[21] = min3.x;
positions[22] = max3.y;
positions[23] = min3.z;
positions[24] = max3.x;
positions[25] = min3.y;
positions[26] = min3.z;
positions[27] = max3.x;
positions[28] = max3.y;
positions[29] = min3.z;
positions[30] = max3.x;
positions[31] = max3.y;
positions[32] = max3.z;
positions[33] = max3.x;
positions[34] = min3.y;
positions[35] = max3.z;
positions[36] = min3.x;
positions[37] = min3.y;
positions[38] = min3.z;
positions[39] = min3.x;
positions[40] = max3.y;
positions[41] = min3.z;
positions[42] = min3.x;
positions[43] = max3.y;
positions[44] = max3.z;
positions[45] = min3.x;
positions[46] = min3.y;
positions[47] = max3.z;
positions[48] = min3.x;
positions[49] = max3.y;
positions[50] = min3.z;
positions[51] = max3.x;
positions[52] = max3.y;
positions[53] = min3.z;
positions[54] = max3.x;
positions[55] = max3.y;
positions[56] = max3.z;
positions[57] = min3.x;
positions[58] = max3.y;
positions[59] = max3.z;
positions[60] = min3.x;
positions[61] = min3.y;
positions[62] = min3.z;
positions[63] = max3.x;
positions[64] = min3.y;
positions[65] = min3.z;
positions[66] = max3.x;
positions[67] = min3.y;
positions[68] = max3.z;
positions[69] = min3.x;
positions[70] = min3.y;
positions[71] = max3.z;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
}
if (vertexFormat.normal) {
const normals = new Float32Array(6 * 4 * 3);
normals[0] = 0;
normals[1] = 0;
normals[2] = 1;
normals[3] = 0;
normals[4] = 0;
normals[5] = 1;
normals[6] = 0;
normals[7] = 0;
normals[8] = 1;
normals[9] = 0;
normals[10] = 0;
normals[11] = 1;
normals[12] = 0;
normals[13] = 0;
normals[14] = -1;
normals[15] = 0;
normals[16] = 0;
normals[17] = -1;
normals[18] = 0;
normals[19] = 0;
normals[20] = -1;
normals[21] = 0;
normals[22] = 0;
normals[23] = -1;
normals[24] = 1;
normals[25] = 0;
normals[26] = 0;
normals[27] = 1;
normals[28] = 0;
normals[29] = 0;
normals[30] = 1;
normals[31] = 0;
normals[32] = 0;
normals[33] = 1;
normals[34] = 0;
normals[35] = 0;
normals[36] = -1;
normals[37] = 0;
normals[38] = 0;
normals[39] = -1;
normals[40] = 0;
normals[41] = 0;
normals[42] = -1;
normals[43] = 0;
normals[44] = 0;
normals[45] = -1;
normals[46] = 0;
normals[47] = 0;
normals[48] = 0;
normals[49] = 1;
normals[50] = 0;
normals[51] = 0;
normals[52] = 1;
normals[53] = 0;
normals[54] = 0;
normals[55] = 1;
normals[56] = 0;
normals[57] = 0;
normals[58] = 1;
normals[59] = 0;
normals[60] = 0;
normals[61] = -1;
normals[62] = 0;
normals[63] = 0;
normals[64] = -1;
normals[65] = 0;
normals[66] = 0;
normals[67] = -1;
normals[68] = 0;
normals[69] = 0;
normals[70] = -1;
normals[71] = 0;
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.st) {
const texCoords = new Float32Array(6 * 4 * 2);
texCoords[0] = 0;
texCoords[1] = 0;
texCoords[2] = 1;
texCoords[3] = 0;
texCoords[4] = 1;
texCoords[5] = 1;
texCoords[6] = 0;
texCoords[7] = 1;
texCoords[8] = 1;
texCoords[9] = 0;
texCoords[10] = 0;
texCoords[11] = 0;
texCoords[12] = 0;
texCoords[13] = 1;
texCoords[14] = 1;
texCoords[15] = 1;
texCoords[16] = 0;
texCoords[17] = 0;
texCoords[18] = 1;
texCoords[19] = 0;
texCoords[20] = 1;
texCoords[21] = 1;
texCoords[22] = 0;
texCoords[23] = 1;
texCoords[24] = 1;
texCoords[25] = 0;
texCoords[26] = 0;
texCoords[27] = 0;
texCoords[28] = 0;
texCoords[29] = 1;
texCoords[30] = 1;
texCoords[31] = 1;
texCoords[32] = 1;
texCoords[33] = 0;
texCoords[34] = 0;
texCoords[35] = 0;
texCoords[36] = 0;
texCoords[37] = 1;
texCoords[38] = 1;
texCoords[39] = 1;
texCoords[40] = 0;
texCoords[41] = 0;
texCoords[42] = 1;
texCoords[43] = 0;
texCoords[44] = 1;
texCoords[45] = 1;
texCoords[46] = 0;
texCoords[47] = 1;
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: texCoords
});
}
if (vertexFormat.tangent) {
const tangents = new Float32Array(6 * 4 * 3);
tangents[0] = 1;
tangents[1] = 0;
tangents[2] = 0;
tangents[3] = 1;
tangents[4] = 0;
tangents[5] = 0;
tangents[6] = 1;
tangents[7] = 0;
tangents[8] = 0;
tangents[9] = 1;
tangents[10] = 0;
tangents[11] = 0;
tangents[12] = -1;
tangents[13] = 0;
tangents[14] = 0;
tangents[15] = -1;
tangents[16] = 0;
tangents[17] = 0;
tangents[18] = -1;
tangents[19] = 0;
tangents[20] = 0;
tangents[21] = -1;
tangents[22] = 0;
tangents[23] = 0;
tangents[24] = 0;
tangents[25] = 1;
tangents[26] = 0;
tangents[27] = 0;
tangents[28] = 1;
tangents[29] = 0;
tangents[30] = 0;
tangents[31] = 1;
tangents[32] = 0;
tangents[33] = 0;
tangents[34] = 1;
tangents[35] = 0;
tangents[36] = 0;
tangents[37] = -1;
tangents[38] = 0;
tangents[39] = 0;
tangents[40] = -1;
tangents[41] = 0;
tangents[42] = 0;
tangents[43] = -1;
tangents[44] = 0;
tangents[45] = 0;
tangents[46] = -1;
tangents[47] = 0;
tangents[48] = -1;
tangents[49] = 0;
tangents[50] = 0;
tangents[51] = -1;
tangents[52] = 0;
tangents[53] = 0;
tangents[54] = -1;
tangents[55] = 0;
tangents[56] = 0;
tangents[57] = -1;
tangents[58] = 0;
tangents[59] = 0;
tangents[60] = 1;
tangents[61] = 0;
tangents[62] = 0;
tangents[63] = 1;
tangents[64] = 0;
tangents[65] = 0;
tangents[66] = 1;
tangents[67] = 0;
tangents[68] = 0;
tangents[69] = 1;
tangents[70] = 0;
tangents[71] = 0;
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
const bitangents = new Float32Array(6 * 4 * 3);
bitangents[0] = 0;
bitangents[1] = 1;
bitangents[2] = 0;
bitangents[3] = 0;
bitangents[4] = 1;
bitangents[5] = 0;
bitangents[6] = 0;
bitangents[7] = 1;
bitangents[8] = 0;
bitangents[9] = 0;
bitangents[10] = 1;
bitangents[11] = 0;
bitangents[12] = 0;
bitangents[13] = 1;
bitangents[14] = 0;
bitangents[15] = 0;
bitangents[16] = 1;
bitangents[17] = 0;
bitangents[18] = 0;
bitangents[19] = 1;
bitangents[20] = 0;
bitangents[21] = 0;
bitangents[22] = 1;
bitangents[23] = 0;
bitangents[24] = 0;
bitangents[25] = 0;
bitangents[26] = 1;
bitangents[27] = 0;
bitangents[28] = 0;
bitangents[29] = 1;
bitangents[30] = 0;
bitangents[31] = 0;
bitangents[32] = 1;
bitangents[33] = 0;
bitangents[34] = 0;
bitangents[35] = 1;
bitangents[36] = 0;
bitangents[37] = 0;
bitangents[38] = 1;
bitangents[39] = 0;
bitangents[40] = 0;
bitangents[41] = 1;
bitangents[42] = 0;
bitangents[43] = 0;
bitangents[44] = 1;
bitangents[45] = 0;
bitangents[46] = 0;
bitangents[47] = 1;
bitangents[48] = 0;
bitangents[49] = 0;
bitangents[50] = 1;
bitangents[51] = 0;
bitangents[52] = 0;
bitangents[53] = 1;
bitangents[54] = 0;
bitangents[55] = 0;
bitangents[56] = 1;
bitangents[57] = 0;
bitangents[58] = 0;
bitangents[59] = 1;
bitangents[60] = 0;
bitangents[61] = 0;
bitangents[62] = 1;
bitangents[63] = 0;
bitangents[64] = 0;
bitangents[65] = 1;
bitangents[66] = 0;
bitangents[67] = 0;
bitangents[68] = 1;
bitangents[69] = 0;
bitangents[70] = 0;
bitangents[71] = 1;
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
indices2 = new Uint16Array(6 * 2 * 3);
indices2[0] = 0;
indices2[1] = 1;
indices2[2] = 2;
indices2[3] = 0;
indices2[4] = 2;
indices2[5] = 3;
indices2[6] = 4 + 2;
indices2[7] = 4 + 1;
indices2[8] = 4 + 0;
indices2[9] = 4 + 3;
indices2[10] = 4 + 2;
indices2[11] = 4 + 0;
indices2[12] = 8 + 0;
indices2[13] = 8 + 1;
indices2[14] = 8 + 2;
indices2[15] = 8 + 0;
indices2[16] = 8 + 2;
indices2[17] = 8 + 3;
indices2[18] = 12 + 2;
indices2[19] = 12 + 1;
indices2[20] = 12 + 0;
indices2[21] = 12 + 3;
indices2[22] = 12 + 2;
indices2[23] = 12 + 0;
indices2[24] = 16 + 2;
indices2[25] = 16 + 1;
indices2[26] = 16 + 0;
indices2[27] = 16 + 3;
indices2[28] = 16 + 2;
indices2[29] = 16 + 0;
indices2[30] = 20 + 0;
indices2[31] = 20 + 1;
indices2[32] = 20 + 2;
indices2[33] = 20 + 0;
indices2[34] = 20 + 2;
indices2[35] = 20 + 3;
} else {
positions = new Float64Array(8 * 3);
positions[0] = min3.x;
positions[1] = min3.y;
positions[2] = min3.z;
positions[3] = max3.x;
positions[4] = min3.y;
positions[5] = min3.z;
positions[6] = max3.x;
positions[7] = max3.y;
positions[8] = min3.z;
positions[9] = min3.x;
positions[10] = max3.y;
positions[11] = min3.z;
positions[12] = min3.x;
positions[13] = min3.y;
positions[14] = max3.z;
positions[15] = max3.x;
positions[16] = min3.y;
positions[17] = max3.z;
positions[18] = max3.x;
positions[19] = max3.y;
positions[20] = max3.z;
positions[21] = min3.x;
positions[22] = max3.y;
positions[23] = max3.z;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
indices2 = new Uint16Array(6 * 2 * 3);
indices2[0] = 4;
indices2[1] = 5;
indices2[2] = 6;
indices2[3] = 4;
indices2[4] = 6;
indices2[5] = 7;
indices2[6] = 1;
indices2[7] = 0;
indices2[8] = 3;
indices2[9] = 1;
indices2[10] = 3;
indices2[11] = 2;
indices2[12] = 1;
indices2[13] = 6;
indices2[14] = 5;
indices2[15] = 1;
indices2[16] = 2;
indices2[17] = 6;
indices2[18] = 2;
indices2[19] = 3;
indices2[20] = 7;
indices2[21] = 2;
indices2[22] = 7;
indices2[23] = 6;
indices2[24] = 3;
indices2[25] = 0;
indices2[26] = 4;
indices2[27] = 3;
indices2[28] = 4;
indices2[29] = 7;
indices2[30] = 0;
indices2[31] = 1;
indices2[32] = 5;
indices2[33] = 0;
indices2[34] = 5;
indices2[35] = 4;
}
const diff = Cartesian3_default.subtract(max3, min3, diffScratch);
const radius = Cartesian3_default.magnitude(diff) * 0.5;
if (defined_default(boxGeometry._offsetAttribute)) {
const length3 = positions.length;
const offsetValue = boxGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere: new BoundingSphere_default(Cartesian3_default.ZERO, radius),
offsetAttribute: boxGeometry._offsetAttribute
});
};
var unitBoxGeometry;
BoxGeometry.getUnitBox = function() {
if (!defined_default(unitBoxGeometry)) {
unitBoxGeometry = BoxGeometry.createGeometry(
BoxGeometry.fromDimensions({
dimensions: new Cartesian3_default(1, 1, 1),
vertexFormat: VertexFormat_default.POSITION_ONLY
})
);
}
return unitBoxGeometry;
};
var BoxGeometry_default = BoxGeometry;
// node_modules/@cesium/engine/Source/Core/BoxOutlineGeometry.js
var diffScratch2 = new Cartesian3_default();
function BoxOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const min3 = options.minimum;
const max3 = options.maximum;
Check_default.typeOf.object("min", min3);
Check_default.typeOf.object("max", max3);
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
this._min = Cartesian3_default.clone(min3);
this._max = Cartesian3_default.clone(max3);
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createBoxOutlineGeometry";
}
BoxOutlineGeometry.fromDimensions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const dimensions = options.dimensions;
Check_default.typeOf.object("dimensions", dimensions);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.x", dimensions.x, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.y", dimensions.y, 0);
Check_default.typeOf.number.greaterThanOrEquals("dimensions.z", dimensions.z, 0);
const corner = Cartesian3_default.multiplyByScalar(dimensions, 0.5, new Cartesian3_default());
return new BoxOutlineGeometry({
minimum: Cartesian3_default.negate(corner, new Cartesian3_default()),
maximum: corner,
offsetAttribute: options.offsetAttribute
});
};
BoxOutlineGeometry.fromAxisAlignedBoundingBox = function(boundingBox) {
Check_default.typeOf.object("boundindBox", boundingBox);
return new BoxOutlineGeometry({
minimum: boundingBox.minimum,
maximum: boundingBox.maximum
});
};
BoxOutlineGeometry.packedLength = 2 * Cartesian3_default.packedLength + 1;
BoxOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._min, array, startingIndex);
Cartesian3_default.pack(value._max, array, startingIndex + Cartesian3_default.packedLength);
array[startingIndex + Cartesian3_default.packedLength * 2] = defaultValue_default(
value._offsetAttribute,
-1
);
return array;
};
var scratchMin2 = new Cartesian3_default();
var scratchMax2 = new Cartesian3_default();
var scratchOptions2 = {
minimum: scratchMin2,
maximum: scratchMax2,
offsetAttribute: void 0
};
BoxOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const min3 = Cartesian3_default.unpack(array, startingIndex, scratchMin2);
const max3 = Cartesian3_default.unpack(
array,
startingIndex + Cartesian3_default.packedLength,
scratchMax2
);
const offsetAttribute = array[startingIndex + Cartesian3_default.packedLength * 2];
if (!defined_default(result)) {
scratchOptions2.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new BoxOutlineGeometry(scratchOptions2);
}
result._min = Cartesian3_default.clone(min3, result._min);
result._max = Cartesian3_default.clone(max3, result._max);
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
BoxOutlineGeometry.createGeometry = function(boxGeometry) {
const min3 = boxGeometry._min;
const max3 = boxGeometry._max;
if (Cartesian3_default.equals(min3, max3)) {
return;
}
const attributes = new GeometryAttributes_default();
const indices2 = new Uint16Array(12 * 2);
const positions = new Float64Array(8 * 3);
positions[0] = min3.x;
positions[1] = min3.y;
positions[2] = min3.z;
positions[3] = max3.x;
positions[4] = min3.y;
positions[5] = min3.z;
positions[6] = max3.x;
positions[7] = max3.y;
positions[8] = min3.z;
positions[9] = min3.x;
positions[10] = max3.y;
positions[11] = min3.z;
positions[12] = min3.x;
positions[13] = min3.y;
positions[14] = max3.z;
positions[15] = max3.x;
positions[16] = min3.y;
positions[17] = max3.z;
positions[18] = max3.x;
positions[19] = max3.y;
positions[20] = max3.z;
positions[21] = min3.x;
positions[22] = max3.y;
positions[23] = max3.z;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
indices2[0] = 4;
indices2[1] = 5;
indices2[2] = 5;
indices2[3] = 6;
indices2[4] = 6;
indices2[5] = 7;
indices2[6] = 7;
indices2[7] = 4;
indices2[8] = 0;
indices2[9] = 1;
indices2[10] = 1;
indices2[11] = 2;
indices2[12] = 2;
indices2[13] = 3;
indices2[14] = 3;
indices2[15] = 0;
indices2[16] = 0;
indices2[17] = 4;
indices2[18] = 1;
indices2[19] = 5;
indices2[20] = 2;
indices2[21] = 6;
indices2[22] = 3;
indices2[23] = 7;
const diff = Cartesian3_default.subtract(max3, min3, diffScratch2);
const radius = Cartesian3_default.magnitude(diff) * 0.5;
if (defined_default(boxGeometry._offsetAttribute)) {
const length3 = positions.length;
const offsetValue = boxGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES,
boundingSphere: new BoundingSphere_default(Cartesian3_default.ZERO, radius),
offsetAttribute: boxGeometry._offsetAttribute
});
};
var BoxOutlineGeometry_default = BoxOutlineGeometry;
// node_modules/@cesium/engine/Source/Core/ColorGeometryInstanceAttribute.js
function ColorGeometryInstanceAttribute(red, green, blue, alpha) {
red = defaultValue_default(red, 1);
green = defaultValue_default(green, 1);
blue = defaultValue_default(blue, 1);
alpha = defaultValue_default(alpha, 1);
this.value = new Uint8Array([
Color_default.floatToByte(red),
Color_default.floatToByte(green),
Color_default.floatToByte(blue),
Color_default.floatToByte(alpha)
]);
}
Object.defineProperties(ColorGeometryInstanceAttribute.prototype, {
componentDatatype: {
get: function() {
return ComponentDatatype_default.UNSIGNED_BYTE;
}
},
componentsPerAttribute: {
get: function() {
return 4;
}
},
normalize: {
get: function() {
return true;
}
}
});
ColorGeometryInstanceAttribute.fromColor = function(color) {
if (!defined_default(color)) {
throw new DeveloperError_default("color is required.");
}
return new ColorGeometryInstanceAttribute(
color.red,
color.green,
color.blue,
color.alpha
);
};
ColorGeometryInstanceAttribute.toValue = function(color, result) {
if (!defined_default(color)) {
throw new DeveloperError_default("color is required.");
}
if (!defined_default(result)) {
return new Uint8Array(color.toBytes());
}
return color.toBytes(result);
};
ColorGeometryInstanceAttribute.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(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];
};
var ColorGeometryInstanceAttribute_default = ColorGeometryInstanceAttribute;
// node_modules/@cesium/engine/Source/Core/DistanceDisplayConditionGeometryInstanceAttribute.js
function DistanceDisplayConditionGeometryInstanceAttribute(near, far) {
near = defaultValue_default(near, 0);
far = defaultValue_default(far, Number.MAX_VALUE);
if (far <= near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
this.value = new Float32Array([near, far]);
}
Object.defineProperties(
DistanceDisplayConditionGeometryInstanceAttribute.prototype,
{
componentDatatype: {
get: function() {
return ComponentDatatype_default.FLOAT;
}
},
componentsPerAttribute: {
get: function() {
return 2;
}
},
normalize: {
get: function() {
return false;
}
}
}
);
DistanceDisplayConditionGeometryInstanceAttribute.fromDistanceDisplayCondition = function(distanceDisplayCondition) {
if (!defined_default(distanceDisplayCondition)) {
throw new DeveloperError_default("distanceDisplayCondition is required.");
}
if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
throw new DeveloperError_default(
"distanceDisplayCondition.far distance must be greater than distanceDisplayCondition.near distance."
);
}
return new DistanceDisplayConditionGeometryInstanceAttribute(
distanceDisplayCondition.near,
distanceDisplayCondition.far
);
};
DistanceDisplayConditionGeometryInstanceAttribute.toValue = function(distanceDisplayCondition, result) {
if (!defined_default(distanceDisplayCondition)) {
throw new DeveloperError_default("distanceDisplayCondition is required.");
}
if (!defined_default(result)) {
return new Float32Array([
distanceDisplayCondition.near,
distanceDisplayCondition.far
]);
}
result[0] = distanceDisplayCondition.near;
result[1] = distanceDisplayCondition.far;
return result;
};
var DistanceDisplayConditionGeometryInstanceAttribute_default = DistanceDisplayConditionGeometryInstanceAttribute;
// node_modules/@cesium/engine/Source/Core/GeometryInstance.js
function GeometryInstance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.geometry)) {
throw new DeveloperError_default("options.geometry is required.");
}
this.geometry = options.geometry;
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this.id = options.id;
this.pickPrimitive = options.pickPrimitive;
this.attributes = defaultValue_default(options.attributes, {});
this.westHemisphereGeometry = void 0;
this.eastHemisphereGeometry = void 0;
}
var GeometryInstance_default = GeometryInstance;
// node_modules/@cesium/engine/Source/Core/TimeInterval.js
function TimeInterval(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.start = defined_default(options.start) ? JulianDate_default.clone(options.start) : new JulianDate_default();
this.stop = defined_default(options.stop) ? JulianDate_default.clone(options.stop) : new JulianDate_default();
this.data = options.data;
this.isStartIncluded = defaultValue_default(options.isStartIncluded, true);
this.isStopIncluded = defaultValue_default(options.isStopIncluded, true);
}
Object.defineProperties(TimeInterval.prototype, {
isEmpty: {
get: function() {
const stopComparedToStart = JulianDate_default.compare(this.stop, this.start);
return stopComparedToStart < 0 || stopComparedToStart === 0 && (!this.isStartIncluded || !this.isStopIncluded);
}
}
});
var scratchInterval = {
start: void 0,
stop: void 0,
isStartIncluded: void 0,
isStopIncluded: void 0,
data: void 0
};
TimeInterval.fromIso8601 = function(options, result) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.string("options.iso8601", options.iso8601);
const dates = options.iso8601.split("/");
if (dates.length !== 2) {
throw new DeveloperError_default(
"options.iso8601 is an invalid ISO 8601 interval."
);
}
const start = JulianDate_default.fromIso8601(dates[0]);
const stop2 = JulianDate_default.fromIso8601(dates[1]);
const isStartIncluded = defaultValue_default(options.isStartIncluded, true);
const isStopIncluded = defaultValue_default(options.isStopIncluded, true);
const data = options.data;
if (!defined_default(result)) {
scratchInterval.start = start;
scratchInterval.stop = stop2;
scratchInterval.isStartIncluded = isStartIncluded;
scratchInterval.isStopIncluded = isStopIncluded;
scratchInterval.data = data;
return new TimeInterval(scratchInterval);
}
result.start = start;
result.stop = stop2;
result.isStartIncluded = isStartIncluded;
result.isStopIncluded = isStopIncluded;
result.data = data;
return result;
};
TimeInterval.toIso8601 = function(timeInterval, precision) {
Check_default.typeOf.object("timeInterval", timeInterval);
return `${JulianDate_default.toIso8601(
timeInterval.start,
precision
)}/${JulianDate_default.toIso8601(timeInterval.stop, precision)}`;
};
TimeInterval.clone = function(timeInterval, result) {
if (!defined_default(timeInterval)) {
return void 0;
}
if (!defined_default(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;
};
TimeInterval.equals = function(left, right, dataComparer) {
return left === right || defined_default(left) && defined_default(right) && (left.isEmpty && right.isEmpty || left.isStartIncluded === right.isStartIncluded && left.isStopIncluded === right.isStopIncluded && JulianDate_default.equals(left.start, right.start) && JulianDate_default.equals(left.stop, right.stop) && (left.data === right.data || defined_default(dataComparer) && dataComparer(left.data, right.data)));
};
TimeInterval.equalsEpsilon = function(left, right, epsilon, dataComparer) {
epsilon = defaultValue_default(epsilon, 0);
return left === right || defined_default(left) && defined_default(right) && (left.isEmpty && right.isEmpty || left.isStartIncluded === right.isStartIncluded && left.isStopIncluded === right.isStopIncluded && JulianDate_default.equalsEpsilon(left.start, right.start, epsilon) && JulianDate_default.equalsEpsilon(left.stop, right.stop, epsilon) && (left.data === right.data || defined_default(dataComparer) && dataComparer(left.data, right.data)));
};
TimeInterval.intersect = function(left, right, result, mergeCallback) {
Check_default.typeOf.object("left", left);
if (!defined_default(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_default.greaterThanOrEquals(rightStart, leftStart) && JulianDate_default.greaterThanOrEquals(leftStop, rightStart);
const intersectsStartLeft = !intersectsStartRight && JulianDate_default.lessThanOrEquals(rightStart, leftStart) && JulianDate_default.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_default.lessThan(leftStop, rightStop);
if (!defined_default(result)) {
result = new TimeInterval();
}
result.start = intersectsStartRight ? rightStart : leftStart;
result.isStartIncluded = leftIsStartIncluded && rightIsStartIncluded || !JulianDate_default.equals(rightStart, leftStart) && (intersectsStartRight && rightIsStartIncluded || intersectsStartLeft && leftIsStartIncluded);
result.stop = leftLessThanRight ? leftStop : rightStop;
result.isStopIncluded = leftLessThanRight ? leftIsStopIncluded : leftIsStopIncluded && rightIsStopIncluded || !JulianDate_default.equals(rightStop, leftStop) && rightIsStopIncluded;
result.data = defined_default(mergeCallback) ? mergeCallback(left.data, right.data) : left.data;
return result;
};
TimeInterval.contains = function(timeInterval, julianDate) {
Check_default.typeOf.object("timeInterval", timeInterval);
Check_default.typeOf.object("julianDate", julianDate);
if (timeInterval.isEmpty) {
return false;
}
const startComparedToDate = JulianDate_default.compare(
timeInterval.start,
julianDate
);
if (startComparedToDate === 0) {
return timeInterval.isStartIncluded;
}
const dateComparedToStop = JulianDate_default.compare(julianDate, timeInterval.stop);
if (dateComparedToStop === 0) {
return timeInterval.isStopIncluded;
}
return startComparedToDate < 0 && dateComparedToStop < 0;
};
TimeInterval.prototype.clone = function(result) {
return TimeInterval.clone(this, result);
};
TimeInterval.prototype.equals = function(right, dataComparer) {
return TimeInterval.equals(this, right, dataComparer);
};
TimeInterval.prototype.equalsEpsilon = function(right, epsilon, dataComparer) {
return TimeInterval.equalsEpsilon(this, right, epsilon, dataComparer);
};
TimeInterval.prototype.toString = function() {
return TimeInterval.toIso8601(this);
};
TimeInterval.EMPTY = Object.freeze(
new TimeInterval({
start: new JulianDate_default(),
stop: new JulianDate_default(),
isStartIncluded: false,
isStopIncluded: false
})
);
var TimeInterval_default = TimeInterval;
// node_modules/@cesium/engine/Source/Core/Iso8601.js
var MINIMUM_VALUE = Object.freeze(
JulianDate_default.fromIso8601("0000-01-01T00:00:00Z")
);
var MAXIMUM_VALUE = Object.freeze(
JulianDate_default.fromIso8601("9999-12-31T24:00:00Z")
);
var MAXIMUM_INTERVAL = Object.freeze(
new TimeInterval_default({
start: MINIMUM_VALUE,
stop: MAXIMUM_VALUE
})
);
var Iso8601 = {
MINIMUM_VALUE,
MAXIMUM_VALUE,
MAXIMUM_INTERVAL
};
var Iso8601_default = Iso8601;
// node_modules/@cesium/engine/Source/Core/OffsetGeometryInstanceAttribute.js
function OffsetGeometryInstanceAttribute(x, y, z) {
x = defaultValue_default(x, 0);
y = defaultValue_default(y, 0);
z = defaultValue_default(z, 0);
this.value = new Float32Array([x, y, z]);
}
Object.defineProperties(OffsetGeometryInstanceAttribute.prototype, {
componentDatatype: {
get: function() {
return ComponentDatatype_default.FLOAT;
}
},
componentsPerAttribute: {
get: function() {
return 3;
}
},
normalize: {
get: function() {
return false;
}
}
});
OffsetGeometryInstanceAttribute.fromCartesian3 = function(offset2) {
Check_default.defined("offset", offset2);
return new OffsetGeometryInstanceAttribute(offset2.x, offset2.y, offset2.z);
};
OffsetGeometryInstanceAttribute.toValue = function(offset2, result) {
Check_default.defined("offset", offset2);
if (!defined_default(result)) {
result = new Float32Array([offset2.x, offset2.y, offset2.z]);
}
result[0] = offset2.x;
result[1] = offset2.y;
result[2] = offset2.z;
return result;
};
var OffsetGeometryInstanceAttribute_default = OffsetGeometryInstanceAttribute;
// node_modules/@cesium/engine/Source/Core/ShowGeometryInstanceAttribute.js
function ShowGeometryInstanceAttribute(show) {
show = defaultValue_default(show, true);
this.value = ShowGeometryInstanceAttribute.toValue(show);
}
Object.defineProperties(ShowGeometryInstanceAttribute.prototype, {
componentDatatype: {
get: function() {
return ComponentDatatype_default.UNSIGNED_BYTE;
}
},
componentsPerAttribute: {
get: function() {
return 1;
}
},
normalize: {
get: function() {
return false;
}
}
});
ShowGeometryInstanceAttribute.toValue = function(show, result) {
if (!defined_default(show)) {
throw new DeveloperError_default("show is required.");
}
if (!defined_default(result)) {
return new Uint8Array([show]);
}
result[0] = show;
return result;
};
var ShowGeometryInstanceAttribute_default = ShowGeometryInstanceAttribute;
// node_modules/@cesium/engine/Source/Shaders/Appearances/AllMaterialAppearanceFS.js
var AllMaterialAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\nin vec3 v_tangentEC;\nin vec3 v_bitangentEC;\nin vec2 v_st;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n mat3 tangentToEyeMatrix = czm_tangentToEyeSpaceMatrix(v_normalEC, v_tangentEC, v_bitangentEC);\n\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\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\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n#endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/AllMaterialAppearanceVS.js
var AllMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin vec3 tangent;\nin vec3 bitangent;\nin vec2 st;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\nout vec3 v_tangentEC;\nout vec3 v_bitangentEC;\nout vec2 v_st;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n v_tangentEC = czm_normal * tangent; // tangent in eye coordinates\n v_bitangentEC = czm_normal * bitangent; // bitangent in eye coordinates\n v_st = st;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/BasicMaterialAppearanceFS.js
var BasicMaterialAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n\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\n czm_materialInput materialInput;\n materialInput.normalEC = normalEC;\n materialInput.positionToEyeEC = positionToEyeEC;\n czm_material material = czm_getMaterial(materialInput);\n\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n#endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/BasicMaterialAppearanceVS.js
var BasicMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/TexturedMaterialAppearanceFS.js
var TexturedMaterialAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\nin vec2 v_st;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n\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\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\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n#endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/TexturedMaterialAppearanceVS.js
var TexturedMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin vec2 st;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\nout vec2 v_st;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n v_st = st;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// node_modules/@cesium/engine/Source/Scene/BlendEquation.js
var BlendEquation = {
ADD: WebGLConstants_default.FUNC_ADD,
SUBTRACT: WebGLConstants_default.FUNC_SUBTRACT,
REVERSE_SUBTRACT: WebGLConstants_default.FUNC_REVERSE_SUBTRACT,
MIN: WebGLConstants_default.MIN,
MAX: WebGLConstants_default.MAX
};
var BlendEquation_default = Object.freeze(BlendEquation);
// node_modules/@cesium/engine/Source/Scene/BlendFunction.js
var BlendFunction = {
ZERO: WebGLConstants_default.ZERO,
ONE: WebGLConstants_default.ONE,
SOURCE_COLOR: WebGLConstants_default.SRC_COLOR,
ONE_MINUS_SOURCE_COLOR: WebGLConstants_default.ONE_MINUS_SRC_COLOR,
DESTINATION_COLOR: WebGLConstants_default.DST_COLOR,
ONE_MINUS_DESTINATION_COLOR: WebGLConstants_default.ONE_MINUS_DST_COLOR,
SOURCE_ALPHA: WebGLConstants_default.SRC_ALPHA,
ONE_MINUS_SOURCE_ALPHA: WebGLConstants_default.ONE_MINUS_SRC_ALPHA,
DESTINATION_ALPHA: WebGLConstants_default.DST_ALPHA,
ONE_MINUS_DESTINATION_ALPHA: WebGLConstants_default.ONE_MINUS_DST_ALPHA,
CONSTANT_COLOR: WebGLConstants_default.CONSTANT_COLOR,
ONE_MINUS_CONSTANT_COLOR: WebGLConstants_default.ONE_MINUS_CONSTANT_COLOR,
CONSTANT_ALPHA: WebGLConstants_default.CONSTANT_ALPHA,
ONE_MINUS_CONSTANT_ALPHA: WebGLConstants_default.ONE_MINUS_CONSTANT_ALPHA,
SOURCE_ALPHA_SATURATE: WebGLConstants_default.SRC_ALPHA_SATURATE
};
var BlendFunction_default = Object.freeze(BlendFunction);
// node_modules/@cesium/engine/Source/Scene/BlendingState.js
var BlendingState = {
DISABLED: Object.freeze({
enabled: false
}),
ALPHA_BLEND: Object.freeze({
enabled: true,
equationRgb: BlendEquation_default.ADD,
equationAlpha: BlendEquation_default.ADD,
functionSourceRgb: BlendFunction_default.SOURCE_ALPHA,
functionSourceAlpha: BlendFunction_default.ONE,
functionDestinationRgb: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA,
functionDestinationAlpha: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA
}),
PRE_MULTIPLIED_ALPHA_BLEND: Object.freeze({
enabled: true,
equationRgb: BlendEquation_default.ADD,
equationAlpha: BlendEquation_default.ADD,
functionSourceRgb: BlendFunction_default.ONE,
functionSourceAlpha: BlendFunction_default.ONE,
functionDestinationRgb: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA,
functionDestinationAlpha: BlendFunction_default.ONE_MINUS_SOURCE_ALPHA
}),
ADDITIVE_BLEND: Object.freeze({
enabled: true,
equationRgb: BlendEquation_default.ADD,
equationAlpha: BlendEquation_default.ADD,
functionSourceRgb: BlendFunction_default.SOURCE_ALPHA,
functionSourceAlpha: BlendFunction_default.ONE,
functionDestinationRgb: BlendFunction_default.ONE,
functionDestinationAlpha: BlendFunction_default.ONE
})
};
var BlendingState_default = Object.freeze(BlendingState);
// node_modules/@cesium/engine/Source/Scene/CullFace.js
var CullFace = {
FRONT: WebGLConstants_default.FRONT,
BACK: WebGLConstants_default.BACK,
FRONT_AND_BACK: WebGLConstants_default.FRONT_AND_BACK
};
var CullFace_default = Object.freeze(CullFace);
// node_modules/@cesium/engine/Source/Scene/Appearance.js
function Appearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.material = options.material;
this.translucent = defaultValue_default(options.translucent, true);
this._vertexShaderSource = options.vertexShaderSource;
this._fragmentShaderSource = options.fragmentShaderSource;
this._renderState = options.renderState;
this._closed = defaultValue_default(options.closed, false);
}
Object.defineProperties(Appearance.prototype, {
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
renderState: {
get: function() {
return this._renderState;
}
},
closed: {
get: function() {
return this._closed;
}
}
});
Appearance.prototype.getFragmentShaderSource = function() {
const parts = [];
if (this.flat) {
parts.push("#define FLAT");
}
if (this.faceForward) {
parts.push("#define FACE_FORWARD");
}
if (defined_default(this.material)) {
parts.push(this.material.shaderSource);
}
parts.push(this.fragmentShaderSource);
return parts.join("\n");
};
Appearance.prototype.isTranslucent = function() {
return defined_default(this.material) && this.material.isTranslucent() || !defined_default(this.material) && this.translucent;
};
Appearance.prototype.getRenderState = function() {
const translucent = this.isTranslucent();
const rs = clone_default(this.renderState, false);
if (translucent) {
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
} else {
rs.depthMask = true;
}
return rs;
};
Appearance.getDefaultRenderState = function(translucent, closed, existing) {
let rs = {
depthTest: {
enabled: true
}
};
if (translucent) {
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
}
if (closed) {
rs.cull = {
enabled: true,
face: CullFace_default.BACK
};
}
if (defined_default(existing)) {
rs = combine_default(existing, rs, true);
}
return rs;
};
var Appearance_default = Appearance;
// node_modules/@cesium/engine/Source/Shaders/Materials/AspectRampMaterial.js
var AspectRampMaterial_default = "uniform sampler2D image;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n vec4 rampColor = texture(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";
// node_modules/@cesium/engine/Source/Shaders/Materials/BumpMapMaterial.js
var BumpMapMaterial_default = "uniform sampler2D image;\nuniform float strength;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\n vec2 centerPixel = fract(repeat * st);\n float centerBump = texture(image, centerPixel).channel;\n\n float imageWidth = float(imageDimensions.x);\n vec2 rightPixel = fract(repeat * (st + vec2(1.0 / imageWidth, 0.0)));\n float rightBump = texture(image, rightPixel).channel;\n\n float imageHeight = float(imageDimensions.y);\n vec2 leftPixel = fract(repeat * (st + vec2(0.0, 1.0 / imageHeight)));\n float topBump = texture(image, leftPixel).channel;\n\n vec3 normalTangentSpace = normalize(vec3(centerBump - rightBump, centerBump - topBump, clamp(1.0 - strength, 0.1, 1.0)));\n vec3 normalEC = materialInput.tangentToEyeMatrix * normalTangentSpace;\n\n material.normal = normalEC;\n material.diffuse = vec3(0.01);\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/CheckerboardMaterial.js
var CheckerboardMaterial_default = "uniform vec4 lightColor;\nuniform vec4 darkColor;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\n // From Stefan Gustavson's Procedural Textures in GLSL in OpenGL Insights\n float b = mod(floor(repeat.s * st.s) + floor(repeat.t * st.t), 2.0); // 0.0 or 1.0\n\n // Find the distance from the closest separator (region between two colors)\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\n vec4 currentColor = mix(lightColor, darkColor, b);\n vec4 color = czm_antialias(lightColor, darkColor, currentColor, value, 0.03);\n\n color = czm_gammaCorrect(color);\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/DotMaterial.js
var DotMaterial_default = "uniform vec4 lightColor;\nuniform vec4 darkColor;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n // From Stefan Gustavson's Procedural Textures in GLSL in OpenGL Insights\n float b = smoothstep(0.3, 0.32, length(fract(repeat * materialInput.st) - 0.5)); // 0.0 or 1.0\n\n vec4 color = mix(lightColor, darkColor, b);\n color = czm_gammaCorrect(color);\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/ElevationBandMaterial.js
var ElevationBandMaterial_default = "uniform sampler2D heights;\nuniform sampler2D colors;\n\n// This material expects heights to be sorted from lowest to highest.\n\nfloat getHeight(int idx, float invTexSize)\n{\n vec2 uv = vec2((float(idx) + 0.5) * invTexSize, 0.5);\n#ifdef OES_texture_float\n return texture(heights, uv).x;\n#else\n return czm_unpackFloat(texture(heights, uv));\n#endif\n}\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n float height = materialInput.height;\n float invTexSize = 1.0 / float(heightsDimensions.x);\n\n float minHeight = getHeight(0, invTexSize);\n float maxHeight = getHeight(heightsDimensions.x - 1, invTexSize);\n\n // early-out when outside the height range\n if (height < minHeight || height > maxHeight) {\n material.diffuse = vec3(0.0);\n material.alpha = 0.0;\n return material;\n }\n\n // Binary search to find heights above and below.\n int idxBelow = 0;\n int idxAbove = heightsDimensions.x;\n float heightBelow = minHeight;\n float heightAbove = maxHeight;\n\n // while loop not allowed, so use for loop with max iterations.\n // maxIterations of 16 supports a texture size up to 65536 (2^16).\n const int maxIterations = 16;\n for (int i = 0; i < maxIterations; i++) {\n if (idxBelow >= idxAbove - 1) {\n break;\n }\n\n int idxMid = (idxBelow + idxAbove) / 2;\n float heightTex = getHeight(idxMid, invTexSize);\n\n if (height > heightTex) {\n idxBelow = idxMid;\n heightBelow = heightTex;\n } else {\n idxAbove = idxMid;\n heightAbove = heightTex;\n }\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 = texture(colors, colorUv);\n\n // undo preumultiplied alpha\n if (color.a > 0.0) \n {\n color.rgb /= color.a;\n }\n \n color.rgb = czm_gammaCorrect(color.rgb);\n\n material.diffuse = color.rgb;\n material.alpha = color.a;\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/ElevationContourMaterial.js
var ElevationContourMaterial_default = "#ifdef GL_OES_standard_derivatives\n #extension GL_OES_standard_derivatives : enable\n#endif\n\nuniform vec4 color;\nuniform float spacing;\nuniform float width;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n float distanceToContour = mod(materialInput.height, spacing);\n\n#if (__VERSION__ == 300 || defined(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 // If no derivatives available (IE 10?), use pixel ratio\n float alpha = (distanceToContour < (czm_pixelRatio * width)) ? 1.0 : 0.0;\n#endif\n\n vec4 outColor = czm_gammaCorrect(vec4(color.rgb, alpha * color.a));\n material.diffuse = outColor.rgb;\n material.alpha = outColor.a;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/ElevationRampMaterial.js
var ElevationRampMaterial_default = "uniform sampler2D image;\nuniform float minimumHeight;\nuniform float maximumHeight;\n\nczm_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 = texture(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";
// node_modules/@cesium/engine/Source/Shaders/Materials/FadeMaterial.js
var FadeMaterial_default = "uniform vec4 fadeInColor;\nuniform vec4 fadeOutColor;\nuniform float maximumDistance;\nuniform bool repeat;\nuniform vec2 fadeDirection;\nuniform vec2 time;\n\nfloat 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\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\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\n float u = length(vec2(s, t));\n vec4 color = mix(fadeInColor, fadeOutColor, u);\n\n color = czm_gammaCorrect(color);\n material.emission = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/GridMaterial.js
var GridMaterial_default = '#ifdef GL_OES_standard_derivatives\n #extension GL_OES_standard_derivatives : enable\n#endif\n\nuniform vec4 color;\nuniform float cellAlpha;\nuniform vec2 lineCount;\nuniform vec2 lineThickness;\nuniform vec2 lineOffset;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\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\n float value;\n\n // Fuzz Factor - Controls blurriness of lines\n#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n const float fuzz = 1.2;\n vec2 thickness = (lineThickness * czm_pixelRatio) - 1.0;\n\n // From "3D Engine Design for Virtual Globes" by Cozzi and Ring, Listing 4.13.\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 // If no derivatives available (IE 10?), revert to view-dependent fuzz\n const float fuzz = 0.05;\n\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\n // Edges taken from RimLightingMaterial.glsl\n // See http://www.fundza.com/rman_shaders/surface/fake_rim/fake_rim1.html\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\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\n return material;\n}\n';
// node_modules/@cesium/engine/Source/Shaders/Materials/NormalMapMaterial.js
var NormalMapMaterial_default = "uniform sampler2D image;\nuniform float strength;\nuniform vec2 repeat;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n \n vec4 textureValue = texture(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 \n material.normal = normalEC;\n \n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/PolylineArrowMaterial.js
var PolylineArrowMaterial_default = "#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives : enable\n#endif\n\nuniform vec4 color;\n\nfloat 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\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n\n#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n float base = 1.0 - abs(fwidth(st.s)) * 10.0 * czm_pixelRatio;\n#else\n // If no derivatives available (IE 10?), 2.5% of the line will be the arrow head\n float base = 0.975;\n#endif\n\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\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\n float t = step(base, materialInput.st.s);\n t *= 1.0 - step(ptOnUpperLine, st.t);\n t *= step(ptOnLowerLine, st.t);\n\n // Find the distance from the closest separator (region between two colors)\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\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\n outColor = czm_gammaCorrect(outColor);\n material.diffuse = outColor.rgb;\n material.alpha = outColor.a;\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/PolylineDashMaterial.js
var PolylineDashMaterial_default = "uniform vec4 color;\nuniform vec4 gapColor;\nuniform float dashLength;\nuniform float dashPattern;\nin float v_polylineAngle;\n\nconst float maskLength = 16.0;\n\nmat2 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\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 pos = rotate(v_polylineAngle) * gl_FragCoord.xy;\n\n // Get the relative position within the dash from 0 to 1\n float dashPosition = fract(pos.x / (dashLength * czm_pixelRatio));\n // Figure out the mask index.\n float maskIndex = floor(dashPosition * maskLength);\n // Test the bit mask.\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) { // matches 0/255 and 1/255\n discard;\n }\n\n fragColor = czm_gammaCorrect(fragColor);\n material.emission = fragColor.rgb;\n material.alpha = fragColor.a;\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/PolylineGlowMaterial.js
var PolylineGlowMaterial_default = "uniform vec4 color;\nuniform float glowPower;\nuniform float taperPower;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n vec2 st = materialInput.st;\n float glow = glowPower / abs(st.t - 0.5) - (glowPower / 0.5);\n\n if (taperPower <= 0.99999) {\n glow *= min(1.0, taperPower / (0.5 - st.s * 0.5) - (taperPower / 0.5));\n }\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\n material.emission = fragColor.rgb;\n material.alpha = fragColor.a;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/PolylineOutlineMaterial.js
var PolylineOutlineMaterial_default = "uniform vec4 color;\nuniform vec4 outlineColor;\nuniform float outlineWidth;\n\nin float v_width;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\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\n // Find the distance from the closest separator (region between two colors)\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\n vec4 currentColor = mix(outlineColor, color, b);\n vec4 outColor = czm_antialias(outlineColor, color, currentColor, dist);\n outColor = czm_gammaCorrect(outColor);\n\n material.diffuse = outColor.rgb;\n material.alpha = outColor.a;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/RimLightingMaterial.js
var RimLightingMaterial_default = "uniform vec4 color;\nuniform vec4 rimColor;\nuniform float width;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n // See http://www.fundza.com/rman_shaders/surface/fake_rim/fake_rim1.html\n float d = 1.0 - dot(materialInput.normalEC, normalize(materialInput.positionToEyeEC));\n float s = smoothstep(1.0 - width, 1.0, d);\n\n vec4 outColor = czm_gammaCorrect(color);\n vec4 outRimColor = czm_gammaCorrect(rimColor);\n\n material.diffuse = outColor.rgb;\n material.emission = outRimColor.rgb * s;\n material.alpha = mix(outColor.a, outRimColor.a, s);\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/SlopeRampMaterial.js
var SlopeRampMaterial_default = "uniform sampler2D image;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n vec4 rampColor = texture(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";
// node_modules/@cesium/engine/Source/Shaders/Materials/StripeMaterial.js
var StripeMaterial_default = "uniform vec4 evenColor;\nuniform vec4 oddColor;\nuniform float offset;\nuniform float repeat;\nuniform bool horizontal;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n // Based on the Stripes Fragment Shader in the Orange Book (11.1.2)\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\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\n material.diffuse = color.rgb;\n material.alpha = color.a;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Materials/Water.js
var Water_default = "// Thanks for the contribution Jonas\n// http://29a.ch/2012/7/19/webgl-terrain-rendering-water-fog\n\nuniform sampler2D specularMap;\nuniform sampler2D normalMap;\nuniform vec4 baseWaterColor;\nuniform vec4 blendColor;\nuniform float frequency;\nuniform float animationSpeed;\nuniform float amplitude;\nuniform float specularIntensity;\nuniform float fadeFactor;\n\nczm_material czm_getMaterial(czm_materialInput materialInput)\n{\n czm_material material = czm_getDefaultMaterial(materialInput);\n\n float time = czm_frameNumber * animationSpeed;\n\n // fade is a function of the distance from the fragment and the frequency of the waves\n float fade = max(1.0, (length(materialInput.positionToEyeEC) / 10000000000.0) * frequency * fadeFactor);\n\n float specularMapValue = texture(specularMap, materialInput.st).r;\n\n // note: not using directional motion at this time, just set the angle to 0.0;\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\n // fade out the normal perturbation as we move further from the water surface\n normalTangentSpace.xy /= fade;\n\n // attempt to fade out the normal perturbation as we approach non water areas (low specular map value)\n normalTangentSpace = mix(vec3(0.0, 0.0, 50.0), normalTangentSpace, specularMapValue);\n\n normalTangentSpace = normalize(normalTangentSpace);\n\n // get ratios for alignment of the new normal vector with a vector perpendicular to the tangent plane\n float tsPerturbationRatio = clamp(dot(normalTangentSpace, vec3(0.0, 0.0, 1.0)), 0.0, 1.0);\n\n // fade out water effect as specular map value decreases\n material.alpha = mix(blendColor.a, baseWaterColor.a, specularMapValue) * specularMapValue;\n\n // base color is a blend of the water and non-water color based on the value from the specular map\n // may need a uniform blend factor to better control this\n material.diffuse = mix(blendColor.rgb, baseWaterColor.rgb, specularMapValue);\n\n // diffuse highlights are based on how perturbed the normal is\n material.diffuse += (0.1 * tsPerturbationRatio);\n\n material.diffuse = material.diffuse;\n\n material.normal = normalize(materialInput.tangentToEyeMatrix * normalTangentSpace);\n\n material.specular = specularIntensity;\n material.shininess = 10.0;\n\n return material;\n}\n";
// node_modules/@cesium/engine/Source/Scene/Material.js
function Material(options) {
this.type = void 0;
this.shaderSource = void 0;
this.materials = void 0;
this.uniforms = void 0;
this._uniforms = void 0;
this.translucent = void 0;
this._minificationFilter = defaultValue_default(
options.minificationFilter,
TextureMinificationFilter_default.LINEAR
);
this._magnificationFilter = defaultValue_default(
options.magnificationFilter,
TextureMagnificationFilter_default.LINEAR
);
this._strict = void 0;
this._template = void 0;
this._count = void 0;
this._texturePaths = {};
this._loadedImages = [];
this._loadedCubeMaps = [];
this._textures = {};
this._updateFunctions = [];
this._defaultTexture = void 0;
initializeMaterial(options, this);
Object.defineProperties(this, {
type: {
value: this.type,
writable: false
}
});
if (!defined_default(Material._uniformList[this.type])) {
Material._uniformList[this.type] = Object.keys(this._uniforms);
}
}
Material._uniformList = {};
Material.fromType = function(type, uniforms) {
if (!defined_default(Material._materialCache.getMaterial(type))) {
throw new DeveloperError_default(`material with type '${type}' does not exist.`);
}
const material = new Material({
fabric: {
type
}
});
if (defined_default(uniforms)) {
for (const name in uniforms) {
if (uniforms.hasOwnProperty(name)) {
material.uniforms[name] = uniforms[name];
}
}
}
return material;
};
Material.prototype.isTranslucent = function() {
if (defined_default(this.translucent)) {
if (typeof this.translucent === "function") {
return this.translucent();
}
return this.translucent;
}
let translucent = true;
const funcs = this._translucentFunctions;
const length3 = funcs.length;
for (let i = 0; i < length3; ++i) {
const func = funcs[i];
if (typeof func === "function") {
translucent = translucent && func();
} else {
translucent = translucent && func;
}
if (!translucent) {
break;
}
}
return translucent;
};
Material.prototype.update = function(context) {
this._defaultTexture = context.defaultTexture;
let i;
let uniformId;
const loadedImages = this._loadedImages;
let length3 = loadedImages.length;
for (i = 0; i < length3; ++i) {
const loadedImage = loadedImages[i];
uniformId = loadedImage.id;
let image = loadedImage.image;
let mipLevels;
if (Array.isArray(image)) {
mipLevels = image.slice(1, image.length).map(function(mipLevel) {
return mipLevel.bufferView;
});
image = image[0];
}
const sampler = new Sampler_default({
minificationFilter: this._minificationFilter,
magnificationFilter: this._magnificationFilter
});
let texture;
if (defined_default(image.internalFormat)) {
texture = new Texture_default({
context,
pixelFormat: image.internalFormat,
width: image.width,
height: image.height,
source: {
arrayBufferView: image.bufferView,
mipLevels
},
sampler
});
} else {
texture = new Texture_default({
context,
source: image,
sampler
});
}
const oldTexture = this._textures[uniformId];
if (defined_default(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;
length3 = loadedCubeMaps.length;
for (i = 0; i < length3; ++i) {
const loadedCubeMap = loadedCubeMaps[i];
uniformId = loadedCubeMap.id;
const images = loadedCubeMap.images;
const cubeMap = new CubeMap_default({
context,
source: {
positiveX: images[0],
negativeX: images[1],
positiveY: images[2],
negativeY: images[3],
positiveZ: images[4],
negativeZ: images[5]
},
sampler: new Sampler_default({
minificationFilter: this._minificationFilter,
magnificationFilter: this._magnificationFilter
})
});
this._textures[uniformId] = cubeMap;
}
loadedCubeMaps.length = 0;
const updateFunctions2 = this._updateFunctions;
length3 = updateFunctions2.length;
for (i = 0; i < length3; ++i) {
updateFunctions2[i](this, context);
}
const subMaterials = this.materials;
for (const name in subMaterials) {
if (subMaterials.hasOwnProperty(name)) {
subMaterials[name].update(context);
}
}
};
Material.prototype.isDestroyed = function() {
return false;
};
Material.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_default(this);
};
function initializeMaterial(options, result) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
result._strict = defaultValue_default(options.strict, false);
result._count = defaultValue_default(options.count, 0);
result._template = clone_default(
defaultValue_default(options.fabric, defaultValue_default.EMPTY_OBJECT)
);
result._template.uniforms = clone_default(
defaultValue_default(result._template.uniforms, defaultValue_default.EMPTY_OBJECT)
);
result._template.materials = clone_default(
defaultValue_default(result._template.materials, defaultValue_default.EMPTY_OBJECT)
);
result.type = defined_default(result._template.type) ? result._template.type : createGuid_default();
result.shaderSource = "";
result.materials = {};
result.uniforms = {};
result._uniforms = {};
result._translucentFunctions = [];
let translucent;
const cachedMaterial = Material._materialCache.getMaterial(result.type);
if (defined_default(cachedMaterial)) {
const template = clone_default(cachedMaterial.fabric, true);
result._template = combine_default(result._template, template, true);
translucent = cachedMaterial.translucent;
}
checkForTemplateErrors(result);
if (!defined_default(cachedMaterial)) {
Material._materialCache.addMaterial(result.type, result);
}
createMethodDefinition(result);
createUniforms(result);
createSubMaterials(result);
const defaultTranslucent = result._translucentFunctions.length === 0 ? true : void 0;
translucent = defaultValue_default(translucent, defaultTranslucent);
translucent = defaultValue_default(options.translucent, translucent);
if (defined_default(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_default(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) {
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_default(errorString);
}
function duplicateNameError(property, properties) {
const errorString = `fabric: uniforms and materials cannot share the same property '${property}'`;
throw new DeveloperError_default(errorString);
}
var templateProperties = [
"type",
"materials",
"uniforms",
"components",
"source"
];
var 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;
if (defined_default(components) && defined_default(template.source)) {
throw new DeveloperError_default(
"fabric: cannot have source and components in the same template."
);
}
checkForValidProperties(template, templateProperties, invalidNameError, true);
checkForValidProperties(
components,
componentProperties,
invalidNameError,
true
);
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;
}
function createMethodDefinition(material) {
const components = material._template.components;
const source = material._template.source;
if (defined_default(source)) {
material.shaderSource += `${source}
`;
} else {
material.shaderSource += "czm_material czm_getMaterial(czm_materialInput materialInput)\n{\n";
material.shaderSource += "czm_material material = czm_getDefaultMaterial(materialInput);\n";
if (defined_default(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};
`;
} else if (component === "alpha") {
material.shaderSource += `material.alpha = ${components.alpha};
`;
} else {
material.shaderSource += `material.${component} = ${components[component]};
`;
}
}
}
}
material.shaderSource += "return material;\n}\n";
}
}
var matrixMap = {
mat2: Matrix2_default,
mat3: Matrix3_default,
mat4: Matrix4_default
};
var ktx2Regex = /\.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_default(uniformValue) || uniformValue === Material.DefaultImageId;
oldUniformValue = uniformValue;
let texture = material._textures[uniformId];
let uniformDimensionsName;
let uniformDimensions;
if (uniformValue instanceof HTMLVideoElement) {
if (uniformValue.readyState >= 2) {
if (uniformChanged && defined_default(texture)) {
if (texture !== context.defaultTexture) {
texture.destroy();
}
texture = void 0;
}
if (!defined_default(texture) || texture === context.defaultTexture) {
const sampler = new Sampler_default({
minificationFilter: material._minificationFilter,
magnificationFilter: material._magnificationFilter
});
texture = new Texture_default({
context,
source: uniformValue,
sampler
});
material._textures[uniformId] = texture;
return;
}
texture.copyFrom({
source: uniformValue
});
} else if (!defined_default(texture)) {
material._textures[uniformId] = context.defaultTexture;
}
return;
}
if (uniformValue instanceof Texture_default && uniformValue !== texture) {
material._texturePaths[uniformId] = void 0;
const tmp2 = material._textures[uniformId];
if (defined_default(tmp2) && tmp2 !== material._defaultTexture) {
tmp2.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_default(texture) && uniformValueIsDefaultImage) {
if (texture !== material._defaultTexture) {
texture.destroy();
}
texture = void 0;
}
if (!defined_default(texture)) {
material._texturePaths[uniformId] = void 0;
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;
}
const isResource = uniformValue instanceof Resource_default;
if (!defined_default(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_default.createIfNeeded(uniformValue);
let promise;
if (ktx2Regex.test(resource.url)) {
promise = loadKTX2_default(resource.url);
} else {
promise = resource.fetchImage();
}
Promise.resolve(promise).then(function(image) {
material._loadedImages.push({
id: uniformId,
image
});
}).catch(function() {
if (defined_default(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_default) {
const tmp2 = material._textures[uniformId];
if (tmp2 !== material._defaultTexture) {
tmp2.destroy();
}
material._texturePaths[uniformId] = void 0;
material._textures[uniformId] = uniformValue;
return;
}
if (!defined_default(material._textures[uniformId])) {
material._texturePaths[uniformId] = void 0;
material._textures[uniformId] = context.defaultCubeMap;
}
if (uniformValue === Material.DefaultCubeMapId) {
return;
}
const path = uniformValue.positiveX + uniformValue.negativeX + uniformValue.positiveY + uniformValue.negativeY + uniformValue.positiveZ + uniformValue.negativeZ;
if (path !== material._texturePaths[uniformId]) {
const promises = [
Resource_default.createIfNeeded(uniformValue.positiveX).fetchImage(),
Resource_default.createIfNeeded(uniformValue.negativeX).fetchImage(),
Resource_default.createIfNeeded(uniformValue.positiveY).fetchImage(),
Resource_default.createIfNeeded(uniformValue.negativeY).fetchImage(),
Resource_default.createIfNeeded(uniformValue.positiveZ).fetchImage(),
Resource_default.createIfNeeded(uniformValue.negativeZ).fetchImage()
];
Promise.all(promises).then(function(images) {
material._loadedCubeMaps.push({
id: uniformId,
images
});
});
material._texturePaths[uniformId] = path;
}
};
}
function createUniforms(material) {
const uniforms = material._template.uniforms;
for (const uniformId in uniforms) {
if (uniforms.hasOwnProperty(uniformId)) {
createUniform2(material, uniformId);
}
}
}
function createUniform2(material, uniformId) {
const strict = material._strict;
const materialUniforms = material._template.uniforms;
const uniformValue = materialUniforms[uniformId];
const uniformType = getUniformType(uniformValue);
if (!defined_default(uniformType)) {
throw new DeveloperError_default(
`fabric: uniform '${uniformId}' has invalid type.`
);
}
let replacedTokenCount;
if (uniformType === "channels") {
replacedTokenCount = replaceToken(material, uniformId, uniformValue, false);
if (replacedTokenCount === 0 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use channels '${uniformId}'.`
);
}
} else {
if (uniformType === "sampler2D") {
const imageDimensionsUniformName = `${uniformId}Dimensions`;
if (getNumberOfTokens(material, imageDimensionsUniformName) > 0) {
materialUniforms[imageDimensionsUniformName] = {
type: "ivec3",
x: 1,
y: 1
};
createUniform2(material, imageDimensionsUniformName);
}
}
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);
if (replacedTokenCount === 1 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use uniform '${uniformId}'.`
);
}
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 scratchMatrix7 = new matrixMap[uniformType]();
material._uniforms[newUniformId] = function() {
return matrixMap[uniformType].fromColumnMajorArray(
material.uniforms[uniformId],
scratchMatrix7
);
};
} else {
material._uniforms[newUniformId] = function() {
return material.uniforms[uniformId];
};
}
}
}
function getUniformType(uniformValue) {
let uniformType = uniformValue.type;
if (!defined_default(uniformType)) {
const type = typeof uniformValue;
if (type === "number") {
uniformType = "float";
} else if (type === "boolean") {
uniformType = "bool";
} else if (type === "string" || uniformValue instanceof Resource_default || uniformValue instanceof HTMLCanvasElement || uniformValue instanceof HTMLImageElement) {
if (/^([rgba]){1,4}$/i.test(uniformValue)) {
uniformType = "channels";
} else if (uniformValue === Material.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;
}
function createSubMaterials(material) {
const strict = material._strict;
const subMaterialTemplates = material._template.materials;
for (const subMaterialId in subMaterialTemplates) {
if (subMaterialTemplates.hasOwnProperty(subMaterialId)) {
const subMaterial = new Material({
strict,
fabric: subMaterialTemplates[subMaterialId],
count: material._count
});
material._count = subMaterial._count;
material._uniforms = combine_default(
material._uniforms,
subMaterial._uniforms,
true
);
material.materials[subMaterialId] = subMaterial;
material._translucentFunctions = material._translucentFunctions.concat(
subMaterial._translucentFunctions
);
const originalMethodName = "czm_getMaterial";
const newMethodName = `${originalMethodName}_${material._count++}`;
replaceToken(subMaterial, originalMethodName, newMethodName);
material.shaderSource = subMaterial.shaderSource + material.shaderSource;
const materialMethodCall = `${newMethodName}(materialInput)`;
const tokensReplacedCount = replaceToken(
material,
subMaterialId,
materialMethodCall
);
if (tokensReplacedCount === 0 && strict) {
throw new DeveloperError_default(
`strict: shader source does not use material '${subMaterialId}'.`
);
}
}
}
}
function replaceToken(material, token, newToken, excludePeriod) {
excludePeriod = defaultValue_default(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._materialCache = {
_materials: {},
addMaterial: function(type, materialTemplate) {
this._materials[type] = materialTemplate;
},
getMaterial: function(type) {
return this._materials[type];
}
};
Material.DefaultImageId = "czm_defaultImage";
Material.DefaultCubeMapId = "czm_defaultCubeMap";
Material.ColorType = "Color";
Material._materialCache.addMaterial(Material.ColorType, {
fabric: {
type: Material.ColorType,
uniforms: {
color: new Color_default(1, 0, 0, 0.5)
},
components: {
diffuse: "color.rgb",
alpha: "color.a"
}
},
translucent: function(material) {
return material.uniforms.color.alpha < 1;
}
});
Material.ImageType = "Image";
Material._materialCache.addMaterial(Material.ImageType, {
fabric: {
type: Material.ImageType,
uniforms: {
image: Material.DefaultImageId,
repeat: new Cartesian2_default(1, 1),
color: new Color_default(1, 1, 1, 1)
},
components: {
diffuse: "texture(image, fract(repeat * materialInput.st)).rgb * color.rgb",
alpha: "texture(image, fract(repeat * materialInput.st)).a * color.a"
}
},
translucent: function(material) {
return material.uniforms.color.alpha < 1;
}
});
Material.DiffuseMapType = "DiffuseMap";
Material._materialCache.addMaterial(Material.DiffuseMapType, {
fabric: {
type: Material.DiffuseMapType,
uniforms: {
image: Material.DefaultImageId,
channels: "rgb",
repeat: new Cartesian2_default(1, 1)
},
components: {
diffuse: "texture(image, fract(repeat * materialInput.st)).channels"
}
},
translucent: false
});
Material.AlphaMapType = "AlphaMap";
Material._materialCache.addMaterial(Material.AlphaMapType, {
fabric: {
type: Material.AlphaMapType,
uniforms: {
image: Material.DefaultImageId,
channel: "a",
repeat: new Cartesian2_default(1, 1)
},
components: {
alpha: "texture(image, fract(repeat * materialInput.st)).channel"
}
},
translucent: true
});
Material.SpecularMapType = "SpecularMap";
Material._materialCache.addMaterial(Material.SpecularMapType, {
fabric: {
type: Material.SpecularMapType,
uniforms: {
image: Material.DefaultImageId,
channel: "r",
repeat: new Cartesian2_default(1, 1)
},
components: {
specular: "texture(image, fract(repeat * materialInput.st)).channel"
}
},
translucent: false
});
Material.EmissionMapType = "EmissionMap";
Material._materialCache.addMaterial(Material.EmissionMapType, {
fabric: {
type: Material.EmissionMapType,
uniforms: {
image: Material.DefaultImageId,
channels: "rgb",
repeat: new Cartesian2_default(1, 1)
},
components: {
emission: "texture(image, fract(repeat * materialInput.st)).channels"
}
},
translucent: false
});
Material.BumpMapType = "BumpMap";
Material._materialCache.addMaterial(Material.BumpMapType, {
fabric: {
type: Material.BumpMapType,
uniforms: {
image: Material.DefaultImageId,
channel: "r",
strength: 0.8,
repeat: new Cartesian2_default(1, 1)
},
source: BumpMapMaterial_default
},
translucent: false
});
Material.NormalMapType = "NormalMap";
Material._materialCache.addMaterial(Material.NormalMapType, {
fabric: {
type: Material.NormalMapType,
uniforms: {
image: Material.DefaultImageId,
channels: "rgb",
strength: 0.8,
repeat: new Cartesian2_default(1, 1)
},
source: NormalMapMaterial_default
},
translucent: false
});
Material.GridType = "Grid";
Material._materialCache.addMaterial(Material.GridType, {
fabric: {
type: Material.GridType,
uniforms: {
color: new Color_default(0, 1, 0, 1),
cellAlpha: 0.1,
lineCount: new Cartesian2_default(8, 8),
lineThickness: new Cartesian2_default(1, 1),
lineOffset: new Cartesian2_default(0, 0)
},
source: GridMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.color.alpha < 1 || uniforms.cellAlpha < 1;
}
});
Material.StripeType = "Stripe";
Material._materialCache.addMaterial(Material.StripeType, {
fabric: {
type: Material.StripeType,
uniforms: {
horizontal: true,
evenColor: new Color_default(1, 1, 1, 0.5),
oddColor: new Color_default(0, 0, 1, 0.5),
offset: 0,
repeat: 5
},
source: StripeMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.evenColor.alpha < 1 || uniforms.oddColor.alpha < 1;
}
});
Material.CheckerboardType = "Checkerboard";
Material._materialCache.addMaterial(Material.CheckerboardType, {
fabric: {
type: Material.CheckerboardType,
uniforms: {
lightColor: new Color_default(1, 1, 1, 0.5),
darkColor: new Color_default(0, 0, 0, 0.5),
repeat: new Cartesian2_default(5, 5)
},
source: CheckerboardMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.lightColor.alpha < 1 || uniforms.darkColor.alpha < 1;
}
});
Material.DotType = "Dot";
Material._materialCache.addMaterial(Material.DotType, {
fabric: {
type: Material.DotType,
uniforms: {
lightColor: new Color_default(1, 1, 0, 0.75),
darkColor: new Color_default(0, 1, 1, 0.75),
repeat: new Cartesian2_default(5, 5)
},
source: DotMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.lightColor.alpha < 1 || uniforms.darkColor.alpha < 1;
}
});
Material.WaterType = "Water";
Material._materialCache.addMaterial(Material.WaterType, {
fabric: {
type: Material.WaterType,
uniforms: {
baseWaterColor: new Color_default(0.2, 0.3, 0.6, 1),
blendColor: new Color_default(0, 1, 0.699, 1),
specularMap: Material.DefaultImageId,
normalMap: Material.DefaultImageId,
frequency: 10,
animationSpeed: 0.01,
amplitude: 1,
specularIntensity: 0.5,
fadeFactor: 1
},
source: Water_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.baseWaterColor.alpha < 1 || uniforms.blendColor.alpha < 1;
}
});
Material.RimLightingType = "RimLighting";
Material._materialCache.addMaterial(Material.RimLightingType, {
fabric: {
type: Material.RimLightingType,
uniforms: {
color: new Color_default(1, 0, 0, 0.7),
rimColor: new Color_default(1, 1, 1, 0.4),
width: 0.3
},
source: RimLightingMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.color.alpha < 1 || uniforms.rimColor.alpha < 1;
}
});
Material.FadeType = "Fade";
Material._materialCache.addMaterial(Material.FadeType, {
fabric: {
type: Material.FadeType,
uniforms: {
fadeInColor: new Color_default(1, 0, 0, 1),
fadeOutColor: new Color_default(0, 0, 0, 0),
maximumDistance: 0.5,
repeat: true,
fadeDirection: {
x: true,
y: true
},
time: new Cartesian2_default(0.5, 0.5)
},
source: FadeMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.fadeInColor.alpha < 1 || uniforms.fadeOutColor.alpha < 1;
}
});
Material.PolylineArrowType = "PolylineArrow";
Material._materialCache.addMaterial(Material.PolylineArrowType, {
fabric: {
type: Material.PolylineArrowType,
uniforms: {
color: new Color_default(1, 1, 1, 1)
},
source: PolylineArrowMaterial_default
},
translucent: true
});
Material.PolylineDashType = "PolylineDash";
Material._materialCache.addMaterial(Material.PolylineDashType, {
fabric: {
type: Material.PolylineDashType,
uniforms: {
color: new Color_default(1, 0, 1, 1),
gapColor: new Color_default(0, 0, 0, 0),
dashLength: 16,
dashPattern: 255
},
source: PolylineDashMaterial_default
},
translucent: true
});
Material.PolylineGlowType = "PolylineGlow";
Material._materialCache.addMaterial(Material.PolylineGlowType, {
fabric: {
type: Material.PolylineGlowType,
uniforms: {
color: new Color_default(0, 0.5, 1, 1),
glowPower: 0.25,
taperPower: 1
},
source: PolylineGlowMaterial_default
},
translucent: true
});
Material.PolylineOutlineType = "PolylineOutline";
Material._materialCache.addMaterial(Material.PolylineOutlineType, {
fabric: {
type: Material.PolylineOutlineType,
uniforms: {
color: new Color_default(1, 1, 1, 1),
outlineColor: new Color_default(1, 0, 0, 1),
outlineWidth: 1
},
source: PolylineOutlineMaterial_default
},
translucent: function(material) {
const uniforms = material.uniforms;
return uniforms.color.alpha < 1 || uniforms.outlineColor.alpha < 1;
}
});
Material.ElevationContourType = "ElevationContour";
Material._materialCache.addMaterial(Material.ElevationContourType, {
fabric: {
type: Material.ElevationContourType,
uniforms: {
spacing: 100,
color: new Color_default(1, 0, 0, 1),
width: 1
},
source: ElevationContourMaterial_default
},
translucent: false
});
Material.ElevationRampType = "ElevationRamp";
Material._materialCache.addMaterial(Material.ElevationRampType, {
fabric: {
type: Material.ElevationRampType,
uniforms: {
image: Material.DefaultImageId,
minimumHeight: 0,
maximumHeight: 1e4
},
source: ElevationRampMaterial_default
},
translucent: false
});
Material.SlopeRampMaterialType = "SlopeRamp";
Material._materialCache.addMaterial(Material.SlopeRampMaterialType, {
fabric: {
type: Material.SlopeRampMaterialType,
uniforms: {
image: Material.DefaultImageId
},
source: SlopeRampMaterial_default
},
translucent: false
});
Material.AspectRampMaterialType = "AspectRamp";
Material._materialCache.addMaterial(Material.AspectRampMaterialType, {
fabric: {
type: Material.AspectRampMaterialType,
uniforms: {
image: Material.DefaultImageId
},
source: AspectRampMaterial_default
},
translucent: false
});
Material.ElevationBandType = "ElevationBand";
Material._materialCache.addMaterial(Material.ElevationBandType, {
fabric: {
type: Material.ElevationBandType,
uniforms: {
heights: Material.DefaultImageId,
colors: Material.DefaultImageId
},
source: ElevationBandMaterial_default
},
translucent: true
});
var Material_default = Material;
// node_modules/@cesium/engine/Source/Scene/MaterialAppearance.js
function MaterialAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const closed = defaultValue_default(options.closed, false);
const materialSupport = defaultValue_default(
options.materialSupport,
MaterialAppearance.MaterialSupport.TEXTURED
);
this.material = defined_default(options.material) ? options.material : Material_default.fromType(Material_default.ColorType);
this.translucent = translucent;
this._vertexShaderSource = defaultValue_default(
options.vertexShaderSource,
materialSupport.vertexShaderSource
);
this._fragmentShaderSource = defaultValue_default(
options.fragmentShaderSource,
materialSupport.fragmentShaderSource
);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._materialSupport = materialSupport;
this._vertexFormat = materialSupport.vertexFormat;
this._flat = defaultValue_default(options.flat, false);
this._faceForward = defaultValue_default(options.faceForward, !closed);
}
Object.defineProperties(MaterialAppearance.prototype, {
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
renderState: {
get: function() {
return this._renderState;
}
},
closed: {
get: function() {
return this._closed;
}
},
materialSupport: {
get: function() {
return this._materialSupport;
}
},
vertexFormat: {
get: function() {
return this._vertexFormat;
}
},
flat: {
get: function() {
return this._flat;
}
},
faceForward: {
get: function() {
return this._faceForward;
}
}
});
MaterialAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
MaterialAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
MaterialAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
MaterialAppearance.MaterialSupport = {
BASIC: Object.freeze({
vertexFormat: VertexFormat_default.POSITION_AND_NORMAL,
vertexShaderSource: BasicMaterialAppearanceVS_default,
fragmentShaderSource: BasicMaterialAppearanceFS_default
}),
TEXTURED: Object.freeze({
vertexFormat: VertexFormat_default.POSITION_NORMAL_AND_ST,
vertexShaderSource: TexturedMaterialAppearanceVS_default,
fragmentShaderSource: TexturedMaterialAppearanceFS_default
}),
ALL: Object.freeze({
vertexFormat: VertexFormat_default.ALL,
vertexShaderSource: AllMaterialAppearanceVS_default,
fragmentShaderSource: AllMaterialAppearanceFS_default
})
};
var MaterialAppearance_default = MaterialAppearance;
// node_modules/@cesium/engine/Source/Shaders/Appearances/PerInstanceColorAppearanceFS.js
var PerInstanceColorAppearanceFS_default = "in vec3 v_positionEC;\nin vec3 v_normalEC;\nin vec4 v_color;\n\nvoid main()\n{\n vec3 positionToEyeEC = -v_positionEC;\n\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\n vec4 color = czm_gammaCorrect(v_color);\n\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\n out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/PerInstanceColorAppearanceVS.js
var PerInstanceColorAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 normal;\nin vec4 color;\nin float batchId;\n\nout vec3 v_positionEC;\nout vec3 v_normalEC;\nout vec4 v_color;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates\n v_normalEC = czm_normal * normal; // normal in eye coordinates\n v_color = color;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/PerInstanceFlatColorAppearanceFS.js
var PerInstanceFlatColorAppearanceFS_default = "in vec4 v_color;\n\nvoid main()\n{\n out_FragColor = czm_gammaCorrect(v_color);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Appearances/PerInstanceFlatColorAppearanceVS.js
var PerInstanceFlatColorAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec4 color;\nin float batchId;\n\nout vec4 v_color;\n\nvoid main()\n{\n vec4 p = czm_computePosition();\n\n v_color = color;\n\n gl_Position = czm_modelViewProjectionRelativeToEye * p;\n}\n";
// node_modules/@cesium/engine/Source/Scene/PerInstanceColorAppearance.js
function PerInstanceColorAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const closed = defaultValue_default(options.closed, false);
const flat = defaultValue_default(options.flat, false);
const vs = flat ? PerInstanceFlatColorAppearanceVS_default : PerInstanceColorAppearanceVS_default;
const fs = flat ? PerInstanceFlatColorAppearanceFS_default : PerInstanceColorAppearanceFS_default;
const vertexFormat = flat ? PerInstanceColorAppearance.FLAT_VERTEX_FORMAT : PerInstanceColorAppearance.VERTEX_FORMAT;
this.material = void 0;
this.translucent = translucent;
this._vertexShaderSource = defaultValue_default(options.vertexShaderSource, vs);
this._fragmentShaderSource = defaultValue_default(options.fragmentShaderSource, fs);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._vertexFormat = vertexFormat;
this._flat = flat;
this._faceForward = defaultValue_default(options.faceForward, !closed);
}
Object.defineProperties(PerInstanceColorAppearance.prototype, {
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
renderState: {
get: function() {
return this._renderState;
}
},
closed: {
get: function() {
return this._closed;
}
},
vertexFormat: {
get: function() {
return this._vertexFormat;
}
},
flat: {
get: function() {
return this._flat;
}
},
faceForward: {
get: function() {
return this._faceForward;
}
}
});
PerInstanceColorAppearance.VERTEX_FORMAT = VertexFormat_default.POSITION_AND_NORMAL;
PerInstanceColorAppearance.FLAT_VERTEX_FORMAT = VertexFormat_default.POSITION_ONLY;
PerInstanceColorAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
PerInstanceColorAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
PerInstanceColorAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var PerInstanceColorAppearance_default = PerInstanceColorAppearance;
// node_modules/@cesium/engine/Source/DataSources/ColorMaterialProperty.js
function ColorMaterialProperty(color) {
this._definitionChanged = new Event_default();
this._color = void 0;
this._colorSubscription = void 0;
this.color = color;
}
Object.defineProperties(ColorMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._color);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
color: createPropertyDescriptor_default("color")
});
ColorMaterialProperty.prototype.getType = function(time) {
return "Color";
};
ColorMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
Color_default.WHITE,
result.color
);
return result;
};
ColorMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof ColorMaterialProperty && Property_default.equals(this._color, other._color);
};
var ColorMaterialProperty_default = ColorMaterialProperty;
// node_modules/@cesium/engine/Source/Core/GeographicTilingScheme.js
function GeographicTilingScheme(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._rectangle = defaultValue_default(options.rectangle, Rectangle_default.MAX_VALUE);
this._projection = new GeographicProjection_default(this._ellipsoid);
this._numberOfLevelZeroTilesX = defaultValue_default(
options.numberOfLevelZeroTilesX,
2
);
this._numberOfLevelZeroTilesY = defaultValue_default(
options.numberOfLevelZeroTilesY,
1
);
}
Object.defineProperties(GeographicTilingScheme.prototype, {
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
rectangle: {
get: function() {
return this._rectangle;
}
},
projection: {
get: function() {
return this._projection;
}
}
});
GeographicTilingScheme.prototype.getNumberOfXTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesX << level;
};
GeographicTilingScheme.prototype.getNumberOfYTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesY << level;
};
GeographicTilingScheme.prototype.rectangleToNativeRectangle = function(rectangle, result) {
Check_default.defined("rectangle", rectangle);
const west = Math_default.toDegrees(rectangle.west);
const south = Math_default.toDegrees(rectangle.south);
const east = Math_default.toDegrees(rectangle.east);
const north = Math_default.toDegrees(rectangle.north);
if (!defined_default(result)) {
return new Rectangle_default(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
GeographicTilingScheme.prototype.tileXYToNativeRectangle = function(x, y, level, result) {
const rectangleRadians = this.tileXYToRectangle(x, y, level, result);
rectangleRadians.west = Math_default.toDegrees(rectangleRadians.west);
rectangleRadians.south = Math_default.toDegrees(rectangleRadians.south);
rectangleRadians.east = Math_default.toDegrees(rectangleRadians.east);
rectangleRadians.north = Math_default.toDegrees(rectangleRadians.north);
return rectangleRadians;
};
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_default(result)) {
result = new Rectangle_default(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
GeographicTilingScheme.prototype.positionToTileXY = function(position, level, result) {
const rectangle = this._rectangle;
if (!Rectangle_default.contains(rectangle, position)) {
return void 0;
}
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 += Math_default.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_default(result)) {
return new Cartesian2_default(xTileCoordinate, yTileCoordinate);
}
result.x = xTileCoordinate;
result.y = yTileCoordinate;
return result;
};
var GeographicTilingScheme_default = GeographicTilingScheme;
// node_modules/@cesium/engine/Source/Core/ApproximateTerrainHeights.js
var scratchDiagonalCartesianNE = new Cartesian3_default();
var scratchDiagonalCartesianSW = new Cartesian3_default();
var scratchDiagonalCartographic = new Cartographic_default();
var scratchCenterCartesian = new Cartesian3_default();
var scratchSurfaceCartesian = new Cartesian3_default();
var scratchBoundingSphere = new BoundingSphere_default();
var tilingScheme = new GeographicTilingScheme_default();
var scratchCorners = [
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default()
];
var scratchTileXY = new Cartesian2_default();
var ApproximateTerrainHeights = {};
ApproximateTerrainHeights.initialize = function() {
let initPromise = ApproximateTerrainHeights._initPromise;
if (defined_default(initPromise)) {
return initPromise;
}
initPromise = Resource_default.fetchJson(
buildModuleUrl_default("Assets/approximateTerrainHeights.json")
).then(function(json) {
ApproximateTerrainHeights._terrainHeights = json;
});
ApproximateTerrainHeights._initPromise = initPromise;
return initPromise;
};
ApproximateTerrainHeights.getMinimumMaximumHeights = function(rectangle, ellipsoid) {
Check_default.defined("rectangle", rectangle);
if (!defined_default(ApproximateTerrainHeights._terrainHeights)) {
throw new DeveloperError_default(
"You must call ApproximateTerrainHeights.initialize and wait for the promise to resolve before using this function"
);
}
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const xyLevel = getTileXYLevel(rectangle);
let minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
let maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
if (defined_default(xyLevel)) {
const key = `${xyLevel.level}-${xyLevel.x}-${xyLevel.y}`;
const heights = ApproximateTerrainHeights._terrainHeights[key];
if (defined_default(heights)) {
minTerrainHeight = heights[0];
maxTerrainHeight = heights[1];
}
ellipsoid.cartographicToCartesian(
Rectangle_default.northeast(rectangle, scratchDiagonalCartographic),
scratchDiagonalCartesianNE
);
ellipsoid.cartographicToCartesian(
Rectangle_default.southwest(rectangle, scratchDiagonalCartographic),
scratchDiagonalCartesianSW
);
Cartesian3_default.midpoint(
scratchDiagonalCartesianSW,
scratchDiagonalCartesianNE,
scratchCenterCartesian
);
const surfacePosition = ellipsoid.scaleToGeodeticSurface(
scratchCenterCartesian,
scratchSurfaceCartesian
);
if (defined_default(surfacePosition)) {
const distance2 = Cartesian3_default.distance(
scratchCenterCartesian,
surfacePosition
);
minTerrainHeight = Math.min(minTerrainHeight, -distance2);
} else {
minTerrainHeight = ApproximateTerrainHeights._defaultMinTerrainHeight;
}
}
minTerrainHeight = Math.max(
ApproximateTerrainHeights._defaultMinTerrainHeight,
minTerrainHeight
);
return {
minimumTerrainHeight: minTerrainHeight,
maximumTerrainHeight: maxTerrainHeight
};
};
ApproximateTerrainHeights.getBoundingSphere = function(rectangle, ellipsoid) {
Check_default.defined("rectangle", rectangle);
if (!defined_default(ApproximateTerrainHeights._terrainHeights)) {
throw new DeveloperError_default(
"You must call ApproximateTerrainHeights.initialize and wait for the promise to resolve before using this function"
);
}
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const xyLevel = getTileXYLevel(rectangle);
let maxTerrainHeight = ApproximateTerrainHeights._defaultMaxTerrainHeight;
if (defined_default(xyLevel)) {
const key = `${xyLevel.level}-${xyLevel.x}-${xyLevel.y}`;
const heights = ApproximateTerrainHeights._terrainHeights[key];
if (defined_default(heights)) {
maxTerrainHeight = heights[1];
}
}
const result = BoundingSphere_default.fromRectangle3D(rectangle, ellipsoid, 0);
BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
maxTerrainHeight,
scratchBoundingSphere
);
return BoundingSphere_default.union(result, scratchBoundingSphere, result);
};
function getTileXYLevel(rectangle) {
Cartographic_default.fromRadians(
rectangle.east,
rectangle.north,
0,
scratchCorners[0]
);
Cartographic_default.fromRadians(
rectangle.west,
rectangle.north,
0,
scratchCorners[1]
);
Cartographic_default.fromRadians(
rectangle.east,
rectangle.south,
0,
scratchCorners[2]
);
Cartographic_default.fromRadians(
rectangle.west,
rectangle.south,
0,
scratchCorners[3]
);
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 void 0;
}
return {
x: lastLevelX,
y: lastLevelY,
level: i > maxLevel ? maxLevel : i - 1
};
}
ApproximateTerrainHeights._terrainHeightsMaxLevel = 6;
ApproximateTerrainHeights._defaultMaxTerrainHeight = 9e3;
ApproximateTerrainHeights._defaultMinTerrainHeight = -1e5;
ApproximateTerrainHeights._terrainHeights = void 0;
ApproximateTerrainHeights._initPromise = void 0;
Object.defineProperties(ApproximateTerrainHeights, {
initialized: {
get: function() {
return defined_default(ApproximateTerrainHeights._terrainHeights);
}
}
});
var ApproximateTerrainHeights_default = ApproximateTerrainHeights;
// node_modules/@cesium/engine/Source/Core/AxisAlignedBoundingBox.js
function AxisAlignedBoundingBox(minimum, maximum, center) {
this.minimum = Cartesian3_default.clone(defaultValue_default(minimum, Cartesian3_default.ZERO));
this.maximum = Cartesian3_default.clone(defaultValue_default(maximum, Cartesian3_default.ZERO));
if (!defined_default(center)) {
center = Cartesian3_default.midpoint(this.minimum, this.maximum, new Cartesian3_default());
} else {
center = Cartesian3_default.clone(center);
}
this.center = center;
}
AxisAlignedBoundingBox.fromCorners = function(minimum, maximum, result) {
Check_default.defined("minimum", minimum);
Check_default.defined("maximum", maximum);
if (!defined_default(result)) {
result = new AxisAlignedBoundingBox();
}
result.minimum = Cartesian3_default.clone(minimum, result.minimum);
result.maximum = Cartesian3_default.clone(maximum, result.maximum);
result.center = Cartesian3_default.midpoint(minimum, maximum, result.center);
return result;
};
AxisAlignedBoundingBox.fromPoints = function(positions, result) {
if (!defined_default(result)) {
result = new AxisAlignedBoundingBox();
}
if (!defined_default(positions) || positions.length === 0) {
result.minimum = Cartesian3_default.clone(Cartesian3_default.ZERO, result.minimum);
result.maximum = Cartesian3_default.clone(Cartesian3_default.ZERO, result.maximum);
result.center = Cartesian3_default.clone(Cartesian3_default.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 length3 = positions.length;
for (let i = 1; i < length3; 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_default.midpoint(minimum, maximum, result.center);
return result;
};
AxisAlignedBoundingBox.clone = function(box, result) {
if (!defined_default(box)) {
return void 0;
}
if (!defined_default(result)) {
return new AxisAlignedBoundingBox(box.minimum, box.maximum, box.center);
}
result.minimum = Cartesian3_default.clone(box.minimum, result.minimum);
result.maximum = Cartesian3_default.clone(box.maximum, result.maximum);
result.center = Cartesian3_default.clone(box.center, result.center);
return result;
};
AxisAlignedBoundingBox.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && Cartesian3_default.equals(left.center, right.center) && Cartesian3_default.equals(left.minimum, right.minimum) && Cartesian3_default.equals(left.maximum, right.maximum);
};
var intersectScratch = new Cartesian3_default();
AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
Check_default.defined("box", box);
Check_default.defined("plane", plane);
intersectScratch = Cartesian3_default.subtract(
box.maximum,
box.minimum,
intersectScratch
);
const h = Cartesian3_default.multiplyByScalar(
intersectScratch,
0.5,
intersectScratch
);
const normal2 = plane.normal;
const e = h.x * Math.abs(normal2.x) + h.y * Math.abs(normal2.y) + h.z * Math.abs(normal2.z);
const s = Cartesian3_default.dot(box.center, normal2) + plane.distance;
if (s - e > 0) {
return Intersect_default.INSIDE;
}
if (s + e < 0) {
return Intersect_default.OUTSIDE;
}
return Intersect_default.INTERSECTING;
};
AxisAlignedBoundingBox.prototype.clone = function(result) {
return AxisAlignedBoundingBox.clone(this, result);
};
AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
return AxisAlignedBoundingBox.intersectPlane(this, plane);
};
AxisAlignedBoundingBox.prototype.equals = function(right) {
return AxisAlignedBoundingBox.equals(this, right);
};
var AxisAlignedBoundingBox_default = AxisAlignedBoundingBox;
// node_modules/@cesium/engine/Source/Core/QuadraticRealPolynomial.js
var QuadraticRealPolynomial = {};
QuadraticRealPolynomial.computeDiscriminant = function(a3, b, c) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
const discriminant = b * b - 4 * a3 * c;
return discriminant;
};
function addWithCancellationCheck(left, right, tolerance) {
const difference = left + right;
if (Math_default.sign(left) !== Math_default.sign(right) && Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
return 0;
}
return difference;
}
QuadraticRealPolynomial.computeRealRoots = function(a3, b, c) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
let ratio;
if (a3 === 0) {
if (b === 0) {
return [];
}
return [-c / b];
} else if (b === 0) {
if (c === 0) {
return [0, 0];
}
const cMagnitude = Math.abs(c);
const aMagnitude = Math.abs(a3);
if (cMagnitude < aMagnitude && cMagnitude / aMagnitude < Math_default.EPSILON14) {
return [0, 0];
} else if (cMagnitude > aMagnitude && aMagnitude / cMagnitude < Math_default.EPSILON14) {
return [];
}
ratio = -c / a3;
if (ratio < 0) {
return [];
}
const root = Math.sqrt(ratio);
return [-root, root];
} else if (c === 0) {
ratio = -b / a3;
if (ratio < 0) {
return [ratio, 0];
}
return [0, ratio];
}
const b2 = b * b;
const four_ac = 4 * a3 * c;
const radicand = addWithCancellationCheck(b2, -four_ac, Math_default.EPSILON14);
if (radicand < 0) {
return [];
}
const q = -0.5 * addWithCancellationCheck(
b,
Math_default.sign(b) * Math.sqrt(radicand),
Math_default.EPSILON14
);
if (b > 0) {
return [q / a3, c / q];
}
return [c / q, q / a3];
};
var QuadraticRealPolynomial_default = QuadraticRealPolynomial;
// node_modules/@cesium/engine/Source/Core/CubicRealPolynomial.js
var CubicRealPolynomial = {};
CubicRealPolynomial.computeDiscriminant = function(a3, b, c, d) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
const a22 = a3 * a3;
const b2 = b * b;
const c22 = c * c;
const d2 = d * d;
const discriminant = 18 * a3 * b * c * d + b2 * c22 - 27 * a22 * d2 - 4 * (a3 * c22 * c + b2 * b * d);
return discriminant;
};
function computeRealRoots(a3, b, c, d) {
const A = a3;
const B = b / 3;
const C = c / 3;
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 * delta1 * delta3 - delta2 * delta2;
let temp;
let temp1;
if (discriminant < 0) {
let ABar;
let CBar;
let DBar;
if (B2 * BD >= AC * C2) {
ABar = A;
CBar = delta1;
DBar = -2 * B * delta1 + A * delta2;
} else {
ABar = D;
CBar = delta3;
DBar = -D * delta2 + 2 * C * delta3;
}
const s = DBar < 0 ? -1 : 1;
const temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
temp1 = -DBar + temp0;
const x = temp1 / 2;
const p = x < 0 ? -Math.pow(-x, 1 / 3) : Math.pow(x, 1 / 3);
const q = temp1 === temp0 ? -p : -CBar / p;
temp = CBar <= 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 * B * delta1 + A * delta2;
const CBarD = delta3;
const DBarD = -D * delta2 + 2 * C * delta3;
const squareRootOfDiscriminant = Math.sqrt(discriminant);
const halfSquareRootOf3 = Math.sqrt(3) / 2;
let theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3);
temp = 2 * Math.sqrt(-CBarA);
let cosine = Math.cos(theta);
temp1 = temp * cosine;
let temp3 = temp * (-cosine / 2 - halfSquareRootOf3 * Math.sin(theta));
const numeratorLarge = temp1 + temp3 > 2 * B ? temp1 - B : temp3 - B;
const denominatorLarge = A;
const root1 = numeratorLarge / denominatorLarge;
theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3);
temp = 2 * Math.sqrt(-CBarD);
cosine = Math.cos(theta);
temp1 = temp * cosine;
temp3 = temp * (-cosine / 2 - halfSquareRootOf3 * Math.sin(theta));
const numeratorSmall = -D;
const denominatorSmall = temp1 + temp3 < 2 * 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];
}
CubicRealPolynomial.computeRealRoots = function(a3, b, c, d) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
let roots;
let ratio;
if (a3 === 0) {
return QuadraticRealPolynomial_default.computeRealRoots(b, c, d);
} else if (b === 0) {
if (c === 0) {
if (d === 0) {
return [0, 0, 0];
}
ratio = -d / a3;
const root = ratio < 0 ? -Math.pow(-ratio, 1 / 3) : Math.pow(ratio, 1 / 3);
return [root, root, root];
} else if (d === 0) {
roots = QuadraticRealPolynomial_default.computeRealRoots(a3, 0, c);
if (roots.Length === 0) {
return [0];
}
return [roots[0], 0, roots[1]];
}
return computeRealRoots(a3, 0, c, d);
} else if (c === 0) {
if (d === 0) {
ratio = -b / a3;
if (ratio < 0) {
return [ratio, 0, 0];
}
return [0, 0, ratio];
}
return computeRealRoots(a3, b, 0, d);
} else if (d === 0) {
roots = QuadraticRealPolynomial_default.computeRealRoots(a3, b, c);
if (roots.length === 0) {
return [0];
} else if (roots[1] <= 0) {
return [roots[0], roots[1], 0];
} else if (roots[0] >= 0) {
return [0, roots[0], roots[1]];
}
return [roots[0], 0, roots[1]];
}
return computeRealRoots(a3, b, c, d);
};
var CubicRealPolynomial_default = CubicRealPolynomial;
// node_modules/@cesium/engine/Source/Core/QuarticRealPolynomial.js
var QuarticRealPolynomial = {};
QuarticRealPolynomial.computeDiscriminant = function(a3, b, c, d, e) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
if (typeof e !== "number") {
throw new DeveloperError_default("e is a required number.");
}
const a22 = a3 * a3;
const a32 = a22 * a3;
const b2 = b * b;
const b3 = b2 * b;
const c22 = c * c;
const c33 = c22 * c;
const d2 = d * d;
const d3 = d2 * d;
const e2 = e * e;
const e3 = e2 * e;
const discriminant = b2 * c22 * d2 - 4 * b3 * d3 - 4 * a3 * c33 * d2 + 18 * a3 * b * c * d3 - 27 * a22 * d2 * d2 + 256 * a32 * e3 + e * (18 * b3 * c * d - 4 * b2 * c33 + 16 * a3 * c22 * c22 - 80 * a3 * b * c22 * d - 6 * a3 * b2 * d2 + 144 * a22 * c * d2) + e2 * (144 * a3 * b2 * c - 27 * b2 * b2 - 128 * a22 * c22 - 192 * a22 * b * d);
return discriminant;
};
function original(a3, a22, a1, a0) {
const a3Squared = a3 * a3;
const p = a22 - 3 * a3Squared / 8;
const q = a1 - a22 * a3 / 2 + a3Squared * a3 / 8;
const r = a0 - a1 * a3 / 4 + a22 * a3Squared / 16 - 3 * a3Squared * a3Squared / 256;
const cubicRoots = CubicRealPolynomial_default.computeRealRoots(
1,
2 * p,
p * p - 4 * r,
-q * q
);
if (cubicRoots.length > 0) {
const temp = -a3 / 4;
const hSquared = cubicRoots[cubicRoots.length - 1];
if (Math.abs(hSquared) < Math_default.EPSILON14) {
const roots = QuadraticRealPolynomial_default.computeRealRoots(1, p, r);
if (roots.length === 2) {
const root0 = roots[0];
const root1 = roots[1];
let y;
if (root0 >= 0 && root1 >= 0) {
const y0 = Math.sqrt(root0);
const y1 = Math.sqrt(root1);
return [temp - y1, temp - y0, temp + y0, temp + y1];
} else if (root0 >= 0 && root1 < 0) {
y = Math.sqrt(root0);
return [temp - y, temp + y];
} else if (root0 < 0 && root1 >= 0) {
y = Math.sqrt(root1);
return [temp - y, temp + y];
}
}
return [];
} else if (hSquared > 0) {
const h = Math.sqrt(hSquared);
const m = (p + hSquared - q / h) / 2;
const n = (p + hSquared + q / h) / 2;
const roots1 = QuadraticRealPolynomial_default.computeRealRoots(1, h, m);
const roots2 = QuadraticRealPolynomial_default.computeRealRoots(1, -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, a22, a1, a0) {
const a1Squared = a1 * a1;
const a2Squared = a22 * a22;
const a3Squared = a3 * a3;
const p = -2 * a22;
const q = a1 * a3 + a2Squared - 4 * a0;
const r = a3Squared * a0 - a1 * a22 * a3 + a1Squared;
const cubicRoots = CubicRealPolynomial_default.computeRealRoots(1, p, q, r);
if (cubicRoots.length > 0) {
const y = cubicRoots[0];
const temp = a22 - y;
const tempSquared = temp * temp;
const g1 = a3 / 2;
const h1 = temp / 2;
const m = tempSquared - 4 * a0;
const mError = tempSquared + 4 * Math.abs(a0);
const n = a3Squared - 4 * y;
const nError = a3Squared + 4 * Math.abs(y);
let g2;
let h2;
if (y < 0 || m * nError < n * mError) {
const squareRootOfN = Math.sqrt(n);
g2 = squareRootOfN / 2;
h2 = squareRootOfN === 0 ? 0 : (a3 * h1 - a1) / squareRootOfN;
} else {
const squareRootOfM = Math.sqrt(m);
g2 = squareRootOfM === 0 ? 0 : (a3 * h1 - a1) / squareRootOfM;
h2 = squareRootOfM / 2;
}
let G;
let g;
if (g1 === 0 && g2 === 0) {
G = 0;
g = 0;
} else if (Math_default.sign(g1) === Math_default.sign(g2)) {
G = g1 + g2;
g = y / G;
} else {
g = g1 - g2;
G = y / g;
}
let H;
let h;
if (h1 === 0 && h2 === 0) {
H = 0;
h = 0;
} else if (Math_default.sign(h1) === Math_default.sign(h2)) {
H = h1 + h2;
h = a0 / H;
} else {
h = h1 - h2;
H = a0 / h;
}
const roots1 = QuadraticRealPolynomial_default.computeRealRoots(1, G, H);
const roots2 = QuadraticRealPolynomial_default.computeRealRoots(1, 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 [];
}
QuarticRealPolynomial.computeRealRoots = function(a3, b, c, d, e) {
if (typeof a3 !== "number") {
throw new DeveloperError_default("a is a required number.");
}
if (typeof b !== "number") {
throw new DeveloperError_default("b is a required number.");
}
if (typeof c !== "number") {
throw new DeveloperError_default("c is a required number.");
}
if (typeof d !== "number") {
throw new DeveloperError_default("d is a required number.");
}
if (typeof e !== "number") {
throw new DeveloperError_default("e is a required number.");
}
if (Math.abs(a3) < Math_default.EPSILON15) {
return CubicRealPolynomial_default.computeRealRoots(b, c, d, e);
}
const a32 = b / a3;
const a22 = c / a3;
const a1 = d / a3;
const a0 = e / a3;
let k = a32 < 0 ? 1 : 0;
k += a22 < 0 ? k + 1 : k;
k += a1 < 0 ? k + 1 : k;
k += a0 < 0 ? k + 1 : k;
switch (k) {
case 0:
return original(a32, a22, a1, a0);
case 1:
return neumark(a32, a22, a1, a0);
case 2:
return neumark(a32, a22, a1, a0);
case 3:
return original(a32, a22, a1, a0);
case 4:
return original(a32, a22, a1, a0);
case 5:
return neumark(a32, a22, a1, a0);
case 6:
return original(a32, a22, a1, a0);
case 7:
return original(a32, a22, a1, a0);
case 8:
return neumark(a32, a22, a1, a0);
case 9:
return original(a32, a22, a1, a0);
case 10:
return original(a32, a22, a1, a0);
case 11:
return neumark(a32, a22, a1, a0);
case 12:
return original(a32, a22, a1, a0);
case 13:
return original(a32, a22, a1, a0);
case 14:
return original(a32, a22, a1, a0);
case 15:
return original(a32, a22, a1, a0);
default:
return void 0;
}
};
var QuarticRealPolynomial_default = QuarticRealPolynomial;
// node_modules/@cesium/engine/Source/Core/Ray.js
function Ray(origin, direction2) {
direction2 = Cartesian3_default.clone(defaultValue_default(direction2, Cartesian3_default.ZERO));
if (!Cartesian3_default.equals(direction2, Cartesian3_default.ZERO)) {
Cartesian3_default.normalize(direction2, direction2);
}
this.origin = Cartesian3_default.clone(defaultValue_default(origin, Cartesian3_default.ZERO));
this.direction = direction2;
}
Ray.clone = function(ray, result) {
if (!defined_default(ray)) {
return void 0;
}
if (!defined_default(result)) {
return new Ray(ray.origin, ray.direction);
}
result.origin = Cartesian3_default.clone(ray.origin);
result.direction = Cartesian3_default.clone(ray.direction);
return result;
};
Ray.getPoint = function(ray, t, result) {
Check_default.typeOf.object("ray", ray);
Check_default.typeOf.number("t", t);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
result = Cartesian3_default.multiplyByScalar(ray.direction, t, result);
return Cartesian3_default.add(ray.origin, result, result);
};
var Ray_default = Ray;
// node_modules/@cesium/engine/Source/Core/IntersectionTests.js
var IntersectionTests = {};
IntersectionTests.rayPlane = function(ray, plane, result) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(plane)) {
throw new DeveloperError_default("plane is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const origin = ray.origin;
const direction2 = ray.direction;
const normal2 = plane.normal;
const denominator = Cartesian3_default.dot(normal2, direction2);
if (Math.abs(denominator) < Math_default.EPSILON15) {
return void 0;
}
const t = (-plane.distance - Cartesian3_default.dot(normal2, origin)) / denominator;
if (t < 0) {
return void 0;
}
result = Cartesian3_default.multiplyByScalar(direction2, t, result);
return Cartesian3_default.add(origin, result, result);
};
var scratchEdge0 = new Cartesian3_default();
var scratchEdge1 = new Cartesian3_default();
var scratchPVec = new Cartesian3_default();
var scratchTVec = new Cartesian3_default();
var scratchQVec = new Cartesian3_default();
IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(p0)) {
throw new DeveloperError_default("p0 is required.");
}
if (!defined_default(p1)) {
throw new DeveloperError_default("p1 is required.");
}
if (!defined_default(p2)) {
throw new DeveloperError_default("p2 is required.");
}
cullBackFaces = defaultValue_default(cullBackFaces, false);
const origin = ray.origin;
const direction2 = ray.direction;
const edge0 = Cartesian3_default.subtract(p1, p0, scratchEdge0);
const edge1 = Cartesian3_default.subtract(p2, p0, scratchEdge1);
const p = Cartesian3_default.cross(direction2, edge1, scratchPVec);
const det = Cartesian3_default.dot(edge0, p);
let tvec;
let q;
let u3;
let v7;
let t;
if (cullBackFaces) {
if (det < Math_default.EPSILON6) {
return void 0;
}
tvec = Cartesian3_default.subtract(origin, p0, scratchTVec);
u3 = Cartesian3_default.dot(tvec, p);
if (u3 < 0 || u3 > det) {
return void 0;
}
q = Cartesian3_default.cross(tvec, edge0, scratchQVec);
v7 = Cartesian3_default.dot(direction2, q);
if (v7 < 0 || u3 + v7 > det) {
return void 0;
}
t = Cartesian3_default.dot(edge1, q) / det;
} else {
if (Math.abs(det) < Math_default.EPSILON6) {
return void 0;
}
const invDet = 1 / det;
tvec = Cartesian3_default.subtract(origin, p0, scratchTVec);
u3 = Cartesian3_default.dot(tvec, p) * invDet;
if (u3 < 0 || u3 > 1) {
return void 0;
}
q = Cartesian3_default.cross(tvec, edge0, scratchQVec);
v7 = Cartesian3_default.dot(direction2, q) * invDet;
if (v7 < 0 || u3 + v7 > 1) {
return void 0;
}
t = Cartesian3_default.dot(edge1, q) * invDet;
}
return t;
};
IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
const t = IntersectionTests.rayTriangleParametric(
ray,
p0,
p1,
p2,
cullBackFaces
);
if (!defined_default(t) || t < 0) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
Cartesian3_default.multiplyByScalar(ray.direction, t, result);
return Cartesian3_default.add(ray.origin, result, result);
};
var scratchLineSegmentTriangleRay = new Ray_default();
IntersectionTests.lineSegmentTriangle = function(v02, v13, p0, p1, p2, cullBackFaces, result) {
if (!defined_default(v02)) {
throw new DeveloperError_default("v0 is required.");
}
if (!defined_default(v13)) {
throw new DeveloperError_default("v1 is required.");
}
if (!defined_default(p0)) {
throw new DeveloperError_default("p0 is required.");
}
if (!defined_default(p1)) {
throw new DeveloperError_default("p1 is required.");
}
if (!defined_default(p2)) {
throw new DeveloperError_default("p2 is required.");
}
const ray = scratchLineSegmentTriangleRay;
Cartesian3_default.clone(v02, ray.origin);
Cartesian3_default.subtract(v13, v02, ray.direction);
Cartesian3_default.normalize(ray.direction, ray.direction);
const t = IntersectionTests.rayTriangleParametric(
ray,
p0,
p1,
p2,
cullBackFaces
);
if (!defined_default(t) || t < 0 || t > Cartesian3_default.distance(v02, v13)) {
return void 0;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
Cartesian3_default.multiplyByScalar(ray.direction, t, result);
return Cartesian3_default.add(ray.origin, result, result);
};
function solveQuadratic(a3, b, c, result) {
const det = b * b - 4 * a3 * c;
if (det < 0) {
return void 0;
} else if (det > 0) {
const denom = 1 / (2 * a3);
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 * a3);
if (root === 0) {
return void 0;
}
result.root0 = result.root1 = root;
return result;
}
var raySphereRoots = {
root0: 0,
root1: 0
};
function raySphere(ray, sphere, result) {
if (!defined_default(result)) {
result = new Interval_default();
}
const origin = ray.origin;
const direction2 = ray.direction;
const center = sphere.center;
const radiusSquared = sphere.radius * sphere.radius;
const diff = Cartesian3_default.subtract(origin, center, scratchPVec);
const a3 = Cartesian3_default.dot(direction2, direction2);
const b = 2 * Cartesian3_default.dot(direction2, diff);
const c = Cartesian3_default.magnitudeSquared(diff) - radiusSquared;
const roots = solveQuadratic(a3, b, c, raySphereRoots);
if (!defined_default(roots)) {
return void 0;
}
result.start = roots.root0;
result.stop = roots.root1;
return result;
}
IntersectionTests.raySphere = function(ray, sphere, result) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(sphere)) {
throw new DeveloperError_default("sphere is required.");
}
result = raySphere(ray, sphere, result);
if (!defined_default(result) || result.stop < 0) {
return void 0;
}
result.start = Math.max(result.start, 0);
return result;
};
var scratchLineSegmentRay = new Ray_default();
IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
if (!defined_default(p0)) {
throw new DeveloperError_default("p0 is required.");
}
if (!defined_default(p1)) {
throw new DeveloperError_default("p1 is required.");
}
if (!defined_default(sphere)) {
throw new DeveloperError_default("sphere is required.");
}
const ray = scratchLineSegmentRay;
Cartesian3_default.clone(p0, ray.origin);
const direction2 = Cartesian3_default.subtract(p1, p0, ray.direction);
const maxT = Cartesian3_default.magnitude(direction2);
Cartesian3_default.normalize(direction2, direction2);
result = raySphere(ray, sphere, result);
if (!defined_default(result) || result.stop < 0 || result.start > maxT) {
return void 0;
}
result.start = Math.max(result.start, 0);
result.stop = Math.min(result.stop, maxT);
return result;
};
var scratchQ = new Cartesian3_default();
var scratchW = new Cartesian3_default();
IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(ellipsoid)) {
throw new DeveloperError_default("ellipsoid is required.");
}
const inverseRadii = ellipsoid.oneOverRadii;
const q = Cartesian3_default.multiplyComponents(inverseRadii, ray.origin, scratchQ);
const w = Cartesian3_default.multiplyComponents(
inverseRadii,
ray.direction,
scratchW
);
const q22 = Cartesian3_default.magnitudeSquared(q);
const qw = Cartesian3_default.dot(q, w);
let difference, w2, product, discriminant, temp;
if (q22 > 1) {
if (qw >= 0) {
return void 0;
}
const qw2 = qw * qw;
difference = q22 - 1;
w2 = Cartesian3_default.magnitudeSquared(w);
product = w2 * difference;
if (qw2 < product) {
return void 0;
} else if (qw2 > product) {
discriminant = qw * qw - product;
temp = -qw + Math.sqrt(discriminant);
const root0 = temp / w2;
const root1 = difference / temp;
if (root0 < root1) {
return new Interval_default(root0, root1);
}
return {
start: root1,
stop: root0
};
}
const root = Math.sqrt(difference / w2);
return new Interval_default(root, root);
} else if (q22 < 1) {
difference = q22 - 1;
w2 = Cartesian3_default.magnitudeSquared(w);
product = w2 * difference;
discriminant = qw * qw - product;
temp = -qw + Math.sqrt(discriminant);
return new Interval_default(0, temp / w2);
}
if (qw < 0) {
w2 = Cartesian3_default.magnitudeSquared(w);
return new Interval_default(0, -qw / w2);
}
return void 0;
};
function addWithCancellationCheck2(left, right, tolerance) {
const difference = left + right;
if (Math_default.sign(left) !== Math_default.sign(right) && Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
return 0;
}
return difference;
}
function quadraticVectorExpression(A, b, c, x, w) {
const xSquared = x * x;
const wSquared = w * w;
const l2 = (A[Matrix3_default.COLUMN1ROW1] - A[Matrix3_default.COLUMN2ROW2]) * wSquared;
const l1 = w * (x * addWithCancellationCheck2(
A[Matrix3_default.COLUMN1ROW0],
A[Matrix3_default.COLUMN0ROW1],
Math_default.EPSILON15
) + b.y);
const l0 = A[Matrix3_default.COLUMN0ROW0] * xSquared + A[Matrix3_default.COLUMN2ROW2] * wSquared + x * b.x + c;
const r1 = wSquared * addWithCancellationCheck2(
A[Matrix3_default.COLUMN2ROW1],
A[Matrix3_default.COLUMN1ROW2],
Math_default.EPSILON15
);
const r0 = w * (x * addWithCancellationCheck2(A[Matrix3_default.COLUMN2ROW0], A[Matrix3_default.COLUMN0ROW2]) + b.z);
let cosines;
const solutions = [];
if (r0 === 0 && r1 === 0) {
cosines = QuadraticRealPolynomial_default.computeRealRoots(l2, l1, l0);
if (cosines.length === 0) {
return solutions;
}
const cosine0 = cosines[0];
const sine0 = Math.sqrt(Math.max(1 - cosine0 * cosine0, 0));
solutions.push(new Cartesian3_default(x, w * cosine0, w * -sine0));
solutions.push(new Cartesian3_default(x, w * cosine0, w * sine0));
if (cosines.length === 2) {
const cosine1 = cosines[1];
const sine1 = Math.sqrt(Math.max(1 - cosine1 * cosine1, 0));
solutions.push(new Cartesian3_default(x, w * cosine1, w * -sine1));
solutions.push(new Cartesian3_default(x, w * cosine1, w * sine1));
}
return solutions;
}
const r0Squared = r0 * r0;
const r1Squared = r1 * r1;
const l2Squared = l2 * l2;
const r0r1 = r0 * r1;
const c42 = l2Squared + r1Squared;
const c33 = 2 * (l1 * l2 + r0r1);
const c22 = 2 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
const c14 = 2 * (l0 * l1 - r0r1);
const c0 = l0 * l0 - r0Squared;
if (c42 === 0 && c33 === 0 && c22 === 0 && c14 === 0) {
return solutions;
}
cosines = QuarticRealPolynomial_default.computeRealRoots(c42, c33, c22, c14, c0);
const length3 = cosines.length;
if (length3 === 0) {
return solutions;
}
for (let i = 0; i < length3; ++i) {
const cosine = cosines[i];
const cosineSquared = cosine * cosine;
const sineSquared = Math.max(1 - cosineSquared, 0);
const sine = Math.sqrt(sineSquared);
let left;
if (Math_default.sign(l2) === Math_default.sign(l0)) {
left = addWithCancellationCheck2(
l2 * cosineSquared + l0,
l1 * cosine,
Math_default.EPSILON12
);
} else if (Math_default.sign(l0) === Math_default.sign(l1 * cosine)) {
left = addWithCancellationCheck2(
l2 * cosineSquared,
l1 * cosine + l0,
Math_default.EPSILON12
);
} else {
left = addWithCancellationCheck2(
l2 * cosineSquared + l1 * cosine,
l0,
Math_default.EPSILON12
);
}
const right = addWithCancellationCheck2(
r1 * cosine,
r0,
Math_default.EPSILON15
);
const product = left * right;
if (product < 0) {
solutions.push(new Cartesian3_default(x, w * cosine, w * sine));
} else if (product > 0) {
solutions.push(new Cartesian3_default(x, w * cosine, w * -sine));
} else if (sine !== 0) {
solutions.push(new Cartesian3_default(x, w * cosine, w * -sine));
solutions.push(new Cartesian3_default(x, w * cosine, w * sine));
++i;
} else {
solutions.push(new Cartesian3_default(x, w * cosine, w * sine));
}
}
return solutions;
}
var firstAxisScratch = new Cartesian3_default();
var secondAxisScratch = new Cartesian3_default();
var thirdAxisScratch = new Cartesian3_default();
var referenceScratch = new Cartesian3_default();
var bCart = new Cartesian3_default();
var bScratch = new Matrix3_default();
var btScratch = new Matrix3_default();
var diScratch = new Matrix3_default();
var dScratch = new Matrix3_default();
var cScratch = new Matrix3_default();
var tempMatrix = new Matrix3_default();
var aScratch = new Matrix3_default();
var sScratch = new Cartesian3_default();
var closestScratch = new Cartesian3_default();
var surfPointScratch = new Cartographic_default();
IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
if (!defined_default(ray)) {
throw new DeveloperError_default("ray is required.");
}
if (!defined_default(ellipsoid)) {
throw new DeveloperError_default("ellipsoid is required.");
}
const position = ray.origin;
const direction2 = ray.direction;
if (!Cartesian3_default.equals(position, Cartesian3_default.ZERO)) {
const normal2 = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
if (Cartesian3_default.dot(direction2, normal2) >= 0) {
return position;
}
}
const intersects2 = defined_default(this.rayEllipsoid(ray, ellipsoid));
const f = ellipsoid.transformPositionToScaledSpace(
direction2,
firstAxisScratch
);
const firstAxis = Cartesian3_default.normalize(f, f);
const reference = Cartesian3_default.mostOrthogonalAxis(f, referenceScratch);
const secondAxis = Cartesian3_default.normalize(
Cartesian3_default.cross(reference, firstAxis, secondAxisScratch),
secondAxisScratch
);
const thirdAxis = Cartesian3_default.normalize(
Cartesian3_default.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_default.transpose(B, btScratch);
const D_I = Matrix3_default.fromScale(ellipsoid.radii, diScratch);
const D = Matrix3_default.fromScale(ellipsoid.oneOverRadii, dScratch);
const C = cScratch;
C[0] = 0;
C[1] = -direction2.z;
C[2] = direction2.y;
C[3] = direction2.z;
C[4] = 0;
C[5] = -direction2.x;
C[6] = -direction2.y;
C[7] = direction2.x;
C[8] = 0;
const temp = Matrix3_default.multiply(
Matrix3_default.multiply(B_T, D, tempMatrix),
C,
tempMatrix
);
const A = Matrix3_default.multiply(
Matrix3_default.multiply(temp, D_I, aScratch),
B,
aScratch
);
const b = Matrix3_default.multiplyByVector(temp, position, bCart);
const solutions = quadraticVectorExpression(
A,
Cartesian3_default.negate(b, firstAxisScratch),
0,
0,
1
);
let s;
let altitude;
const length3 = solutions.length;
if (length3 > 0) {
let closest = Cartesian3_default.clone(Cartesian3_default.ZERO, closestScratch);
let maximumValue = Number.NEGATIVE_INFINITY;
for (let i = 0; i < length3; ++i) {
s = Matrix3_default.multiplyByVector(
D_I,
Matrix3_default.multiplyByVector(B, solutions[i], sScratch),
sScratch
);
const v7 = Cartesian3_default.normalize(
Cartesian3_default.subtract(s, position, referenceScratch),
referenceScratch
);
const dotProduct = Cartesian3_default.dot(v7, direction2);
if (dotProduct > maximumValue) {
maximumValue = dotProduct;
closest = Cartesian3_default.clone(s, closest);
}
}
const surfacePoint = ellipsoid.cartesianToCartographic(
closest,
surfPointScratch
);
maximumValue = Math_default.clamp(maximumValue, 0, 1);
altitude = Cartesian3_default.magnitude(
Cartesian3_default.subtract(closest, position, referenceScratch)
) * Math.sqrt(1 - maximumValue * maximumValue);
altitude = intersects2 ? -altitude : altitude;
surfacePoint.height = altitude;
return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3_default());
}
return void 0;
};
var lineSegmentPlaneDifference = new Cartesian3_default();
IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
if (!defined_default(endPoint0)) {
throw new DeveloperError_default("endPoint0 is required.");
}
if (!defined_default(endPoint1)) {
throw new DeveloperError_default("endPoint1 is required.");
}
if (!defined_default(plane)) {
throw new DeveloperError_default("plane is required.");
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const difference = Cartesian3_default.subtract(
endPoint1,
endPoint0,
lineSegmentPlaneDifference
);
const normal2 = plane.normal;
const nDotDiff = Cartesian3_default.dot(normal2, difference);
if (Math.abs(nDotDiff) < Math_default.EPSILON6) {
return void 0;
}
const nDotP0 = Cartesian3_default.dot(normal2, endPoint0);
const t = -(plane.distance + nDotP0) / nDotDiff;
if (t < 0 || t > 1) {
return void 0;
}
Cartesian3_default.multiplyByScalar(difference, t, result);
Cartesian3_default.add(endPoint0, result, result);
return result;
};
IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
if (!defined_default(p0) || !defined_default(p1) || !defined_default(p2) || !defined_default(plane)) {
throw new DeveloperError_default("p0, p1, p2, and plane are required.");
}
const planeNormal = plane.normal;
const planeD = plane.distance;
const p0Behind = Cartesian3_default.dot(planeNormal, p0) + planeD < 0;
const p1Behind = Cartesian3_default.dot(planeNormal, p1) + planeD < 0;
const p2Behind = Cartesian3_default.dot(planeNormal, p2) + planeD < 0;
let numBehind = 0;
numBehind += p0Behind ? 1 : 0;
numBehind += p1Behind ? 1 : 0;
numBehind += p2Behind ? 1 : 0;
let u12, u22;
if (numBehind === 1 || numBehind === 2) {
u12 = new Cartesian3_default();
u22 = new Cartesian3_default();
}
if (numBehind === 1) {
if (p0Behind) {
IntersectionTests.lineSegmentPlane(p0, p1, plane, u12);
IntersectionTests.lineSegmentPlane(p0, p2, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
0,
3,
4,
1,
2,
4,
1,
4,
3
]
};
} else if (p1Behind) {
IntersectionTests.lineSegmentPlane(p1, p2, plane, u12);
IntersectionTests.lineSegmentPlane(p1, p0, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
1,
3,
4,
2,
0,
4,
2,
4,
3
]
};
} else if (p2Behind) {
IntersectionTests.lineSegmentPlane(p2, p0, plane, u12);
IntersectionTests.lineSegmentPlane(p2, p1, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
2,
3,
4,
0,
1,
4,
0,
4,
3
]
};
}
} else if (numBehind === 2) {
if (!p0Behind) {
IntersectionTests.lineSegmentPlane(p1, p0, plane, u12);
IntersectionTests.lineSegmentPlane(p2, p0, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
1,
2,
4,
1,
4,
3,
0,
3,
4
]
};
} else if (!p1Behind) {
IntersectionTests.lineSegmentPlane(p2, p1, plane, u12);
IntersectionTests.lineSegmentPlane(p0, p1, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
2,
0,
4,
2,
4,
3,
1,
3,
4
]
};
} else if (!p2Behind) {
IntersectionTests.lineSegmentPlane(p0, p2, plane, u12);
IntersectionTests.lineSegmentPlane(p1, p2, plane, u22);
return {
positions: [p0, p1, p2, u12, u22],
indices: [
0,
1,
4,
0,
4,
3,
2,
3,
4
]
};
}
}
return void 0;
};
var IntersectionTests_default = IntersectionTests;
// node_modules/@cesium/engine/Source/Core/EllipsoidTangentPlane.js
var scratchCart4 = new Cartesian4_default();
function EllipsoidTangentPlane(origin, ellipsoid) {
Check_default.defined("origin", origin);
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
origin = ellipsoid.scaleToGeodeticSurface(origin);
if (!defined_default(origin)) {
throw new DeveloperError_default(
"origin must not be at the center of the ellipsoid."
);
}
const eastNorthUp = Transforms_default.eastNorthUpToFixedFrame(origin, ellipsoid);
this._ellipsoid = ellipsoid;
this._origin = origin;
this._xAxis = Cartesian3_default.fromCartesian4(
Matrix4_default.getColumn(eastNorthUp, 0, scratchCart4)
);
this._yAxis = Cartesian3_default.fromCartesian4(
Matrix4_default.getColumn(eastNorthUp, 1, scratchCart4)
);
const normal2 = Cartesian3_default.fromCartesian4(
Matrix4_default.getColumn(eastNorthUp, 2, scratchCart4)
);
this._plane = Plane_default.fromPointNormal(origin, normal2);
}
Object.defineProperties(EllipsoidTangentPlane.prototype, {
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
origin: {
get: function() {
return this._origin;
}
},
plane: {
get: function() {
return this._plane;
}
},
xAxis: {
get: function() {
return this._xAxis;
}
},
yAxis: {
get: function() {
return this._yAxis;
}
},
zAxis: {
get: function() {
return this._plane.normal;
}
}
});
var tmp = new AxisAlignedBoundingBox_default();
EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
Check_default.defined("cartesians", cartesians);
const box = AxisAlignedBoundingBox_default.fromPoints(cartesians, tmp);
return new EllipsoidTangentPlane(box.center, ellipsoid);
};
var scratchProjectPointOntoPlaneRay = new Ray_default();
var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3_default();
EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian11, result) {
Check_default.defined("cartesian", cartesian11);
const ray = scratchProjectPointOntoPlaneRay;
ray.origin = cartesian11;
Cartesian3_default.normalize(cartesian11, ray.direction);
let intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
if (!defined_default(intersectionPoint)) {
Cartesian3_default.negate(ray.direction, ray.direction);
intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
}
if (defined_default(intersectionPoint)) {
const v7 = Cartesian3_default.subtract(
intersectionPoint,
this._origin,
intersectionPoint
);
const x = Cartesian3_default.dot(this._xAxis, v7);
const y = Cartesian3_default.dot(this._yAxis, v7);
if (!defined_default(result)) {
return new Cartesian2_default(x, y);
}
result.x = x;
result.y = y;
return result;
}
return void 0;
};
EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
Check_default.defined("cartesians", cartesians);
if (!defined_default(result)) {
result = [];
}
let count = 0;
const length3 = cartesians.length;
for (let i = 0; i < length3; i++) {
const p = this.projectPointOntoPlane(cartesians[i], result[count]);
if (defined_default(p)) {
result[count] = p;
count++;
}
}
result.length = count;
return result;
};
EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian11, result) {
Check_default.defined("cartesian", cartesian11);
if (!defined_default(result)) {
result = new Cartesian2_default();
}
const ray = scratchProjectPointOntoPlaneRay;
ray.origin = cartesian11;
Cartesian3_default.clone(this._plane.normal, ray.direction);
let intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
if (!defined_default(intersectionPoint)) {
Cartesian3_default.negate(ray.direction, ray.direction);
intersectionPoint = IntersectionTests_default.rayPlane(
ray,
this._plane,
scratchProjectPointOntoPlaneCartesian3
);
}
const v7 = Cartesian3_default.subtract(
intersectionPoint,
this._origin,
intersectionPoint
);
const x = Cartesian3_default.dot(this._xAxis, v7);
const y = Cartesian3_default.dot(this._yAxis, v7);
result.x = x;
result.y = y;
return result;
};
EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
Check_default.defined("cartesians", cartesians);
if (!defined_default(result)) {
result = [];
}
const length3 = cartesians.length;
result.length = length3;
for (let i = 0; i < length3; i++) {
result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
}
return result;
};
var projectPointsOntoEllipsoidScratch = new Cartesian3_default();
EllipsoidTangentPlane.prototype.projectPointOntoEllipsoid = function(cartesian11, result) {
Check_default.defined("cartesian", cartesian11);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const ellipsoid = this._ellipsoid;
const origin = this._origin;
const xAxis = this._xAxis;
const yAxis = this._yAxis;
const tmp2 = projectPointsOntoEllipsoidScratch;
Cartesian3_default.multiplyByScalar(xAxis, cartesian11.x, tmp2);
result = Cartesian3_default.add(origin, tmp2, result);
Cartesian3_default.multiplyByScalar(yAxis, cartesian11.y, tmp2);
Cartesian3_default.add(result, tmp2, result);
ellipsoid.scaleToGeocentricSurface(result, result);
return result;
};
EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
Check_default.defined("cartesians", cartesians);
const length3 = cartesians.length;
if (!defined_default(result)) {
result = new Array(length3);
} else {
result.length = length3;
}
for (let i = 0; i < length3; ++i) {
result[i] = this.projectPointOntoEllipsoid(cartesians[i], result[i]);
}
return result;
};
var EllipsoidTangentPlane_default = EllipsoidTangentPlane;
// node_modules/@cesium/engine/Source/Core/OrientedBoundingBox.js
function OrientedBoundingBox(center, halfAxes) {
this.center = Cartesian3_default.clone(defaultValue_default(center, Cartesian3_default.ZERO));
this.halfAxes = Matrix3_default.clone(defaultValue_default(halfAxes, Matrix3_default.ZERO));
}
OrientedBoundingBox.packedLength = Cartesian3_default.packedLength + Matrix3_default.packedLength;
OrientedBoundingBox.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value.center, array, startingIndex);
Matrix3_default.pack(value.halfAxes, array, startingIndex + Cartesian3_default.packedLength);
return array;
};
OrientedBoundingBox.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
Cartesian3_default.unpack(array, startingIndex, result.center);
Matrix3_default.unpack(
array,
startingIndex + Cartesian3_default.packedLength,
result.halfAxes
);
return result;
};
var scratchCartesian1 = new Cartesian3_default();
var scratchCartesian2 = new Cartesian3_default();
var scratchCartesian32 = new Cartesian3_default();
var scratchCartesian4 = new Cartesian3_default();
var scratchCartesian5 = new Cartesian3_default();
var scratchCartesian6 = new Cartesian3_default();
var scratchCovarianceResult = new Matrix3_default();
var scratchEigenResult = {
unitary: new Matrix3_default(),
diagonal: new Matrix3_default()
};
OrientedBoundingBox.fromPoints = function(positions, result) {
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
if (!defined_default(positions) || positions.length === 0) {
result.halfAxes = Matrix3_default.ZERO;
result.center = Cartesian3_default.ZERO;
return result;
}
let i;
const length3 = positions.length;
const meanPoint = Cartesian3_default.clone(positions[0], scratchCartesian1);
for (i = 1; i < length3; i++) {
Cartesian3_default.add(meanPoint, positions[i], meanPoint);
}
const invLength = 1 / length3;
Cartesian3_default.multiplyByScalar(meanPoint, invLength, meanPoint);
let exx = 0;
let exy = 0;
let exz = 0;
let eyy = 0;
let eyz = 0;
let ezz = 0;
let p;
for (i = 0; i < length3; i++) {
p = Cartesian3_default.subtract(positions[i], meanPoint, scratchCartesian2);
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_default.computeEigenDecomposition(
covarianceMatrix,
scratchEigenResult
);
const rotation = Matrix3_default.clone(eigenDecomposition.unitary, result.halfAxes);
let v13 = Matrix3_default.getColumn(rotation, 0, scratchCartesian4);
let v23 = Matrix3_default.getColumn(rotation, 1, scratchCartesian5);
let v32 = Matrix3_default.getColumn(rotation, 2, scratchCartesian6);
let u12 = -Number.MAX_VALUE;
let u22 = -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 < length3; i++) {
p = positions[i];
u12 = Math.max(Cartesian3_default.dot(v13, p), u12);
u22 = Math.max(Cartesian3_default.dot(v23, p), u22);
u3 = Math.max(Cartesian3_default.dot(v32, p), u3);
l1 = Math.min(Cartesian3_default.dot(v13, p), l1);
l2 = Math.min(Cartesian3_default.dot(v23, p), l2);
l3 = Math.min(Cartesian3_default.dot(v32, p), l3);
}
v13 = Cartesian3_default.multiplyByScalar(v13, 0.5 * (l1 + u12), v13);
v23 = Cartesian3_default.multiplyByScalar(v23, 0.5 * (l2 + u22), v23);
v32 = Cartesian3_default.multiplyByScalar(v32, 0.5 * (l3 + u3), v32);
const center = Cartesian3_default.add(v13, v23, result.center);
Cartesian3_default.add(center, v32, center);
const scale = scratchCartesian32;
scale.x = u12 - l1;
scale.y = u22 - l2;
scale.z = u3 - l3;
Cartesian3_default.multiplyByScalar(scale, 0.5, scale);
Matrix3_default.multiplyByScale(result.halfAxes, scale, result.halfAxes);
return result;
};
var scratchOffset = new Cartesian3_default();
var scratchScale2 = new Cartesian3_default();
function fromPlaneExtents(planeOrigin, planeXAxis, planeYAxis, planeZAxis, minimumX, maximumX, minimumY, maximumY, minimumZ, maximumZ, result) {
if (!defined_default(minimumX) || !defined_default(maximumX) || !defined_default(minimumY) || !defined_default(maximumY) || !defined_default(minimumZ) || !defined_default(maximumZ)) {
throw new DeveloperError_default(
"all extents (minimum/maximum X/Y/Z) are required."
);
}
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
const halfAxes = result.halfAxes;
Matrix3_default.setColumn(halfAxes, 0, planeXAxis, halfAxes);
Matrix3_default.setColumn(halfAxes, 1, planeYAxis, halfAxes);
Matrix3_default.setColumn(halfAxes, 2, planeZAxis, halfAxes);
let centerOffset = scratchOffset;
centerOffset.x = (minimumX + maximumX) / 2;
centerOffset.y = (minimumY + maximumY) / 2;
centerOffset.z = (minimumZ + maximumZ) / 2;
const scale = scratchScale2;
scale.x = (maximumX - minimumX) / 2;
scale.y = (maximumY - minimumY) / 2;
scale.z = (maximumZ - minimumZ) / 2;
const center = result.center;
centerOffset = Matrix3_default.multiplyByVector(halfAxes, centerOffset, centerOffset);
Cartesian3_default.add(planeOrigin, centerOffset, center);
Matrix3_default.multiplyByScale(halfAxes, scale, halfAxes);
return result;
}
var scratchRectangleCenterCartographic = new Cartographic_default();
var scratchRectangleCenter = new Cartesian3_default();
var scratchPerimeterCartographicNC = new Cartographic_default();
var scratchPerimeterCartographicNW = new Cartographic_default();
var scratchPerimeterCartographicCW = new Cartographic_default();
var scratchPerimeterCartographicSW = new Cartographic_default();
var scratchPerimeterCartographicSC = new Cartographic_default();
var scratchPerimeterCartesianNC = new Cartesian3_default();
var scratchPerimeterCartesianNW = new Cartesian3_default();
var scratchPerimeterCartesianCW = new Cartesian3_default();
var scratchPerimeterCartesianSW = new Cartesian3_default();
var scratchPerimeterCartesianSC = new Cartesian3_default();
var scratchPerimeterProjectedNC = new Cartesian2_default();
var scratchPerimeterProjectedNW = new Cartesian2_default();
var scratchPerimeterProjectedCW = new Cartesian2_default();
var scratchPerimeterProjectedSW = new Cartesian2_default();
var scratchPerimeterProjectedSC = new Cartesian2_default();
var scratchPlaneOrigin = new Cartesian3_default();
var scratchPlaneNormal2 = new Cartesian3_default();
var scratchPlaneXAxis = new Cartesian3_default();
var scratchHorizonCartesian = new Cartesian3_default();
var scratchHorizonProjected = new Cartesian2_default();
var scratchMaxY = new Cartesian3_default();
var scratchMinY = new Cartesian3_default();
var scratchZ = new Cartesian3_default();
var scratchPlane2 = new Plane_default(Cartesian3_default.UNIT_X, 0);
OrientedBoundingBox.fromRectangle = function(rectangle, minimumHeight, maximumHeight, ellipsoid, result) {
if (!defined_default(rectangle)) {
throw new DeveloperError_default("rectangle is required");
}
if (rectangle.width < 0 || rectangle.width > Math_default.TWO_PI) {
throw new DeveloperError_default("Rectangle width must be between 0 and 2 * pi");
}
if (rectangle.height < 0 || rectangle.height > Math_default.PI) {
throw new DeveloperError_default("Rectangle height must be between 0 and pi");
}
if (defined_default(ellipsoid) && !Math_default.equalsEpsilon(
ellipsoid.radii.x,
ellipsoid.radii.y,
Math_default.EPSILON15
)) {
throw new DeveloperError_default(
"Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)"
);
}
minimumHeight = defaultValue_default(minimumHeight, 0);
maximumHeight = defaultValue_default(maximumHeight, 0);
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
let minX, maxX, minY, maxY, minZ, maxZ, plane;
if (rectangle.width <= Math_default.PI) {
const tangentPointCartographic = Rectangle_default.center(
rectangle,
scratchRectangleCenterCartographic
);
const tangentPoint = ellipsoid.cartographicToCartesian(
tangentPointCartographic,
scratchRectangleCenter
);
const tangentPlane = new EllipsoidTangentPlane_default(tangentPoint, ellipsoid);
plane = tangentPlane.plane;
const lonCenter = tangentPointCartographic.longitude;
const latCenter = rectangle.south < 0 && rectangle.north > 0 ? 0 : tangentPointCartographic.latitude;
const perimeterCartographicNC = Cartographic_default.fromRadians(
lonCenter,
rectangle.north,
maximumHeight,
scratchPerimeterCartographicNC
);
const perimeterCartographicNW = Cartographic_default.fromRadians(
rectangle.west,
rectangle.north,
maximumHeight,
scratchPerimeterCartographicNW
);
const perimeterCartographicCW = Cartographic_default.fromRadians(
rectangle.west,
latCenter,
maximumHeight,
scratchPerimeterCartographicCW
);
const perimeterCartographicSW = Cartographic_default.fromRadians(
rectangle.west,
rectangle.south,
maximumHeight,
scratchPerimeterCartographicSW
);
const perimeterCartographicSC = Cartographic_default.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;
maxY = Math.max(perimeterProjectedNW.y, perimeterProjectedNC.y);
minY = Math.min(perimeterProjectedSW.y, perimeterProjectedSC.y);
perimeterCartographicNW.height = perimeterCartographicSW.height = minimumHeight;
perimeterCartesianNW = ellipsoid.cartographicToCartesian(
perimeterCartographicNW,
scratchPerimeterCartesianNW
);
perimeterCartesianSW = ellipsoid.cartographicToCartesian(
perimeterCartographicSW,
scratchPerimeterCartesianSW
);
minZ = Math.min(
Plane_default.getPointDistance(plane, perimeterCartesianNW),
Plane_default.getPointDistance(plane, perimeterCartesianSW)
);
maxZ = maximumHeight;
return fromPlaneExtents(
tangentPlane.origin,
tangentPlane.xAxis,
tangentPlane.yAxis,
tangentPlane.zAxis,
minX,
maxX,
minY,
maxY,
minZ,
maxZ,
result
);
}
const fullyAboveEquator = rectangle.south > 0;
const fullyBelowEquator = rectangle.north < 0;
const latitudeNearestToEquator = fullyAboveEquator ? rectangle.south : fullyBelowEquator ? rectangle.north : 0;
const centerLongitude = Rectangle_default.center(
rectangle,
scratchRectangleCenterCartographic
).longitude;
const planeOrigin = Cartesian3_default.fromRadians(
centerLongitude,
latitudeNearestToEquator,
maximumHeight,
ellipsoid,
scratchPlaneOrigin
);
planeOrigin.z = 0;
const isPole = Math.abs(planeOrigin.x) < Math_default.EPSILON10 && Math.abs(planeOrigin.y) < Math_default.EPSILON10;
const planeNormal = !isPole ? Cartesian3_default.normalize(planeOrigin, scratchPlaneNormal2) : Cartesian3_default.UNIT_X;
const planeYAxis = Cartesian3_default.UNIT_Z;
const planeXAxis = Cartesian3_default.cross(
planeNormal,
planeYAxis,
scratchPlaneXAxis
);
plane = Plane_default.fromPointNormal(planeOrigin, planeNormal, scratchPlane2);
const horizonCartesian = Cartesian3_default.fromRadians(
centerLongitude + Math_default.PI_OVER_TWO,
latitudeNearestToEquator,
maximumHeight,
ellipsoid,
scratchHorizonCartesian
);
maxX = Cartesian3_default.dot(
Plane_default.projectPointOntoPlane(
plane,
horizonCartesian,
scratchHorizonProjected
),
planeXAxis
);
minX = -maxX;
maxY = Cartesian3_default.fromRadians(
0,
rectangle.north,
fullyBelowEquator ? minimumHeight : maximumHeight,
ellipsoid,
scratchMaxY
).z;
minY = Cartesian3_default.fromRadians(
0,
rectangle.south,
fullyAboveEquator ? minimumHeight : maximumHeight,
ellipsoid,
scratchMinY
).z;
const farZ = Cartesian3_default.fromRadians(
rectangle.east,
latitudeNearestToEquator,
maximumHeight,
ellipsoid,
scratchZ
);
minZ = Plane_default.getPointDistance(plane, farZ);
maxZ = 0;
return fromPlaneExtents(
planeOrigin,
planeXAxis,
planeYAxis,
planeNormal,
minX,
maxX,
minY,
maxY,
minZ,
maxZ,
result
);
};
OrientedBoundingBox.fromTransformation = function(transformation, result) {
Check_default.typeOf.object("transformation", transformation);
if (!defined_default(result)) {
result = new OrientedBoundingBox();
}
result.center = Matrix4_default.getTranslation(transformation, result.center);
result.halfAxes = Matrix4_default.getMatrix3(transformation, result.halfAxes);
result.halfAxes = Matrix3_default.multiplyByScalar(
result.halfAxes,
0.5,
result.halfAxes
);
return result;
};
OrientedBoundingBox.clone = function(box, result) {
if (!defined_default(box)) {
return void 0;
}
if (!defined_default(result)) {
return new OrientedBoundingBox(box.center, box.halfAxes);
}
Cartesian3_default.clone(box.center, result.center);
Matrix3_default.clone(box.halfAxes, result.halfAxes);
return result;
};
OrientedBoundingBox.intersectPlane = function(box, plane) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(plane)) {
throw new DeveloperError_default("plane is required.");
}
const center = box.center;
const normal2 = plane.normal;
const halfAxes = box.halfAxes;
const normalX = normal2.x, normalY = normal2.y, normalZ = normal2.z;
const radEffective = Math.abs(
normalX * halfAxes[Matrix3_default.COLUMN0ROW0] + normalY * halfAxes[Matrix3_default.COLUMN0ROW1] + normalZ * halfAxes[Matrix3_default.COLUMN0ROW2]
) + Math.abs(
normalX * halfAxes[Matrix3_default.COLUMN1ROW0] + normalY * halfAxes[Matrix3_default.COLUMN1ROW1] + normalZ * halfAxes[Matrix3_default.COLUMN1ROW2]
) + Math.abs(
normalX * halfAxes[Matrix3_default.COLUMN2ROW0] + normalY * halfAxes[Matrix3_default.COLUMN2ROW1] + normalZ * halfAxes[Matrix3_default.COLUMN2ROW2]
);
const distanceToPlane = Cartesian3_default.dot(normal2, center) + plane.distance;
if (distanceToPlane <= -radEffective) {
return Intersect_default.OUTSIDE;
} else if (distanceToPlane >= radEffective) {
return Intersect_default.INSIDE;
}
return Intersect_default.INTERSECTING;
};
var scratchCartesianU = new Cartesian3_default();
var scratchCartesianV = new Cartesian3_default();
var scratchCartesianW = new Cartesian3_default();
var scratchValidAxis2 = new Cartesian3_default();
var scratchValidAxis3 = new Cartesian3_default();
var scratchPPrime = new Cartesian3_default();
OrientedBoundingBox.distanceSquaredTo = function(box, cartesian11) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required.");
}
const offset2 = Cartesian3_default.subtract(cartesian11, box.center, scratchOffset);
const halfAxes = box.halfAxes;
let u3 = Matrix3_default.getColumn(halfAxes, 0, scratchCartesianU);
let v7 = Matrix3_default.getColumn(halfAxes, 1, scratchCartesianV);
let w = Matrix3_default.getColumn(halfAxes, 2, scratchCartesianW);
const uHalf = Cartesian3_default.magnitude(u3);
const vHalf = Cartesian3_default.magnitude(v7);
const wHalf = Cartesian3_default.magnitude(w);
let uValid = true;
let vValid = true;
let wValid = true;
if (uHalf > 0) {
Cartesian3_default.divideByScalar(u3, uHalf, u3);
} else {
uValid = false;
}
if (vHalf > 0) {
Cartesian3_default.divideByScalar(v7, vHalf, v7);
} else {
vValid = false;
}
if (wHalf > 0) {
Cartesian3_default.divideByScalar(w, wHalf, w);
} else {
wValid = false;
}
const numberOfDegenerateAxes = !uValid + !vValid + !wValid;
let validAxis1;
let validAxis2;
let validAxis3;
if (numberOfDegenerateAxes === 1) {
let degenerateAxis = u3;
validAxis1 = v7;
validAxis2 = w;
if (!vValid) {
degenerateAxis = v7;
validAxis1 = u3;
} else if (!wValid) {
degenerateAxis = w;
validAxis2 = u3;
}
validAxis3 = Cartesian3_default.cross(validAxis1, validAxis2, scratchValidAxis3);
if (degenerateAxis === u3) {
u3 = validAxis3;
} else if (degenerateAxis === v7) {
v7 = validAxis3;
} else if (degenerateAxis === w) {
w = validAxis3;
}
} else if (numberOfDegenerateAxes === 2) {
validAxis1 = u3;
if (vValid) {
validAxis1 = v7;
} else if (wValid) {
validAxis1 = w;
}
let crossVector = Cartesian3_default.UNIT_Y;
if (crossVector.equalsEpsilon(validAxis1, Math_default.EPSILON3)) {
crossVector = Cartesian3_default.UNIT_X;
}
validAxis2 = Cartesian3_default.cross(validAxis1, crossVector, scratchValidAxis2);
Cartesian3_default.normalize(validAxis2, validAxis2);
validAxis3 = Cartesian3_default.cross(validAxis1, validAxis2, scratchValidAxis3);
Cartesian3_default.normalize(validAxis3, validAxis3);
if (validAxis1 === u3) {
v7 = validAxis2;
w = validAxis3;
} else if (validAxis1 === v7) {
w = validAxis2;
u3 = validAxis3;
} else if (validAxis1 === w) {
u3 = validAxis2;
v7 = validAxis3;
}
} else if (numberOfDegenerateAxes === 3) {
u3 = Cartesian3_default.UNIT_X;
v7 = Cartesian3_default.UNIT_Y;
w = Cartesian3_default.UNIT_Z;
}
const pPrime = scratchPPrime;
pPrime.x = Cartesian3_default.dot(offset2, u3);
pPrime.y = Cartesian3_default.dot(offset2, v7);
pPrime.z = Cartesian3_default.dot(offset2, w);
let distanceSquared = 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;
};
var scratchCorner = new Cartesian3_default();
var scratchToCenter = new Cartesian3_default();
OrientedBoundingBox.computePlaneDistances = function(box, position, direction2, result) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(position)) {
throw new DeveloperError_default("position is required.");
}
if (!defined_default(direction2)) {
throw new DeveloperError_default("direction is required.");
}
if (!defined_default(result)) {
result = new Interval_default();
}
let minDist = Number.POSITIVE_INFINITY;
let maxDist = Number.NEGATIVE_INFINITY;
const center = box.center;
const halfAxes = box.halfAxes;
const u3 = Matrix3_default.getColumn(halfAxes, 0, scratchCartesianU);
const v7 = Matrix3_default.getColumn(halfAxes, 1, scratchCartesianV);
const w = Matrix3_default.getColumn(halfAxes, 2, scratchCartesianW);
const corner = Cartesian3_default.add(u3, v7, scratchCorner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.add(corner, center, corner);
const toCenter = Cartesian3_default.subtract(corner, position, scratchToCenter);
let mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.add(center, u3, corner);
Cartesian3_default.add(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.add(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.add(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.add(corner, v7, corner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.add(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.add(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
Cartesian3_default.subtract(center, u3, corner);
Cartesian3_default.subtract(corner, v7, corner);
Cartesian3_default.subtract(corner, w, corner);
Cartesian3_default.subtract(corner, position, toCenter);
mag = Cartesian3_default.dot(direction2, toCenter);
minDist = Math.min(mag, minDist);
maxDist = Math.max(mag, maxDist);
result.start = minDist;
result.stop = maxDist;
return result;
};
var scratchXAxis = new Cartesian3_default();
var scratchYAxis = new Cartesian3_default();
var scratchZAxis = new Cartesian3_default();
OrientedBoundingBox.computeCorners = function(box, result) {
Check_default.typeOf.object("box", box);
if (!defined_default(result)) {
result = [
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default()
];
}
const center = box.center;
const halfAxes = box.halfAxes;
const xAxis = Matrix3_default.getColumn(halfAxes, 0, scratchXAxis);
const yAxis = Matrix3_default.getColumn(halfAxes, 1, scratchYAxis);
const zAxis = Matrix3_default.getColumn(halfAxes, 2, scratchZAxis);
Cartesian3_default.clone(center, result[0]);
Cartesian3_default.subtract(result[0], xAxis, result[0]);
Cartesian3_default.subtract(result[0], yAxis, result[0]);
Cartesian3_default.subtract(result[0], zAxis, result[0]);
Cartesian3_default.clone(center, result[1]);
Cartesian3_default.subtract(result[1], xAxis, result[1]);
Cartesian3_default.subtract(result[1], yAxis, result[1]);
Cartesian3_default.add(result[1], zAxis, result[1]);
Cartesian3_default.clone(center, result[2]);
Cartesian3_default.subtract(result[2], xAxis, result[2]);
Cartesian3_default.add(result[2], yAxis, result[2]);
Cartesian3_default.subtract(result[2], zAxis, result[2]);
Cartesian3_default.clone(center, result[3]);
Cartesian3_default.subtract(result[3], xAxis, result[3]);
Cartesian3_default.add(result[3], yAxis, result[3]);
Cartesian3_default.add(result[3], zAxis, result[3]);
Cartesian3_default.clone(center, result[4]);
Cartesian3_default.add(result[4], xAxis, result[4]);
Cartesian3_default.subtract(result[4], yAxis, result[4]);
Cartesian3_default.subtract(result[4], zAxis, result[4]);
Cartesian3_default.clone(center, result[5]);
Cartesian3_default.add(result[5], xAxis, result[5]);
Cartesian3_default.subtract(result[5], yAxis, result[5]);
Cartesian3_default.add(result[5], zAxis, result[5]);
Cartesian3_default.clone(center, result[6]);
Cartesian3_default.add(result[6], xAxis, result[6]);
Cartesian3_default.add(result[6], yAxis, result[6]);
Cartesian3_default.subtract(result[6], zAxis, result[6]);
Cartesian3_default.clone(center, result[7]);
Cartesian3_default.add(result[7], xAxis, result[7]);
Cartesian3_default.add(result[7], yAxis, result[7]);
Cartesian3_default.add(result[7], zAxis, result[7]);
return result;
};
var scratchRotationScale = new Matrix3_default();
OrientedBoundingBox.computeTransformation = function(box, result) {
Check_default.typeOf.object("box", box);
if (!defined_default(result)) {
result = new Matrix4_default();
}
const translation3 = box.center;
const rotationScale = Matrix3_default.multiplyByUniformScale(
box.halfAxes,
2,
scratchRotationScale
);
return Matrix4_default.fromRotationTranslation(rotationScale, translation3, result);
};
var scratchBoundingSphere2 = new BoundingSphere_default();
OrientedBoundingBox.isOccluded = function(box, occluder) {
if (!defined_default(box)) {
throw new DeveloperError_default("box is required.");
}
if (!defined_default(occluder)) {
throw new DeveloperError_default("occluder is required.");
}
const sphere = BoundingSphere_default.fromOrientedBoundingBox(
box,
scratchBoundingSphere2
);
return !occluder.isBoundingSphereVisible(sphere);
};
OrientedBoundingBox.prototype.intersectPlane = function(plane) {
return OrientedBoundingBox.intersectPlane(this, plane);
};
OrientedBoundingBox.prototype.distanceSquaredTo = function(cartesian11) {
return OrientedBoundingBox.distanceSquaredTo(this, cartesian11);
};
OrientedBoundingBox.prototype.computePlaneDistances = function(position, direction2, result) {
return OrientedBoundingBox.computePlaneDistances(
this,
position,
direction2,
result
);
};
OrientedBoundingBox.prototype.computeCorners = function(result) {
return OrientedBoundingBox.computeCorners(this, result);
};
OrientedBoundingBox.prototype.computeTransformation = function(result) {
return OrientedBoundingBox.computeTransformation(this, result);
};
OrientedBoundingBox.prototype.isOccluded = function(occluder) {
return OrientedBoundingBox.isOccluded(this, occluder);
};
OrientedBoundingBox.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && Cartesian3_default.equals(left.center, right.center) && Matrix3_default.equals(left.halfAxes, right.halfAxes);
};
OrientedBoundingBox.prototype.clone = function(result) {
return OrientedBoundingBox.clone(this, result);
};
OrientedBoundingBox.prototype.equals = function(right) {
return OrientedBoundingBox.equals(this, right);
};
var OrientedBoundingBox_default = OrientedBoundingBox;
// node_modules/@cesium/engine/Source/Core/TerrainExaggeration.js
var TerrainExaggeration = {};
TerrainExaggeration.getHeight = function(height, scale, relativeHeight) {
return (height - relativeHeight) * scale + relativeHeight;
};
var scratchCartographic2 = new Cartesian3_default();
TerrainExaggeration.getPosition = function(position, ellipsoid, terrainExaggeration, terrainExaggerationRelativeHeight, result) {
const cartographic2 = ellipsoid.cartesianToCartographic(
position,
scratchCartographic2
);
const newHeight = TerrainExaggeration.getHeight(
cartographic2.height,
terrainExaggeration,
terrainExaggerationRelativeHeight
);
return Cartesian3_default.fromRadians(
cartographic2.longitude,
cartographic2.latitude,
newHeight,
ellipsoid,
result
);
};
var TerrainExaggeration_default = TerrainExaggeration;
// node_modules/@cesium/engine/Source/Shaders/ShadowVolumeAppearanceVS.js
var ShadowVolumeAppearanceVS_default = 'in vec3 position3DHigh;\nin vec3 position3DLow;\nin float batchId;\n\n#ifdef EXTRUDED_GEOMETRY\nin vec3 extrudeDirection;\n\nuniform float u_globeMinimumAltitude;\n#endif // EXTRUDED_GEOMETRY\n\n#ifdef PER_INSTANCE_COLOR\nout vec4 v_color;\n#endif // PER_INSTANCE_COLOR\n\n#ifdef TEXTURE_COORDINATES\n#ifdef SPHERICAL\nout vec4 v_sphericalExtents;\n#else // SPHERICAL\nout vec2 v_inversePlaneExtents;\nout vec4 v_westPlane;\nout vec4 v_southPlane;\n#endif // SPHERICAL\nout vec3 v_uvMinAndSphericalLongitudeRotation;\nout vec3 v_uMaxAndInverseDistance;\nout vec3 v_vMaxAndInverseDistance;\n#endif // TEXTURE_COORDINATES\n\nvoid main()\n{\n vec4 position = czm_computePosition();\n\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\n //extrudeDirection is zero for the top layer\n position = position + vec4(extrudeDirection * delta, 0.0);\n#endif\n\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\n // If the primitive is split across the IDL (planes2D_high.x > planes2D_high.w):\n // - If this vertex is on the east side of the IDL (position3DLow.y > 0.0, comparison with position3DHigh may produce artifacts)\n // - existing "east" is on the wrong side of the world, far away (planes2D_high/low.w)\n // - so set "east" as beyond the eastmost extent of the projection (idlSplitNewPlaneHiLow)\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\n // - else, if this vertex is on the west side of the IDL (position3DLow.y < 0.0)\n // - existing "west" is on the wrong side of the world, far away (planes2D_high/low.x)\n // - so set "west" as beyond the westmost extent of the projection (idlSplitNewPlaneHiLow)\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\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 // 3D case has smaller "plane extents," so planes encoded as a 64 bit position and 2 vec3s for distances/direction\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\n vec3 eastWard = southEastCorner - southWestCorner;\n float eastExtent = length(eastWard);\n eastWard /= eastExtent;\n\n vec3 northWard = northWestCorner - southWestCorner;\n float northExtent = length(northWard);\n northWard /= northExtent;\n\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\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\n#ifdef PER_INSTANCE_COLOR\n v_color = czm_batchTable_color(batchId);\n#endif\n\n gl_Position = czm_depthClamp(czm_modelViewProjectionRelativeToEye * position);\n}\n';
// node_modules/@cesium/engine/Source/Shaders/ShadowVolumeFS.js
var ShadowVolumeFS_default = "#ifdef VECTOR_TILE\nuniform vec4 u_highlightColor;\n#endif\n\nvoid main(void)\n{\n#ifdef VECTOR_TILE\n out_FragColor = czm_gammaCorrect(u_highlightColor);\n#else\n out_FragColor = vec4(1.0);\n#endif\n czm_writeDepthClamp();\n}\n";
// node_modules/@cesium/engine/Source/Scene/ClassificationType.js
var ClassificationType = {
TERRAIN: 0,
CESIUM_3D_TILE: 1,
BOTH: 2
};
ClassificationType.NUMBER_OF_CLASSIFICATION_TYPES = 3;
var ClassificationType_default = Object.freeze(ClassificationType);
// node_modules/@cesium/engine/Source/Scene/DepthFunction.js
var DepthFunction = {
NEVER: WebGLConstants_default.NEVER,
LESS: WebGLConstants_default.LESS,
EQUAL: WebGLConstants_default.EQUAL,
LESS_OR_EQUAL: WebGLConstants_default.LEQUAL,
GREATER: WebGLConstants_default.GREATER,
NOT_EQUAL: WebGLConstants_default.NOTEQUAL,
GREATER_OR_EQUAL: WebGLConstants_default.GEQUAL,
ALWAYS: WebGLConstants_default.ALWAYS
};
var DepthFunction_default = Object.freeze(DepthFunction);
// node_modules/@cesium/engine/Source/Core/subdivideArray.js
function subdivideArray(array, numberOfArrays) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required.");
}
if (!defined_default(numberOfArrays) || numberOfArrays < 1) {
throw new DeveloperError_default("numberOfArrays must be greater than 0.");
}
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;
}
var subdivideArray_default = subdivideArray;
// node_modules/@cesium/engine/Source/Scene/BatchTable.js
function BatchTable(context, attributes, numberOfInstances) {
if (!defined_default(context)) {
throw new DeveloperError_default("context is required");
}
if (!defined_default(attributes)) {
throw new DeveloperError_default("attributes is required");
}
if (!defined_default(numberOfInstances)) {
throw new DeveloperError_default("numberOfInstances is required");
}
this._attributes = attributes;
this._numberOfInstances = numberOfInstances;
if (attributes.length === 0) {
return;
}
const pixelDatatype = getDatatype(attributes);
const textureFloatSupported = context.floatingPointTexture;
const packFloats = pixelDatatype === PixelDatatype_default.FLOAT && !textureFloatSupported;
const offsets = createOffsets(attributes, packFloats);
const stride = getStride(offsets, attributes, packFloats);
const maxNumberOfInstancesPerRow = Math.floor(
ContextLimits_default.maximumTextureSize / stride
);
const instancesPerWidth = Math.min(
numberOfInstances,
maxNumberOfInstancesPerRow
);
const width = stride * instancesPerWidth;
const height = Math.ceil(numberOfInstances / instancesPerWidth);
const stepX = 1 / width;
const centerX = stepX * 0.5;
const stepY = 1 / height;
const centerY = stepY * 0.5;
this._textureDimensions = new Cartesian2_default(width, height);
this._textureStep = new Cartesian4_default(stepX, centerX, stepY, centerY);
this._pixelDatatype = !packFloats ? pixelDatatype : PixelDatatype_default.UNSIGNED_BYTE;
this._packFloats = packFloats;
this._offsets = offsets;
this._stride = stride;
this._texture = void 0;
const batchLength = 4 * width * height;
this._batchValues = pixelDatatype === PixelDatatype_default.FLOAT && !packFloats ? new Float32Array(batchLength) : new Uint8Array(batchLength);
this._batchValuesDirty = false;
}
Object.defineProperties(BatchTable.prototype, {
attributes: {
get: function() {
return this._attributes;
}
},
numberOfInstances: {
get: function() {
return this._numberOfInstances;
}
}
});
function getDatatype(attributes) {
let foundFloatDatatype = false;
const length3 = attributes.length;
for (let i = 0; i < length3; ++i) {
if (attributes[i].componentDatatype !== ComponentDatatype_default.UNSIGNED_BYTE) {
foundFloatDatatype = true;
break;
}
}
return foundFloatDatatype ? PixelDatatype_default.FLOAT : PixelDatatype_default.UNSIGNED_BYTE;
}
function getAttributeType(attributes, attributeIndex) {
const componentsPerAttribute = attributes[attributeIndex].componentsPerAttribute;
if (componentsPerAttribute === 2) {
return Cartesian2_default;
} else if (componentsPerAttribute === 3) {
return Cartesian3_default;
} else if (componentsPerAttribute === 4) {
return Cartesian4_default;
}
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_default.UNSIGNED_BYTE && packFloats) {
currentOffset += 4;
} else {
++currentOffset;
}
}
return offsets;
}
function getStride(offsets, attributes, packFloats) {
const length3 = offsets.length;
const lastOffset = offsets[length3 - 1];
const lastAttribute = attributes[length3 - 1];
const componentDatatype = lastAttribute.componentDatatype;
if (componentDatatype !== ComponentDatatype_default.UNSIGNED_BYTE && packFloats) {
return lastOffset + 4;
}
return lastOffset + 1;
}
var scratchPackedFloatCartesian4 = new Cartesian4_default();
function getPackedFloat(array, index, result) {
let packed = Cartesian4_default.unpack(array, index, scratchPackedFloatCartesian4);
const x = Cartesian4_default.unpackFloat(packed);
packed = Cartesian4_default.unpack(array, index + 4, scratchPackedFloatCartesian4);
const y = Cartesian4_default.unpackFloat(packed);
packed = Cartesian4_default.unpack(array, index + 8, scratchPackedFloatCartesian4);
const z = Cartesian4_default.unpackFloat(packed);
packed = Cartesian4_default.unpack(array, index + 12, scratchPackedFloatCartesian4);
const w = Cartesian4_default.unpackFloat(packed);
return Cartesian4_default.fromElements(x, y, z, w, result);
}
function setPackedAttribute(value, array, index) {
let packed = Cartesian4_default.packFloat(value.x, scratchPackedFloatCartesian4);
Cartesian4_default.pack(packed, array, index);
packed = Cartesian4_default.packFloat(value.y, packed);
Cartesian4_default.pack(packed, array, index + 4);
packed = Cartesian4_default.packFloat(value.z, packed);
Cartesian4_default.pack(packed, array, index + 8);
packed = Cartesian4_default.packFloat(value.w, packed);
Cartesian4_default.pack(packed, array, index + 12);
}
var scratchGetAttributeCartesian4 = new Cartesian4_default();
BatchTable.prototype.getBatchedAttribute = function(instanceIndex, attributeIndex, result) {
if (instanceIndex < 0 || instanceIndex >= this._numberOfInstances) {
throw new DeveloperError_default("instanceIndex is out of range.");
}
if (attributeIndex < 0 || attributeIndex >= this._attributes.length) {
throw new DeveloperError_default("attributeIndex is out of range");
}
const attributes = this._attributes;
const offset2 = this._offsets[attributeIndex];
const stride = this._stride;
const index = 4 * stride * instanceIndex + 4 * offset2;
let value;
if (this._packFloats && attributes[attributeIndex].componentDatatype !== PixelDatatype_default.UNSIGNED_BYTE) {
value = getPackedFloat(
this._batchValues,
index,
scratchGetAttributeCartesian4
);
} else {
value = Cartesian4_default.unpack(
this._batchValues,
index,
scratchGetAttributeCartesian4
);
}
const attributeType = getAttributeType(attributes, attributeIndex);
if (defined_default(attributeType.fromCartesian4)) {
return attributeType.fromCartesian4(value, result);
} else if (defined_default(attributeType.clone)) {
return attributeType.clone(value, result);
}
return value.x;
};
var setAttributeScratchValues = [
void 0,
void 0,
new Cartesian2_default(),
new Cartesian3_default(),
new Cartesian4_default()
];
var setAttributeScratchCartesian4 = new Cartesian4_default();
BatchTable.prototype.setBatchedAttribute = function(instanceIndex, attributeIndex, value) {
if (instanceIndex < 0 || instanceIndex >= this._numberOfInstances) {
throw new DeveloperError_default("instanceIndex is out of range.");
}
if (attributeIndex < 0 || attributeIndex >= this._attributes.length) {
throw new DeveloperError_default("attributeIndex is out of range");
}
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
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_default(attributeType.equals) ? attributeType.equals(currentAttribute, value) : currentAttribute === value;
if (entriesEqual) {
return;
}
const attributeValue = setAttributeScratchCartesian4;
attributeValue.x = defined_default(value.x) ? value.x : value;
attributeValue.y = defined_default(value.y) ? value.y : 0;
attributeValue.z = defined_default(value.z) ? value.z : 0;
attributeValue.w = defined_default(value.w) ? value.w : 0;
const offset2 = this._offsets[attributeIndex];
const stride = this._stride;
const index = 4 * stride * instanceIndex + 4 * offset2;
if (this._packFloats && attributes[attributeIndex].componentDatatype !== PixelDatatype_default.UNSIGNED_BYTE) {
setPackedAttribute(attributeValue, this._batchValues, index);
} else {
Cartesian4_default.pack(attributeValue, this._batchValues, index);
}
this._batchValuesDirty = true;
};
function createTexture(batchTable, context) {
const dimensions = batchTable._textureDimensions;
batchTable._texture = new Texture_default({
context,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: batchTable._pixelDatatype,
width: dimensions.x,
height: dimensions.y,
sampler: Sampler_default.NEAREST,
flipY: false
});
}
function updateTexture(batchTable) {
const dimensions = batchTable._textureDimensions;
batchTable._texture.copyFrom({
source: {
width: dimensions.x,
height: dimensions.y,
arrayBufferView: batchTable._batchValues
}
});
}
BatchTable.prototype.update = function(frameState) {
if (defined_default(this._texture) && !this._batchValuesDirty || this._attributes.length === 0) {
return;
}
this._batchValuesDirty = false;
if (!defined_default(this._texture)) {
createTexture(this, frameState.context);
}
updateTexture(this);
};
BatchTable.prototype.getUniformMapCallback = function() {
const that = this;
return function(uniformMap2) {
if (that._attributes.length === 0) {
return uniformMap2;
}
const batchUniformMap = {
batchTexture: function() {
return that._texture;
},
batchTextureDimensions: function() {
return that._textureDimensions;
},
batchTextureStep: function() {
return that._textureStep;
}
};
return combine_default(uniformMap2, batchUniformMap);
};
};
function getGlslComputeSt(batchTable) {
const stride = batchTable._stride;
if (batchTable._textureDimensions.y === 1) {
return `${"uniform vec4 batchTextureStep; \nvec2 computeSt(float batchId) \n{ \n float stepX = batchTextureStep.x; \n float centerX = batchTextureStep.y; \n float numberOfAttributes = float("}${stride});
return vec2(centerX + (batchId * numberOfAttributes * stepX), 0.5);
}
`;
}
return `${"uniform vec4 batchTextureStep; \nuniform vec2 batchTextureDimensions; \nvec2 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});
float xId = mod(batchId * numberOfAttributes, batchTextureDimensions.x);
float yId = floor(batchId * numberOfAttributes / batchTextureDimensions.x);
return vec2(centerX + (xId * stepX), centerY + (yId * stepY));
}
`;
}
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 offset2 = batchTable._offsets[attributeIndex];
let glslFunction = `${functionReturnType} ${functionName}(float batchId)
{
vec2 st = computeSt(batchId);
st.x += batchTextureStep.x * float(${offset2});
`;
if (batchTable._packFloats && attribute.componentDatatype !== PixelDatatype_default.UNSIGNED_BYTE) {
glslFunction += "vec4 textureValue; \ntextureValue.x = czm_unpackFloat(texture(batchTexture, st)); \ntextureValue.y = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x, 0.0))); \ntextureValue.z = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x * 2.0, 0.0))); \ntextureValue.w = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x * 3.0, 0.0))); \n";
} else {
glslFunction += " vec4 textureValue = texture(batchTexture, st); \n";
}
glslFunction += ` ${functionReturnType} value = textureValue${functionReturnValue};
`;
if (batchTable._pixelDatatype === PixelDatatype_default.UNSIGNED_BYTE && attribute.componentDatatype === ComponentDatatype_default.UNSIGNED_BYTE && !attribute.normalize) {
glslFunction += "value *= 255.0; \n";
} else if (batchTable._pixelDatatype === PixelDatatype_default.FLOAT && attribute.componentDatatype === ComponentDatatype_default.UNSIGNED_BYTE && attribute.normalize) {
glslFunction += "value /= 255.0; \n";
}
glslFunction += " return value; \n} \n";
return glslFunction;
}
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(this)}
`;
const length3 = attributes.length;
for (let i = 0; i < length3; ++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}
${batchTableShader}
${afterMain}`;
};
};
BatchTable.prototype.isDestroyed = function() {
return false;
};
BatchTable.prototype.destroy = function() {
this._texture = this._texture && this._texture.destroy();
return destroyObject_default(this);
};
var BatchTable_default = BatchTable;
// node_modules/@cesium/engine/Source/Scene/AttributeType.js
var AttributeType = {
SCALAR: "SCALAR",
VEC2: "VEC2",
VEC3: "VEC3",
VEC4: "VEC4",
MAT2: "MAT2",
MAT3: "MAT3",
MAT4: "MAT4"
};
AttributeType.getMathType = function(attributeType) {
switch (attributeType) {
case AttributeType.SCALAR:
return Number;
case AttributeType.VEC2:
return Cartesian2_default;
case AttributeType.VEC3:
return Cartesian3_default;
case AttributeType.VEC4:
return Cartesian4_default;
case AttributeType.MAT2:
return Matrix2_default;
case AttributeType.MAT3:
return Matrix3_default;
case AttributeType.MAT4:
return Matrix4_default;
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
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;
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
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;
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
AttributeType.getGlslType = function(attributeType) {
Check_default.typeOf.string("attributeType", attributeType);
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";
default:
throw new DeveloperError_default("attributeType is not a valid value.");
}
};
var AttributeType_default = Object.freeze(AttributeType);
// node_modules/@cesium/engine/Source/Core/AttributeCompression.js
var RIGHT_SHIFT = 1 / 256;
var LEFT_SHIFT = 256;
var AttributeCompression = {};
AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
Check_default.defined("vector", vector);
Check_default.defined("result", result);
const magSquared = Cartesian3_default.magnitudeSquared(vector);
if (Math.abs(magSquared - 1) > Math_default.EPSILON6) {
throw new DeveloperError_default("vector must be normalized.");
}
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 - Math.abs(y)) * Math_default.signNotZero(x);
result.y = (1 - Math.abs(x)) * Math_default.signNotZero(y);
}
result.x = Math_default.toSNorm(result.x, rangeMax);
result.y = Math_default.toSNorm(result.y, rangeMax);
return result;
};
AttributeCompression.octEncode = function(vector, result) {
return AttributeCompression.octEncodeInRange(vector, 255, result);
};
var octEncodeScratch = new Cartesian2_default();
var uint8ForceArray = new Uint8Array(1);
function forceUint8(value) {
uint8ForceArray[0] = value;
return uint8ForceArray[0];
}
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;
};
AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
Check_default.defined("result", result);
if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
throw new DeveloperError_default(
`x and y must be unsigned normalized integers between 0 and ${rangeMax}`
);
}
result.x = Math_default.fromSNorm(x, rangeMax);
result.y = Math_default.fromSNorm(y, rangeMax);
result.z = 1 - (Math.abs(result.x) + Math.abs(result.y));
if (result.z < 0) {
const oldVX = result.x;
result.x = (1 - Math.abs(result.y)) * Math_default.signNotZero(oldVX);
result.y = (1 - Math.abs(oldVX)) * Math_default.signNotZero(result.y);
}
return Cartesian3_default.normalize(result, result);
};
AttributeCompression.octDecode = function(x, y, result) {
return AttributeCompression.octDecodeInRange(x, y, 255, result);
};
AttributeCompression.octDecodeFromCartesian4 = function(encoded, result) {
Check_default.typeOf.object("encoded", encoded);
Check_default.typeOf.object("result", result);
const x = encoded.x;
const y = encoded.y;
const z = encoded.z;
const w = encoded.w;
if (x < 0 || x > 255 || y < 0 || y > 255 || z < 0 || z > 255 || w < 0 || w > 255) {
throw new DeveloperError_default(
"x, y, z, and w must be unsigned normalized integers between 0 and 255"
);
}
const xOct16 = x * LEFT_SHIFT + y;
const yOct16 = z * LEFT_SHIFT + w;
return AttributeCompression.octDecodeInRange(xOct16, yOct16, 65535, result);
};
AttributeCompression.octPackFloat = function(encoded) {
Check_default.defined("encoded", encoded);
return 256 * encoded.x + encoded.y;
};
var scratchEncodeCart2 = new Cartesian2_default();
AttributeCompression.octEncodeFloat = function(vector) {
AttributeCompression.octEncode(vector, scratchEncodeCart2);
return AttributeCompression.octPackFloat(scratchEncodeCart2);
};
AttributeCompression.octDecodeFloat = function(value, result) {
Check_default.defined("value", value);
const temp = value / 256;
const x = Math.floor(temp);
const y = (temp - x) * 256;
return AttributeCompression.octDecode(x, y, result);
};
AttributeCompression.octPack = function(v13, v23, v32, result) {
Check_default.defined("v1", v13);
Check_default.defined("v2", v23);
Check_default.defined("v3", v32);
Check_default.defined("result", result);
const encoded1 = AttributeCompression.octEncodeFloat(v13);
const encoded2 = AttributeCompression.octEncodeFloat(v23);
const encoded3 = AttributeCompression.octEncode(v32, scratchEncodeCart2);
result.x = 65536 * encoded3.x + encoded1;
result.y = 65536 * encoded3.y + encoded2;
return result;
};
AttributeCompression.octUnpack = function(packed, v13, v23, v32) {
Check_default.defined("packed", packed);
Check_default.defined("v1", v13);
Check_default.defined("v2", v23);
Check_default.defined("v3", v32);
let temp = packed.x / 65536;
const x = Math.floor(temp);
const encodedFloat1 = (temp - x) * 65536;
temp = packed.y / 65536;
const y = Math.floor(temp);
const encodedFloat2 = (temp - y) * 65536;
AttributeCompression.octDecodeFloat(encodedFloat1, v13);
AttributeCompression.octDecodeFloat(encodedFloat2, v23);
AttributeCompression.octDecode(x, y, v32);
};
AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
Check_default.defined("textureCoordinates", textureCoordinates);
const x = textureCoordinates.x * 4095 | 0;
const y = textureCoordinates.y * 4095 | 0;
return 4096 * x + y;
};
AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
Check_default.defined("compressed", compressed);
Check_default.defined("result", result);
const temp = compressed / 4096;
const xZeroTo4095 = Math.floor(temp);
result.x = xZeroTo4095 / 4095;
result.y = (compressed - xZeroTo4095 * 4096) / 4095;
return result;
};
function zigZagDecode(value) {
return value >> 1 ^ -(value & 1);
}
AttributeCompression.zigZagDeltaDecode = function(uBuffer, vBuffer, heightBuffer) {
Check_default.defined("uBuffer", uBuffer);
Check_default.defined("vBuffer", vBuffer);
Check_default.typeOf.number.equals(
"uBuffer.length",
"vBuffer.length",
uBuffer.length,
vBuffer.length
);
if (defined_default(heightBuffer)) {
Check_default.typeOf.number.equals(
"uBuffer.length",
"heightBuffer.length",
uBuffer.length,
heightBuffer.length
);
}
const count = uBuffer.length;
let u3 = 0;
let v7 = 0;
let height = 0;
for (let i = 0; i < count; ++i) {
u3 += zigZagDecode(uBuffer[i]);
v7 += zigZagDecode(vBuffer[i]);
uBuffer[i] = u3;
vBuffer[i] = v7;
if (defined_default(heightBuffer)) {
height += zigZagDecode(heightBuffer[i]);
heightBuffer[i] = height;
}
}
};
AttributeCompression.dequantize = function(typedArray, componentDatatype, type, count) {
Check_default.defined("typedArray", typedArray);
Check_default.defined("componentDatatype", componentDatatype);
Check_default.defined("type", type);
Check_default.defined("count", count);
const componentsPerAttribute = AttributeType_default.getNumberOfComponents(type);
let divisor;
switch (componentDatatype) {
case ComponentDatatype_default.BYTE:
divisor = 127;
break;
case ComponentDatatype_default.UNSIGNED_BYTE:
divisor = 255;
break;
case ComponentDatatype_default.SHORT:
divisor = 32767;
break;
case ComponentDatatype_default.UNSIGNED_SHORT:
divisor = 65535;
break;
case ComponentDatatype_default.INT:
divisor = 2147483647;
break;
case ComponentDatatype_default.UNSIGNED_INT:
divisor = 4294967295;
break;
default:
throw new DeveloperError_default(
`Cannot dequantize component datatype: ${componentDatatype}`
);
}
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
);
}
}
return dequantizedTypedArray;
};
AttributeCompression.decodeRGB565 = function(typedArray, result) {
Check_default.defined("typedArray", typedArray);
const expectedLength = typedArray.length * 3;
if (defined_default(result)) {
Check_default.typeOf.number.equals(
"result.length",
"typedArray.length * 3",
result.length,
expectedLength
);
}
const count = typedArray.length;
if (!defined_default(result)) {
result = new Float32Array(count * 3);
}
const mask5 = (1 << 5) - 1;
const mask6 = (1 << 6) - 1;
const normalize5 = 1 / 31;
const normalize6 = 1 / 63;
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 offset2 = 3 * i;
result[offset2] = red * normalize5;
result[offset2 + 1] = green * normalize6;
result[offset2 + 2] = blue * normalize5;
}
return result;
};
var AttributeCompression_default = AttributeCompression;
// node_modules/@cesium/engine/Source/Core/barycentricCoordinates.js
var scratchCartesian12 = new Cartesian3_default();
var scratchCartesian22 = new Cartesian3_default();
var scratchCartesian33 = new Cartesian3_default();
function barycentricCoordinates(point, p0, p1, p2, result) {
Check_default.defined("point", point);
Check_default.defined("p0", p0);
Check_default.defined("p1", p1);
Check_default.defined("p2", p2);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
let v02;
let v13;
let v23;
let dot00;
let dot01;
let dot02;
let dot11;
let dot12;
if (!defined_default(p0.z)) {
if (Cartesian2_default.equalsEpsilon(point, p0, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_X, result);
}
if (Cartesian2_default.equalsEpsilon(point, p1, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Y, result);
}
if (Cartesian2_default.equalsEpsilon(point, p2, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Z, result);
}
v02 = Cartesian2_default.subtract(p1, p0, scratchCartesian12);
v13 = Cartesian2_default.subtract(p2, p0, scratchCartesian22);
v23 = Cartesian2_default.subtract(point, p0, scratchCartesian33);
dot00 = Cartesian2_default.dot(v02, v02);
dot01 = Cartesian2_default.dot(v02, v13);
dot02 = Cartesian2_default.dot(v02, v23);
dot11 = Cartesian2_default.dot(v13, v13);
dot12 = Cartesian2_default.dot(v13, v23);
} else {
if (Cartesian3_default.equalsEpsilon(point, p0, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_X, result);
}
if (Cartesian3_default.equalsEpsilon(point, p1, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Y, result);
}
if (Cartesian3_default.equalsEpsilon(point, p2, Math_default.EPSILON14)) {
return Cartesian3_default.clone(Cartesian3_default.UNIT_Z, result);
}
v02 = Cartesian3_default.subtract(p1, p0, scratchCartesian12);
v13 = Cartesian3_default.subtract(p2, p0, scratchCartesian22);
v23 = Cartesian3_default.subtract(point, p0, scratchCartesian33);
dot00 = Cartesian3_default.dot(v02, v02);
dot01 = Cartesian3_default.dot(v02, v13);
dot02 = Cartesian3_default.dot(v02, v23);
dot11 = Cartesian3_default.dot(v13, v13);
dot12 = Cartesian3_default.dot(v13, v23);
}
result.y = dot11 * dot02 - dot01 * dot12;
result.z = dot00 * dot12 - dot01 * dot02;
const q = dot00 * dot11 - dot01 * dot01;
if (q === 0) {
return void 0;
}
result.y /= q;
result.z /= q;
result.x = 1 - result.y - result.z;
return result;
}
var barycentricCoordinates_default = barycentricCoordinates;
// node_modules/@cesium/engine/Source/Core/Tipsify.js
var Tipsify = {};
Tipsify.calculateACMR = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const indices2 = options.indices;
let maximumIndex = options.maximumIndex;
const cacheSize = defaultValue_default(options.cacheSize, 24);
if (!defined_default(indices2)) {
throw new DeveloperError_default("indices is required.");
}
const numIndices = indices2.length;
if (numIndices < 3 || numIndices % 3 !== 0) {
throw new DeveloperError_default("indices length must be a multiple of three.");
}
if (maximumIndex <= 0) {
throw new DeveloperError_default("maximumIndex must be greater than zero.");
}
if (cacheSize < 3) {
throw new DeveloperError_default("cacheSize must be greater than two.");
}
if (!defined_default(maximumIndex)) {
maximumIndex = 0;
let currentIndex = 0;
let intoIndices = indices2[currentIndex];
while (currentIndex < numIndices) {
if (intoIndices > maximumIndex) {
maximumIndex = intoIndices;
}
++currentIndex;
intoIndices = indices2[currentIndex];
}
}
const vertexTimeStamps = [];
for (let i = 0; i < maximumIndex + 1; i++) {
vertexTimeStamps[i] = 0;
}
let s = cacheSize + 1;
for (let j = 0; j < numIndices; ++j) {
if (s - vertexTimeStamps[indices2[j]] > cacheSize) {
vertexTimeStamps[indices2[j]] = s;
++s;
}
}
return (s - cacheSize + 1) / (numIndices / 3);
};
Tipsify.tipsify = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const indices2 = options.indices;
const maximumIndex = options.maximumIndex;
const cacheSize = defaultValue_default(options.cacheSize, 24);
let cursor;
function skipDeadEnd(vertices2, deadEnd2, indices3, maximumIndexPlusOne2) {
while (deadEnd2.length >= 1) {
const d = deadEnd2[deadEnd2.length - 1];
deadEnd2.splice(deadEnd2.length - 1, 1);
if (vertices2[d].numLiveTriangles > 0) {
return d;
}
}
while (cursor < maximumIndexPlusOne2) {
if (vertices2[cursor].numLiveTriangles > 0) {
++cursor;
return cursor - 1;
}
++cursor;
}
return -1;
}
function getNextVertex(indices3, cacheSize2, oneRing2, vertices2, s2, deadEnd2, maximumIndexPlusOne2) {
let n = -1;
let p;
let m = -1;
let itOneRing = 0;
while (itOneRing < oneRing2.length) {
const index2 = oneRing2[itOneRing];
if (vertices2[index2].numLiveTriangles) {
p = 0;
if (s2 - vertices2[index2].timeStamp + 2 * vertices2[index2].numLiveTriangles <= cacheSize2) {
p = s2 - vertices2[index2].timeStamp;
}
if (p > m || m === -1) {
m = p;
n = index2;
}
}
++itOneRing;
}
if (n === -1) {
return skipDeadEnd(vertices2, deadEnd2, indices3, maximumIndexPlusOne2);
}
return n;
}
if (!defined_default(indices2)) {
throw new DeveloperError_default("indices is required.");
}
const numIndices = indices2.length;
if (numIndices < 3 || numIndices % 3 !== 0) {
throw new DeveloperError_default("indices length must be a multiple of three.");
}
if (maximumIndex <= 0) {
throw new DeveloperError_default("maximumIndex must be greater than zero.");
}
if (cacheSize < 3) {
throw new DeveloperError_default("cacheSize must be greater than two.");
}
let maximumIndexPlusOne = 0;
let currentIndex = 0;
let intoIndices = indices2[currentIndex];
const endIndex = numIndices;
if (defined_default(maximumIndex)) {
maximumIndexPlusOne = maximumIndex + 1;
} else {
while (currentIndex < endIndex) {
if (intoIndices > maximumIndexPlusOne) {
maximumIndexPlusOne = intoIndices;
}
++currentIndex;
intoIndices = indices2[currentIndex];
}
if (maximumIndexPlusOne === -1) {
return 0;
}
++maximumIndexPlusOne;
}
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[indices2[currentIndex]].vertexTriangles.push(triangle);
++vertices[indices2[currentIndex]].numLiveTriangles;
vertices[indices2[currentIndex + 1]].vertexTriangles.push(triangle);
++vertices[indices2[currentIndex + 1]].numLiveTriangles;
vertices[indices2[currentIndex + 2]].vertexTriangles.push(triangle);
++vertices[indices2[currentIndex + 2]].numLiveTriangles;
++triangle;
currentIndex += 3;
}
let f = 0;
let s = cacheSize + 1;
cursor = 1;
let oneRing = [];
const deadEnd = [];
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) {
index = indices2[currentIndex];
oneRing.push(index);
deadEnd.push(index);
outputIndices[currentOutputIndex] = index;
++currentOutputIndex;
vertex = vertices[index];
--vertex.numLiveTriangles;
if (s - vertex.timeStamp > cacheSize) {
vertex.timeStamp = s;
++s;
}
++currentIndex;
}
}
}
f = getNextVertex(
indices2,
cacheSize,
oneRing,
vertices,
s,
deadEnd,
maximumIndexPlusOne
);
}
return outputIndices;
};
var Tipsify_default = Tipsify;
// node_modules/@cesium/engine/Source/Core/GeometryPipeline.js
var 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_default.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_default.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_default.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();
}
GeometryPipeline.toWireframe = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const indices2 = geometry.indices;
if (defined_default(indices2)) {
switch (geometry.primitiveType) {
case PrimitiveType_default.TRIANGLES:
geometry.indices = trianglesToLines(indices2);
break;
case PrimitiveType_default.TRIANGLE_STRIP:
geometry.indices = triangleStripToLines(indices2);
break;
case PrimitiveType_default.TRIANGLE_FAN:
geometry.indices = triangleFanToLines(indices2);
break;
default:
throw new DeveloperError_default(
"geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN."
);
}
geometry.primitiveType = PrimitiveType_default.LINES;
}
return geometry;
};
GeometryPipeline.createLineSegmentsForVectors = function(geometry, attributeName, length3) {
attributeName = defaultValue_default(attributeName, "normal");
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(geometry.attributes.position)) {
throw new DeveloperError_default("geometry.attributes.position is required.");
}
if (!defined_default(geometry.attributes[attributeName])) {
throw new DeveloperError_default(
`geometry.attributes must have an attribute with the same name as the attributeName parameter, ${attributeName}.`
);
}
length3 = defaultValue_default(length3, 1e4);
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] * length3;
newPositions[j++] = positions[i + 1] + vectors[i + 1] * length3;
newPositions[j++] = positions[i + 2] + vectors[i + 2] * length3;
}
let newBoundingSphere;
const bs = geometry.boundingSphere;
if (defined_default(bs)) {
newBoundingSphere = new BoundingSphere_default(bs.center, bs.radius + length3);
}
return new Geometry_default({
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: newPositions
})
},
primitiveType: PrimitiveType_default.LINES,
boundingSphere: newBoundingSphere
});
};
GeometryPipeline.createAttributeLocations = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const semantics = [
"position",
"positionHigh",
"positionLow",
"position3DHigh",
"position3DLow",
"position2DHigh",
"position2DLow",
"pickColor",
"normal",
"st",
"tangent",
"bitangent",
"extrudeDirection",
"compressedAttributes"
];
const attributes = geometry.attributes;
const indices2 = {};
let j = 0;
let i;
const len = semantics.length;
for (i = 0; i < len; ++i) {
const semantic = semantics[i];
if (defined_default(attributes[semantic])) {
indices2[semantic] = j++;
}
}
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && !defined_default(indices2[name])) {
indices2[name] = j++;
}
}
return indices2;
};
GeometryPipeline.reorderForPreVertexCache = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const numVertices = Geometry_default.computeNumberOfVertices(geometry);
const indices2 = geometry.indices;
if (defined_default(indices2)) {
const indexCrossReferenceOldToNew = new Int32Array(numVertices);
for (let i = 0; i < numVertices; i++) {
indexCrossReferenceOldToNew[i] = -1;
}
const indicesIn = indices2;
const numIndices = indicesIn.length;
const indicesOut = IndexDatatype_default.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;
const attributes = geometry.attributes;
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property]) && defined_default(attributes[property].values)) {
const attribute = attributes[property];
const elementsIn = attribute.values;
let intoElementsIn = 0;
const numComponents = attribute.componentsPerAttribute;
const elementsOut = ComponentDatatype_default.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;
};
GeometryPipeline.reorderForPostVertexCache = function(geometry, cacheCapacity) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const indices2 = geometry.indices;
if (geometry.primitiveType === PrimitiveType_default.TRIANGLES && defined_default(indices2)) {
const numIndices = indices2.length;
let maximumIndex = 0;
for (let j = 0; j < numIndices; j++) {
if (indices2[j] > maximumIndex) {
maximumIndex = indices2[j];
}
}
geometry.indices = Tipsify_default.tipsify({
indices: indices2,
maximumIndex,
cacheSize: cacheCapacity
});
}
return geometry;
};
function copyAttributesDescriptions(attributes) {
const newAttributes = {};
for (const attribute in attributes) {
if (attributes.hasOwnProperty(attribute) && defined_default(attributes[attribute]) && defined_default(attributes[attribute].values)) {
const attr = attributes[attribute];
newAttributes[attribute] = new GeometryAttribute_default({
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_default(sourceAttributes[attribute]) && defined_default(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]
);
}
}
}
}
GeometryPipeline.fitToUnsignedShortIndices = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (defined_default(geometry.indices) && geometry.primitiveType !== PrimitiveType_default.TRIANGLES && geometry.primitiveType !== PrimitiveType_default.LINES && geometry.primitiveType !== PrimitiveType_default.POINTS) {
throw new DeveloperError_default(
"geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS."
);
}
const geometries = [];
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (defined_default(geometry.indices) && numberOfVertices >= Math_default.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_default.TRIANGLES) {
indicesPerPrimitive = 3;
} else if (geometry.primitiveType === PrimitiveType_default.LINES) {
indicesPerPrimitive = 2;
} else if (geometry.primitiveType === PrimitiveType_default.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_default(i)) {
i = currentIndex++;
oldToNewIndex[x] = i;
copyVertex(newAttributes, geometry.attributes, x);
}
newIndices.push(i);
}
if (currentIndex + indicesPerPrimitive >= Math_default.SIXTY_FOUR_KILOBYTES) {
geometries.push(
new Geometry_default({
attributes: newAttributes,
indices: newIndices,
primitiveType: geometry.primitiveType,
boundingSphere: geometry.boundingSphere,
boundingSphereCV: geometry.boundingSphereCV
})
);
oldToNewIndex = [];
newIndices = [];
currentIndex = 0;
newAttributes = copyAttributesDescriptions(geometry.attributes);
}
}
if (newIndices.length !== 0) {
geometries.push(
new Geometry_default({
attributes: newAttributes,
indices: newIndices,
primitiveType: geometry.primitiveType,
boundingSphere: geometry.boundingSphere,
boundingSphereCV: geometry.boundingSphereCV
})
);
}
} else {
geometries.push(geometry);
}
return geometries;
};
var scratchProjectTo2DCartesian3 = new Cartesian3_default();
var scratchProjectTo2DCartographic = new Cartographic_default();
GeometryPipeline.projectTo2D = function(geometry, attributeName, attributeName3D, attributeName2D, projection) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(attributeName)) {
throw new DeveloperError_default("attributeName is required.");
}
if (!defined_default(attributeName3D)) {
throw new DeveloperError_default("attributeName3D is required.");
}
if (!defined_default(attributeName2D)) {
throw new DeveloperError_default("attributeName2D is required.");
}
if (!defined_default(geometry.attributes[attributeName])) {
throw new DeveloperError_default(
`geometry must have attribute matching the attributeName argument: ${attributeName}.`
);
}
if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype_default.DOUBLE) {
throw new DeveloperError_default(
"The attribute componentDatatype must be ComponentDatatype.DOUBLE."
);
}
const attribute = geometry.attributes[attributeName];
projection = defined_default(projection) ? projection : new GeographicProjection_default();
const ellipsoid = projection.ellipsoid;
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_default.fromArray(
values3D,
i,
scratchProjectTo2DCartesian3
);
const lonLat = ellipsoid.cartesianToCartographic(
value,
scratchProjectTo2DCartographic
);
if (!defined_default(lonLat)) {
throw new DeveloperError_default(
`Could not project point (${value.x}, ${value.y}, ${value.z}) to 2D.`
);
}
const projectedLonLat = projection.project(
lonLat,
scratchProjectTo2DCartesian3
);
projectedValues[index++] = projectedLonLat.x;
projectedValues[index++] = projectedLonLat.y;
projectedValues[index++] = projectedLonLat.z;
}
geometry.attributes[attributeName3D] = attribute;
geometry.attributes[attributeName2D] = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: projectedValues
});
delete geometry.attributes[attributeName];
return geometry;
};
var encodedResult = {
high: 0,
low: 0
};
GeometryPipeline.encodeAttribute = function(geometry, attributeName, attributeHighName, attributeLowName) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(attributeName)) {
throw new DeveloperError_default("attributeName is required.");
}
if (!defined_default(attributeHighName)) {
throw new DeveloperError_default("attributeHighName is required.");
}
if (!defined_default(attributeLowName)) {
throw new DeveloperError_default("attributeLowName is required.");
}
if (!defined_default(geometry.attributes[attributeName])) {
throw new DeveloperError_default(
`geometry must have attribute matching the attributeName argument: ${attributeName}.`
);
}
if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype_default.DOUBLE) {
throw new DeveloperError_default(
"The attribute componentDatatype must be ComponentDatatype.DOUBLE."
);
}
const attribute = geometry.attributes[attributeName];
const values = attribute.values;
const length3 = values.length;
const highValues = new Float32Array(length3);
const lowValues = new Float32Array(length3);
for (let i = 0; i < length3; ++i) {
EncodedCartesian3_default.encode(values[i], encodedResult);
highValues[i] = encodedResult.high;
lowValues[i] = encodedResult.low;
}
const componentsPerAttribute = attribute.componentsPerAttribute;
geometry.attributes[attributeHighName] = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute,
values: highValues
});
geometry.attributes[attributeLowName] = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute,
values: lowValues
});
delete geometry.attributes[attributeName];
return geometry;
};
var scratchCartesian34 = new Cartesian3_default();
function transformPoint(matrix, attribute) {
if (defined_default(attribute)) {
const values = attribute.values;
const length3 = values.length;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.unpack(values, i, scratchCartesian34);
Matrix4_default.multiplyByPoint(matrix, scratchCartesian34, scratchCartesian34);
Cartesian3_default.pack(scratchCartesian34, values, i);
}
}
}
function transformVector(matrix, attribute) {
if (defined_default(attribute)) {
const values = attribute.values;
const length3 = values.length;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.unpack(values, i, scratchCartesian34);
Matrix3_default.multiplyByVector(matrix, scratchCartesian34, scratchCartesian34);
scratchCartesian34 = Cartesian3_default.normalize(
scratchCartesian34,
scratchCartesian34
);
Cartesian3_default.pack(scratchCartesian34, values, i);
}
}
}
var inverseTranspose = new Matrix4_default();
var normalMatrix = new Matrix3_default();
GeometryPipeline.transformToWorldCoordinates = function(instance) {
if (!defined_default(instance)) {
throw new DeveloperError_default("instance is required.");
}
const modelMatrix = instance.modelMatrix;
if (Matrix4_default.equals(modelMatrix, Matrix4_default.IDENTITY)) {
return instance;
}
const attributes = instance.geometry.attributes;
transformPoint(modelMatrix, attributes.position);
transformPoint(modelMatrix, attributes.prevPosition);
transformPoint(modelMatrix, attributes.nextPosition);
if (defined_default(attributes.normal) || defined_default(attributes.tangent) || defined_default(attributes.bitangent)) {
Matrix4_default.inverse(modelMatrix, inverseTranspose);
Matrix4_default.transpose(inverseTranspose, inverseTranspose);
Matrix4_default.getMatrix3(inverseTranspose, normalMatrix);
transformVector(normalMatrix, attributes.normal);
transformVector(normalMatrix, attributes.tangent);
transformVector(normalMatrix, attributes.bitangent);
}
const boundingSphere = instance.geometry.boundingSphere;
if (defined_default(boundingSphere)) {
instance.geometry.boundingSphere = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
boundingSphere
);
}
instance.modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
return instance;
};
function findAttributesInAllGeometries(instances, propertyName) {
const length3 = instances.length;
const attributesInAllGeometries = {};
const attributes0 = instances[0][propertyName].attributes;
let name;
for (name in attributes0) {
if (attributes0.hasOwnProperty(name) && defined_default(attributes0[name]) && defined_default(attributes0[name].values)) {
const attribute = attributes0[name];
let numberOfComponents = attribute.values.length;
let inAllGeometries = true;
for (let i = 1; i < length3; ++i) {
const otherAttribute = instances[i][propertyName].attributes[name];
if (!defined_default(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_default({
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
values: ComponentDatatype_default.createTypedArray(
attribute.componentDatatype,
numberOfComponents
)
});
}
}
}
return attributesInAllGeometries;
}
var tempScratch = new Cartesian3_default();
function combineGeometries(instances, propertyName) {
const length3 = instances.length;
let name;
let i;
let j;
let k;
const m = instances[0].modelMatrix;
const haveIndices = defined_default(instances[0][propertyName].indices);
const primitiveType = instances[0][propertyName].primitiveType;
for (i = 1; i < length3; ++i) {
if (!Matrix4_default.equals(instances[i].modelMatrix, m)) {
throw new DeveloperError_default("All instances must have the same modelMatrix.");
}
if (defined_default(instances[i][propertyName].indices) !== haveIndices) {
throw new DeveloperError_default(
"All instance geometries must have an indices or not have one."
);
}
if (instances[i][propertyName].primitiveType !== primitiveType) {
throw new DeveloperError_default(
"All instance geometries must have the same primitiveType."
);
}
}
const attributes = findAttributesInAllGeometries(instances, propertyName);
let values;
let sourceValues;
let sourceValuesLength;
for (name in attributes) {
if (attributes.hasOwnProperty(name)) {
values = attributes[name].values;
k = 0;
for (i = 0; i < length3; ++i) {
sourceValues = instances[i][propertyName].attributes[name].values;
sourceValuesLength = sourceValues.length;
for (j = 0; j < sourceValuesLength; ++j) {
values[k++] = sourceValues[j];
}
}
}
}
let indices2;
if (haveIndices) {
let numberOfIndices = 0;
for (i = 0; i < length3; ++i) {
numberOfIndices += instances[i][propertyName].indices.length;
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(
new Geometry_default({
attributes,
primitiveType: PrimitiveType_default.POINTS
})
);
const destIndices = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfIndices
);
let destOffset = 0;
let offset2 = 0;
for (i = 0; i < length3; ++i) {
const sourceIndices = instances[i][propertyName].indices;
const sourceIndicesLen = sourceIndices.length;
for (k = 0; k < sourceIndicesLen; ++k) {
destIndices[destOffset++] = offset2 + sourceIndices[k];
}
offset2 += Geometry_default.computeNumberOfVertices(instances[i][propertyName]);
}
indices2 = destIndices;
}
let center = new Cartesian3_default();
let radius = 0;
let bs;
for (i = 0; i < length3; ++i) {
bs = instances[i][propertyName].boundingSphere;
if (!defined_default(bs)) {
center = void 0;
break;
}
Cartesian3_default.add(bs.center, center, center);
}
if (defined_default(center)) {
Cartesian3_default.divideByScalar(center, length3, center);
for (i = 0; i < length3; ++i) {
bs = instances[i][propertyName].boundingSphere;
const tempRadius = Cartesian3_default.magnitude(
Cartesian3_default.subtract(bs.center, center, tempScratch)
) + bs.radius;
if (tempRadius > radius) {
radius = tempRadius;
}
}
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType,
boundingSphere: defined_default(center) ? new BoundingSphere_default(center, radius) : void 0
});
}
GeometryPipeline.combineInstances = function(instances) {
if (!defined_default(instances) || instances.length < 1) {
throw new DeveloperError_default(
"instances is required and must have length greater than zero."
);
}
const instanceGeometry = [];
const instanceSplitGeometry = [];
const length3 = instances.length;
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
if (defined_default(instance.geometry)) {
instanceGeometry.push(instance);
} else if (defined_default(instance.westHemisphereGeometry) && defined_default(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;
};
var normal = new Cartesian3_default();
var v0 = new Cartesian3_default();
var v1 = new Cartesian3_default();
var v2 = new Cartesian3_default();
GeometryPipeline.computeNormal = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
if (!defined_default(geometry.attributes.position) || !defined_default(geometry.attributes.position.values)) {
throw new DeveloperError_default(
"geometry.attributes.position.values is required."
);
}
if (!defined_default(geometry.indices)) {
throw new DeveloperError_default("geometry.indices is required.");
}
if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) {
throw new DeveloperError_default(
"geometry.indices length must be greater than 0 and be a multiple of 3."
);
}
if (geometry.primitiveType !== PrimitiveType_default.TRIANGLES) {
throw new DeveloperError_default(
"geometry.primitiveType must be PrimitiveType.TRIANGLES."
);
}
const indices2 = geometry.indices;
const attributes = geometry.attributes;
const vertices = attributes.position.values;
const numVertices = attributes.position.values.length / 3;
const numIndices = indices2.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 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[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.x = vertices[i13];
v1.y = vertices[i13 + 1];
v1.z = vertices[i13 + 2];
v2.x = vertices[i23];
v2.y = vertices[i23 + 1];
v2.z = vertices[i23 + 2];
normalsPerVertex[i0].count++;
normalsPerVertex[i1].count++;
normalsPerVertex[i2].count++;
Cartesian3_default.subtract(v1, v0, v1);
Cartesian3_default.subtract(v2, v0, v2);
normalsPerTriangle[j] = Cartesian3_default.cross(v1, v2, new Cartesian3_default());
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[indices2[i]];
let index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
normalIndices[index] = j;
vertexNormalData.currentCount++;
vertexNormalData = normalsPerVertex[indices2[i + 1]];
index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
normalIndices[index] = j;
vertexNormalData.currentCount++;
vertexNormalData = normalsPerVertex[indices2[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_default.clone(Cartesian3_default.ZERO, normal);
if (vertexNormalData.count > 0) {
for (j = 0; j < vertexNormalData.count; j++) {
Cartesian3_default.add(
normal,
normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]],
normal
);
}
if (Cartesian3_default.equalsEpsilon(Cartesian3_default.ZERO, normal, Math_default.EPSILON10)) {
Cartesian3_default.clone(
normalsPerTriangle[normalIndices[vertexNormalData.indexOffset]],
normal
);
}
}
if (Cartesian3_default.equalsEpsilon(Cartesian3_default.ZERO, normal, Math_default.EPSILON10)) {
normal.z = 1;
}
Cartesian3_default.normalize(normal, normal);
normalValues[i3] = normal.x;
normalValues[i3 + 1] = normal.y;
normalValues[i3 + 2] = normal.z;
}
geometry.attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normalValues
});
return geometry;
};
var normalScratch2 = new Cartesian3_default();
var normalScale = new Cartesian3_default();
var tScratch = new Cartesian3_default();
GeometryPipeline.computeTangentAndBitangent = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const attributes = geometry.attributes;
const indices2 = geometry.indices;
if (!defined_default(attributes.position) || !defined_default(attributes.position.values)) {
throw new DeveloperError_default(
"geometry.attributes.position.values is required."
);
}
if (!defined_default(attributes.normal) || !defined_default(attributes.normal.values)) {
throw new DeveloperError_default("geometry.attributes.normal.values is required.");
}
if (!defined_default(attributes.st) || !defined_default(attributes.st.values)) {
throw new DeveloperError_default("geometry.attributes.st.values is required.");
}
if (!defined_default(indices2)) {
throw new DeveloperError_default("geometry.indices is required.");
}
if (indices2.length < 2 || indices2.length % 3 !== 0) {
throw new DeveloperError_default(
"geometry.indices length must be greater than 0 and be a multiple of 3."
);
}
if (geometry.primitiveType !== PrimitiveType_default.TRIANGLES) {
throw new DeveloperError_default(
"geometry.primitiveType must be PrimitiveType.TRIANGLES."
);
}
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 = indices2.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 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[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 / ((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_default.fromArray(normals, i03, normalScratch2);
const t = Cartesian3_default.fromArray(tan1, i03, tScratch);
const scalar = Cartesian3_default.dot(n, t);
Cartesian3_default.multiplyByScalar(n, scalar, normalScale);
Cartesian3_default.normalize(Cartesian3_default.subtract(t, normalScale, t), t);
tangentValues[i03] = t.x;
tangentValues[i13] = t.y;
tangentValues[i23] = t.z;
Cartesian3_default.normalize(Cartesian3_default.cross(n, t, t), t);
bitangentValues[i03] = t.x;
bitangentValues[i13] = t.y;
bitangentValues[i23] = t.z;
}
geometry.attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangentValues
});
geometry.attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangentValues
});
return geometry;
};
var scratchCartesian23 = new Cartesian2_default();
var toEncode1 = new Cartesian3_default();
var toEncode2 = new Cartesian3_default();
var toEncode3 = new Cartesian3_default();
var encodeResult2 = new Cartesian2_default();
GeometryPipeline.compressVertices = function(geometry) {
if (!defined_default(geometry)) {
throw new DeveloperError_default("geometry is required.");
}
const extrudeAttribute = geometry.attributes.extrudeDirection;
let i;
let numVertices;
if (defined_default(extrudeAttribute)) {
const extrudeDirections = extrudeAttribute.values;
numVertices = extrudeDirections.length / 3;
const compressedDirections = new Float32Array(numVertices * 2);
let i2 = 0;
for (i = 0; i < numVertices; ++i) {
Cartesian3_default.fromArray(extrudeDirections, i * 3, toEncode1);
if (Cartesian3_default.equals(toEncode1, Cartesian3_default.ZERO)) {
i2 += 2;
continue;
}
encodeResult2 = AttributeCompression_default.octEncodeInRange(
toEncode1,
65535,
encodeResult2
);
compressedDirections[i2++] = encodeResult2.x;
compressedDirections[i2++] = encodeResult2.y;
}
geometry.attributes.compressedAttributes = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: compressedDirections
});
delete geometry.attributes.extrudeDirection;
return geometry;
}
const normalAttribute = geometry.attributes.normal;
const stAttribute = geometry.attributes.st;
const hasNormal = defined_default(normalAttribute);
const hasSt = defined_default(stAttribute);
if (!hasNormal && !hasSt) {
return geometry;
}
const tangentAttribute = geometry.attributes.tangent;
const bitangentAttribute = geometry.attributes.bitangent;
const hasTangent = defined_default(tangentAttribute);
const hasBitangent = defined_default(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 length3 = hasNormal ? normals.length : st.length;
const numComponents = hasNormal ? 3 : 2;
numVertices = length3 / numComponents;
let compressedLength = numVertices;
let numCompressedComponents = hasSt && hasNormal ? 2 : 1;
numCompressedComponents += hasTangent || hasBitangent ? 1 : 0;
compressedLength *= numCompressedComponents;
const compressedAttributes = new Float32Array(compressedLength);
let normalIndex = 0;
for (i = 0; i < numVertices; ++i) {
if (hasSt) {
Cartesian2_default.fromArray(st, i * 2, scratchCartesian23);
compressedAttributes[normalIndex++] = AttributeCompression_default.compressTextureCoordinates(scratchCartesian23);
}
const index = i * 3;
if (hasNormal && defined_default(tangents) && defined_default(bitangents)) {
Cartesian3_default.fromArray(normals, index, toEncode1);
Cartesian3_default.fromArray(tangents, index, toEncode2);
Cartesian3_default.fromArray(bitangents, index, toEncode3);
AttributeCompression_default.octPack(
toEncode1,
toEncode2,
toEncode3,
scratchCartesian23
);
compressedAttributes[normalIndex++] = scratchCartesian23.x;
compressedAttributes[normalIndex++] = scratchCartesian23.y;
} else {
if (hasNormal) {
Cartesian3_default.fromArray(normals, index, toEncode1);
compressedAttributes[normalIndex++] = AttributeCompression_default.octEncodeFloat(toEncode1);
}
if (hasTangent) {
Cartesian3_default.fromArray(tangents, index, toEncode1);
compressedAttributes[normalIndex++] = AttributeCompression_default.octEncodeFloat(toEncode1);
}
if (hasBitangent) {
Cartesian3_default.fromArray(bitangents, index, toEncode1);
compressedAttributes[normalIndex++] = AttributeCompression_default.octEncodeFloat(toEncode1);
}
}
}
geometry.attributes.compressedAttributes = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.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_default(geometry.indices)) {
return geometry;
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 3) {
throw new DeveloperError_default("The number of vertices must be at least three.");
}
if (numberOfVertices % 3 !== 0) {
throw new DeveloperError_default(
"The number of vertices must be a multiple of three."
);
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices
);
for (let i = 0; i < numberOfVertices; ++i) {
indices2[i] = i;
}
geometry.indices = indices2;
return geometry;
}
function indexTriangleFan(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 3) {
throw new DeveloperError_default("The number of vertices must be at least three.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 2) * 3
);
indices2[0] = 1;
indices2[1] = 0;
indices2[2] = 2;
let indicesIndex = 3;
for (let i = 3; i < numberOfVertices; ++i) {
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = 0;
indices2[indicesIndex++] = i;
}
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.TRIANGLES;
return geometry;
}
function indexTriangleStrip(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 3) {
throw new DeveloperError_default("The number of vertices must be at least 3.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 2) * 3
);
indices2[0] = 0;
indices2[1] = 1;
indices2[2] = 2;
if (numberOfVertices > 3) {
indices2[3] = 0;
indices2[4] = 2;
indices2[5] = 3;
}
let indicesIndex = 6;
for (let i = 3; i < numberOfVertices - 1; i += 2) {
indices2[indicesIndex++] = i;
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = i + 1;
if (i + 2 < numberOfVertices) {
indices2[indicesIndex++] = i;
indices2[indicesIndex++] = i + 1;
indices2[indicesIndex++] = i + 2;
}
}
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.TRIANGLES;
return geometry;
}
function indexLines(geometry) {
if (defined_default(geometry.indices)) {
return geometry;
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 2) {
throw new DeveloperError_default("The number of vertices must be at least two.");
}
if (numberOfVertices % 2 !== 0) {
throw new DeveloperError_default("The number of vertices must be a multiple of 2.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices
);
for (let i = 0; i < numberOfVertices; ++i) {
indices2[i] = i;
}
geometry.indices = indices2;
return geometry;
}
function indexLineStrip(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 2) {
throw new DeveloperError_default("The number of vertices must be at least two.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
(numberOfVertices - 1) * 2
);
indices2[0] = 0;
indices2[1] = 1;
let indicesIndex = 2;
for (let i = 2; i < numberOfVertices; ++i) {
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = i;
}
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.LINES;
return geometry;
}
function indexLineLoop(geometry) {
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
if (numberOfVertices < 2) {
throw new DeveloperError_default("The number of vertices must be at least two.");
}
const indices2 = IndexDatatype_default.createTypedArray(
numberOfVertices,
numberOfVertices * 2
);
indices2[0] = 0;
indices2[1] = 1;
let indicesIndex = 2;
for (let i = 2; i < numberOfVertices; ++i) {
indices2[indicesIndex++] = i - 1;
indices2[indicesIndex++] = i;
}
indices2[indicesIndex++] = numberOfVertices - 1;
indices2[indicesIndex] = 0;
geometry.indices = indices2;
geometry.primitiveType = PrimitiveType_default.LINES;
return geometry;
}
function indexPrimitive(geometry) {
switch (geometry.primitiveType) {
case PrimitiveType_default.TRIANGLE_FAN:
return indexTriangleFan(geometry);
case PrimitiveType_default.TRIANGLE_STRIP:
return indexTriangleStrip(geometry);
case PrimitiveType_default.TRIANGLES:
return indexTriangles(geometry);
case PrimitiveType_default.LINE_STRIP:
return indexLineStrip(geometry);
case PrimitiveType_default.LINE_LOOP:
return indexLineLoop(geometry);
case PrimitiveType_default.LINES:
return indexLines(geometry);
}
return geometry;
}
function offsetPointFromXZPlane(p, isBehind) {
if (Math.abs(p.y) < Math_default.EPSILON6) {
if (isBehind) {
p.y = -Math_default.EPSILON6;
} else {
p.y = Math_default.EPSILON6;
}
}
}
function offsetTriangleFromXZPlane(p0, p1, p2) {
if (p0.y !== 0 && p1.y !== 0 && p2.y !== 0) {
offsetPointFromXZPlane(p0, p0.y < 0);
offsetPointFromXZPlane(p1, p1.y < 0);
offsetPointFromXZPlane(p2, p2.y < 0);
return;
}
const p0y = Math.abs(p0.y);
const p1y = Math.abs(p1.y);
const p2y = Math.abs(p2.y);
let sign2;
if (p0y > p1y) {
if (p0y > p2y) {
sign2 = Math_default.sign(p0.y);
} else {
sign2 = Math_default.sign(p2.y);
}
} else if (p1y > p2y) {
sign2 = Math_default.sign(p1.y);
} else {
sign2 = Math_default.sign(p2.y);
}
const isBehind = sign2 < 0;
offsetPointFromXZPlane(p0, isBehind);
offsetPointFromXZPlane(p1, isBehind);
offsetPointFromXZPlane(p2, isBehind);
}
var c3 = new Cartesian3_default();
function getXZIntersectionOffsetPoints(p, p1, u12, v13) {
Cartesian3_default.add(
p,
Cartesian3_default.multiplyByScalar(
Cartesian3_default.subtract(p1, p, c3),
p.y / (p.y - p1.y),
c3
),
u12
);
Cartesian3_default.clone(u12, v13);
offsetPointFromXZPlane(u12, true);
offsetPointFromXZPlane(v13, false);
}
var u1 = new Cartesian3_default();
var u2 = new Cartesian3_default();
var q1 = new Cartesian3_default();
var q2 = new Cartesian3_default();
var splitTriangleResult = {
positions: new Array(7),
indices: new Array(3 * 3)
};
function splitTriangle(p0, p1, p2) {
if (p0.x >= 0 || p1.x >= 0 || p2.x >= 0) {
return void 0;
}
offsetTriangleFromXZPlane(p0, p1, p2);
const p0Behind = p0.y < 0;
const p1Behind = p1.y < 0;
const p2Behind = p2.y < 0;
let numBehind = 0;
numBehind += p0Behind ? 1 : 0;
numBehind += p1Behind ? 1 : 0;
numBehind += p2Behind ? 1 : 0;
const indices2 = splitTriangleResult.indices;
if (numBehind === 1) {
indices2[1] = 3;
indices2[2] = 4;
indices2[5] = 6;
indices2[7] = 6;
indices2[8] = 5;
if (p0Behind) {
getXZIntersectionOffsetPoints(p0, p1, u1, q1);
getXZIntersectionOffsetPoints(p0, p2, u2, q2);
indices2[0] = 0;
indices2[3] = 1;
indices2[4] = 2;
indices2[6] = 1;
} else if (p1Behind) {
getXZIntersectionOffsetPoints(p1, p2, u1, q1);
getXZIntersectionOffsetPoints(p1, p0, u2, q2);
indices2[0] = 1;
indices2[3] = 2;
indices2[4] = 0;
indices2[6] = 2;
} else if (p2Behind) {
getXZIntersectionOffsetPoints(p2, p0, u1, q1);
getXZIntersectionOffsetPoints(p2, p1, u2, q2);
indices2[0] = 2;
indices2[3] = 0;
indices2[4] = 1;
indices2[6] = 0;
}
} else if (numBehind === 2) {
indices2[2] = 4;
indices2[4] = 4;
indices2[5] = 3;
indices2[7] = 5;
indices2[8] = 6;
if (!p0Behind) {
getXZIntersectionOffsetPoints(p0, p1, u1, q1);
getXZIntersectionOffsetPoints(p0, p2, u2, q2);
indices2[0] = 1;
indices2[1] = 2;
indices2[3] = 1;
indices2[6] = 0;
} else if (!p1Behind) {
getXZIntersectionOffsetPoints(p1, p2, u1, q1);
getXZIntersectionOffsetPoints(p1, p0, u2, q2);
indices2[0] = 2;
indices2[1] = 0;
indices2[3] = 2;
indices2[6] = 1;
} else if (!p2Behind) {
getXZIntersectionOffsetPoints(p2, p0, u1, q1);
getXZIntersectionOffsetPoints(p2, p1, u2, q2);
indices2[0] = 0;
indices2[1] = 1;
indices2[3] = 0;
indices2[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 void 0;
}
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property]) && defined_default(attributes[property].values)) {
const attribute = attributes[property];
attribute.values = ComponentDatatype_default.createTypedArray(
attribute.componentDatatype,
attribute.values
);
}
}
const numberOfVertices = Geometry_default.computeNumberOfVertices(geometry);
geometry.indices = IndexDatatype_default.createTypedArray(
numberOfVertices,
geometry.indices
);
if (computeBoundingSphere) {
geometry.boundingSphere = BoundingSphere_default.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_default(attributes[property]) && defined_default(attributes[property].values)) {
const attribute = attributes[property];
copiedAttributes[property] = new GeometryAttribute_default({
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
values: []
});
}
}
return new Geometry_default({
attributes: copiedAttributes,
indices: [],
primitiveType: geometry.primitiveType
});
}
function updateInstanceAfterSplit(instance, westGeometry, eastGeometry) {
const computeBoundingSphere = defined_default(instance.geometry.boundingSphere);
westGeometry = updateGeometryAfterSplit(westGeometry, computeBoundingSphere);
eastGeometry = updateGeometryAfterSplit(eastGeometry, computeBoundingSphere);
if (defined_default(eastGeometry) && !defined_default(westGeometry)) {
instance.geometry = eastGeometry;
} else if (!defined_default(eastGeometry) && defined_default(westGeometry)) {
instance.geometry = westGeometry;
} else {
instance.westHemisphereGeometry = westGeometry;
instance.eastHemisphereGeometry = eastGeometry;
instance.geometry = void 0;
}
}
function generateBarycentricInterpolateFunction(CartesianType, numberOfComponents) {
const v0Scratch = new CartesianType();
const v1Scratch2 = new CartesianType();
const v2Scratch2 = new CartesianType();
return function(i0, i1, i2, coords, sourceValues, currentValues, insertedIndex, normalize2) {
const v02 = CartesianType.fromArray(
sourceValues,
i0 * numberOfComponents,
v0Scratch
);
const v13 = CartesianType.fromArray(
sourceValues,
i1 * numberOfComponents,
v1Scratch2
);
const v23 = CartesianType.fromArray(
sourceValues,
i2 * numberOfComponents,
v2Scratch2
);
CartesianType.multiplyByScalar(v02, coords.x, v02);
CartesianType.multiplyByScalar(v13, coords.y, v13);
CartesianType.multiplyByScalar(v23, coords.z, v23);
const value = CartesianType.add(v02, v13, v02);
CartesianType.add(value, v23, value);
if (normalize2) {
CartesianType.normalize(value, value);
}
CartesianType.pack(
value,
currentValues,
insertedIndex * numberOfComponents
);
};
}
var interpolateAndPackCartesian4 = generateBarycentricInterpolateFunction(
Cartesian4_default,
4
);
var interpolateAndPackCartesian3 = generateBarycentricInterpolateFunction(
Cartesian3_default,
3
);
var interpolateAndPackCartesian2 = generateBarycentricInterpolateFunction(
Cartesian2_default,
2
);
var interpolateAndPackBoolean = function(i0, i1, i2, coords, sourceValues, currentValues, insertedIndex) {
const v13 = sourceValues[i0] * coords.x;
const v23 = sourceValues[i1] * coords.y;
const v32 = sourceValues[i2] * coords.z;
currentValues[insertedIndex] = v13 + v23 + v32 > Math_default.EPSILON6 ? 1 : 0;
};
var p0Scratch = new Cartesian3_default();
var p1Scratch = new Cartesian3_default();
var p2Scratch = new Cartesian3_default();
var barycentricScratch = new Cartesian3_default();
function computeTriangleAttributes(i0, i1, i2, point, positions, normals, tangents, bitangents, texCoords, extrudeDirections, applyOffset, currentAttributes, customAttributeNames, customAttributesLength, allAttributes, insertedIndex) {
if (!defined_default(normals) && !defined_default(tangents) && !defined_default(bitangents) && !defined_default(texCoords) && !defined_default(extrudeDirections) && customAttributesLength === 0) {
return;
}
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, p0Scratch);
const p1 = Cartesian3_default.fromArray(positions, i1 * 3, p1Scratch);
const p2 = Cartesian3_default.fromArray(positions, i2 * 3, p2Scratch);
const coords = barycentricCoordinates_default(point, p0, p1, p2, barycentricScratch);
if (!defined_default(coords)) {
return;
}
if (defined_default(normals)) {
interpolateAndPackCartesian3(
i0,
i1,
i2,
coords,
normals,
currentAttributes.normal.values,
insertedIndex,
true
);
}
if (defined_default(extrudeDirections)) {
const d0 = Cartesian3_default.fromArray(extrudeDirections, i0 * 3, p0Scratch);
const d1 = Cartesian3_default.fromArray(extrudeDirections, i1 * 3, p1Scratch);
const d2 = Cartesian3_default.fromArray(extrudeDirections, i2 * 3, p2Scratch);
Cartesian3_default.multiplyByScalar(d0, coords.x, d0);
Cartesian3_default.multiplyByScalar(d1, coords.y, d1);
Cartesian3_default.multiplyByScalar(d2, coords.z, d2);
let direction2;
if (!Cartesian3_default.equals(d0, Cartesian3_default.ZERO) || !Cartesian3_default.equals(d1, Cartesian3_default.ZERO) || !Cartesian3_default.equals(d2, Cartesian3_default.ZERO)) {
direction2 = Cartesian3_default.add(d0, d1, d0);
Cartesian3_default.add(direction2, d2, direction2);
Cartesian3_default.normalize(direction2, direction2);
} else {
direction2 = p0Scratch;
direction2.x = 0;
direction2.y = 0;
direction2.z = 0;
}
Cartesian3_default.pack(
direction2,
currentAttributes.extrudeDirection.values,
insertedIndex * 3
);
}
if (defined_default(applyOffset)) {
interpolateAndPackBoolean(
i0,
i1,
i2,
coords,
applyOffset,
currentAttributes.applyOffset.values,
insertedIndex
);
}
if (defined_default(tangents)) {
interpolateAndPackCartesian3(
i0,
i1,
i2,
coords,
tangents,
currentAttributes.tangent.values,
insertedIndex,
true
);
}
if (defined_default(bitangents)) {
interpolateAndPackCartesian3(
i0,
i1,
i2,
coords,
bitangents,
currentAttributes.bitangent.values,
insertedIndex,
true
);
}
if (defined_default(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, indices2, currentIndex, point) {
const insertIndex = currentAttributes.position.values.length / 3;
if (currentIndex !== -1) {
const prevIndex = indices2[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;
}
var 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_default(attributes.normal) ? attributes.normal.values : void 0;
const bitangents = defined_default(attributes.bitangent) ? attributes.bitangent.values : void 0;
const tangents = defined_default(attributes.tangent) ? attributes.tangent.values : void 0;
const texCoords = defined_default(attributes.st) ? attributes.st.values : void 0;
const extrudeDirections = defined_default(attributes.extrudeDirection) ? attributes.extrudeDirection.values : void 0;
const applyOffset = defined_default(attributes.applyOffset) ? attributes.applyOffset.values : void 0;
const indices2 = geometry.indices;
const customAttributeNames = [];
for (const attributeName in attributes) {
if (attributes.hasOwnProperty(attributeName) && !NAMED_ATTRIBUTES[attributeName] && defined_default(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 = indices2.length;
for (i = 0; i < len; i += 3) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[i + 2];
let p0 = Cartesian3_default.fromArray(positions, i0 * 3);
let p1 = Cartesian3_default.fromArray(positions, i1 * 3);
let p2 = Cartesian3_default.fromArray(positions, i2 * 3);
const result = splitTriangle(p0, p1, p2);
if (defined_default(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) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
currentIndexMap = westGeometryIndexMap;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
currentIndexMap = eastGeometryIndexMap;
}
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
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_default(result)) {
p0 = result.positions[0];
p1 = result.positions[1];
p2 = result.positions[2];
}
if (p0.y < 0) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
currentIndexMap = westGeometryIndexMap;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
currentIndexMap = eastGeometryIndexMap;
}
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i,
p0
);
computeTriangleAttributes(
i0,
i1,
i2,
p0,
positions,
normals,
tangents,
bitangents,
texCoords,
extrudeDirections,
applyOffset,
currentAttributes,
customAttributeNames,
customAttributesLength,
attributes,
insertedIndex
);
insertedIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
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,
indices2,
i + 2,
p2
);
computeTriangleAttributes(
i0,
i1,
i2,
p2,
positions,
normals,
tangents,
bitangents,
texCoords,
extrudeDirections,
applyOffset,
currentAttributes,
customAttributeNames,
customAttributesLength,
attributes,
insertedIndex
);
}
}
updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
}
var xzPlane = Plane_default.fromPointNormal(Cartesian3_default.ZERO, Cartesian3_default.UNIT_Y);
var offsetScratch = new Cartesian3_default();
var offsetPointScratch = new Cartesian3_default();
function computeLineAttributes(i0, i1, point, positions, insertIndex, currentAttributes, applyOffset) {
if (!defined_default(applyOffset)) {
return;
}
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, p0Scratch);
if (Cartesian3_default.equalsEpsilon(p0, point, Math_default.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_default(attributes.applyOffset) ? attributes.applyOffset.values : void 0;
const indices2 = geometry.indices;
const eastGeometry = copyGeometryForSplit(geometry);
const westGeometry = copyGeometryForSplit(geometry);
let i;
const length3 = indices2.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 < length3; i += 2) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, p0Scratch);
const p1 = Cartesian3_default.fromArray(positions, i1 * 3, p1Scratch);
let insertIndex;
if (Math.abs(p0.y) < Math_default.EPSILON6) {
if (p0.y < 0) {
p0.y = -Math_default.EPSILON6;
} else {
p0.y = Math_default.EPSILON6;
}
}
if (Math.abs(p1.y) < Math_default.EPSILON6) {
if (p1.y < 0) {
p1.y = -Math_default.EPSILON6;
} else {
p1.y = Math_default.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_default.lineSegmentPlane(
p0,
p1,
xzPlane,
p2Scratch
);
if (defined_default(intersection)) {
const offset2 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.UNIT_Y,
5 * Math_default.EPSILON9,
offsetScratch
);
if (p0.y < 0) {
Cartesian3_default.negate(offset2, offset2);
p0Attributes = westGeometry.attributes;
p0Indices = westGeometry.indices;
p0IndexMap = westGeometryIndexMap;
p1Attributes = eastGeometry.attributes;
p1Indices = eastGeometry.indices;
p1IndexMap = eastGeometryIndexMap;
}
const offsetPoint = Cartesian3_default.add(
intersection,
offset2,
offsetPointScratch
);
insertIndex = insertSplitPoint(
p0Attributes,
p0Indices,
p0IndexMap,
indices2,
i,
p0
);
computeLineAttributes(
i0,
i1,
p0,
positions,
insertIndex,
p0Attributes,
applyOffset
);
insertIndex = insertSplitPoint(
p0Attributes,
p0Indices,
p0IndexMap,
indices2,
-1,
offsetPoint
);
computeLineAttributes(
i0,
i1,
offsetPoint,
positions,
insertIndex,
p0Attributes,
applyOffset
);
Cartesian3_default.negate(offset2, offset2);
Cartesian3_default.add(intersection, offset2, offsetPoint);
insertIndex = insertSplitPoint(
p1Attributes,
p1Indices,
p1IndexMap,
indices2,
-1,
offsetPoint
);
computeLineAttributes(
i0,
i1,
offsetPoint,
positions,
insertIndex,
p1Attributes,
applyOffset
);
insertIndex = insertSplitPoint(
p1Attributes,
p1Indices,
p1IndexMap,
indices2,
i + 1,
p1
);
computeLineAttributes(
i0,
i1,
p1,
positions,
insertIndex,
p1Attributes,
applyOffset
);
} else {
let currentAttributes;
let currentIndices;
let currentIndexMap;
if (p0.y < 0) {
currentAttributes = westGeometry.attributes;
currentIndices = westGeometry.indices;
currentIndexMap = westGeometryIndexMap;
} else {
currentAttributes = eastGeometry.attributes;
currentIndices = eastGeometry.indices;
currentIndexMap = eastGeometryIndexMap;
}
insertIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i,
p0
);
computeLineAttributes(
i0,
i1,
p0,
positions,
insertIndex,
currentAttributes,
applyOffset
);
insertIndex = insertSplitPoint(
currentAttributes,
currentIndices,
currentIndexMap,
indices2,
i + 1,
p1
);
computeLineAttributes(
i0,
i1,
p1,
positions,
insertIndex,
currentAttributes,
applyOffset
);
}
}
updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
}
var cartesian2Scratch0 = new Cartesian2_default();
var cartesian2Scratch1 = new Cartesian2_default();
var cartesian3Scratch0 = new Cartesian3_default();
var cartesian3Scratch2 = new Cartesian3_default();
var cartesian3Scratch3 = new Cartesian3_default();
var cartesian3Scratch4 = new Cartesian3_default();
var cartesian3Scratch5 = new Cartesian3_default();
var cartesian3Scratch6 = new Cartesian3_default();
var cartesian4Scratch0 = new Cartesian4_default();
function updateAdjacencyAfterSplit(geometry) {
const attributes = geometry.attributes;
const positions = attributes.position.values;
const prevPositions = attributes.prevPosition.values;
const nextPositions = attributes.nextPosition.values;
const length3 = positions.length;
for (let j = 0; j < length3; j += 3) {
const position = Cartesian3_default.unpack(positions, j, cartesian3Scratch0);
if (position.x > 0) {
continue;
}
const prevPosition = Cartesian3_default.unpack(
prevPositions,
j,
cartesian3Scratch2
);
if (position.y < 0 && prevPosition.y > 0 || position.y > 0 && prevPosition.y < 0) {
if (j - 3 > 0) {
prevPositions[j] = positions[j - 3];
prevPositions[j + 1] = positions[j - 2];
prevPositions[j + 2] = positions[j - 1];
} else {
Cartesian3_default.pack(position, prevPositions, j);
}
}
const nextPosition = Cartesian3_default.unpack(
nextPositions,
j,
cartesian3Scratch3
);
if (position.y < 0 && nextPosition.y > 0 || position.y > 0 && nextPosition.y < 0) {
if (j + 3 < length3) {
nextPositions[j] = positions[j + 3];
nextPositions[j + 1] = positions[j + 4];
nextPositions[j + 2] = positions[j + 5];
} else {
Cartesian3_default.pack(position, nextPositions, j);
}
}
}
}
var offsetScalar = 5 * Math_default.EPSILON9;
var coplanarOffset = Math_default.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_default(attributes.st) ? attributes.st.values : void 0;
const colors = defined_default(attributes.color) ? attributes.color.values : void 0;
const eastGeometry = copyGeometryForSplit(geometry);
const westGeometry = copyGeometryForSplit(geometry);
let i;
let j;
let index;
let intersectionFound = false;
const length3 = positions.length / 3;
for (i = 0; i < length3; i += 4) {
const i0 = i;
const i2 = i + 2;
const p0 = Cartesian3_default.fromArray(positions, i0 * 3, cartesian3Scratch0);
const p2 = Cartesian3_default.fromArray(positions, i2 * 3, cartesian3Scratch2);
if (Math.abs(p0.y) < coplanarOffset) {
p0.y = coplanarOffset * (p2.y < 0 ? -1 : 1);
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];
}
}
if (Math.abs(p2.y) < coplanarOffset) {
p2.y = coplanarOffset * (p0.y < 0 ? -1 : 1);
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_default.lineSegmentPlane(
p0,
p2,
xzPlane,
cartesian3Scratch4
);
if (defined_default(intersection)) {
intersectionFound = true;
const offset2 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.UNIT_Y,
offsetScalar,
cartesian3Scratch5
);
if (p0.y < 0) {
Cartesian3_default.negate(offset2, offset2);
p0Attributes = westGeometry.attributes;
p0Indices = westGeometry.indices;
p2Attributes = eastGeometry.attributes;
p2Indices = eastGeometry.indices;
}
const offsetPoint = Cartesian3_default.add(
intersection,
offset2,
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_default.negate(offset2, offset2);
Cartesian3_default.add(intersection, offset2, 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_default.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_default.magnitudeSquared(
Cartesian3_default.subtract(intersection, p0, cartesian3Scratch3)
);
t /= Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(p2, p0, cartesian3Scratch3)
);
if (defined_default(colors)) {
const c0 = Cartesian4_default.fromArray(colors, i0 * 4, cartesian4Scratch0);
const c22 = Cartesian4_default.fromArray(colors, i2 * 4, cartesian4Scratch0);
const r = Math_default.lerp(c0.x, c22.x, t);
const g = Math_default.lerp(c0.y, c22.y, t);
const b = Math_default.lerp(c0.z, c22.z, t);
const a3 = Math_default.lerp(c0.w, c22.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, a3);
p0Attributes.color.values.push(r, g, b, a3);
p2Attributes.color.values.push(r, g, b, a3);
p2Attributes.color.values.push(r, g, b, a3);
for (j = i2 * 4; j < i2 * 4 + 2 * 4; ++j) {
p2Attributes.color.values.push(colors[j]);
}
}
if (defined_default(texCoords)) {
const s0 = Cartesian2_default.fromArray(texCoords, i0 * 2, cartesian2Scratch0);
const s3 = Cartesian2_default.fromArray(
texCoords,
(i + 3) * 2,
cartesian2Scratch1
);
const sx = Math_default.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) {
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_default(texCoords)) {
currentAttributes.st.values.push(texCoords[j]);
}
}
if (defined_default(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);
}
GeometryPipeline.splitLongitude = function(instance) {
if (!defined_default(instance)) {
throw new DeveloperError_default("instance is required.");
}
const geometry = instance.geometry;
const boundingSphere = geometry.boundingSphere;
if (defined_default(boundingSphere)) {
const minX = boundingSphere.center.x - boundingSphere.radius;
if (minX > 0 || BoundingSphere_default.intersectPlane(boundingSphere, Plane_default.ORIGIN_ZX_PLANE) !== Intersect_default.INTERSECTING) {
return instance;
}
}
if (geometry.geometryType !== GeometryType_default.NONE) {
switch (geometry.geometryType) {
case GeometryType_default.POLYLINES:
splitLongitudePolyline(instance);
break;
case GeometryType_default.TRIANGLES:
splitLongitudeTriangles(instance);
break;
case GeometryType_default.LINES:
splitLongitudeLines(instance);
break;
}
} else {
indexPrimitive(geometry);
if (geometry.primitiveType === PrimitiveType_default.TRIANGLES) {
splitLongitudeTriangles(instance);
} else if (geometry.primitiveType === PrimitiveType_default.LINES) {
splitLongitudeLines(instance);
}
}
return instance;
};
var GeometryPipeline_default = GeometryPipeline;
// node_modules/@cesium/engine/Source/Core/WebMercatorProjection.js
function WebMercatorProjection(ellipsoid) {
this._ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1 / this._semimajorAxis;
}
Object.defineProperties(WebMercatorProjection.prototype, {
ellipsoid: {
get: function() {
return this._ellipsoid;
}
}
});
WebMercatorProjection.mercatorAngleToGeodeticLatitude = function(mercatorAngle) {
return Math_default.PI_OVER_TWO - 2 * Math.atan(Math.exp(-mercatorAngle));
};
WebMercatorProjection.geodeticLatitudeToMercatorAngle = function(latitude) {
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 + sinLatitude) / (1 - sinLatitude));
};
WebMercatorProjection.MaximumLatitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(
Math.PI
);
WebMercatorProjection.prototype.project = function(cartographic2, result) {
const semimajorAxis = this._semimajorAxis;
const x = cartographic2.longitude * semimajorAxis;
const y = WebMercatorProjection.geodeticLatitudeToMercatorAngle(
cartographic2.latitude
) * semimajorAxis;
const z = cartographic2.height;
if (!defined_default(result)) {
return new Cartesian3_default(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
WebMercatorProjection.prototype.unproject = function(cartesian11, result) {
if (!defined_default(cartesian11)) {
throw new DeveloperError_default("cartesian is required");
}
const oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
const longitude = cartesian11.x * oneOverEarthSemimajorAxis;
const latitude = WebMercatorProjection.mercatorAngleToGeodeticLatitude(
cartesian11.y * oneOverEarthSemimajorAxis
);
const height = cartesian11.z;
if (!defined_default(result)) {
return new Cartographic_default(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
var WebMercatorProjection_default = WebMercatorProjection;
// node_modules/@cesium/engine/Source/Scene/PrimitivePipeline.js
function transformToWorldCoordinates(instances, primitiveModelMatrix, scene3DOnly) {
let toWorld = !scene3DOnly;
const length3 = instances.length;
let i;
if (!toWorld && length3 > 1) {
const modelMatrix = instances[0].modelMatrix;
for (i = 1; i < length3; ++i) {
if (!Matrix4_default.equals(modelMatrix, instances[i].modelMatrix)) {
toWorld = true;
break;
}
}
}
if (toWorld) {
for (i = 0; i < length3; ++i) {
if (defined_default(instances[i].geometry)) {
GeometryPipeline_default.transformToWorldCoordinates(instances[i]);
}
}
} else {
Matrix4_default.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_default({
componentDatatype: ComponentDatatype_default.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 length3 = instances.length;
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
if (defined_default(instance.geometry)) {
addGeometryBatchId(instance.geometry, i);
} else if (defined_default(instance.westHemisphereGeometry) && defined_default(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 length3 = instances.length;
for (i = 0; i < length3; ++i) {
if (defined_default(instances[i].geometry)) {
primitiveType = instances[i].geometry.primitiveType;
break;
}
}
for (i = 1; i < length3; ++i) {
if (defined_default(instances[i].geometry) && instances[i].geometry.primitiveType !== primitiveType) {
throw new DeveloperError_default(
"All instance geometries must have the same primitiveType."
);
}
}
transformToWorldCoordinates(instances, modelMatrix, scene3DOnly);
if (!scene3DOnly) {
for (i = 0; i < length3; ++i) {
if (defined_default(instances[i].geometry)) {
GeometryPipeline_default.splitLongitude(instances[i]);
}
}
}
addBatchIds(instances);
if (vertexCacheOptimize) {
for (i = 0; i < length3; ++i) {
const instance = instances[i];
if (defined_default(instance.geometry)) {
GeometryPipeline_default.reorderForPostVertexCache(instance.geometry);
GeometryPipeline_default.reorderForPreVertexCache(instance.geometry);
} else if (defined_default(instance.westHemisphereGeometry) && defined_default(instance.eastHemisphereGeometry)) {
GeometryPipeline_default.reorderForPostVertexCache(
instance.westHemisphereGeometry
);
GeometryPipeline_default.reorderForPreVertexCache(
instance.westHemisphereGeometry
);
GeometryPipeline_default.reorderForPostVertexCache(
instance.eastHemisphereGeometry
);
GeometryPipeline_default.reorderForPreVertexCache(
instance.eastHemisphereGeometry
);
}
}
}
let geometries = GeometryPipeline_default.combineInstances(instances);
length3 = geometries.length;
for (i = 0; i < length3; ++i) {
geometry = geometries[i];
const attributes = geometry.attributes;
if (!scene3DOnly) {
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && attributes[name].componentDatatype === ComponentDatatype_default.DOUBLE) {
const name3D = `${name}3D`;
const name2D = `${name}2D`;
GeometryPipeline_default.projectTo2D(
geometry,
name,
name3D,
name2D,
projection
);
if (defined_default(geometry.boundingSphere) && name === "position") {
geometry.boundingSphereCV = BoundingSphere_default.fromVertices(
geometry.attributes.position2D.values
);
}
GeometryPipeline_default.encodeAttribute(
geometry,
name3D,
`${name3D}High`,
`${name3D}Low`
);
GeometryPipeline_default.encodeAttribute(
geometry,
name2D,
`${name2D}High`,
`${name2D}Low`
);
}
}
} else {
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && attributes[name].componentDatatype === ComponentDatatype_default.DOUBLE) {
GeometryPipeline_default.encodeAttribute(
geometry,
name,
`${name}3DHigh`,
`${name}3DLow`
);
}
}
}
if (compressVertices) {
GeometryPipeline_default.compressVertices(geometry);
}
}
if (!uintIndexSupport) {
let splitGeometries = [];
length3 = geometries.length;
for (i = 0; i < length3; ++i) {
geometry = geometries[i];
splitGeometries = splitGeometries.concat(
GeometryPipeline_default.fitToUnsignedShortIndices(geometry)
);
}
geometries = splitGeometries;
}
return geometries;
}
function createPickOffsets(instances, geometryName, geometries, pickOffsets) {
let offset2;
let indexCount;
let geometryIndex;
const offsetIndex = pickOffsets.length - 1;
if (offsetIndex >= 0) {
const pickOffset = pickOffsets[offsetIndex];
offset2 = pickOffset.offset + pickOffset.count;
geometryIndex = pickOffset.index;
indexCount = geometries[geometryIndex].indices.length;
} else {
offset2 = 0;
geometryIndex = 0;
indexCount = geometries[geometryIndex].indices.length;
}
const length3 = instances.length;
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
const geometry = instance[geometryName];
if (!defined_default(geometry)) {
continue;
}
const count = geometry.indices.length;
if (offset2 + count > indexCount) {
offset2 = 0;
indexCount = geometries[++geometryIndex].indices.length;
}
pickOffsets.push({
index: geometryIndex,
offset: offset2,
count
});
offset2 += count;
}
}
function createInstancePickOffsets(instances, geometries) {
const pickOffsets = [];
createPickOffsets(instances, "geometry", geometries, pickOffsets);
createPickOffsets(
instances,
"westHemisphereGeometry",
geometries,
pickOffsets
);
createPickOffsets(
instances,
"eastHemisphereGeometry",
geometries,
pickOffsets
);
return pickOffsets;
}
var PrimitivePipeline = {};
PrimitivePipeline.combineGeometry = function(parameters) {
let geometries;
let attributeLocations8;
const instances = parameters.instances;
const length3 = instances.length;
let pickOffsets;
let offsetInstanceExtend;
let hasOffset = false;
if (length3 > 0) {
geometries = geometryPipeline(parameters);
if (geometries.length > 0) {
attributeLocations8 = GeometryPipeline_default.createAttributeLocations(
geometries[0]
);
if (parameters.createPickOffsets) {
pickOffsets = createInstancePickOffsets(instances, geometries);
}
}
if (defined_default(instances[0].attributes) && defined_default(instances[0].attributes.offset)) {
offsetInstanceExtend = new Array(length3);
hasOffset = true;
}
}
const boundingSpheres = new Array(length3);
const boundingSpheresCV = new Array(length3);
for (let i = 0; i < length3; ++i) {
const instance = instances[i];
const geometry = instance.geometry;
if (defined_default(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_default(eastHemisphereGeometry) && defined_default(westHemisphereGeometry)) {
if (defined_default(eastHemisphereGeometry.boundingSphere) && defined_default(westHemisphereGeometry.boundingSphere)) {
boundingSpheres[i] = BoundingSphere_default.union(
eastHemisphereGeometry.boundingSphere,
westHemisphereGeometry.boundingSphere
);
}
if (defined_default(eastHemisphereGeometry.boundingSphereCV) && defined_default(westHemisphereGeometry.boundingSphereCV)) {
boundingSpheresCV[i] = BoundingSphere_default.union(
eastHemisphereGeometry.boundingSphereCV,
westHemisphereGeometry.boundingSphereCV
);
}
}
}
return {
geometries,
modelMatrix: parameters.modelMatrix,
attributeLocations: attributeLocations8,
pickOffsets,
offsetInstanceExtend,
boundingSpheres,
boundingSpheresCV
};
};
function transferGeometry(geometry, transferableObjects) {
const attributes = geometry.attributes;
for (const name in attributes) {
if (attributes.hasOwnProperty(name)) {
const attribute = attributes[name];
if (defined_default(attribute) && defined_default(attribute.values)) {
transferableObjects.push(attribute.values.buffer);
}
}
}
if (defined_default(geometry.indices)) {
transferableObjects.push(geometry.indices.buffer);
}
}
function transferGeometries(geometries, transferableObjects) {
const length3 = geometries.length;
for (let i = 0; i < length3; ++i) {
transferGeometry(geometries[i], transferableObjects);
}
}
function countCreateGeometryResults(items) {
let count = 1;
const length3 = items.length;
for (let i = 0; i < length3; i++) {
const geometry = items[i];
++count;
if (!defined_default(geometry)) {
continue;
}
const attributes = geometry.attributes;
count += 7 + 2 * BoundingSphere_default.packedLength + (defined_default(geometry.indices) ? geometry.indices.length : 0);
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property])) {
const attribute = attributes[property];
count += 5 + attribute.values.length;
}
}
}
return count;
}
PrimitivePipeline.packCreateGeometryResults = function(items, transferableObjects) {
const packedData = new Float64Array(countCreateGeometryResults(items));
const stringTable = [];
const stringHash = {};
const length3 = items.length;
let count = 0;
packedData[count++] = length3;
for (let i = 0; i < length3; i++) {
const geometry = items[i];
const validGeometry = defined_default(geometry);
packedData[count++] = validGeometry ? 1 : 0;
if (!validGeometry) {
continue;
}
packedData[count++] = geometry.primitiveType;
packedData[count++] = geometry.geometryType;
packedData[count++] = defaultValue_default(geometry.offsetAttribute, -1);
const validBoundingSphere = defined_default(geometry.boundingSphere) ? 1 : 0;
packedData[count++] = validBoundingSphere;
if (validBoundingSphere) {
BoundingSphere_default.pack(geometry.boundingSphere, packedData, count);
}
count += BoundingSphere_default.packedLength;
const validBoundingSphereCV = defined_default(geometry.boundingSphereCV) ? 1 : 0;
packedData[count++] = validBoundingSphereCV;
if (validBoundingSphereCV) {
BoundingSphere_default.pack(geometry.boundingSphereCV, packedData, count);
}
count += BoundingSphere_default.packedLength;
const attributes = geometry.attributes;
const attributesToWrite = [];
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property])) {
attributesToWrite.push(property);
if (!defined_default(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_default(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,
packedData
};
};
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;
if (!valid) {
result[resultIndex++] = void 0;
continue;
}
const primitiveType = packedGeometry[packedGeometryIndex++];
const geometryType = packedGeometry[packedGeometryIndex++];
let offsetAttribute = packedGeometry[packedGeometryIndex++];
if (offsetAttribute === -1) {
offsetAttribute = void 0;
}
let boundingSphere;
let boundingSphereCV;
const validBoundingSphere = packedGeometry[packedGeometryIndex++] === 1;
if (validBoundingSphere) {
boundingSphere = BoundingSphere_default.unpack(
packedGeometry,
packedGeometryIndex
);
}
packedGeometryIndex += BoundingSphere_default.packedLength;
const validBoundingSphereCV = packedGeometry[packedGeometryIndex++] === 1;
if (validBoundingSphereCV) {
boundingSphereCV = BoundingSphere_default.unpack(
packedGeometry,
packedGeometryIndex
);
}
packedGeometryIndex += BoundingSphere_default.packedLength;
let length3;
let values;
let componentsPerAttribute;
const attributes = new GeometryAttributes_default();
const numAttributes = packedGeometry[packedGeometryIndex++];
for (i = 0; i < numAttributes; i++) {
const name = stringTable[packedGeometry[packedGeometryIndex++]];
const componentDatatype = packedGeometry[packedGeometryIndex++];
componentsPerAttribute = packedGeometry[packedGeometryIndex++];
const normalize2 = packedGeometry[packedGeometryIndex++] !== 0;
length3 = packedGeometry[packedGeometryIndex++];
values = ComponentDatatype_default.createTypedArray(componentDatatype, length3);
for (let valuesIndex = 0; valuesIndex < length3; valuesIndex++) {
values[valuesIndex] = packedGeometry[packedGeometryIndex++];
}
attributes[name] = new GeometryAttribute_default({
componentDatatype,
componentsPerAttribute,
normalize: normalize2,
values
});
}
let indices2;
length3 = packedGeometry[packedGeometryIndex++];
if (length3 > 0) {
const numberOfVertices = values.length / componentsPerAttribute;
indices2 = IndexDatatype_default.createTypedArray(numberOfVertices, length3);
for (i = 0; i < length3; i++) {
indices2[i] = packedGeometry[packedGeometryIndex++];
}
}
result[resultIndex++] = new Geometry_default({
primitiveType,
geometryType,
boundingSphere,
boundingSphereCV,
indices: indices2,
attributes,
offsetAttribute
});
}
return result;
};
function packInstancesForCombine(instances, transferableObjects) {
const length3 = instances.length;
const packedData = new Float64Array(1 + length3 * 19);
let count = 0;
packedData[count++] = length3;
for (let i = 0; i < length3; i++) {
const instance = instances[i];
Matrix4_default.pack(instance.modelMatrix, packedData, count);
count += Matrix4_default.packedLength;
if (defined_default(instance.attributes) && defined_default(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_default.unpack(packedInstances, i);
let attributes;
i += Matrix4_default.packedLength;
if (defined_default(packedInstances[i])) {
attributes = {
offset: new OffsetGeometryInstanceAttribute_default(
packedInstances[i],
packedInstances[i + 1],
packedInstances[i + 2]
)
};
}
i += 3;
result[count++] = {
modelMatrix,
attributes
};
}
return result;
}
PrimitivePipeline.packCombineGeometryParameters = function(parameters, transferableObjects) {
const createGeometryResults = parameters.createGeometryResults;
const length3 = createGeometryResults.length;
for (let i = 0; i < length3; i++) {
transferableObjects.push(createGeometryResults[i].packedData.buffer);
}
return {
createGeometryResults: parameters.createGeometryResults,
packedInstances: packInstancesForCombine(
parameters.instances,
transferableObjects
),
ellipsoid: parameters.ellipsoid,
isGeographic: parameters.projection instanceof GeographicProjection_default,
elementIndexUintSupported: parameters.elementIndexUintSupported,
scene3DOnly: parameters.scene3DOnly,
vertexCacheOptimize: parameters.vertexCacheOptimize,
compressVertices: parameters.compressVertices,
modelMatrix: parameters.modelMatrix,
createPickOffsets: parameters.createPickOffsets
};
};
PrimitivePipeline.unpackCombineGeometryParameters = function(packedParameters) {
const instances = unpackInstancesForCombine(packedParameters.packedInstances);
const createGeometryResults = packedParameters.createGeometryResults;
const length3 = createGeometryResults.length;
let instanceIndex = 0;
for (let resultIndex = 0; resultIndex < length3; 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_default.clone(packedParameters.ellipsoid);
const projection = packedParameters.isGeographic ? new GeographicProjection_default(ellipsoid) : new WebMercatorProjection_default(ellipsoid);
return {
instances,
ellipsoid,
projection,
elementIndexUintSupported: packedParameters.elementIndexUintSupported,
scene3DOnly: packedParameters.scene3DOnly,
vertexCacheOptimize: packedParameters.vertexCacheOptimize,
compressVertices: packedParameters.compressVertices,
modelMatrix: Matrix4_default.clone(packedParameters.modelMatrix),
createPickOffsets: packedParameters.createPickOffsets
};
};
function packBoundingSpheres(boundingSpheres) {
const length3 = boundingSpheres.length;
const bufferLength = 1 + (BoundingSphere_default.packedLength + 1) * length3;
const buffer = new Float32Array(bufferLength);
let bufferIndex = 0;
buffer[bufferIndex++] = length3;
for (let i = 0; i < length3; ++i) {
const bs = boundingSpheres[i];
if (!defined_default(bs)) {
buffer[bufferIndex++] = 0;
} else {
buffer[bufferIndex++] = 1;
BoundingSphere_default.pack(boundingSpheres[i], buffer, bufferIndex);
}
bufferIndex += BoundingSphere_default.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) {
result[count] = BoundingSphere_default.unpack(buffer, i);
}
++count;
i += BoundingSphere_default.packedLength;
}
return result;
}
PrimitivePipeline.packCombineGeometryResults = function(results, transferableObjects) {
if (defined_default(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
};
};
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)
};
};
var PrimitivePipeline_default = PrimitivePipeline;
// node_modules/@cesium/engine/Source/Scene/PrimitiveState.js
var PrimitiveState = {
READY: 0,
CREATING: 1,
CREATED: 2,
COMBINING: 3,
COMBINED: 4,
COMPLETE: 5,
FAILED: 6
};
var PrimitiveState_default = Object.freeze(PrimitiveState);
// node_modules/@cesium/engine/Source/Scene/ShadowMode.js
var ShadowMode = {
DISABLED: 0,
ENABLED: 1,
CAST_ONLY: 2,
RECEIVE_ONLY: 3
};
ShadowMode.NUMBER_OF_SHADOW_MODES = 4;
ShadowMode.castShadows = function(shadowMode) {
return shadowMode === ShadowMode.ENABLED || shadowMode === ShadowMode.CAST_ONLY;
};
ShadowMode.receiveShadows = function(shadowMode) {
return shadowMode === ShadowMode.ENABLED || shadowMode === ShadowMode.RECEIVE_ONLY;
};
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_default = Object.freeze(ShadowMode);
// node_modules/@cesium/engine/Source/Scene/Primitive.js
function Primitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.geometryInstances = options.geometryInstances;
this.appearance = options.appearance;
this._appearance = void 0;
this._material = void 0;
this.depthFailAppearance = options.depthFailAppearance;
this._depthFailAppearance = void 0;
this._depthFailMaterial = void 0;
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = new Matrix4_default();
this.show = defaultValue_default(options.show, true);
this._vertexCacheOptimize = defaultValue_default(options.vertexCacheOptimize, false);
this._interleave = defaultValue_default(options.interleave, false);
this._releaseGeometryInstances = defaultValue_default(
options.releaseGeometryInstances,
true
);
this._allowPicking = defaultValue_default(options.allowPicking, true);
this._asynchronous = defaultValue_default(options.asynchronous, true);
this._compressVertices = defaultValue_default(options.compressVertices, true);
this.cull = defaultValue_default(options.cull, true);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.rtcCenter = options.rtcCenter;
if (defined_default(this.rtcCenter) && (!defined_default(this.geometryInstances) || Array.isArray(this.geometryInstances) && this.geometryInstances.length !== 1)) {
throw new DeveloperError_default(
"Relative-to-center rendering only supports one geometry instance."
);
}
this.shadows = defaultValue_default(options.shadows, ShadowMode_default.DISABLED);
this._translucent = void 0;
this._state = PrimitiveState_default.READY;
this._geometries = [];
this._error = void 0;
this._numberOfInstances = 0;
this._boundingSpheres = [];
this._boundingSphereWC = [];
this._boundingSphereCV = [];
this._boundingSphere2D = [];
this._boundingSphereMorph = [];
this._perInstanceAttributeCache = /* @__PURE__ */ new Map();
this._instanceIds = [];
this._lastPerInstanceAttributeIndex = 0;
this._va = [];
this._attributeLocations = void 0;
this._primitiveType = void 0;
this._frontFaceRS = void 0;
this._backFaceRS = void 0;
this._sp = void 0;
this._depthFailAppearance = void 0;
this._spDepthFail = void 0;
this._frontFaceDepthFailRS = void 0;
this._backFaceDepthFailRS = void 0;
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 = void 0;
this._createGeometryResults = void 0;
this._ready = false;
const primitive = this;
this._readyPromise = new Promise((resolve2, reject) => {
primitive._completeLoad = (frameState, state, error) => {
this._error = error;
this._state = state;
frameState.afterRender.push(function() {
primitive._ready = primitive._state === PrimitiveState_default.COMPLETE || primitive._state === PrimitiveState_default.FAILED;
if (!defined_default(error)) {
resolve2(primitive);
return true;
}
reject(error);
});
};
});
this._batchTable = void 0;
this._batchTableAttributeIndices = void 0;
this._offsetInstanceExtend = void 0;
this._batchTableOffsetAttribute2DIndex = void 0;
this._batchTableOffsetsUpdated = false;
this._instanceBoundingSpheres = void 0;
this._instanceBoundingSpheresCV = void 0;
this._tempBoundingSpheres = void 0;
this._recomputeBoundingSpheres = false;
this._batchTableBoundingSpheresUpdated = false;
this._batchTableBoundingSphereAttributeIndices = void 0;
}
Object.defineProperties(Primitive.prototype, {
vertexCacheOptimize: {
get: function() {
return this._vertexCacheOptimize;
}
},
interleave: {
get: function() {
return this._interleave;
}
},
releaseGeometryInstances: {
get: function() {
return this._releaseGeometryInstances;
}
},
allowPicking: {
get: function() {
return this._allowPicking;
}
},
asynchronous: {
get: function() {
return this._asynchronous;
}
},
compressVertices: {
get: function() {
return this._compressVertices;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Primitive.readyPromise",
"Primitive.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Primitive.ready to return true instead."
);
return this._readyPromise;
}
}
});
function getCommonPerInstanceAttributeNames(instances) {
const length3 = instances.length;
const attributesInAllInstances = [];
const attributes0 = instances[0].attributes;
let name;
for (name in attributes0) {
if (attributes0.hasOwnProperty(name) && defined_default(attributes0[name])) {
const attribute = attributes0[name];
let inAllInstances = true;
for (let i = 1; i < length3; ++i) {
const otherAttribute = instances[i].attributes[name];
if (!defined_default(otherAttribute) || attribute.componentDatatype !== otherAttribute.componentDatatype || attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute || attribute.normalize !== otherAttribute.normalize) {
inAllInstances = false;
break;
}
}
if (inAllInstances) {
attributesInAllInstances.push(name);
}
}
}
return attributesInAllInstances;
}
var scratchGetAttributeCartesian2 = new Cartesian2_default();
var scratchGetAttributeCartesian3 = new Cartesian3_default();
var scratchGetAttributeCartesian42 = new Cartesian4_default();
function getAttributeValue(value) {
const componentsPerAttribute = value.length;
if (componentsPerAttribute === 1) {
return value[0];
} else if (componentsPerAttribute === 2) {
return Cartesian2_default.unpack(value, 0, scratchGetAttributeCartesian2);
} else if (componentsPerAttribute === 3) {
return Cartesian3_default.unpack(value, 0, scratchGetAttributeCartesian3);
} else if (componentsPerAttribute === 4) {
return Cartesian4_default.unpack(value, 0, scratchGetAttributeCartesian42);
}
}
function createBatchTable(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 length3 = 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 < length3; ++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_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereCenter3DLow",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereCenter2DHigh",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereCenter2DLow",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "czm_batchTable_boundingSphereRadius",
componentDatatype: ComponentDatatype_default.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_default.FLOAT,
componentsPerAttribute: 3
});
offset2DIndex = attributes.length - 1;
}
attributes.push({
functionName: "czm_batchTable_pickColor",
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 4,
normalize: true
});
const attributesLength = attributes.length;
const batchTable = new BatchTable_default(context, attributes, numberOfInstances);
for (i = 0; i < numberOfInstances; ++i) {
const instance = instances[i];
instanceAttributes = instance.attributes;
for (let j = 0; j < length3; ++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_default(instance.pickPrimitive, primitive)
};
if (defined_default(instance.id)) {
pickObject.id = instance.id;
}
const pickId = context.createPickId(pickObject);
primitive._pickIds.push(pickId);
const pickColor = pickId.color;
const color = scratchGetAttributeCartesian42;
color.x = Color_default.floatToByte(pickColor.red);
color.y = Color_default.floatToByte(pickColor.green);
color.z = Color_default.floatToByte(pickColor.blue);
color.w = Color_default.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_default({
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
values: clonedValues
});
}
function cloneGeometry(geometry) {
const attributes = geometry.attributes;
const newAttributes = new GeometryAttributes_default();
for (const property in attributes) {
if (attributes.hasOwnProperty(property) && defined_default(attributes[property])) {
newAttributes[property] = cloneAttribute(attributes[property]);
}
}
let indices2;
if (defined_default(geometry.indices)) {
const sourceValues = geometry.indices;
if (Array.isArray(sourceValues)) {
indices2 = sourceValues.slice(0);
} else {
indices2 = new sourceValues.constructor(sourceValues);
}
}
return new Geometry_default({
attributes: newAttributes,
indices: indices2,
primitiveType: geometry.primitiveType,
boundingSphere: BoundingSphere_default.clone(geometry.boundingSphere)
});
}
function cloneInstance(instance, geometry) {
return {
geometry,
attributes: instance.attributes,
modelMatrix: Matrix4_default.clone(instance.modelMatrix),
pickPrimitive: instance.pickPrimitive,
id: instance.id
};
}
var positionRegex = /in\s+vec(?:3|4)\s+(.*)3DHigh;/g;
Primitive._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
)}()`;
if (functionName !== "vec4 czm_computePosition()") {
forwardDecl += `${functionName};
`;
}
if (!defined_default(primitive.rtcCenter)) {
if (!scene3DOnly) {
attributes += `in vec3 ${name}2DHigh;
in vec3 ${name}2DLow;
`;
computeFunctions += `${functionName}
{
vec4 p;
if (czm_morphTime == 1.0)
{
p = czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);
}
else if (czm_morphTime == 0.0)
{
p = czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy);
}
else
{
p = czm_columbusViewMorph(
czm_translateRelativeToEye(${name}2DHigh.zxy, ${name}2DLow.zxy),
czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow),
czm_morphTime);
}
return p;
}
`;
} else {
computeFunctions += `${functionName}
{
return czm_translateRelativeToEye(${name}3DHigh, ${name}3DLow);
}
`;
}
} else {
vertexShaderSource = vertexShaderSource.replace(
/in\s+vec(?:3|4)\s+position3DHigh;/g,
""
);
vertexShaderSource = vertexShaderSource.replace(
/in\s+vec(?:3|4)\s+position3DLow;/g,
""
);
forwardDecl += "uniform mat4 u_modifiedModelView;\n";
attributes += "in vec4 position;\n";
computeFunctions += `${functionName}
{
return u_modifiedModelView * position;
}
`;
vertexShaderSource = vertexShaderSource.replace(
/czm_modelViewRelativeToEye\s+\*\s+/g,
""
);
vertexShaderSource = vertexShaderSource.replace(
/czm_modelViewProjectionRelativeToEye/g,
"czm_projection"
);
}
}
return [forwardDecl, attributes, vertexShaderSource, computeFunctions].join(
"\n"
);
};
Primitive._appendShowToShader = function(primitive, vertexShaderSource) {
if (!defined_default(primitive._batchTableAttributeIndices.show)) {
return vertexShaderSource;
}
const renamedVS = ShaderSource_default.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}
${showMain}`;
};
Primitive._updateColorAttribute = function(primitive, vertexShaderSource, isDepthFail) {
if (!defined_default(primitive._batchTableAttributeIndices.color) && !defined_default(primitive._batchTableAttributeIndices.depthFailColor)) {
return vertexShaderSource;
}
if (vertexShaderSource.search(/in\s+vec4\s+color;/g) === -1) {
return vertexShaderSource;
}
if (isDepthFail && !defined_default(primitive._batchTableAttributeIndices.depthFailColor)) {
throw new DeveloperError_default(
"A depthFailColor per-instance attribute is required when using a depth fail appearance that uses a color attribute."
);
}
let modifiedVS = vertexShaderSource;
modifiedVS = modifiedVS.replace(/in\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_default.replaceMain(source, "czm_non_pick_main");
const pickMain = "out vec4 v_pickColor; \nvoid main() \n{ \n czm_non_pick_main(); \n v_pickColor = czm_batchTable_pickColor(batchId); \n}";
return `${renamedVS}
${pickMain}`;
}
function appendPickToFragmentShader(source) {
return `in vec4 v_pickColor;
${source}`;
}
Primitive._updatePickColorAttribute = function(source) {
let vsPick = source.replace(/in\s+vec4\s+pickColor;/g, "");
vsPick = vsPick.replace(
/(\b)pickColor(\b)/g,
"$1czm_batchTable_pickColor(batchId)$2"
);
return vsPick;
};
Primitive._appendOffsetToShader = function(primitive, vertexShaderSource) {
if (!defined_default(primitive._batchTableAttributeIndices.offset)) {
return vertexShaderSource;
}
let attr = "in float batchId;\n";
attr += "in float applyOffset;";
let modifiedShader = vertexShaderSource.replace(
/in\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._appendDistanceDisplayConditionToShader = function(primitive, vertexShaderSource, scene3DOnly) {
if (!defined_default(primitive._batchTableAttributeIndices.distanceDisplayCondition)) {
return vertexShaderSource;
}
const renamedVS = ShaderSource_default.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}
${distanceDisplayConditionMain}`;
};
function modifyForEncodedNormals(primitive, vertexShaderSource) {
if (!primitive.compressVertices) {
return vertexShaderSource;
}
const containsNormal = vertexShaderSource.search(/in\s+vec3\s+normal;/g) !== -1;
const containsSt = vertexShaderSource.search(/in\s+vec2\s+st;/g) !== -1;
if (!containsNormal && !containsSt) {
return vertexShaderSource;
}
const containsTangent = vertexShaderSource.search(/in\s+vec3\s+tangent;/g) !== -1;
const containsBitangent = vertexShaderSource.search(/in\s+vec3\s+bitangent;/g) !== -1;
let numComponents = containsSt && containsNormal ? 2 : 1;
numComponents += containsTangent || containsBitangent ? 1 : 0;
const type = numComponents > 1 ? `vec${numComponents}` : "float";
const attributeName = "compressedAttributes";
const attributeDecl = `in ${type} ${attributeName};`;
let globalDecl = "";
let decode = "";
if (containsSt) {
globalDecl += "vec2 st;\n";
const stComponent = numComponents > 1 ? `${attributeName}.x` : attributeName;
decode += ` st = czm_decompressTextureCoordinates(${stComponent});
`;
}
if (containsNormal && containsTangent && containsBitangent) {
globalDecl += "vec3 normal;\nvec3 tangent;\nvec3 bitangent;\n";
decode += ` czm_octDecode(${attributeName}.${containsSt ? "yz" : "xy"}, normal, tangent, bitangent);
`;
} else {
if (containsNormal) {
globalDecl += "vec3 normal;\n";
decode += ` normal = czm_octDecode(${attributeName}${numComponents > 1 ? `.${containsSt ? "y" : "x"}` : ""});
`;
}
if (containsTangent) {
globalDecl += "vec3 tangent;\n";
decode += ` tangent = czm_octDecode(${attributeName}.${containsSt && containsNormal ? "z" : "y"});
`;
}
if (containsBitangent) {
globalDecl += "vec3 bitangent;\n";
decode += ` bitangent = czm_octDecode(${attributeName}.${containsSt && containsNormal ? "z" : "y"});
`;
}
}
let modifiedVS = vertexShaderSource;
modifiedVS = modifiedVS.replace(/in\s+vec3\s+normal;/g, "");
modifiedVS = modifiedVS.replace(/in\s+vec2\s+st;/g, "");
modifiedVS = modifiedVS.replace(/in\s+vec3\s+tangent;/g, "");
modifiedVS = modifiedVS.replace(/in\s+vec3\s+bitangent;/g, "");
modifiedVS = ShaderSource_default.replaceMain(modifiedVS, "czm_non_compressed_main");
const compressedMain = `${"void main() \n{ \n"}${decode} czm_non_compressed_main();
}`;
return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
}
function depthClampVS(vertexShaderSource) {
let modifiedVS = ShaderSource_default.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_default.replaceMain(
fragmentShaderSource,
"czm_non_depth_clamp_main"
);
modifiedFS += "void main() {\n czm_non_depth_clamp_main();\n #if defined(LOG_DEPTH)\n czm_writeLogDepth();\n #else\n czm_writeDepthClamp();\n #endif\n}\n";
return modifiedFS;
}
function validateShaderMatching(shaderProgram, attributeLocations8) {
const shaderAttributes = shaderProgram.vertexAttributes;
for (const name in shaderAttributes) {
if (shaderAttributes.hasOwnProperty(name)) {
if (!defined_default(attributeLocations8[name])) {
throw new DeveloperError_default(
`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.`
);
}
}
}
}
function getUniformFunction(uniforms, name) {
return function() {
return uniforms[name];
};
}
var numberOfCreationWorkers = Math.max(
FeatureDetection_default.hardwareConcurrency - 1,
1
);
var createGeometryTaskProcessors;
var combineGeometryTaskProcessor = new TaskProcessor_default("combineGeometry");
function loadAsynchronous(primitive, frameState) {
let instances;
let geometry;
let i;
let j;
const instanceIds = primitive._instanceIds;
if (primitive._state === PrimitiveState_default.READY) {
instances = Array.isArray(primitive.geometryInstances) ? primitive.geometryInstances : [primitive.geometryInstances];
const length3 = primitive._numberOfInstances = instances.length;
const promises = [];
let subTasks = [];
for (i = 0; i < length3; ++i) {
geometry = instances[i].geometry;
instanceIds.push(instances[i].id);
if (!defined_default(geometry._workerName)) {
throw new DeveloperError_default(
"_workerName must be defined for asynchronous geometry."
);
}
subTasks.push({
moduleName: geometry._workerName,
geometry
});
}
if (!defined_default(createGeometryTaskProcessors)) {
createGeometryTaskProcessors = new Array(numberOfCreationWorkers);
for (i = 0; i < numberOfCreationWorkers; i++) {
createGeometryTaskProcessors[i] = new TaskProcessor_default("createGeometry");
}
}
let subTask;
subTasks = subdivideArray_default(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_default(geometry.constructor.pack)) {
subTask.offset = packedLength;
packedLength += defaultValue_default(
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_default(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_default.CREATING;
Promise.all(promises).then(function(results) {
primitive._createGeometryResults = results;
primitive._state = PrimitiveState_default.CREATED;
}).catch(function(error) {
setReady(primitive, frameState, PrimitiveState_default.FAILED, error);
});
} else if (primitive._state === PrimitiveState_default.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_default.packCombineGeometryParameters(
{
createGeometryResults: primitive._createGeometryResults,
instances,
ellipsoid: projection.ellipsoid,
projection,
elementIndexUintSupported: frameState.context.elementIndexUint,
scene3DOnly,
vertexCacheOptimize: primitive.vertexCacheOptimize,
compressVertices: primitive.compressVertices,
modelMatrix: primitive.modelMatrix,
createPickOffsets: primitive._createPickOffsets
},
transferableObjects
),
transferableObjects
);
primitive._createGeometryResults = void 0;
primitive._state = PrimitiveState_default.COMBINING;
Promise.resolve(promise).then(function(packedResult) {
const result = PrimitivePipeline_default.unpackCombineGeometryResults(
packedResult
);
primitive._geometries = result.geometries;
primitive._attributeLocations = result.attributeLocations;
primitive.modelMatrix = Matrix4_default.clone(
result.modelMatrix,
primitive.modelMatrix
);
primitive._pickOffsets = result.pickOffsets;
primitive._offsetInstanceExtend = result.offsetInstanceExtend;
primitive._instanceBoundingSpheres = result.boundingSpheres;
primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
if (defined_default(primitive._geometries) && primitive._geometries.length > 0) {
primitive._recomputeBoundingSpheres = true;
primitive._state = PrimitiveState_default.COMBINED;
} else {
setReady(primitive, frameState, PrimitiveState_default.FAILED, void 0);
}
}).catch(function(error) {
setReady(primitive, frameState, PrimitiveState_default.FAILED, error);
});
}
}
function loadSynchronous(primitive, frameState) {
const instances = Array.isArray(primitive.geometryInstances) ? primitive.geometryInstances : [primitive.geometryInstances];
const length3 = primitive._numberOfInstances = instances.length;
const clonedInstances = new Array(length3);
const instanceIds = primitive._instanceIds;
let instance;
let i;
let geometryIndex = 0;
for (i = 0; i < length3; i++) {
instance = instances[i];
const geometry = instance.geometry;
let createdGeometry;
if (defined_default(geometry.attributes) && defined_default(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_default.combineGeometry({
instances: clonedInstances,
ellipsoid: projection.ellipsoid,
projection,
elementIndexUintSupported: frameState.context.elementIndexUint,
scene3DOnly,
vertexCacheOptimize: primitive.vertexCacheOptimize,
compressVertices: primitive.compressVertices,
modelMatrix: primitive.modelMatrix,
createPickOffsets: primitive._createPickOffsets
});
primitive._geometries = result.geometries;
primitive._attributeLocations = result.attributeLocations;
primitive.modelMatrix = Matrix4_default.clone(
result.modelMatrix,
primitive.modelMatrix
);
primitive._pickOffsets = result.pickOffsets;
primitive._offsetInstanceExtend = result.offsetInstanceExtend;
primitive._instanceBoundingSpheres = result.boundingSpheres;
primitive._instanceBoundingSpheresCV = result.boundingSpheresCV;
if (defined_default(primitive._geometries) && primitive._geometries.length > 0) {
primitive._recomputeBoundingSpheres = true;
primitive._state = PrimitiveState_default.COMBINED;
} else {
setReady(primitive, frameState, PrimitiveState_default.FAILED, void 0);
}
}
function recomputeBoundingSpheres(primitive, frameState) {
const offsetIndex = primitive._batchTableAttributeIndices.offset;
if (!primitive._recomputeBoundingSpheres || !defined_default(offsetIndex)) {
primitive._recomputeBoundingSpheres = false;
return;
}
let i;
const offsetInstanceExtend = primitive._offsetInstanceExtend;
const boundingSpheres = primitive._instanceBoundingSpheres;
const length3 = boundingSpheres.length;
let newBoundingSpheres = primitive._tempBoundingSpheres;
if (!defined_default(newBoundingSpheres)) {
newBoundingSpheres = new Array(length3);
for (i = 0; i < length3; i++) {
newBoundingSpheres[i] = new BoundingSphere_default();
}
primitive._tempBoundingSpheres = newBoundingSpheres;
}
for (i = 0; i < length3; ++i) {
let newBS = newBoundingSpheres[i];
const offset2 = primitive._batchTable.getBatchedAttribute(
i,
offsetIndex,
new Cartesian3_default()
);
newBS = boundingSpheres[i].clone(newBS);
transformBoundingSphere(newBS, offset2, offsetInstanceExtend[i]);
}
const combinedBS = [];
const combinedWestBS = [];
const combinedEastBS = [];
for (i = 0; i < length3; ++i) {
const bs = newBoundingSpheres[i];
const minX = bs.center.x - bs.radius;
if (minX > 0 || BoundingSphere_default.intersectPlane(bs, Plane_default.ORIGIN_ZX_PLANE) !== Intersect_default.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_default.union(resultBS1, combinedBS[i]);
}
for (i = 1; i < combinedEastBS.length; i++) {
resultBS2 = BoundingSphere_default.union(resultBS2, combinedEastBS[i]);
}
for (i = 1; i < combinedWestBS.length; i++) {
resultBS3 = BoundingSphere_default.union(resultBS3, combinedWestBS[i]);
}
const result = [];
if (defined_default(resultBS1)) {
result.push(resultBS1);
}
if (defined_default(resultBS2)) {
result.push(resultBS2);
}
if (defined_default(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_default.projectTo2D(
boundingSphere,
frameState.mapProjection,
primitive._boundingSphereCV[i]
);
}
Primitive._updateBoundingVolumes(
primitive,
frameState,
primitive.modelMatrix,
true
);
primitive._recomputeBoundingSpheres = false;
}
var scratchBoundingSphereCenterEncoded = new EncodedCartesian3_default();
var scratchBoundingSphereCartographic = new Cartographic_default();
var scratchBoundingSphereCenter2D = new Cartesian3_default();
var scratchBoundingSphere3 = new BoundingSphere_default();
function updateBatchTableBoundingSpheres(primitive, frameState) {
const hasDistanceDisplayCondition = defined_default(
primitive._batchTableAttributeIndices.distanceDisplayCondition
);
if (!hasDistanceDisplayCondition || primitive._batchTableBoundingSpheresUpdated) {
return;
}
const indices2 = primitive._batchTableBoundingSphereAttributeIndices;
const center3DHighIndex = indices2.center3DHigh;
const center3DLowIndex = indices2.center3DLow;
const center2DHighIndex = indices2.center2DHigh;
const center2DLowIndex = indices2.center2DLow;
const radiusIndex = indices2.radius;
const projection = frameState.mapProjection;
const ellipsoid = projection.ellipsoid;
const batchTable = primitive._batchTable;
const boundingSpheres = primitive._instanceBoundingSpheres;
const length3 = boundingSpheres.length;
for (let i = 0; i < length3; ++i) {
let boundingSphere = boundingSpheres[i];
if (!defined_default(boundingSphere)) {
continue;
}
const modelMatrix = primitive.modelMatrix;
if (defined_default(modelMatrix)) {
boundingSphere = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
scratchBoundingSphere3
);
}
const center = boundingSphere.center;
const radius = boundingSphere.radius;
let encodedCenter = EncodedCartesian3_default.fromCartesian(
center,
scratchBoundingSphereCenterEncoded
);
batchTable.setBatchedAttribute(i, center3DHighIndex, encodedCenter.high);
batchTable.setBatchedAttribute(i, center3DLowIndex, encodedCenter.low);
if (!frameState.scene3DOnly) {
const cartographic2 = ellipsoid.cartesianToCartographic(
center,
scratchBoundingSphereCartographic
);
const center2D = projection.project(
cartographic2,
scratchBoundingSphereCenter2D
);
encodedCenter = EncodedCartesian3_default.fromCartesian(
center2D,
scratchBoundingSphereCenterEncoded
);
batchTable.setBatchedAttribute(i, center2DHighIndex, encodedCenter.high);
batchTable.setBatchedAttribute(i, center2DLowIndex, encodedCenter.low);
}
batchTable.setBatchedAttribute(i, radiusIndex, radius);
}
primitive._batchTableBoundingSpheresUpdated = true;
}
var offsetScratchCartesian = new Cartesian3_default();
var offsetCenterScratch = new Cartesian3_default();
function updateBatchTableOffsets(primitive, frameState) {
const hasOffset = defined_default(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 length3 = boundingSpheres.length;
for (let i = 0; i < length3; ++i) {
let boundingSphere = boundingSpheres[i];
if (!defined_default(boundingSphere)) {
continue;
}
const offset2 = batchTable.getBatchedAttribute(
i,
primitive._batchTableAttributeIndices.offset
);
if (Cartesian3_default.equals(offset2, Cartesian3_default.ZERO)) {
batchTable.setBatchedAttribute(i, index2D, Cartesian3_default.ZERO);
continue;
}
const modelMatrix = primitive.modelMatrix;
if (defined_default(modelMatrix)) {
boundingSphere = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
scratchBoundingSphere3
);
}
let center = boundingSphere.center;
center = ellipsoid.scaleToGeodeticSurface(center, offsetCenterScratch);
let cartographic2 = ellipsoid.cartesianToCartographic(
center,
scratchBoundingSphereCartographic
);
const center2D = projection.project(
cartographic2,
scratchBoundingSphereCenter2D
);
const newPoint = Cartesian3_default.add(offset2, center, offsetScratchCartesian);
cartographic2 = ellipsoid.cartesianToCartographic(newPoint, cartographic2);
const newPointProjected = projection.project(
cartographic2,
offsetScratchCartesian
);
const newVector = Cartesian3_default.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(primitive, frameState) {
const attributeLocations8 = primitive._attributeLocations;
const geometries = primitive._geometries;
const scene3DOnly = frameState.scene3DOnly;
const context = frameState.context;
const va = [];
const length3 = geometries.length;
for (let i = 0; i < length3; ++i) {
const geometry = geometries[i];
va.push(
VertexArray_default.fromGeometry({
context,
geometry,
attributeLocations: attributeLocations8,
bufferUsage: BufferUsage_default.STATIC_DRAW,
interleave: primitive._interleave
})
);
if (defined_default(primitive._createBoundingVolumeFunction)) {
primitive._createBoundingVolumeFunction(frameState, geometry);
} else {
primitive._boundingSpheres.push(
BoundingSphere_default.clone(geometry.boundingSphere)
);
primitive._boundingSphereWC.push(new BoundingSphere_default());
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_default.clone(geometry.boundingSphereCV)
);
primitive._boundingSphere2D.push(new BoundingSphere_default());
primitive._boundingSphereMorph.push(new BoundingSphere_default());
}
}
}
primitive._va = va;
primitive._primitiveType = geometries[0].primitiveType;
if (primitive.releaseGeometryInstances) {
primitive.geometryInstances = void 0;
}
primitive._geometries = void 0;
setReady(primitive, frameState, PrimitiveState_default.COMPLETE, void 0);
}
function createRenderStates(primitive, context, appearance, twoPasses) {
let renderState = appearance.getRenderState();
let rs;
if (twoPasses) {
rs = clone_default(renderState, false);
rs.cull = {
enabled: true,
face: CullFace_default.BACK
};
primitive._frontFaceRS = RenderState_default.fromCache(rs);
rs.cull.face = CullFace_default.FRONT;
primitive._backFaceRS = RenderState_default.fromCache(rs);
} else {
primitive._frontFaceRS = RenderState_default.fromCache(renderState);
primitive._backFaceRS = primitive._frontFaceRS;
}
rs = clone_default(renderState, false);
if (defined_default(primitive._depthFailAppearance)) {
rs.depthTest.enabled = false;
}
if (defined_default(primitive._depthFailAppearance)) {
renderState = primitive._depthFailAppearance.getRenderState();
rs = clone_default(renderState, false);
rs.depthTest.func = DepthFunction_default.GREATER;
if (twoPasses) {
rs.cull = {
enabled: true,
face: CullFace_default.BACK
};
primitive._frontFaceDepthFailRS = RenderState_default.fromCache(rs);
rs.cull.face = CullFace_default.FRONT;
primitive._backFaceDepthFailRS = RenderState_default.fromCache(rs);
} else {
primitive._frontFaceDepthFailRS = RenderState_default.fromCache(rs);
primitive._backFaceDepthFailRS = primitive._frontFaceRS;
}
}
}
function createShaderProgram(primitive, frameState, appearance) {
const context = frameState.context;
const attributeLocations8 = primitive._attributeLocations;
let vs = primitive._batchTable.getVertexShaderCallback()(
appearance.vertexShaderSource
);
vs = Primitive._appendOffsetToShader(primitive, vs);
vs = Primitive._appendShowToShader(primitive, vs);
vs = Primitive._appendDistanceDisplayConditionToShader(
primitive,
vs,
frameState.scene3DOnly
);
vs = appendPickToVertexShader(vs);
vs = Primitive._updateColorAttribute(primitive, vs, false);
vs = modifyForEncodedNormals(primitive, vs);
vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
let fs = appearance.getFragmentShaderSource();
fs = appendPickToFragmentShader(fs);
primitive._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: primitive._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
});
validateShaderMatching(primitive._sp, attributeLocations8);
if (defined_default(primitive._depthFailAppearance)) {
vs = primitive._batchTable.getVertexShaderCallback()(
primitive._depthFailAppearance.vertexShaderSource
);
vs = Primitive._appendShowToShader(primitive, vs);
vs = Primitive._appendDistanceDisplayConditionToShader(
primitive,
vs,
frameState.scene3DOnly
);
vs = appendPickToVertexShader(vs);
vs = Primitive._updateColorAttribute(primitive, vs, true);
vs = modifyForEncodedNormals(primitive, vs);
vs = Primitive._modifyShaderPosition(primitive, vs, frameState.scene3DOnly);
vs = depthClampVS(vs);
fs = primitive._depthFailAppearance.getFragmentShaderSource();
fs = appendPickToFragmentShader(fs);
fs = depthClampFS(fs);
primitive._spDepthFail = ShaderProgram_default.replaceCache({
context,
shaderProgram: primitive._spDepthFail,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
});
validateShaderMatching(primitive._spDepthFail, attributeLocations8);
}
}
var modifiedModelViewScratch = new Matrix4_default();
var rtcScratch = new Cartesian3_default();
function getUniforms(primitive, appearance, material, frameState) {
const materialUniformMap = defined_default(material) ? material._uniforms : void 0;
const appearanceUniformMap = {};
const appearanceUniforms = appearance.uniforms;
if (defined_default(appearanceUniforms)) {
for (const name in appearanceUniforms) {
if (appearanceUniforms.hasOwnProperty(name)) {
if (defined_default(materialUniformMap) && defined_default(materialUniformMap[name])) {
throw new DeveloperError_default(
`Appearance and material have a uniform with the same name: ${name}`
);
}
appearanceUniformMap[name] = getUniformFunction(
appearanceUniforms,
name
);
}
}
}
let uniforms = combine_default(appearanceUniformMap, materialUniformMap);
uniforms = primitive._batchTable.getUniformMapCallback()(uniforms);
if (defined_default(primitive.rtcCenter)) {
uniforms.u_modifiedModelView = function() {
const viewMatrix = frameState.context.uniformState.view;
Matrix4_default.multiply(
viewMatrix,
primitive._modelMatrix,
modifiedModelViewScratch
);
Matrix4_default.multiplyByPoint(
modifiedModelViewScratch,
primitive.rtcCenter,
rtcScratch
);
Matrix4_default.setTranslation(
modifiedModelViewScratch,
rtcScratch,
modifiedModelViewScratch
);
return modifiedModelViewScratch;
};
}
return uniforms;
}
function createCommands(primitive, appearance, material, translucent, twoPasses, colorCommands, pickCommands, frameState) {
const uniforms = getUniforms(primitive, appearance, material, frameState);
let depthFailUniforms;
if (defined_default(primitive._depthFailAppearance)) {
depthFailUniforms = getUniforms(
primitive,
primitive._depthFailAppearance,
primitive._depthFailAppearance.material,
frameState
);
}
const pass = translucent ? Pass_default.TRANSLUCENT : Pass_default.OPAQUE;
let multiplier = twoPasses ? 2 : 1;
multiplier *= defined_default(primitive._depthFailAppearance) ? 2 : 1;
colorCommands.length = primitive._va.length * multiplier;
const length3 = colorCommands.length;
let vaIndex = 0;
for (let i = 0; i < length3; ++i) {
let colorCommand;
if (twoPasses) {
colorCommand = colorCommands[i];
if (!defined_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
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_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
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_default(primitive._depthFailAppearance)) {
if (twoPasses) {
++i;
colorCommand = colorCommands[i];
if (!defined_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
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_default(colorCommand)) {
colorCommand = colorCommands[i] = new DrawCommand_default({
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._updateBoundingVolumes = function(primitive, frameState, modelMatrix, forceUpdate) {
let i;
let length3;
let boundingSphere;
if (forceUpdate || !Matrix4_default.equals(modelMatrix, primitive._modelMatrix)) {
Matrix4_default.clone(modelMatrix, primitive._modelMatrix);
length3 = primitive._boundingSpheres.length;
for (i = 0; i < length3; ++i) {
boundingSphere = primitive._boundingSpheres[i];
if (defined_default(boundingSphere)) {
primitive._boundingSphereWC[i] = BoundingSphere_default.transform(
boundingSphere,
modelMatrix,
primitive._boundingSphereWC[i]
);
if (!frameState.scene3DOnly) {
primitive._boundingSphere2D[i] = BoundingSphere_default.clone(
primitive._boundingSphereCV[i],
primitive._boundingSphere2D[i]
);
primitive._boundingSphere2D[i].center.x = 0;
primitive._boundingSphereMorph[i] = BoundingSphere_default.union(
primitive._boundingSphereWC[i],
primitive._boundingSphereCV[i]
);
}
}
}
}
const pixelSize = primitive.appearance.pixelSize;
if (defined_default(pixelSize)) {
length3 = primitive._boundingSpheres.length;
for (i = 0; i < length3; ++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(primitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
if (frameState.mode !== SceneMode_default.SCENE3D && !Matrix4_default.equals(modelMatrix, Matrix4_default.IDENTITY)) {
throw new DeveloperError_default(
"Primitive.modelMatrix is only supported in 3D mode."
);
}
Primitive._updateBoundingVolumes(primitive, frameState, modelMatrix);
let boundingSpheres;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingSpheres = primitive._boundingSphereWC;
} else if (frameState.mode === SceneMode_default.COLUMBUS_VIEW) {
boundingSpheres = primitive._boundingSphereCV;
} else if (frameState.mode === SceneMode_default.SCENE2D && defined_default(primitive._boundingSphere2D)) {
boundingSpheres = primitive._boundingSphere2D;
} else if (defined_default(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_default.castShadows(primitive.shadows);
const receiveShadows = ShadowMode_default.receiveShadows(primitive.shadows);
const colorLength = colorCommands.length;
let factor2 = twoPasses ? 2 : 1;
factor2 *= defined_default(primitive._depthFailAppearance) ? 2 : 1;
for (let j = 0; j < colorLength; ++j) {
const sphereIndex = Math.floor(j / factor2);
const colorCommand = colorCommands[j];
colorCommand.modelMatrix = modelMatrix;
colorCommand.boundingVolume = boundingSpheres[sphereIndex];
colorCommand.cull = cull;
colorCommand.debugShowBoundingVolume = debugShowBoundingVolume2;
colorCommand.castShadows = castShadows;
colorCommand.receiveShadows = receiveShadows;
if (allowPicking) {
colorCommand.pickId = "v_pickColor";
} else {
colorCommand.pickId = void 0;
}
commandList.push(colorCommand);
}
}
}
Primitive.prototype.update = function(frameState) {
if (!defined_default(this.geometryInstances) && this._va.length === 0 || defined_default(this.geometryInstances) && Array.isArray(this.geometryInstances) && this.geometryInstances.length === 0 || !defined_default(this.appearance) || frameState.mode !== SceneMode_default.SCENE3D && frameState.scene3DOnly || !frameState.passes.render && !frameState.passes.pick) {
return;
}
if (defined_default(this._error)) {
throw this._error;
}
if (defined_default(this.rtcCenter) && !frameState.scene3DOnly) {
throw new DeveloperError_default(
"RTC rendering is only available for 3D only scenes."
);
}
if (this._state === PrimitiveState_default.FAILED) {
return;
}
const context = frameState.context;
if (!defined_default(this._batchTable)) {
createBatchTable(this, context);
}
if (this._batchTable.attributes.length > 0) {
if (ContextLimits_default.maximumVertexTextureImageUnits === 0) {
throw new RuntimeError_default(
"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_default.COMPLETE && this._state !== PrimitiveState_default.COMBINED) {
if (this.asynchronous) {
loadAsynchronous(this, frameState);
} else {
loadSynchronous(this, frameState);
}
}
if (this._state === PrimitiveState_default.COMBINED) {
updateBatchTableBoundingSpheres(this, frameState);
updateBatchTableOffsets(this, frameState);
createVertexArray(this, frameState);
}
if (!this.show || this._state !== PrimitiveState_default.COMPLETE) {
return;
}
if (!this._batchTableOffsetsUpdated) {
updateBatchTableOffsets(this, frameState);
}
if (this._recomputeBoundingSpheres) {
recomputeBoundingSpheres(this, frameState);
}
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_default(depthFailAppearance) ? depthFailAppearance.material : void 0;
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_default(this._material)) {
this._material.update(context);
}
const twoPasses = appearance.closed && translucent;
if (createRS) {
const rsFunc = defaultValue_default(
this._createRenderStatesFunction,
createRenderStates
);
rsFunc(this, context, appearance, twoPasses);
}
if (createSP) {
const spFunc = defaultValue_default(
this._createShaderProgramFunction,
createShaderProgram
);
spFunc(this, frameState, appearance);
}
if (createRS || createSP) {
const commandFunc = defaultValue_default(
this._createCommandsFunction,
createCommands
);
commandFunc(
this,
appearance,
material,
translucent,
twoPasses,
this._colorCommands,
this._pickCommands,
frameState
);
}
const updateAndQueueCommandsFunc = defaultValue_default(
this._updateAndQueueCommandsFunction,
updateAndQueueCommands
);
updateAndQueueCommandsFunc(
this,
frameState,
this._colorCommands,
this._pickCommands,
this.modelMatrix,
this.cull,
this.debugShowBoundingVolume,
twoPasses
);
};
var offsetBoundingSphereScratch1 = new BoundingSphere_default();
var offsetBoundingSphereScratch2 = new BoundingSphere_default();
function transformBoundingSphere(boundingSphere, offset2, offsetAttribute) {
if (offsetAttribute === GeometryOffsetAttribute_default.TOP) {
const origBS = BoundingSphere_default.clone(
boundingSphere,
offsetBoundingSphereScratch1
);
const offsetBS = BoundingSphere_default.clone(
boundingSphere,
offsetBoundingSphereScratch2
);
offsetBS.center = Cartesian3_default.add(offsetBS.center, offset2, offsetBS.center);
boundingSphere = BoundingSphere_default.union(origBS, offsetBS, boundingSphere);
} else if (offsetAttribute === GeometryOffsetAttribute_default.ALL) {
boundingSphere.center = Cartesian3_default.add(
boundingSphere.center,
offset2,
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_default.createTypedArray(
attribute.componentDatatype,
componentsPerAttribute
);
if (defined_default(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) {
if (!defined_default(value) || !defined_default(value.length) || value.length < 1 || value.length > 4) {
throw new DeveloperError_default(
"value must be and array with length between 1 and 4."
);
}
const attributeValue = getAttributeValue(value);
batchTable.setBatchedAttribute(
instanceIndex,
attributeIndex,
attributeValue
);
if (name === "offset") {
primitive._recomputeBoundingSpheres = true;
primitive._batchTableOffsetsUpdated = false;
}
};
}
var offsetScratch2 = new Cartesian3_default();
function createBoundingSphereProperties(primitive, properties, index) {
properties.boundingSphere = {
get: function() {
let boundingSphere = primitive._instanceBoundingSpheres[index];
if (defined_default(boundingSphere)) {
boundingSphere = boundingSphere.clone();
const modelMatrix = primitive.modelMatrix;
const offset2 = properties.offset;
if (defined_default(offset2)) {
transformBoundingSphere(
boundingSphere,
Cartesian3_default.fromArray(offset2.get(), 0, offsetScratch2),
primitive._offsetInstanceExtend[index]
);
}
if (defined_default(modelMatrix)) {
boundingSphere = BoundingSphere_default.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];
}
};
}
Primitive.prototype.getGeometryInstanceAttributes = function(id) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required");
}
if (!defined_default(this._batchTable)) {
throw new DeveloperError_default(
"must call update before calling getGeometryInstanceAttributes"
);
}
let attributes = this._perInstanceAttributeCache.get(id);
if (defined_default(attributes)) {
return attributes;
}
let index = -1;
const lastIndex = this._lastPerInstanceAttributeIndex;
const ids = this._instanceIds;
const length3 = ids.length;
for (let i = 0; i < length3; ++i) {
const curIndex = (lastIndex + i) % length3;
if (id === ids[curIndex]) {
index = curIndex;
break;
}
}
if (index === -1) {
return void 0;
}
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.set(id, attributes);
return attributes;
};
Primitive.prototype.isDestroyed = function() {
return false;
};
Primitive.prototype.destroy = function() {
let length3;
let i;
this._sp = this._sp && this._sp.destroy();
this._spDepthFail = this._spDepthFail && this._spDepthFail.destroy();
const va = this._va;
length3 = va.length;
for (i = 0; i < length3; ++i) {
va[i].destroy();
}
this._va = void 0;
const pickIds = this._pickIds;
length3 = pickIds.length;
for (i = 0; i < length3; ++i) {
pickIds[i].destroy();
}
this._pickIds = void 0;
this._batchTable = this._batchTable && this._batchTable.destroy();
this._instanceIds = void 0;
this._perInstanceAttributeCache = void 0;
this._attributeLocations = void 0;
return destroyObject_default(this);
};
function setReady(primitive, frameState, state, error) {
primitive._completeLoad(frameState, state, error);
}
var Primitive_default = Primitive;
// node_modules/@cesium/engine/Source/Core/GeometryInstanceAttribute.js
function GeometryInstanceAttribute(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.componentDatatype)) {
throw new DeveloperError_default("options.componentDatatype is required.");
}
if (!defined_default(options.componentsPerAttribute)) {
throw new DeveloperError_default("options.componentsPerAttribute is required.");
}
if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
throw new DeveloperError_default(
"options.componentsPerAttribute must be between 1 and 4."
);
}
if (!defined_default(options.value)) {
throw new DeveloperError_default("options.value is required.");
}
this.componentDatatype = options.componentDatatype;
this.componentsPerAttribute = options.componentsPerAttribute;
this.normalize = defaultValue_default(options.normalize, false);
this.value = options.value;
}
var GeometryInstanceAttribute_default = GeometryInstanceAttribute;
// node_modules/@cesium/engine/Source/Shaders/ShadowVolumeAppearanceFS.js
var ShadowVolumeAppearanceFS_default = "#ifdef TEXTURE_COORDINATES\n#ifdef SPHERICAL\nin vec4 v_sphericalExtents;\n#else // SPHERICAL\nin vec2 v_inversePlaneExtents;\nin vec4 v_westPlane;\nin vec4 v_southPlane;\n#endif // SPHERICAL\nin vec3 v_uvMinAndSphericalLongitudeRotation;\nin vec3 v_uMaxAndInverseDistance;\nin vec3 v_vMaxAndInverseDistance;\n#endif // TEXTURE_COORDINATES\n\n#ifdef PER_INSTANCE_COLOR\nin vec4 v_color;\n#endif\n\n#ifdef NORMAL_EC\nvec3 getEyeCoordinate3FromWindowCoordinate(vec2 fragCoord, float logDepthOrDepth) {\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(fragCoord, logDepthOrDepth);\n return eyeCoordinate.xyz / eyeCoordinate.w;\n}\n\nvec3 vectorFromOffset(vec4 eyeCoordinate, vec2 positiveOffset) {\n vec2 glFragCoordXY = gl_FragCoord.xy;\n // Sample depths at both offset and negative offset\n float upOrRightLogDepth = czm_unpackDepth(texture(czm_globeDepthTexture, (glFragCoordXY + positiveOffset) / czm_viewport.zw));\n float downOrLeftLogDepth = czm_unpackDepth(texture(czm_globeDepthTexture, (glFragCoordXY - positiveOffset) / czm_viewport.zw));\n // Explicitly evaluate both paths\n // Necessary for multifrustum and for edges of the screen\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\nvoid main(void)\n{\n#ifdef REQUIRES_EC\n float logDepthOrDepth = czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw));\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n#endif\n\n#ifdef REQUIRES_WC\n vec4 worldCoordinate4 = czm_inverseView * eyeCoordinate;\n vec3 worldCoordinate = worldCoordinate4.xyz / worldCoordinate4.w;\n#endif\n\n#ifdef TEXTURE_COORDINATES\n vec2 uv;\n#ifdef SPHERICAL\n // Treat world coords as a sphere normal for spherical coordinates\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 // Unpack planes and transform to eye space\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\n#ifdef PICK\n#ifdef CULL_FRAGMENTS\n // When classifying translucent geometry, logDepthOrDepth == 0.0\n // indicates a region that should not be classified, possibly due to there\n // being opaque pixels there in another buffer.\n // Check for logDepthOrDepth != 0.0 to make sure this should be classified.\n if (0.0 <= uv.x && uv.x <= 1.0 && 0.0 <= uv.y && uv.y <= 1.0 || logDepthOrDepth != 0.0) {\n out_FragColor.a = 1.0; // 0.0 alpha leads to discard from ShaderSource.createPickFragmentShaderSource\n czm_writeDepthClamp();\n }\n#else // CULL_FRAGMENTS\n out_FragColor.a = 1.0;\n#endif // CULL_FRAGMENTS\n#else // PICK\n\n#ifdef CULL_FRAGMENTS\n // When classifying translucent geometry, logDepthOrDepth == 0.0\n // indicates a region that should not be classified, possibly due to there\n // being opaque pixels there in another buffer.\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\n#ifdef NORMAL_EC\n // Compute normal by sampling adjacent pixels in 2x2 block in screen space\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\n\n#ifdef PER_INSTANCE_COLOR\n\n vec4 color = czm_gammaCorrect(v_color);\n#ifdef FLAT\n out_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\n out_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);\n#endif // FLAT\n\n // Premultiply alpha. Required for classification primitives on translucent globe.\n out_FragColor.rgb *= out_FragColor.a;\n\n#else // PER_INSTANCE_COLOR\n\n // Material support.\n // USES_ is distinct from REQUIRES_, because some things are dependencies of each other or\n // dependencies for culling but might not actually be used by the material.\n\n czm_materialInput materialInput;\n\n#ifdef USES_NORMAL_EC\n materialInput.normalEC = normalEC;\n#endif\n\n#ifdef USES_POSITION_TO_EYE_EC\n materialInput.positionToEyeEC = -eyeCoordinate.xyz;\n#endif\n\n#ifdef USES_TANGENT_TO_EYE\n materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(worldCoordinate, normalEC);\n#endif\n\n#ifdef USES_ST\n // Remap texture coordinates from computed (approximately aligned with cartographic space) to the desired\n // texture coordinate system, which typically forms a tight oriented bounding box around the geometry.\n // Shader is provided a set of reference points for remapping.\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\n czm_material material = czm_getMaterial(materialInput);\n\n#ifdef FLAT\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else // FLAT\n out_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);\n#endif // FLAT\n\n // Premultiply alpha. Required for classification primitives on translucent globe.\n out_FragColor.rgb *= out_FragColor.a;\n\n#endif // PER_INSTANCE_COLOR\n czm_writeDepthClamp();\n#endif // PICK\n}\n";
// node_modules/@cesium/engine/Source/Scene/ShadowVolumeAppearance.js
function ShadowVolumeAppearance(extentsCulling, planarExtents, appearance) {
Check_default.typeOf.bool("extentsCulling", extentsCulling);
Check_default.typeOf.bool("planarExtents", planarExtents);
Check_default.typeOf.object("appearance", appearance);
this._projectionExtentDefines = {
eastMostYhighDefine: "",
eastMostYlowDefine: "",
westMostYhighDefine: "",
westMostYlowDefine: ""
};
const colorShaderDependencies = new ShaderDependencies();
colorShaderDependencies.requiresTextureCoordinates = extentsCulling;
colorShaderDependencies.requiresEC = !appearance.flat;
const pickShaderDependencies = new ShaderDependencies();
pickShaderDependencies.requiresTextureCoordinates = extentsCulling;
if (appearance instanceof PerInstanceColorAppearance_default) {
colorShaderDependencies.requiresNormalEC = !appearance.flat;
} else {
const materialShaderSource = `${appearance.material.shaderSource}
${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;
}
ShadowVolumeAppearance.prototype.createFragmentShader = function(columbusView2D) {
Check_default.typeOf.bool("columbusView2D", columbusView2D);
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_default) {
defines.push("PER_INSTANCE_COLOR");
}
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_default)) {
materialSource = appearance.material.shaderSource;
}
return new ShaderSource_default({
defines,
sources: [materialSource, ShadowVolumeAppearanceFS_default]
});
};
ShadowVolumeAppearance.prototype.createPickFragmentShader = function(columbusView2D) {
Check_default.typeOf.bool("columbusView2D", columbusView2D);
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_default({
defines,
sources: [ShadowVolumeAppearanceFS_default],
pickColorQualifier: "in"
});
};
ShadowVolumeAppearance.prototype.createVertexShader = function(defines, vertexShaderSource, columbusView2D, mapProjection) {
Check_default.defined("defines", defines);
Check_default.typeOf.string("vertexShaderSource", vertexShaderSource);
Check_default.typeOf.bool("columbusView2D", columbusView2D);
Check_default.defined("mapProjection", mapProjection);
return createShadowVolumeAppearanceVS(
this._colorShaderDependencies,
this._planarExtents,
columbusView2D,
defines,
vertexShaderSource,
this._appearance,
mapProjection,
this._projectionExtentDefines
);
};
ShadowVolumeAppearance.prototype.createPickVertexShader = function(defines, vertexShaderSource, columbusView2D, mapProjection) {
Check_default.defined("defines", defines);
Check_default.typeOf.string("vertexShaderSource", vertexShaderSource);
Check_default.typeOf.bool("columbusView2D", columbusView2D);
Check_default.defined("mapProjection", mapProjection);
return createShadowVolumeAppearanceVS(
this._pickShaderDependencies,
this._planarExtents,
columbusView2D,
defines,
vertexShaderSource,
void 0,
mapProjection,
this._projectionExtentDefines
);
};
var longitudeExtentsCartesianScratch = new Cartesian3_default();
var longitudeExtentsCartographicScratch = new Cartographic_default();
var longitudeExtentsEncodeScratch = {
high: 0,
low: 0
};
function createShadowVolumeAppearanceVS(shaderDependencies, planarExtents, columbusView2D, defines, vertexShaderSource, appearance, mapProjection, projectionExtentDefines) {
const allDefines = defines.slice();
if (projectionExtentDefines.eastMostYhighDefine === "") {
const eastMostCartographic = longitudeExtentsCartographicScratch;
eastMostCartographic.longitude = Math_default.PI;
eastMostCartographic.latitude = 0;
eastMostCartographic.height = 0;
const eastMostCartesian = mapProjection.project(
eastMostCartographic,
longitudeExtentsCartesianScratch
);
let encoded = EncodedCartesian3_default.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 = -Math_default.PI;
westMostCartographic.latitude = 0;
westMostCartographic.height = 0;
const westMostCartesian = mapProjection.project(
westMostCartographic,
longitudeExtentsCartesianScratch
);
encoded = EncodedCartesian3_default.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_default(appearance) && appearance instanceof PerInstanceColorAppearance_default) {
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_default({
defines: allDefines,
sources: [vertexShaderSource]
});
}
function ShaderDependencies() {
this._requiresEC = false;
this._requiresWC = false;
this._requiresNormalEC = false;
this._requiresTextureCoordinates = false;
this._usesNormalEC = false;
this._usesPositionToEyeEC = false;
this._usesTangentToEyeMat = false;
this._usesSt = false;
}
Object.defineProperties(ShaderDependencies.prototype, {
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;
}
},
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_default.distance(point2, point1);
}
var points2DScratch2 = [
new Cartesian2_default(),
new Cartesian2_default(),
new Cartesian2_default(),
new Cartesian2_default()
];
function addTextureCoordinateRotationAttributes(attributes, textureCoordinateRotationPoints4) {
const points2D = points2DScratch2;
const minXYCorner = Cartesian2_default.unpack(
textureCoordinateRotationPoints4,
0,
points2D[0]
);
const maxYCorner = Cartesian2_default.unpack(
textureCoordinateRotationPoints4,
2,
points2D[1]
);
const maxXCorner = Cartesian2_default.unpack(
textureCoordinateRotationPoints4,
4,
points2D[2]
);
attributes.uMaxVmax = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: [maxYCorner.x, maxYCorner.y, maxXCorner.x, maxXCorner.y]
});
const inverseExtentX = 1 / pointLineDistance(minXYCorner, maxYCorner, maxXCorner);
const inverseExtentY = 1 / pointLineDistance(minXYCorner, maxXCorner, maxYCorner);
attributes.uvMinAndExtents = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: [minXYCorner.x, minXYCorner.y, inverseExtentX, inverseExtentY]
});
}
var cartographicScratch = new Cartographic_default();
var cornerScratch = new Cartesian3_default();
var northWestScratch = new Cartesian3_default();
var southEastScratch = new Cartesian3_default();
var highLowScratch = { high: 0, low: 0 };
function add2DTextureCoordinateAttributes(rectangle, projection, attributes) {
const carto = cartographicScratch;
carto.height = 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);
const valuesHigh = [0, 0, 0, 0];
const valuesLow = [0, 0, 0, 0];
let encoded = EncodedCartesian3_default.encode(southWestCorner.x, highLowScratch);
valuesHigh[0] = encoded.high;
valuesLow[0] = encoded.low;
encoded = EncodedCartesian3_default.encode(southWestCorner.y, highLowScratch);
valuesHigh[1] = encoded.high;
valuesLow[1] = encoded.low;
encoded = EncodedCartesian3_default.encode(northWest.y, highLowScratch);
valuesHigh[2] = encoded.high;
valuesLow[2] = encoded.low;
encoded = EncodedCartesian3_default.encode(southEast.x, highLowScratch);
valuesHigh[3] = encoded.high;
valuesLow[3] = encoded.low;
attributes.planes2D_HIGH = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: valuesHigh
});
attributes.planes2D_LOW = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: valuesLow
});
}
var enuMatrixScratch = new Matrix4_default();
var inverseEnuScratch = new Matrix4_default();
var rectanglePointCartesianScratch = new Cartesian3_default();
var rectangleCenterScratch2 = new Cartographic_default();
var pointsCartographicScratch = [
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default(),
new Cartographic_default()
];
function computeRectangleBounds(rectangle, ellipsoid, height, southWestCornerResult, eastVectorResult, northVectorResult) {
const centerCartographic = Rectangle_default.center(
rectangle,
rectangleCenterScratch2
);
centerCartographic.height = height;
const centerCartesian2 = Cartographic_default.toCartesian(
centerCartographic,
ellipsoid,
rectanglePointCartesianScratch
);
const enuMatrix = Transforms_default.eastNorthUpToFixedFrame(
centerCartesian2,
ellipsoid,
enuMatrixScratch
);
const inverseEnu = Matrix4_default.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_default.toCartesian(
cartographics[i],
ellipsoid,
rectanglePointCartesianScratch
);
Matrix4_default.multiplyByPoint(inverseEnu, pointCartesian, pointCartesian);
pointCartesian.z = 0;
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;
Matrix4_default.multiplyByPoint(enuMatrix, southWestCorner, southWestCorner);
const southEastCorner = eastVectorResult;
southEastCorner.x = maxX;
southEastCorner.y = minY;
southEastCorner.z = 0;
Matrix4_default.multiplyByPoint(enuMatrix, southEastCorner, southEastCorner);
Cartesian3_default.subtract(southEastCorner, southWestCorner, eastVectorResult);
const northWestCorner = northVectorResult;
northWestCorner.x = minX;
northWestCorner.y = maxY;
northWestCorner.z = 0;
Matrix4_default.multiplyByPoint(enuMatrix, northWestCorner, northWestCorner);
Cartesian3_default.subtract(northWestCorner, southWestCorner, northVectorResult);
}
var eastwardScratch = new Cartesian3_default();
var northwardScratch = new Cartesian3_default();
var encodeScratch = new EncodedCartesian3_default();
ShadowVolumeAppearance.getPlanarTextureCoordinateAttributes = function(boundingRectangle, textureCoordinateRotationPoints4, ellipsoid, projection, height) {
Check_default.typeOf.object("boundingRectangle", boundingRectangle);
Check_default.defined(
"textureCoordinateRotationPoints",
textureCoordinateRotationPoints4
);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.typeOf.object("projection", projection);
const corner = cornerScratch;
const eastward = eastwardScratch;
const northward = northwardScratch;
computeRectangleBounds(
boundingRectangle,
ellipsoid,
defaultValue_default(height, 0),
corner,
eastward,
northward
);
const attributes = {};
addTextureCoordinateRotationAttributes(
attributes,
textureCoordinateRotationPoints4
);
const encoded = EncodedCartesian3_default.fromCartesian(corner, encodeScratch);
attributes.southWest_HIGH = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(encoded.high, [0, 0, 0])
});
attributes.southWest_LOW = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(encoded.low, [0, 0, 0])
});
attributes.eastward = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(eastward, [0, 0, 0])
});
attributes.northward = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
normalize: false,
value: Cartesian3_default.pack(northward, [0, 0, 0])
});
add2DTextureCoordinateAttributes(boundingRectangle, projection, attributes);
return attributes;
};
var spherePointScratch = new Cartesian3_default();
function latLongToSpherical(latitude, longitude, ellipsoid, result) {
const cartographic2 = cartographicScratch;
cartographic2.latitude = latitude;
cartographic2.longitude = longitude;
cartographic2.height = 0;
const spherePoint = Cartographic_default.toCartesian(
cartographic2,
ellipsoid,
spherePointScratch
);
const magXY = Math.sqrt(
spherePoint.x * spherePoint.x + spherePoint.y * spherePoint.y
);
const sphereLatitude = Math_default.fastApproximateAtan2(magXY, spherePoint.z);
const sphereLongitude = Math_default.fastApproximateAtan2(
spherePoint.x,
spherePoint.y
);
result.x = sphereLatitude;
result.y = sphereLongitude;
return result;
}
var sphericalScratch = new Cartesian2_default();
ShadowVolumeAppearance.getSphericalExtentGeometryInstanceAttributes = function(boundingRectangle, textureCoordinateRotationPoints4, ellipsoid, projection) {
Check_default.typeOf.object("boundingRectangle", boundingRectangle);
Check_default.defined(
"textureCoordinateRotationPoints",
textureCoordinateRotationPoints4
);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.typeOf.object("projection", projection);
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;
let rotationRadians = 0;
if (west > east) {
rotationRadians = Math_default.PI - west;
west = -Math_default.PI;
east += rotationRadians;
}
south -= Math_default.EPSILON5;
west -= Math_default.EPSILON5;
north += Math_default.EPSILON5;
east += Math_default.EPSILON5;
const longitudeRangeInverse = 1 / (east - west);
const latitudeRangeInverse = 1 / (north - south);
const attributes = {
sphericalExtents: new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
value: [south, west, latitudeRangeInverse, longitudeRangeInverse]
}),
longitudeRotation: new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 1,
normalize: false,
value: [rotationRadians]
})
};
addTextureCoordinateRotationAttributes(
attributes,
textureCoordinateRotationPoints4
);
add2DTextureCoordinateAttributes(boundingRectangle, projection, attributes);
return attributes;
};
ShadowVolumeAppearance.hasAttributesForTextureCoordinatePlanes = function(attributes) {
return defined_default(attributes.southWest_HIGH) && defined_default(attributes.southWest_LOW) && defined_default(attributes.northward) && defined_default(attributes.eastward) && defined_default(attributes.planes2D_HIGH) && defined_default(attributes.planes2D_LOW) && defined_default(attributes.uMaxVmax) && defined_default(attributes.uvMinAndExtents);
};
ShadowVolumeAppearance.hasAttributesForSphericalExtents = function(attributes) {
return defined_default(attributes.sphericalExtents) && defined_default(attributes.longitudeRotation) && defined_default(attributes.planes2D_HIGH) && defined_default(attributes.planes2D_LOW) && defined_default(attributes.uMaxVmax) && defined_default(attributes.uvMinAndExtents);
};
function shouldUseSpherical(rectangle) {
return Math.max(rectangle.width, rectangle.height) > ShadowVolumeAppearance.MAX_WIDTH_FOR_PLANAR_EXTENTS;
}
ShadowVolumeAppearance.shouldUseSphericalCoordinates = function(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
return shouldUseSpherical(rectangle);
};
ShadowVolumeAppearance.MAX_WIDTH_FOR_PLANAR_EXTENTS = Math_default.toRadians(1);
var ShadowVolumeAppearance_default = ShadowVolumeAppearance;
// node_modules/@cesium/engine/Source/Scene/StencilFunction.js
var StencilFunction = {
NEVER: WebGLConstants_default.NEVER,
LESS: WebGLConstants_default.LESS,
EQUAL: WebGLConstants_default.EQUAL,
LESS_OR_EQUAL: WebGLConstants_default.LEQUAL,
GREATER: WebGLConstants_default.GREATER,
NOT_EQUAL: WebGLConstants_default.NOTEQUAL,
GREATER_OR_EQUAL: WebGLConstants_default.GEQUAL,
ALWAYS: WebGLConstants_default.ALWAYS
};
var StencilFunction_default = Object.freeze(StencilFunction);
// node_modules/@cesium/engine/Source/Scene/StencilOperation.js
var StencilOperation = {
ZERO: WebGLConstants_default.ZERO,
KEEP: WebGLConstants_default.KEEP,
REPLACE: WebGLConstants_default.REPLACE,
INCREMENT: WebGLConstants_default.INCR,
DECREMENT: WebGLConstants_default.DECR,
INVERT: WebGLConstants_default.INVERT,
INCREMENT_WRAP: WebGLConstants_default.INCR_WRAP,
DECREMENT_WRAP: WebGLConstants_default.DECR_WRAP
};
var StencilOperation_default = Object.freeze(StencilOperation);
// node_modules/@cesium/engine/Source/Scene/StencilConstants.js
var StencilConstants = {
CESIUM_3D_TILE_MASK: 128,
SKIP_LOD_MASK: 112,
SKIP_LOD_BIT_SHIFT: 4,
CLASSIFICATION_MASK: 15
};
StencilConstants.setCesium3DTileBit = function() {
return {
enabled: true,
frontFunction: StencilFunction_default.ALWAYS,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.REPLACE
},
backFunction: StencilFunction_default.ALWAYS,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.REPLACE
},
reference: StencilConstants.CESIUM_3D_TILE_MASK,
mask: StencilConstants.CESIUM_3D_TILE_MASK
};
};
var StencilConstants_default = Object.freeze(StencilConstants);
// node_modules/@cesium/engine/Source/Scene/ClassificationPrimitive.js
function ClassificationPrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const geometryInstances = options.geometryInstances;
this.geometryInstances = geometryInstances;
this.show = defaultValue_default(options.show, true);
this.classificationType = defaultValue_default(
options.classificationType,
ClassificationType_default.BOTH
);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.debugShowShadowVolume = defaultValue_default(
options.debugShowShadowVolume,
false
);
this._debugShowShadowVolume = false;
this._extruded = defaultValue_default(options._extruded, false);
this._uniformMap = options._uniformMap;
this._sp = void 0;
this._spStencil = void 0;
this._spPick = void 0;
this._spColor = void 0;
this._spPick2D = void 0;
this._spColor2D = void 0;
this._rsStencilDepthPass = void 0;
this._rsStencilDepthPass3DTiles = void 0;
this._rsColorPass = void 0;
this._rsPickPass = void 0;
this._commandsIgnoreShow = [];
this._ready = false;
const classificationPrimitive = this;
this._readyPromise = new Promise((resolve2, reject) => {
classificationPrimitive._completeLoad = () => {
if (this._ready) {
return;
}
this._ready = true;
if (this.releaseGeometryInstances) {
this.geometryInstances = void 0;
}
const error = this._error;
if (!defined_default(error)) {
resolve2(this);
} else {
reject(error);
}
};
});
this._primitive = void 0;
this._pickPrimitive = options._pickPrimitive;
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: void 0,
appearance: void 0,
vertexCacheOptimize: defaultValue_default(options.vertexCacheOptimize, false),
interleave: defaultValue_default(options.interleave, false),
releaseGeometryInstances: defaultValue_default(
options.releaseGeometryInstances,
true
),
allowPicking: defaultValue_default(options.allowPicking, true),
asynchronous: defaultValue_default(options.asynchronous, true),
compressVertices: defaultValue_default(options.compressVertices, true),
_createBoundingVolumeFunction: void 0,
_createRenderStatesFunction: void 0,
_createShaderProgramFunction: void 0,
_createCommandsFunction: void 0,
_updateAndQueueCommandsFunction: void 0,
_createPickOffsets: true
};
}
Object.defineProperties(ClassificationPrimitive.prototype, {
vertexCacheOptimize: {
get: function() {
return this._primitiveOptions.vertexCacheOptimize;
}
},
interleave: {
get: function() {
return this._primitiveOptions.interleave;
}
},
releaseGeometryInstances: {
get: function() {
return this._primitiveOptions.releaseGeometryInstances;
}
},
allowPicking: {
get: function() {
return this._primitiveOptions.allowPicking;
}
},
asynchronous: {
get: function() {
return this._primitiveOptions.asynchronous;
}
},
compressVertices: {
get: function() {
return this._primitiveOptions.compressVertices;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"ClassificationPrimitive.readyPromise",
"ClassificationPrimitive.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for ClassificationPrimitive.ready to return true instead."
);
return this._readyPromise;
}
},
_needs2DShader: {
get: function() {
return this._hasPlanarExtentsAttributes || this._hasSphericalExtentsAttribute;
}
}
});
ClassificationPrimitive.isSupported = function(scene) {
return scene.context.stencilBuffer;
};
function getStencilDepthRenderState(enableStencil, mask3DTiles) {
const stencilFunction = mask3DTiles ? StencilFunction_default.EQUAL : StencilFunction_default.ALWAYS;
return {
colorMask: {
red: false,
green: false,
blue: false,
alpha: false
},
stencilTest: {
enabled: enableStencil,
frontFunction: stencilFunction,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.DECREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
backFunction: stencilFunction,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.INCREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
reference: StencilConstants_default.CESIUM_3D_TILE_MASK,
mask: StencilConstants_default.CESIUM_3D_TILE_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: true,
func: DepthFunction_default.LESS_OR_EQUAL
},
depthMask: false
};
}
function getColorRenderState(enableStencil) {
return {
stencilTest: {
enabled: enableStencil,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false,
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND
};
}
var pickRenderState = {
stencilTest: {
enabled: true,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false
};
function createRenderStates2(classificationPrimitive, context, appearance, twoPasses) {
if (defined_default(classificationPrimitive._rsStencilDepthPass)) {
return;
}
const stencilEnabled = !classificationPrimitive.debugShowShadowVolume;
classificationPrimitive._rsStencilDepthPass = RenderState_default.fromCache(
getStencilDepthRenderState(stencilEnabled, false)
);
classificationPrimitive._rsStencilDepthPass3DTiles = RenderState_default.fromCache(
getStencilDepthRenderState(stencilEnabled, true)
);
classificationPrimitive._rsColorPass = RenderState_default.fromCache(
getColorRenderState(stencilEnabled, false)
);
classificationPrimitive._rsPickPass = RenderState_default.fromCache(pickRenderState);
}
function modifyForEncodedNormals2(primitive, vertexShaderSource) {
if (!primitive.compressVertices) {
return vertexShaderSource;
}
if (vertexShaderSource.search(/in\s+vec3\s+extrudeDirection;/g) !== -1) {
const attributeName = "compressedAttributes";
const attributeDecl = `in vec2 ${attributeName};`;
const globalDecl = "vec3 extrudeDirection;\n";
const decode = ` extrudeDirection = czm_octDecode(${attributeName}, 65535.0);
`;
let modifiedVS = vertexShaderSource;
modifiedVS = modifiedVS.replace(/in\s+vec3\s+extrudeDirection;/g, "");
modifiedVS = ShaderSource_default.replaceMain(
modifiedVS,
"czm_non_compressed_main"
);
const compressedMain = `${"void main() \n{ \n"}${decode} czm_non_compressed_main();
}`;
return [attributeDecl, globalDecl, modifiedVS, compressedMain].join("\n");
}
}
function createShaderProgram2(classificationPrimitive, frameState) {
const context = frameState.context;
const primitive = classificationPrimitive._primitive;
let vs = ShadowVolumeAppearanceVS_default;
vs = classificationPrimitive._primitive._batchTable.getVertexShaderCallback()(
vs
);
vs = Primitive_default._appendDistanceDisplayConditionToShader(primitive, vs);
vs = Primitive_default._modifyShaderPosition(
classificationPrimitive,
vs,
frameState.scene3DOnly
);
vs = Primitive_default._updateColorAttribute(primitive, vs);
const planarExtents = classificationPrimitive._hasPlanarExtentsAttributes;
const cullFragmentsUsingExtents = planarExtents || classificationPrimitive._hasSphericalExtentsAttribute;
if (classificationPrimitive._extruded) {
vs = modifyForEncodedNormals2(primitive, vs);
}
const extrudedDefine = classificationPrimitive._extruded ? "EXTRUDED_GEOMETRY" : "";
let vsSource = new ShaderSource_default({
defines: [extrudedDefine],
sources: [vs]
});
const fsSource = new ShaderSource_default({
sources: [ShadowVolumeFS_default]
});
const attributeLocations8 = classificationPrimitive._primitive._attributeLocations;
const shadowVolumeAppearance = new ShadowVolumeAppearance_default(
cullFragmentsUsingExtents,
planarExtents,
classificationPrimitive.appearance
);
classificationPrimitive._spStencil = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._spStencil,
vertexShaderSource: vsSource,
fragmentShaderSource: fsSource,
attributeLocations: attributeLocations8
});
if (classificationPrimitive._primitive.allowPicking) {
let vsPick = ShaderSource_default.createPickVertexShaderSource(vs);
vsPick = Primitive_default._appendShowToShader(primitive, vsPick);
vsPick = Primitive_default._updatePickColorAttribute(vsPick);
const pickFS3D = shadowVolumeAppearance.createPickFragmentShader(false);
const pickVS3D = shadowVolumeAppearance.createPickVertexShader(
[extrudedDefine],
vsPick,
false,
frameState.mapProjection
);
classificationPrimitive._spPick = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._spPick,
vertexShaderSource: pickVS3D,
fragmentShaderSource: pickFS3D,
attributeLocations: attributeLocations8
});
if (cullFragmentsUsingExtents) {
let pickProgram2D = context.shaderCache.getDerivedShaderProgram(
classificationPrimitive._spPick,
"2dPick"
);
if (!defined_default(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: attributeLocations8
}
);
}
classificationPrimitive._spPick2D = pickProgram2D;
}
} else {
classificationPrimitive._spPick = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vsSource,
fragmentShaderSource: fsSource,
attributeLocations: attributeLocations8
});
}
vs = Primitive_default._appendShowToShader(primitive, vs);
vsSource = new ShaderSource_default({
defines: [extrudedDefine],
sources: [vs]
});
classificationPrimitive._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._sp,
vertexShaderSource: vsSource,
fragmentShaderSource: fsSource,
attributeLocations: attributeLocations8
});
const fsColorSource = shadowVolumeAppearance.createFragmentShader(false);
const vsColorSource = shadowVolumeAppearance.createVertexShader(
[extrudedDefine],
vs,
false,
frameState.mapProjection
);
classificationPrimitive._spColor = ShaderProgram_default.replaceCache({
context,
shaderProgram: classificationPrimitive._spColor,
vertexShaderSource: vsColorSource,
fragmentShaderSource: fsColorSource,
attributeLocations: attributeLocations8
});
if (cullFragmentsUsingExtents) {
let colorProgram2D = context.shaderCache.getDerivedShaderProgram(
classificationPrimitive._spColor,
"2dColor"
);
if (!defined_default(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: attributeLocations8
}
);
}
classificationPrimitive._spColor2D = colorProgram2D;
}
}
function createColorCommands(classificationPrimitive, colorCommands) {
const primitive = classificationPrimitive._primitive;
let length3 = primitive._va.length * 2;
colorCommands.length = length3;
let i;
let command;
let derivedCommand;
let vaIndex = 0;
let uniformMap2 = primitive._batchTable.getUniformMapCallback()(
classificationPrimitive._uniformMap
);
const needs2DShader = classificationPrimitive._needs2DShader;
for (i = 0; i < length3; i += 2) {
const vertexArray = primitive._va[vaIndex++];
command = colorCommands[i];
if (!defined_default(command)) {
command = colorCommands[i] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsStencilDepthPass;
command.shaderProgram = classificationPrimitive._sp;
command.uniformMap = uniformMap2;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.renderState = classificationPrimitive._rsStencilDepthPass3DTiles;
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
command = colorCommands[i + 1];
if (!defined_default(command)) {
command = colorCommands[i + 1] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsColorPass;
command.shaderProgram = classificationPrimitive._spColor;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
const appearance = classificationPrimitive.appearance;
const material = appearance.material;
if (defined_default(material)) {
uniformMap2 = combine_default(uniformMap2, material._uniforms);
}
command.uniformMap = uniformMap2;
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
if (needs2DShader) {
let derived2DCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.appearance2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spColor2D;
command.derivedCommands.appearance2D = derived2DCommand;
derived2DCommand = DrawCommand_default.shallowClone(
derivedCommand,
derivedCommand.derivedCommands.appearance2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spColor2D;
derivedCommand.derivedCommands.appearance2D = derived2DCommand;
}
}
const commandsIgnoreShow = classificationPrimitive._commandsIgnoreShow;
const spStencil = classificationPrimitive._spStencil;
let commandIndex = 0;
length3 = commandsIgnoreShow.length = length3 / 2;
for (let j = 0; j < length3; ++j) {
const commandIgnoreShow = commandsIgnoreShow[j] = DrawCommand_default.shallowClone(
colorCommands[commandIndex],
commandsIgnoreShow[j]
);
commandIgnoreShow.shaderProgram = spStencil;
commandIgnoreShow.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;
commandIndex += 2;
}
}
function createPickCommands(classificationPrimitive, pickCommands) {
const usePickOffsets = classificationPrimitive._usePickOffsets;
const primitive = classificationPrimitive._primitive;
let length3 = primitive._va.length * 2;
let pickOffsets;
let pickIndex = 0;
let pickOffset;
if (usePickOffsets) {
pickOffsets = primitive._pickOffsets;
length3 = pickOffsets.length * 2;
}
pickCommands.length = length3;
let j;
let command;
let derivedCommand;
let vaIndex = 0;
const uniformMap2 = primitive._batchTable.getUniformMapCallback()(
classificationPrimitive._uniformMap
);
const needs2DShader = classificationPrimitive._needs2DShader;
for (j = 0; j < length3; j += 2) {
let vertexArray = primitive._va[vaIndex++];
if (usePickOffsets) {
pickOffset = pickOffsets[pickIndex++];
vertexArray = primitive._va[pickOffset.index];
}
command = pickCommands[j];
if (!defined_default(command)) {
command = pickCommands[j] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType,
pickOnly: true
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsStencilDepthPass;
command.shaderProgram = classificationPrimitive._sp;
command.uniformMap = uniformMap2;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
if (usePickOffsets) {
command.offset = pickOffset.offset;
command.count = pickOffset.count;
}
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.renderState = classificationPrimitive._rsStencilDepthPass3DTiles;
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
command = pickCommands[j + 1];
if (!defined_default(command)) {
command = pickCommands[j + 1] = new DrawCommand_default({
owner: classificationPrimitive,
primitiveType: primitive._primitiveType,
pickOnly: true
});
}
command.vertexArray = vertexArray;
command.renderState = classificationPrimitive._rsPickPass;
command.shaderProgram = classificationPrimitive._spPick;
command.uniformMap = uniformMap2;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
if (usePickOffsets) {
command.offset = pickOffset.offset;
command.count = pickOffset.count;
}
derivedCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedCommand;
if (needs2DShader) {
let derived2DCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.pick2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spPick2D;
command.derivedCommands.pick2D = derived2DCommand;
derived2DCommand = DrawCommand_default.shallowClone(
derivedCommand,
derivedCommand.derivedCommands.pick2D
);
derived2DCommand.shaderProgram = classificationPrimitive._spPick2D;
derivedCommand.derivedCommands.pick2D = derived2DCommand;
}
}
}
function createCommands2(classificationPrimitive, appearance, material, translucent, twoPasses, colorCommands, pickCommands) {
createColorCommands(classificationPrimitive, colorCommands);
createPickCommands(classificationPrimitive, pickCommands);
}
function boundingVolumeIndex(commandIndex, length3) {
return Math.floor(commandIndex % length3 / 2);
}
function updateAndQueueRenderCommand(command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume2) {
command.modelMatrix = modelMatrix;
command.boundingVolume = boundingVolume;
command.cull = cull;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
frameState.commandList.push(command);
}
function updateAndQueuePickCommand(command, frameState, modelMatrix, cull, boundingVolume) {
command.modelMatrix = modelMatrix;
command.boundingVolume = boundingVolume;
command.cull = cull;
frameState.commandList.push(command);
}
function updateAndQueueCommands2(classificationPrimitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
const primitive = classificationPrimitive._primitive;
Primitive_default._updateBoundingVolumes(primitive, frameState, modelMatrix);
let boundingVolumes;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolumes = primitive._boundingSphereWC;
} else if (frameState.mode === SceneMode_default.COLUMBUS_VIEW) {
boundingVolumes = primitive._boundingSphereCV;
} else if (frameState.mode === SceneMode_default.SCENE2D && defined_default(primitive._boundingSphere2D)) {
boundingVolumes = primitive._boundingSphere2D;
} else if (defined_default(primitive._boundingSphereMorph)) {
boundingVolumes = primitive._boundingSphereMorph;
}
const classificationType = classificationPrimitive.classificationType;
const queueTerrainCommands = classificationType !== ClassificationType_default.CESIUM_3D_TILE;
const queue3DTilesCommands = classificationType !== ClassificationType_default.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(i, colorLength)];
if (queueTerrainCommands) {
command = colorCommands[i];
updateAndQueueRenderCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
if (queue3DTilesCommands) {
command = colorCommands[i].derivedCommands.tileset;
updateAndQueueRenderCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
if (frameState.invertClassification) {
const ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
const ignoreShowCommandsLength = ignoreShowCommands.length;
for (i = 0; i < ignoreShowCommandsLength; ++i) {
boundingVolume = boundingVolumes[i];
command = ignoreShowCommands[i];
updateAndQueueRenderCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
}
if (passes.pick) {
const pickLength = pickCommands.length;
const pickOffsets = primitive._pickOffsets;
for (i = 0; i < pickLength; ++i) {
const pickOffset = pickOffsets[boundingVolumeIndex(i, pickLength)];
boundingVolume = boundingVolumes[pickOffset.index];
if (queueTerrainCommands) {
command = pickCommands[i];
updateAndQueuePickCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
if (queue3DTilesCommands) {
command = pickCommands[i].derivedCommands.tileset;
updateAndQueuePickCommand(
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
}
}
}
ClassificationPrimitive.prototype.update = function(frameState) {
if (!defined_default(this._primitive) && !defined_default(this.geometryInstances)) {
return;
}
let appearance = this.appearance;
if (defined_default(appearance) && defined_default(appearance.material)) {
appearance.material.update(frameState.context);
}
const that = this;
const primitiveOptions = this._primitiveOptions;
if (!defined_default(this._primitive)) {
const instances = Array.isArray(this.geometryInstances) ? this.geometryInstances : [this.geometryInstances];
const length3 = instances.length;
let i;
let instance;
let attributes;
let hasPerColorAttribute = false;
let allColorsSame = true;
let firstColor;
let hasSphericalExtentsAttribute = false;
let hasPlanarExtentsAttributes = false;
if (length3 > 0) {
attributes = instances[0].attributes;
hasSphericalExtentsAttribute = ShadowVolumeAppearance_default.hasAttributesForSphericalExtents(
attributes
);
hasPlanarExtentsAttributes = ShadowVolumeAppearance_default.hasAttributesForTextureCoordinatePlanes(
attributes
);
firstColor = attributes.color;
}
for (i = 0; i < length3; i++) {
instance = instances[i];
const color = instance.attributes.color;
if (defined_default(color)) {
hasPerColorAttribute = true;
} else if (hasPerColorAttribute) {
throw new DeveloperError_default(
"All GeometryInstances must have color attributes to use per-instance color."
);
}
allColorsSame = allColorsSame && defined_default(color) && ColorGeometryInstanceAttribute_default.equals(firstColor, color);
}
if (!allColorsSame && !hasSphericalExtentsAttribute && !hasPlanarExtentsAttributes) {
throw new DeveloperError_default(
"All GeometryInstances must have the same color attribute except via GroundPrimitives"
);
}
if (hasPerColorAttribute && !defined_default(appearance)) {
appearance = new PerInstanceColorAppearance_default({
flat: true
});
this.appearance = appearance;
}
if (!hasPerColorAttribute && appearance instanceof PerInstanceColorAppearance_default) {
throw new DeveloperError_default(
"PerInstanceColorAppearance requires color GeometryInstanceAttributes on all GeometryInstances"
);
}
if (defined_default(appearance.material) && !hasSphericalExtentsAttribute && !hasPlanarExtentsAttributes) {
throw new DeveloperError_default(
"Materials on ClassificationPrimitives are not supported except via GroundPrimitives"
);
}
this._usePickOffsets = !hasSphericalExtentsAttribute && !hasPlanarExtentsAttributes;
this._hasSphericalExtentsAttribute = hasSphericalExtentsAttribute;
this._hasPlanarExtentsAttributes = hasPlanarExtentsAttributes;
this._hasPerColorAttribute = hasPerColorAttribute;
const geometryInstances = new Array(length3);
for (i = 0; i < length3; ++i) {
instance = instances[i];
geometryInstances[i] = new GeometryInstance_default({
geometry: instance.geometry,
attributes: instance.attributes,
modelMatrix: instance.modelMatrix,
id: instance.id,
pickPrimitive: defaultValue_default(this._pickPrimitive, that)
});
}
primitiveOptions.appearance = appearance;
primitiveOptions.geometryInstances = geometryInstances;
if (defined_default(this._createBoundingVolumeFunction)) {
primitiveOptions._createBoundingVolumeFunction = function(frameState2, geometry) {
that._createBoundingVolumeFunction(frameState2, geometry);
};
}
primitiveOptions._createRenderStatesFunction = function(primitive, context, appearance2, twoPasses) {
createRenderStates2(that, context);
};
primitiveOptions._createShaderProgramFunction = function(primitive, frameState2, appearance2) {
createShaderProgram2(that, frameState2);
};
primitiveOptions._createCommandsFunction = function(primitive, appearance2, material, translucent, twoPasses, colorCommands, pickCommands) {
createCommands2(
that,
void 0,
void 0,
true,
false,
colorCommands,
pickCommands
);
};
if (defined_default(this._updateAndQueueCommandsFunction)) {
primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
that._updateAndQueueCommandsFunction(
primitive,
frameState2,
colorCommands,
pickCommands,
modelMatrix,
cull,
debugShowBoundingVolume2,
twoPasses
);
};
} else {
primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
updateAndQueueCommands2(
that,
frameState2,
colorCommands,
pickCommands,
modelMatrix,
cull,
debugShowBoundingVolume2,
twoPasses
);
};
}
this._primitive = new Primitive_default(primitiveOptions);
}
if (this.debugShowShadowVolume && !this._debugShowShadowVolume && this._ready) {
this._debugShowShadowVolume = true;
this._rsStencilDepthPass = RenderState_default.fromCache(
getStencilDepthRenderState(false, false)
);
this._rsStencilDepthPass3DTiles = RenderState_default.fromCache(
getStencilDepthRenderState(false, true)
);
this._rsColorPass = RenderState_default.fromCache(getColorRenderState(false));
} else if (!this.debugShowShadowVolume && this._debugShowShadowVolume) {
this._debugShowShadowVolume = false;
this._rsStencilDepthPass = RenderState_default.fromCache(
getStencilDepthRenderState(true, false)
);
this._rsStencilDepthPass3DTiles = RenderState_default.fromCache(
getStencilDepthRenderState(true, true)
);
this._rsColorPass = RenderState_default.fromCache(getColorRenderState(true));
}
if (this._primitive.appearance !== appearance) {
if (!this._hasSphericalExtentsAttribute && !this._hasPlanarExtentsAttributes && defined_default(appearance.material)) {
throw new DeveloperError_default(
"Materials on ClassificationPrimitives are not supported except via GroundPrimitive"
);
}
if (!this._hasPerColorAttribute && appearance instanceof PerInstanceColorAppearance_default) {
throw new DeveloperError_default(
"PerInstanceColorAppearance requires color GeometryInstanceAttribute"
);
}
this._primitive.appearance = appearance;
}
this._primitive.show = this.show;
this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
this._primitive.update(frameState);
frameState.afterRender.push(() => {
if (defined_default(this._primitive) && this._primitive.ready) {
this._completeLoad();
}
});
};
ClassificationPrimitive.prototype.getGeometryInstanceAttributes = function(id) {
if (!defined_default(this._primitive)) {
throw new DeveloperError_default(
"must call update before calling getGeometryInstanceAttributes"
);
}
return this._primitive.getGeometryInstanceAttributes(id);
};
ClassificationPrimitive.prototype.isDestroyed = function() {
return false;
};
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();
this._spPick2D = void 0;
this._spColor2D = void 0;
return destroyObject_default(this);
};
var ClassificationPrimitive_default = ClassificationPrimitive;
// node_modules/@cesium/engine/Source/Scene/GroundPrimitive.js
var GroundPrimitiveUniformMap = {
u_globeMinimumAltitude: function() {
return 55e3;
}
};
function GroundPrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let appearance = options.appearance;
const geometryInstances = options.geometryInstances;
if (!defined_default(appearance) && defined_default(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_default(attributes) && defined_default(attributes.color)) {
appearance = new PerInstanceColorAppearance_default({
flat: true
});
break;
}
}
}
this.appearance = appearance;
this.geometryInstances = options.geometryInstances;
this.show = defaultValue_default(options.show, true);
this.classificationType = defaultValue_default(
options.classificationType,
ClassificationType_default.BOTH
);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.debugShowShadowVolume = defaultValue_default(
options.debugShowShadowVolume,
false
);
this._boundingVolumes = [];
this._boundingVolumes2D = [];
this._ready = false;
const groundPrimitive = this;
this._readyPromise = new Promise((resolve2, reject) => {
groundPrimitive._completeLoad = () => {
if (this._ready) {
return;
}
this._ready = true;
if (this.releaseGeometryInstances) {
this.geometryInstances = void 0;
}
const error = this._error;
if (!defined_default(error)) {
resolve2(this);
} else {
reject(error);
}
};
});
this._primitive = void 0;
this._maxHeight = void 0;
this._minHeight = void 0;
this._maxTerrainHeight = ApproximateTerrainHeights_default._defaultMaxTerrainHeight;
this._minTerrainHeight = ApproximateTerrainHeights_default._defaultMinTerrainHeight;
this._boundingSpheresKeys = [];
this._boundingSpheres = [];
this._useFragmentCulling = false;
this._zIndex = void 0;
const that = this;
this._classificationPrimitiveOptions = {
geometryInstances: void 0,
appearance: void 0,
vertexCacheOptimize: defaultValue_default(options.vertexCacheOptimize, false),
interleave: defaultValue_default(options.interleave, false),
releaseGeometryInstances: defaultValue_default(
options.releaseGeometryInstances,
true
),
allowPicking: defaultValue_default(options.allowPicking, true),
asynchronous: defaultValue_default(options.asynchronous, true),
compressVertices: defaultValue_default(options.compressVertices, true),
_createBoundingVolumeFunction: void 0,
_updateAndQueueCommandsFunction: void 0,
_pickPrimitive: that,
_extruded: true,
_uniformMap: GroundPrimitiveUniformMap
};
}
Object.defineProperties(GroundPrimitive.prototype, {
vertexCacheOptimize: {
get: function() {
return this._classificationPrimitiveOptions.vertexCacheOptimize;
}
},
interleave: {
get: function() {
return this._classificationPrimitiveOptions.interleave;
}
},
releaseGeometryInstances: {
get: function() {
return this._classificationPrimitiveOptions.releaseGeometryInstances;
}
},
allowPicking: {
get: function() {
return this._classificationPrimitiveOptions.allowPicking;
}
},
asynchronous: {
get: function() {
return this._classificationPrimitiveOptions.asynchronous;
}
},
compressVertices: {
get: function() {
return this._classificationPrimitiveOptions.compressVertices;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"GroundPrimitive.readyPromise",
"GroundPrimitive.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for GroundPrimitive.ready to return true instead."
);
return this._readyPromise;
}
}
});
GroundPrimitive.isSupported = ClassificationPrimitive_default.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;
};
}
var scratchBVCartesianHigh = new Cartesian3_default();
var scratchBVCartesianLow = new Cartesian3_default();
var scratchBVCartesian = new Cartesian3_default();
var scratchBVCartographic = new Cartographic_default();
var scratchBVRectangle = new Rectangle_default();
function getRectangle(frameState, geometry) {
const ellipsoid = frameState.mapProjection.ellipsoid;
if (!defined_default(geometry.attributes) || !defined_default(geometry.attributes.position3DHigh)) {
if (defined_default(geometry.rectangle)) {
return geometry.rectangle;
}
return void 0;
}
const highPositions = geometry.attributes.position3DHigh.values;
const lowPositions = geometry.attributes.position3DLow.values;
const length3 = 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 < length3; i += 3) {
const highPosition = Cartesian3_default.unpack(
highPositions,
i,
scratchBVCartesianHigh
);
const lowPosition = Cartesian3_default.unpack(
lowPositions,
i,
scratchBVCartesianLow
);
const position = Cartesian3_default.add(
highPosition,
lowPosition,
scratchBVCartesian
);
const cartographic2 = ellipsoid.cartesianToCartographic(
position,
scratchBVCartographic
);
const latitude = cartographic2.latitude;
const longitude = cartographic2.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_default.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_default.fromRectangle(
rectangle,
groundPrimitive._minHeight,
groundPrimitive._maxHeight,
ellipsoid
);
groundPrimitive._boundingVolumes.push(obb);
if (!frameState.scene3DOnly) {
const projection = frameState.mapProjection;
const boundingVolume = BoundingSphere_default.fromRectangleWithHeights2D(
rectangle,
projection,
groundPrimitive._maxHeight,
groundPrimitive._minHeight
);
Cartesian3_default.fromElements(
boundingVolume.center.z,
boundingVolume.center.x,
boundingVolume.center.y,
boundingVolume.center
);
groundPrimitive._boundingVolumes2D.push(boundingVolume);
}
}
function boundingVolumeIndex2(commandIndex, length3) {
return Math.floor(commandIndex % length3 / 2);
}
function updateAndQueueRenderCommand2(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume, debugShowBoundingVolume2) {
const classificationPrimitive = groundPrimitive._primitive;
if (frameState.mode !== SceneMode_default.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 = debugShowBoundingVolume2;
frameState.commandList.push(command);
}
function updateAndQueuePickCommand2(groundPrimitive, command, frameState, modelMatrix, cull, boundingVolume) {
const classificationPrimitive = groundPrimitive._primitive;
if (frameState.mode !== SceneMode_default.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 updateAndQueueCommands3(groundPrimitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
let boundingVolumes;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolumes = groundPrimitive._boundingVolumes;
} else {
boundingVolumes = groundPrimitive._boundingVolumes2D;
}
const classificationType = groundPrimitive.classificationType;
const queueTerrainCommands = classificationType !== ClassificationType_default.CESIUM_3D_TILE;
const queue3DTilesCommands = classificationType !== ClassificationType_default.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[boundingVolumeIndex2(i, colorLength)];
if (queueTerrainCommands) {
command = colorCommands[i];
updateAndQueueRenderCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
if (queue3DTilesCommands) {
command = colorCommands[i].derivedCommands.tileset;
updateAndQueueRenderCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
if (frameState.invertClassification) {
const ignoreShowCommands = classificationPrimitive._commandsIgnoreShow;
const ignoreShowCommandsLength = ignoreShowCommands.length;
for (i = 0; i < ignoreShowCommandsLength; ++i) {
boundingVolume = boundingVolumes[i];
command = ignoreShowCommands[i];
updateAndQueueRenderCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
}
if (passes.pick) {
const pickLength = pickCommands.length;
let pickOffsets;
if (!groundPrimitive._useFragmentCulling) {
pickOffsets = classificationPrimitive._primitive._pickOffsets;
}
for (i = 0; i < pickLength; ++i) {
boundingVolume = boundingVolumes[boundingVolumeIndex2(i, pickLength)];
if (!groundPrimitive._useFragmentCulling) {
const pickOffset = pickOffsets[boundingVolumeIndex2(i, pickLength)];
boundingVolume = boundingVolumes[pickOffset.index];
}
if (queueTerrainCommands) {
command = pickCommands[i];
updateAndQueuePickCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
if (queue3DTilesCommands) {
command = pickCommands[i].derivedCommands.tileset;
updateAndQueuePickCommand2(
groundPrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume
);
}
}
}
}
GroundPrimitive.initializeTerrainHeights = function() {
return ApproximateTerrainHeights_default.initialize();
};
GroundPrimitive.prototype.update = function(frameState) {
if (!defined_default(this._primitive) && !defined_default(this.geometryInstances)) {
return;
}
if (!ApproximateTerrainHeights_default.initialized) {
if (!this.asynchronous) {
throw new DeveloperError_default(
"For synchronous GroundPrimitives, you must call GroundPrimitive.initializeTerrainHeights() and wait for the returned promise to resolve."
);
}
GroundPrimitive.initializeTerrainHeights();
return;
}
const that = this;
const primitiveOptions = this._classificationPrimitiveOptions;
if (!defined_default(this._primitive)) {
const ellipsoid = frameState.mapProjection.ellipsoid;
let instance;
let geometry;
let instanceType;
const instances = Array.isArray(this.geometryInstances) ? this.geometryInstances : [this.geometryInstances];
const length3 = instances.length;
const groundInstances = new Array(length3);
let i;
let rectangle;
for (i = 0; i < length3; ++i) {
instance = instances[i];
geometry = instance.geometry;
const instanceRectangle = getRectangle(frameState, geometry);
if (!defined_default(rectangle)) {
rectangle = Rectangle_default.clone(instanceRectangle);
} else if (defined_default(instanceRectangle)) {
Rectangle_default.union(rectangle, instanceRectangle, rectangle);
}
const id = instance.id;
if (defined_default(id) && defined_default(instanceRectangle)) {
const boundingSphere = ApproximateTerrainHeights_default.getBoundingSphere(
instanceRectangle,
ellipsoid
);
this._boundingSpheresKeys.push(id);
this._boundingSpheres.push(boundingSphere);
}
instanceType = geometry.constructor;
if (!defined_default(instanceType) || !defined_default(instanceType.createShadowVolume)) {
throw new DeveloperError_default(
"Not all of the geometry instances have GroundPrimitive support."
);
}
}
setMinMaxTerrainHeights(this, rectangle, ellipsoid);
const exaggeration = frameState.terrainExaggeration;
const exaggerationRelativeHeight = frameState.terrainExaggerationRelativeHeight;
this._minHeight = TerrainExaggeration_default.getHeight(
this._minTerrainHeight,
exaggeration,
exaggerationRelativeHeight
);
this._maxHeight = TerrainExaggeration_default.getHeight(
this._maxTerrainHeight,
exaggeration,
exaggerationRelativeHeight
);
const useFragmentCulling = GroundPrimitive._supportsMaterials(
frameState.context
);
this._useFragmentCulling = useFragmentCulling;
if (useFragmentCulling) {
let attributes;
let usePlanarExtents = true;
for (i = 0; i < length3; ++i) {
instance = instances[i];
geometry = instance.geometry;
rectangle = getRectangle(frameState, geometry);
if (ShadowVolumeAppearance_default.shouldUseSphericalCoordinates(rectangle)) {
usePlanarExtents = false;
break;
}
}
for (i = 0; i < length3; ++i) {
instance = instances[i];
geometry = instance.geometry;
instanceType = geometry.constructor;
const boundingRectangle = getRectangle(frameState, geometry);
const textureCoordinateRotationPoints4 = geometry.textureCoordinateRotationPoints;
if (usePlanarExtents) {
attributes = ShadowVolumeAppearance_default.getPlanarTextureCoordinateAttributes(
boundingRectangle,
textureCoordinateRotationPoints4,
ellipsoid,
frameState.mapProjection,
this._maxHeight
);
} else {
attributes = ShadowVolumeAppearance_default.getSphericalExtentGeometryInstanceAttributes(
boundingRectangle,
textureCoordinateRotationPoints4,
ellipsoid,
frameState.mapProjection
);
}
const instanceAttributes = instance.attributes;
for (const attributeKey in instanceAttributes) {
if (instanceAttributes.hasOwnProperty(attributeKey)) {
attributes[attributeKey] = instanceAttributes[attributeKey];
}
}
groundInstances[i] = new GeometryInstance_default({
geometry: instanceType.createShadowVolume(
geometry,
getComputeMinimumHeightFunction(this),
getComputeMaximumHeightFunction(this)
),
attributes,
id: instance.id
});
}
} else {
for (i = 0; i < length3; ++i) {
instance = instances[i];
geometry = instance.geometry;
instanceType = geometry.constructor;
groundInstances[i] = new GeometryInstance_default({
geometry: instanceType.createShadowVolume(
geometry,
getComputeMinimumHeightFunction(this),
getComputeMaximumHeightFunction(this)
),
attributes: instance.attributes,
id: instance.id
});
}
}
primitiveOptions.geometryInstances = groundInstances;
primitiveOptions.appearance = this.appearance;
primitiveOptions._createBoundingVolumeFunction = function(frameState2, geometry2) {
createBoundingVolume(that, frameState2, geometry2);
};
primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
updateAndQueueCommands3(
that,
frameState2,
colorCommands,
pickCommands,
modelMatrix,
cull,
debugShowBoundingVolume2,
twoPasses
);
};
this._primitive = new ClassificationPrimitive_default(primitiveOptions);
}
this._primitive.appearance = this.appearance;
this._primitive.show = this.show;
this._primitive.debugShowShadowVolume = this.debugShowShadowVolume;
this._primitive.debugShowBoundingVolume = this.debugShowBoundingVolume;
this._primitive.update(frameState);
frameState.afterRender.push(() => {
if (!this._ready && defined_default(this._primitive) && this._primitive.ready) {
this._completeLoad();
}
});
};
GroundPrimitive.prototype.getBoundingSphere = function(id) {
const index = this._boundingSpheresKeys.indexOf(id);
if (index !== -1) {
return this._boundingSpheres[index];
}
return void 0;
};
GroundPrimitive.prototype.getGeometryInstanceAttributes = function(id) {
if (!defined_default(this._primitive)) {
throw new DeveloperError_default(
"must call update before calling getGeometryInstanceAttributes"
);
}
return this._primitive.getGeometryInstanceAttributes(id);
};
GroundPrimitive.prototype.isDestroyed = function() {
return false;
};
GroundPrimitive.prototype.destroy = function() {
this._primitive = this._primitive && this._primitive.destroy();
return destroyObject_default(this);
};
GroundPrimitive._supportsMaterials = function(context) {
return context.depthTexture;
};
GroundPrimitive.supportsMaterials = function(scene) {
Check_default.typeOf.object("scene", scene);
return GroundPrimitive._supportsMaterials(scene.frameState.context);
};
var GroundPrimitive_default = GroundPrimitive;
// node_modules/@cesium/engine/Source/DataSources/MaterialProperty.js
function MaterialProperty() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(MaterialProperty.prototype, {
isConstant: {
get: DeveloperError_default.throwInstantiationError
},
definitionChanged: {
get: DeveloperError_default.throwInstantiationError
}
});
MaterialProperty.prototype.getType = DeveloperError_default.throwInstantiationError;
MaterialProperty.prototype.getValue = DeveloperError_default.throwInstantiationError;
MaterialProperty.prototype.equals = DeveloperError_default.throwInstantiationError;
MaterialProperty.getValue = function(time, materialProperty, material) {
let type;
if (defined_default(materialProperty)) {
type = materialProperty.getType(time);
if (defined_default(type)) {
if (!defined_default(material) || material.type !== type) {
material = Material_default.fromType(type);
}
materialProperty.getValue(time, material.uniforms);
return material;
}
}
if (!defined_default(material) || material.type !== Material_default.ColorType) {
material = Material_default.fromType(Material_default.ColorType);
}
Color_default.clone(Color_default.WHITE, material.uniforms.color);
return material;
};
var MaterialProperty_default = MaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/DynamicGeometryUpdater.js
function DynamicGeometryUpdater(geometryUpdater, primitives, orderedGroundPrimitives) {
Check_default.defined("geometryUpdater", geometryUpdater);
Check_default.defined("primitives", primitives);
Check_default.defined("orderedGroundPrimitives", orderedGroundPrimitives);
this._primitives = primitives;
this._orderedGroundPrimitives = orderedGroundPrimitives;
this._primitive = void 0;
this._outlinePrimitive = void 0;
this._geometryUpdater = geometryUpdater;
this._options = geometryUpdater._options;
this._entity = geometryUpdater._entity;
this._material = void 0;
}
DynamicGeometryUpdater.prototype._isHidden = function(entity, geometry, time) {
return !entity.isShowing || !entity.isAvailable(time) || !Property_default.getValueOrDefault(geometry.show, time, true);
};
DynamicGeometryUpdater.prototype._setOptions = DeveloperError_default.throwInstantiationError;
DynamicGeometryUpdater.prototype.update = function(time) {
Check_default.defined("time", time);
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 = void 0;
}
this._primitive = void 0;
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_default(geometry.fill) || geometry.fill.getValue(time)) {
const fillMaterialProperty = geometryUpdater.fillMaterialProperty;
const isColorAppearance = fillMaterialProperty instanceof ColorMaterialProperty_default;
let appearance;
const closed = geometryUpdater._getIsClosed(options);
if (isColorAppearance) {
appearance = new PerInstanceColorAppearance_default({
closed,
flat: onTerrain && !geometryUpdater._supportsMaterialsforEntitiesOnTerrain
});
} else {
const material = MaterialProperty_default.getValue(
time,
fillMaterialProperty,
this._material
);
this._material = material;
appearance = new MaterialAppearance_default({
material,
translucent: material.isTranslucent(),
closed
});
}
if (onTerrain) {
options.vertexFormat = PerInstanceColorAppearance_default.VERTEX_FORMAT;
this._primitive = orderedGroundPrimitives.add(
new GroundPrimitive_default({
geometryInstances: this._geometryUpdater.createFillGeometryInstance(
time
),
appearance,
asynchronous: false,
shadows,
classificationType: this._geometryUpdater.classificationTypeProperty.getValue(
time
)
}),
Property_default.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_default({
geometryInstances: fillInstance,
appearance,
asynchronous: false,
shadows
})
);
}
}
if (!onTerrain && defined_default(geometry.outline) && geometry.outline.getValue(time)) {
const outlineInstance = this._geometryUpdater.createOutlineGeometryInstance(
time
);
const outlineWidth = Property_default.getValueOrDefault(
geometry.outlineWidth,
time,
1
);
this._outlinePrimitive = primitives.add(
new Primitive_default({
geometryInstances: outlineInstance,
appearance: new PerInstanceColorAppearance_default({
flat: true,
translucent: outlineInstance.attributes.color.value[3] !== 255,
renderState: {
lineWidth: geometryUpdater._scene.clampLineWidth(outlineWidth)
}
}),
asynchronous: false,
shadows
})
);
}
};
DynamicGeometryUpdater.prototype.getBoundingSphere = function(result) {
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const entity = this._entity;
const primitive = this._primitive;
const outlinePrimitive = this._outlinePrimitive;
let attributes;
if (defined_default(primitive) && primitive.show && primitive.ready) {
attributes = primitive.getGeometryInstanceAttributes(entity);
if (defined_default(attributes) && defined_default(attributes.boundingSphere)) {
BoundingSphere_default.clone(attributes.boundingSphere, result);
return BoundingSphereState_default.DONE;
}
}
if (defined_default(outlinePrimitive) && outlinePrimitive.show && outlinePrimitive.ready) {
attributes = outlinePrimitive.getGeometryInstanceAttributes(entity);
if (defined_default(attributes) && defined_default(attributes.boundingSphere)) {
BoundingSphere_default.clone(attributes.boundingSphere, result);
return BoundingSphereState_default.DONE;
}
}
if (defined_default(primitive) && !primitive.ready || defined_default(outlinePrimitive) && !outlinePrimitive.ready) {
return BoundingSphereState_default.PENDING;
}
return BoundingSphereState_default.FAILED;
};
DynamicGeometryUpdater.prototype.isDestroyed = function() {
return false;
};
DynamicGeometryUpdater.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_default(this);
};
var DynamicGeometryUpdater_default = DynamicGeometryUpdater;
// node_modules/@cesium/engine/Source/Core/ArcType.js
var ArcType = {
NONE: 0,
GEODESIC: 1,
RHUMB: 2
};
var ArcType_default = Object.freeze(ArcType);
// node_modules/@cesium/engine/Source/Core/arrayRemoveDuplicates.js
var removeDuplicatesEpsilon = Math_default.EPSILON10;
function arrayRemoveDuplicates(values, equalsEpsilon, wrapAround, removedIndices) {
Check_default.defined("equalsEpsilon", equalsEpsilon);
if (!defined_default(values)) {
return void 0;
}
wrapAround = defaultValue_default(wrapAround, false);
const storeRemovedIndices = defined_default(removedIndices);
const length3 = values.length;
if (length3 < 2) {
return values;
}
let i;
let v02 = values[0];
let v13;
let cleanedValues;
let lastCleanIndex = 0;
let removedIndexLCI = -1;
for (i = 1; i < length3; ++i) {
v13 = values[i];
if (equalsEpsilon(v02, v13, removeDuplicatesEpsilon)) {
if (!defined_default(cleanedValues)) {
cleanedValues = values.slice(0, i);
lastCleanIndex = i - 1;
removedIndexLCI = 0;
}
if (storeRemovedIndices) {
removedIndices.push(i);
}
} else {
if (defined_default(cleanedValues)) {
cleanedValues.push(v13);
lastCleanIndex = i;
if (storeRemovedIndices) {
removedIndexLCI = removedIndices.length;
}
}
v02 = v13;
}
}
if (wrapAround && equalsEpsilon(values[0], values[length3 - 1], removeDuplicatesEpsilon)) {
if (storeRemovedIndices) {
if (defined_default(cleanedValues)) {
removedIndices.splice(removedIndexLCI, 0, lastCleanIndex);
} else {
removedIndices.push(length3 - 1);
}
}
if (defined_default(cleanedValues)) {
cleanedValues.length -= 1;
} else {
cleanedValues = values.slice(0, -1);
}
}
return defined_default(cleanedValues) ? cleanedValues : values;
}
var arrayRemoveDuplicates_default = arrayRemoveDuplicates;
// node_modules/@cesium/engine/Source/Core/EllipsoidGeodesic.js
function setConstants(ellipsoidGeodesic3) {
const uSquared = ellipsoidGeodesic3._uSquared;
const a3 = ellipsoidGeodesic3._ellipsoid.maximumRadius;
const b = ellipsoidGeodesic3._ellipsoid.minimumRadius;
const f = (a3 - b) / a3;
const cosineHeading = Math.cos(ellipsoidGeodesic3._startHeading);
const sineHeading = Math.sin(ellipsoidGeodesic3._startHeading);
const tanU = (1 - f) * Math.tan(ellipsoidGeodesic3._start.latitude);
const cosineU = 1 / Math.sqrt(1 + tanU * tanU);
const sineU = cosineU * tanU;
const sigma = Math.atan2(tanU, cosineHeading);
const sineAlpha = cosineU * sineHeading;
const sineSquaredAlpha = sineAlpha * sineAlpha;
const cosineSquaredAlpha = 1 - sineSquaredAlpha;
const cosineAlpha = Math.sqrt(cosineSquaredAlpha);
const u2Over4 = uSquared / 4;
const u4Over16 = u2Over4 * u2Over4;
const u6Over64 = u4Over16 * u2Over4;
const u8Over256 = u4Over16 * u4Over16;
const a0 = 1 + u2Over4 - 3 * u4Over16 / 4 + 5 * u6Over64 / 4 - 175 * u8Over256 / 64;
const a1 = 1 - u2Over4 + 15 * u4Over16 / 8 - 35 * u6Over64 / 8;
const a22 = 1 - 3 * u2Over4 + 35 * u4Over16 / 4;
const a32 = 1 - 5 * u2Over4;
const distanceRatio = a0 * sigma - a1 * Math.sin(2 * sigma) * u2Over4 / 2 - a22 * Math.sin(4 * sigma) * u4Over16 / 16 - a32 * Math.sin(6 * sigma) * u6Over64 / 48 - Math.sin(8 * sigma) * 5 * u8Over256 / 512;
const constants = ellipsoidGeodesic3._constants;
constants.a = a3;
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 = a22;
constants.a3 = a32;
constants.distanceRatio = distanceRatio;
}
function computeC(f, cosineSquaredAlpha) {
return f * cosineSquaredAlpha * (4 + f * (4 - 3 * cosineSquaredAlpha)) / 16;
}
function computeDeltaLambda(f, sineAlpha, cosineSquaredAlpha, sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint) {
const C = computeC(f, cosineSquaredAlpha);
return (1 - C) * f * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint + C * cosineSigma * (2 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1)));
}
function vincentyInverseFormula(ellipsoidGeodesic3, major, minor, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
const eff = (major - minor) / major;
const l = secondLongitude - firstLongitude;
const u12 = Math.atan((1 - eff) * Math.tan(firstLatitude));
const u22 = Math.atan((1 - eff) * Math.tan(secondLatitude));
const cosineU1 = Math.cos(u12);
const sineU1 = Math.sin(u12);
const cosineU2 = Math.cos(u22);
const sineU2 = Math.sin(u22);
const cc = cosineU1 * cosineU2;
const cs = cosineU1 * sineU2;
const ss = sineU1 * sineU2;
const sc = sineU1 * cosineU2;
let lambda = l;
let lambdaDot = Math_default.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) {
sineAlpha = 0;
cosineSquaredAlpha = 1;
} else {
sineAlpha = cc * sineLambda / sineSigma;
cosineSquaredAlpha = 1 - sineAlpha * sineAlpha;
}
lambdaDot = lambda;
cosineTwiceSigmaMidpoint = cosineSigma - 2 * ss / cosineSquaredAlpha;
if (!isFinite(cosineTwiceSigmaMidpoint)) {
cosineTwiceSigmaMidpoint = 0;
}
lambda = l + computeDeltaLambda(
eff,
sineAlpha,
cosineSquaredAlpha,
sigma,
sineSigma,
cosineSigma,
cosineTwiceSigmaMidpoint
);
} while (Math.abs(lambda - lambdaDot) > Math_default.EPSILON12);
const uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor);
const A = 1 + uSquared * (4096 + uSquared * (uSquared * (320 - 175 * uSquared) - 768)) / 16384;
const B = uSquared * (256 + uSquared * (uSquared * (74 - 47 * uSquared) - 128)) / 1024;
const cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint;
const deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma * (2 * cosineSquaredTwiceSigmaMidpoint - 1) - B * cosineTwiceSigmaMidpoint * (4 * sineSigma * sineSigma - 3) * (4 * cosineSquaredTwiceSigmaMidpoint - 3) / 6) / 4);
const distance2 = minor * A * (sigma - deltaSigma);
const startHeading = Math.atan2(
cosineU2 * sineLambda,
cs - sc * cosineLambda
);
const endHeading = Math.atan2(cosineU1 * sineLambda, cs * cosineLambda - sc);
ellipsoidGeodesic3._distance = distance2;
ellipsoidGeodesic3._startHeading = startHeading;
ellipsoidGeodesic3._endHeading = endHeading;
ellipsoidGeodesic3._uSquared = uSquared;
}
var scratchCart1 = new Cartesian3_default();
var scratchCart2 = new Cartesian3_default();
function computeProperties(ellipsoidGeodesic3, start, end, ellipsoid) {
const firstCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(start, scratchCart2),
scratchCart1
);
const lastCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(end, scratchCart2),
scratchCart2
);
Check_default.typeOf.number.greaterThanOrEquals(
"value",
Math.abs(
Math.abs(Cartesian3_default.angleBetween(firstCartesian, lastCartesian)) - Math.PI
),
0.0125
);
vincentyInverseFormula(
ellipsoidGeodesic3,
ellipsoid.maximumRadius,
ellipsoid.minimumRadius,
start.longitude,
start.latitude,
end.longitude,
end.latitude
);
ellipsoidGeodesic3._start = Cartographic_default.clone(
start,
ellipsoidGeodesic3._start
);
ellipsoidGeodesic3._end = Cartographic_default.clone(end, ellipsoidGeodesic3._end);
ellipsoidGeodesic3._start.height = 0;
ellipsoidGeodesic3._end.height = 0;
setConstants(ellipsoidGeodesic3);
}
function EllipsoidGeodesic(start, end, ellipsoid) {
const e = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
this._ellipsoid = e;
this._start = new Cartographic_default();
this._end = new Cartographic_default();
this._constants = {};
this._startHeading = void 0;
this._endHeading = void 0;
this._distance = void 0;
this._uSquared = void 0;
if (defined_default(start) && defined_default(end)) {
computeProperties(this, start, end, e);
}
}
Object.defineProperties(EllipsoidGeodesic.prototype, {
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
surfaceDistance: {
get: function() {
Check_default.defined("distance", this._distance);
return this._distance;
}
},
start: {
get: function() {
return this._start;
}
},
end: {
get: function() {
return this._end;
}
},
startHeading: {
get: function() {
Check_default.defined("distance", this._distance);
return this._startHeading;
}
},
endHeading: {
get: function() {
Check_default.defined("distance", this._distance);
return this._endHeading;
}
}
});
EllipsoidGeodesic.prototype.setEndPoints = function(start, end) {
Check_default.defined("start", start);
Check_default.defined("end", end);
computeProperties(this, start, end, this._ellipsoid);
};
EllipsoidGeodesic.prototype.interpolateUsingFraction = function(fraction, result) {
return this.interpolateUsingSurfaceDistance(
this._distance * fraction,
result
);
};
EllipsoidGeodesic.prototype.interpolateUsingSurfaceDistance = function(distance2, result) {
Check_default.defined("distance", this._distance);
const constants = this._constants;
const s = constants.distanceRatio + distance2 / constants.b;
const cosine2S = Math.cos(2 * s);
const cosine4S = Math.cos(4 * s);
const cosine6S = Math.cos(6 * s);
const sine2S = Math.sin(2 * s);
const sine4S = Math.sin(4 * s);
const sine6S = Math.sin(6 * s);
const sine8S = Math.sin(8 * 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 * s3 * u8Over256 * cosine2S / 3 + s * (1 - u2Over4 + 7 * u4Over16 / 4 - 15 * u6Over64 / 4 + 579 * u8Over256 / 64 - (u4Over16 - 15 * u6Over64 / 4 + 187 * u8Over256 / 16) * cosine2S - (5 * u6Over64 / 4 - 115 * u8Over256 / 16) * cosine4S - 29 * u8Over256 * cosine6S / 16) + (u2Over4 / 2 - u4Over16 + 71 * u6Over64 / 32 - 85 * u8Over256 / 16) * sine2S + (5 * u4Over16 / 16 - 5 * u6Over64 / 4 + 383 * u8Over256 / 96) * sine4S - s2 * ((u6Over64 - 11 * u8Over256 / 2) * sine2S + 5 * u8Over256 * sine4S / 2) + (29 * u6Over64 / 96 - 29 * u8Over256 / 16) * sine6S + 539 * u8Over256 * sine8S / 1536;
const theta = Math.asin(Math.sin(sigma) * constants.cosineAlpha);
const latitude = Math.atan(constants.a / constants.b * Math.tan(theta));
sigma = sigma - constants.sigma;
const cosineTwiceSigmaMidpoint = Math.cos(2 * 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_default(result)) {
result.longitude = this._start.longitude + l;
result.latitude = latitude;
result.height = 0;
return result;
}
return new Cartographic_default(this._start.longitude + l, latitude, 0);
};
var EllipsoidGeodesic_default = EllipsoidGeodesic;
// node_modules/@cesium/engine/Source/Core/EllipsoidRhumbLine.js
function calculateM(ellipticity, major, latitude) {
if (ellipticity === 0) {
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) {
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) {
return Math.log(Math.tan(0.5 * (Math_default.PI_OVER_TWO + latitude)));
}
const eSinL = ellipticity * Math.sin(latitude);
return Math.log(Math.tan(0.5 * (Math_default.PI_OVER_TWO + latitude))) - ellipticity / 2 * 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(
Math_default.negativePiToPi(secondLongitude - firstLongitude),
sigma2 - sigma1
);
}
function calculateArcLength(ellipsoidRhumbLine, major, minor, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
const heading = ellipsoidRhumbLine._heading;
const deltaLongitude = secondLongitude - firstLongitude;
let distance2 = 0;
if (Math_default.equalsEpsilon(
Math.abs(heading),
Math_default.PI_OVER_TWO,
Math_default.EPSILON8
)) {
if (major === minor) {
distance2 = major * Math.cos(firstLatitude) * Math_default.negativePiToPi(deltaLongitude);
} else {
const sinPhi = Math.sin(firstLatitude);
distance2 = major * Math.cos(firstLatitude) * Math_default.negativePiToPi(deltaLongitude) / Math.sqrt(1 - ellipsoidRhumbLine._ellipticitySquared * sinPhi * sinPhi);
}
} else {
const M1 = calculateM(
ellipsoidRhumbLine._ellipticity,
major,
firstLatitude
);
const M2 = calculateM(
ellipsoidRhumbLine._ellipticity,
major,
secondLatitude
);
distance2 = (M2 - M1) / Math.cos(heading);
}
return Math.abs(distance2);
}
var scratchCart12 = new Cartesian3_default();
var scratchCart22 = new Cartesian3_default();
function computeProperties2(ellipsoidRhumbLine, start, end, ellipsoid) {
const firstCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(start, scratchCart22),
scratchCart12
);
const lastCartesian = Cartesian3_default.normalize(
ellipsoid.cartographicToCartesian(end, scratchCart22),
scratchCart22
);
Check_default.typeOf.number.greaterThanOrEquals(
"value",
Math.abs(
Math.abs(Cartesian3_default.angleBetween(firstCartesian, lastCartesian)) - Math.PI
),
0.0125
);
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_default.clone(
start,
ellipsoidRhumbLine._start
);
ellipsoidRhumbLine._start.height = 0;
ellipsoidRhumbLine._end = Cartographic_default.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, distance2, major, ellipticity, result) {
if (distance2 === 0) {
return Cartographic_default.clone(start, result);
}
const ellipticitySquared = ellipticity * ellipticity;
let longitude;
let latitude;
let deltaLongitude;
if (Math.abs(Math_default.PI_OVER_TWO - Math.abs(heading)) > Math_default.EPSILON8) {
const M1 = calculateM(ellipticity, major, start.latitude);
const deltaM = distance2 * Math.cos(heading);
const M2 = M1 + deltaM;
latitude = calculateInverseM(M2, ellipticity, major);
const sigma1 = calculateSigma(ellipticity, start.latitude);
const sigma2 = calculateSigma(ellipticity, latitude);
deltaLongitude = Math.tan(heading) * (sigma2 - sigma1);
longitude = Math_default.negativePiToPi(start.longitude + deltaLongitude);
} else {
latitude = start.latitude;
let localRad;
if (ellipticity === 0) {
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 = distance2 / localRad;
if (heading > 0) {
longitude = Math_default.negativePiToPi(start.longitude + deltaLongitude);
} else {
longitude = Math_default.negativePiToPi(start.longitude - deltaLongitude);
}
}
if (defined_default(result)) {
result.longitude = longitude;
result.latitude = latitude;
result.height = 0;
return result;
}
return new Cartographic_default(longitude, latitude, 0);
}
function EllipsoidRhumbLine(start, end, ellipsoid) {
const e = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
this._ellipsoid = e;
this._start = new Cartographic_default();
this._end = new Cartographic_default();
this._heading = void 0;
this._distance = void 0;
this._ellipticity = void 0;
this._ellipticitySquared = void 0;
if (defined_default(start) && defined_default(end)) {
computeProperties2(this, start, end, e);
}
}
Object.defineProperties(EllipsoidRhumbLine.prototype, {
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
surfaceDistance: {
get: function() {
Check_default.defined("distance", this._distance);
return this._distance;
}
},
start: {
get: function() {
return this._start;
}
},
end: {
get: function() {
return this._end;
}
},
heading: {
get: function() {
Check_default.defined("distance", this._distance);
return this._heading;
}
}
});
EllipsoidRhumbLine.fromStartHeadingDistance = function(start, heading, distance2, ellipsoid, result) {
Check_default.defined("start", start);
Check_default.defined("heading", heading);
Check_default.defined("distance", distance2);
Check_default.typeOf.number.greaterThan("distance", distance2, 0);
const e = defaultValue_default(ellipsoid, Ellipsoid_default.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 = Math_default.negativePiToPi(heading);
const end = interpolateUsingSurfaceDistance(
start,
heading,
distance2,
e.maximumRadius,
ellipticity
);
if (!defined_default(result) || defined_default(ellipsoid) && !ellipsoid.equals(result.ellipsoid)) {
return new EllipsoidRhumbLine(start, end, e);
}
result.setEndPoints(start, end);
return result;
};
EllipsoidRhumbLine.prototype.setEndPoints = function(start, end) {
Check_default.defined("start", start);
Check_default.defined("end", end);
computeProperties2(this, start, end, this._ellipsoid);
};
EllipsoidRhumbLine.prototype.interpolateUsingFraction = function(fraction, result) {
return this.interpolateUsingSurfaceDistance(
fraction * this._distance,
result
);
};
EllipsoidRhumbLine.prototype.interpolateUsingSurfaceDistance = function(distance2, result) {
Check_default.typeOf.number("distance", distance2);
if (!defined_default(this._distance) || this._distance === 0) {
throw new DeveloperError_default(
"EllipsoidRhumbLine must have distinct start and end set."
);
}
return interpolateUsingSurfaceDistance(
this._start,
this._heading,
distance2,
this._ellipsoid.maximumRadius,
this._ellipticity,
result
);
};
EllipsoidRhumbLine.prototype.findIntersectionWithLongitude = function(intersectionLongitude, result) {
Check_default.typeOf.number("intersectionLongitude", intersectionLongitude);
if (!defined_default(this._distance) || this._distance === 0) {
throw new DeveloperError_default(
"EllipsoidRhumbLine must have distinct start and end set."
);
}
const ellipticity = this._ellipticity;
const heading = this._heading;
const absHeading = Math.abs(heading);
const start = this._start;
intersectionLongitude = Math_default.negativePiToPi(intersectionLongitude);
if (Math_default.equalsEpsilon(
Math.abs(intersectionLongitude),
Math.PI,
Math_default.EPSILON14
)) {
intersectionLongitude = Math_default.sign(start.longitude) * Math.PI;
}
if (!defined_default(result)) {
result = new Cartographic_default();
}
if (Math.abs(Math_default.PI_OVER_TWO - absHeading) <= Math_default.EPSILON8) {
result.longitude = intersectionLongitude;
result.latitude = start.latitude;
result.height = 0;
return result;
} else if (Math_default.equalsEpsilon(
Math.abs(Math_default.PI_OVER_TWO - absHeading),
Math_default.PI_OVER_TWO,
Math_default.EPSILON8
)) {
if (Math_default.equalsEpsilon(
intersectionLongitude,
start.longitude,
Math_default.EPSILON12
)) {
return void 0;
}
result.longitude = intersectionLongitude;
result.latitude = Math_default.PI_OVER_TWO * Math_default.sign(Math_default.PI_OVER_TWO - heading);
result.height = 0;
return result;
}
const phi1 = start.latitude;
const eSinPhi1 = ellipticity * Math.sin(phi1);
const leftComponent = Math.tan(0.5 * (Math_default.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)
) - Math_default.PI_OVER_TWO;
} while (!Math_default.equalsEpsilon(newPhi, phi, Math_default.EPSILON12));
result.longitude = intersectionLongitude;
result.latitude = newPhi;
result.height = 0;
return result;
};
EllipsoidRhumbLine.prototype.findIntersectionWithLatitude = function(intersectionLatitude, result) {
Check_default.typeOf.number("intersectionLatitude", intersectionLatitude);
if (!defined_default(this._distance) || this._distance === 0) {
throw new DeveloperError_default(
"EllipsoidRhumbLine must have distinct start and end set."
);
}
const ellipticity = this._ellipticity;
const heading = this._heading;
const start = this._start;
if (Math_default.equalsEpsilon(
Math.abs(heading),
Math_default.PI_OVER_TWO,
Math_default.EPSILON8
)) {
return;
}
const sigma1 = calculateSigma(ellipticity, start.latitude);
const sigma2 = calculateSigma(ellipticity, intersectionLatitude);
const deltaLongitude = Math.tan(heading) * (sigma2 - sigma1);
const longitude = Math_default.negativePiToPi(start.longitude + deltaLongitude);
if (defined_default(result)) {
result.longitude = longitude;
result.latitude = intersectionLatitude;
result.height = 0;
return result;
}
return new Cartographic_default(longitude, intersectionLatitude, 0);
};
var EllipsoidRhumbLine_default = EllipsoidRhumbLine;
// node_modules/@cesium/engine/Source/Core/GroundPolylineGeometry.js
var PROJECTIONS = [GeographicProjection_default, WebMercatorProjection_default];
var PROJECTION_COUNT = PROJECTIONS.length;
var MITER_BREAK_SMALL = Math.cos(Math_default.toRadians(30));
var MITER_BREAK_LARGE = Math.cos(Math_default.toRadians(150));
var WALL_INITIAL_MIN_HEIGHT = 0;
var WALL_INITIAL_MAX_HEIGHT = 1e3;
function GroundPolylineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.positions;
if (!defined_default(positions) || positions.length < 2) {
throw new DeveloperError_default("At least two positions are required.");
}
if (defined_default(options.arcType) && options.arcType !== ArcType_default.GEODESIC && options.arcType !== ArcType_default.RHUMB) {
throw new DeveloperError_default(
"Valid options for arcType are ArcType.GEODESIC and ArcType.RHUMB."
);
}
this.width = defaultValue_default(options.width, 1);
this._positions = positions;
this.granularity = defaultValue_default(options.granularity, 9999);
this.loop = defaultValue_default(options.loop, false);
this.arcType = defaultValue_default(options.arcType, ArcType_default.GEODESIC);
this._ellipsoid = Ellipsoid_default.WGS84;
this._projectionIndex = 0;
this._workerName = "createGroundPolylineGeometry";
this._scene3DOnly = false;
}
Object.defineProperties(GroundPolylineGeometry.prototype, {
packedLength: {
get: function() {
return 1 + this._positions.length * 3 + 1 + 1 + 1 + Ellipsoid_default.packedLength + 1 + 1;
}
}
});
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;
};
var cart3Scratch1 = new Cartesian3_default();
var cart3Scratch2 = new Cartesian3_default();
var cart3Scratch3 = new Cartesian3_default();
function computeRightNormal(start, end, maxHeight, ellipsoid, result) {
const startBottom = getPosition(ellipsoid, start, 0, cart3Scratch1);
const startTop = getPosition(ellipsoid, start, maxHeight, cart3Scratch2);
const endBottom = getPosition(ellipsoid, end, 0, cart3Scratch3);
const up = direction(startTop, startBottom, cart3Scratch2);
const forward = direction(endBottom, startBottom, cart3Scratch3);
Cartesian3_default.cross(forward, up, result);
return Cartesian3_default.normalize(result, result);
}
var interpolatedCartographicScratch = new Cartographic_default();
var interpolatedBottomScratch = new Cartesian3_default();
var interpolatedTopScratch = new Cartesian3_default();
var interpolatedNormalScratch = new Cartesian3_default();
function interpolateSegment(start, end, minHeight, maxHeight, granularity, arcType, ellipsoid, normalsArray, bottomPositionsArray, topPositionsArray, cartographicsArray) {
if (granularity === 0) {
return;
}
let ellipsoidLine;
if (arcType === ArcType_default.GEODESIC) {
ellipsoidLine = new EllipsoidGeodesic_default(start, end, ellipsoid);
} else if (arcType === ArcType_default.RHUMB) {
ellipsoidLine = new EllipsoidRhumbLine_default(start, end, ellipsoid);
}
const surfaceDistance = ellipsoidLine.surfaceDistance;
if (surfaceDistance < granularity) {
return;
}
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
);
const interpolatedBottom = getPosition(
ellipsoid,
interpolatedCartographic,
minHeight,
interpolatedBottomScratch
);
const interpolatedTop = getPosition(
ellipsoid,
interpolatedCartographic,
maxHeight,
interpolatedTopScratch
);
Cartesian3_default.pack(interpolatedNormal, normalsArray, packIndex);
Cartesian3_default.pack(interpolatedBottom, bottomPositionsArray, packIndex);
Cartesian3_default.pack(interpolatedTop, topPositionsArray, packIndex);
cartographicsArray.push(interpolatedCartographic.latitude);
cartographicsArray.push(interpolatedCartographic.longitude);
packIndex += 3;
distanceFromStart += interpointDistance;
}
}
var heightlessCartographicScratch = new Cartographic_default();
function getPosition(ellipsoid, cartographic2, height, result) {
Cartographic_default.clone(cartographic2, heightlessCartographicScratch);
heightlessCartographicScratch.height = height;
return Cartographic_default.toCartesian(
heightlessCartographicScratch,
ellipsoid,
result
);
}
GroundPolylineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
let index = defaultValue_default(startingIndex, 0);
const positions = value._positions;
const positionsLength = positions.length;
array[index++] = positionsLength;
for (let i = 0; i < positionsLength; ++i) {
const cartesian11 = positions[i];
Cartesian3_default.pack(cartesian11, array, index);
index += 3;
}
array[index++] = value.granularity;
array[index++] = value.loop ? 1 : 0;
array[index++] = value.arcType;
Ellipsoid_default.pack(value._ellipsoid, array, index);
index += Ellipsoid_default.packedLength;
array[index++] = value._projectionIndex;
array[index++] = value._scene3DOnly ? 1 : 0;
return array;
};
GroundPolylineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
let index = defaultValue_default(startingIndex, 0);
const positionsLength = array[index++];
const positions = new Array(positionsLength);
for (let i = 0; i < positionsLength; i++) {
positions[i] = Cartesian3_default.unpack(array, index);
index += 3;
}
const granularity = array[index++];
const loop = array[index++] === 1;
const arcType = array[index++];
const ellipsoid = Ellipsoid_default.unpack(array, index);
index += Ellipsoid_default.packedLength;
const projectionIndex = array[index++];
const scene3DOnly = array[index++] === 1;
if (!defined_default(result)) {
result = new GroundPolylineGeometry({
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_default.subtract(target, origin, result);
Cartesian3_default.normalize(result, result);
return result;
}
function tangentDirection(target, origin, up, result) {
result = direction(target, origin, result);
result = Cartesian3_default.cross(result, up, result);
result = Cartesian3_default.normalize(result, result);
result = Cartesian3_default.cross(up, result, result);
return result;
}
var toPreviousScratch = new Cartesian3_default();
var toNextScratch = new Cartesian3_default();
var forwardScratch = new Cartesian3_default();
var vertexUpScratch = new Cartesian3_default();
var cosine90 = 0;
var cosine180 = -1;
function computeVertexMiterNormal(previousBottom, vertexBottom, vertexTop, nextBottom, result) {
const up = direction(vertexTop, vertexBottom, vertexUpScratch);
const toPrevious = tangentDirection(
previousBottom,
vertexBottom,
up,
toPreviousScratch
);
const toNext = tangentDirection(nextBottom, vertexBottom, up, toNextScratch);
if (Math_default.equalsEpsilon(
Cartesian3_default.dot(toPrevious, toNext),
cosine180,
Math_default.EPSILON5
)) {
result = Cartesian3_default.cross(up, toPrevious, result);
result = Cartesian3_default.normalize(result, result);
return result;
}
result = Cartesian3_default.add(toNext, toPrevious, result);
result = Cartesian3_default.normalize(result, result);
const forward = Cartesian3_default.cross(up, result, forwardScratch);
if (Cartesian3_default.dot(toNext, forward) < cosine90) {
result = Cartesian3_default.negate(result, result);
}
return result;
}
var XZ_PLANE = Plane_default.fromPointNormal(Cartesian3_default.ZERO, Cartesian3_default.UNIT_Y);
var previousBottomScratch = new Cartesian3_default();
var vertexBottomScratch = new Cartesian3_default();
var vertexTopScratch = new Cartesian3_default();
var nextBottomScratch = new Cartesian3_default();
var vertexNormalScratch = new Cartesian3_default();
var intersectionScratch = new Cartesian3_default();
var cartographicScratch0 = new Cartographic_default();
var cartographicScratch1 = new Cartographic_default();
var cartographicIntersectionScratch = new Cartographic_default();
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;
}
let p0;
let p1;
let c0;
let c14;
const rhumbLine = new EllipsoidRhumbLine_default(void 0, void 0, 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_default.lineSegmentPlane(
p0,
p1,
XZ_PLANE,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
if (groundPolylineGeometry.arcType === ArcType_default.GEODESIC) {
splitPositions.push(Cartesian3_default.clone(intersection));
} else if (groundPolylineGeometry.arcType === ArcType_default.RHUMB) {
intersectionLongitude = ellipsoid.cartesianToCartographic(
intersection,
cartographicScratch0
).longitude;
c0 = ellipsoid.cartesianToCartographic(p0, cartographicScratch0);
c14 = ellipsoid.cartesianToCartographic(p1, cartographicScratch1);
rhumbLine.setEndPoints(c0, c14);
intersectionCartographic = rhumbLine.findIntersectionWithLongitude(
intersectionLongitude,
cartographicIntersectionScratch
);
intersection = ellipsoid.cartographicToCartesian(
intersectionCartographic,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
splitPositions.push(Cartesian3_default.clone(intersection));
}
}
}
splitPositions.push(p1);
}
if (loop) {
p0 = positions[positionsLength - 1];
p1 = positions[0];
intersection = IntersectionTests_default.lineSegmentPlane(
p0,
p1,
XZ_PLANE,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
if (groundPolylineGeometry.arcType === ArcType_default.GEODESIC) {
splitPositions.push(Cartesian3_default.clone(intersection));
} else if (groundPolylineGeometry.arcType === ArcType_default.RHUMB) {
intersectionLongitude = ellipsoid.cartesianToCartographic(
intersection,
cartographicScratch0
).longitude;
c0 = ellipsoid.cartesianToCartographic(p0, cartographicScratch0);
c14 = ellipsoid.cartesianToCartographic(p1, cartographicScratch1);
rhumbLine.setEndPoints(c0, c14);
intersectionCartographic = rhumbLine.findIntersectionWithLongitude(
intersectionLongitude,
cartographicIntersectionScratch
);
intersection = ellipsoid.cartographicToCartesian(
intersectionCartographic,
intersectionScratch
);
if (defined_default(intersection) && !Cartesian3_default.equalsEpsilon(intersection, p0, Math_default.EPSILON7) && !Cartesian3_default.equalsEpsilon(intersection, p1, Math_default.EPSILON7)) {
splitPositions.push(Cartesian3_default.clone(intersection));
}
}
}
}
let cartographicsLength = splitPositions.length;
let cartographics = new Array(cartographicsLength);
for (i = 0; i < cartographicsLength; i++) {
const cartographic2 = Cartographic_default.fromCartesian(
splitPositions[i],
ellipsoid
);
cartographic2.height = 0;
cartographics[i] = cartographic2;
}
cartographics = arrayRemoveDuplicates_default(
cartographics,
Cartographic_default.equalsEpsilon
);
cartographicsLength = cartographics.length;
if (cartographicsLength < 2) {
return void 0;
}
const cartographicsArray = [];
const normalsArray = [];
const bottomPositionsArray = [];
const topPositionsArray = [];
let previousBottom = previousBottomScratch;
let vertexBottom = vertexBottomScratch;
let vertexTop = vertexTopScratch;
let nextBottom = nextBottomScratch;
let vertexNormal = vertexNormalScratch;
const startCartographic = cartographics[0];
const nextCartographic = cartographics[1];
const prestartCartographic = cartographics[cartographicsLength - 1];
previousBottom = getPosition(
ellipsoid,
prestartCartographic,
minHeight,
previousBottom
);
nextBottom = getPosition(ellipsoid, nextCartographic, minHeight, nextBottom);
vertexBottom = getPosition(
ellipsoid,
startCartographic,
minHeight,
vertexBottom
);
vertexTop = getPosition(ellipsoid, startCartographic, maxHeight, vertexTop);
if (loop) {
vertexNormal = computeVertexMiterNormal(
previousBottom,
vertexBottom,
vertexTop,
nextBottom,
vertexNormal
);
} else {
vertexNormal = computeRightNormal(
startCartographic,
nextCartographic,
maxHeight,
ellipsoid,
vertexNormal
);
}
Cartesian3_default.pack(vertexNormal, normalsArray, 0);
Cartesian3_default.pack(vertexBottom, bottomPositionsArray, 0);
Cartesian3_default.pack(vertexTop, topPositionsArray, 0);
cartographicsArray.push(startCartographic.latitude);
cartographicsArray.push(startCartographic.longitude);
interpolateSegment(
startCartographic,
nextCartographic,
minHeight,
maxHeight,
granularity,
arcType,
ellipsoid,
normalsArray,
bottomPositionsArray,
topPositionsArray,
cartographicsArray
);
for (i = 1; i < cartographicsLength - 1; ++i) {
previousBottom = Cartesian3_default.clone(vertexBottom, previousBottom);
vertexBottom = Cartesian3_default.clone(nextBottom, vertexBottom);
const vertexCartographic = cartographics[i];
getPosition(ellipsoid, vertexCartographic, maxHeight, vertexTop);
getPosition(ellipsoid, cartographics[i + 1], minHeight, nextBottom);
computeVertexMiterNormal(
previousBottom,
vertexBottom,
vertexTop,
nextBottom,
vertexNormal
);
index = normalsArray.length;
Cartesian3_default.pack(vertexNormal, normalsArray, index);
Cartesian3_default.pack(vertexBottom, bottomPositionsArray, index);
Cartesian3_default.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
);
}
const endCartographic = cartographics[cartographicsLength - 1];
const preEndCartographic = cartographics[cartographicsLength - 2];
vertexBottom = getPosition(
ellipsoid,
endCartographic,
minHeight,
vertexBottom
);
vertexTop = getPosition(ellipsoid, endCartographic, maxHeight, vertexTop);
if (loop) {
const postEndCartographic = cartographics[0];
previousBottom = getPosition(
ellipsoid,
preEndCartographic,
minHeight,
previousBottom
);
nextBottom = getPosition(
ellipsoid,
postEndCartographic,
minHeight,
nextBottom
);
vertexNormal = computeVertexMiterNormal(
previousBottom,
vertexBottom,
vertexTop,
nextBottom,
vertexNormal
);
} else {
vertexNormal = computeRightNormal(
preEndCartographic,
endCartographic,
maxHeight,
ellipsoid,
vertexNormal
);
}
index = normalsArray.length;
Cartesian3_default.pack(vertexNormal, normalsArray, index);
Cartesian3_default.pack(vertexBottom, bottomPositionsArray, index);
Cartesian3_default.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
);
};
var lineDirectionScratch = new Cartesian3_default();
var matrix3Scratch = new Matrix3_default();
var quaternionScratch = new Quaternion_default();
function breakMiter(endGeometryNormal, startBottom, endBottom, endTop) {
const lineDirection = direction(endBottom, startBottom, lineDirectionScratch);
const dot2 = Cartesian3_default.dot(lineDirection, endGeometryNormal);
if (dot2 > MITER_BREAK_SMALL || dot2 < MITER_BREAK_LARGE) {
const vertexUp = direction(endTop, endBottom, vertexUpScratch);
const angle = dot2 < MITER_BREAK_LARGE ? Math_default.PI_OVER_TWO : -Math_default.PI_OVER_TWO;
const quaternion = Quaternion_default.fromAxisAngle(
vertexUp,
angle,
quaternionScratch
);
const rotationMatrix = Matrix3_default.fromQuaternion(quaternion, matrix3Scratch);
Matrix3_default.multiplyByVector(
rotationMatrix,
endGeometryNormal,
endGeometryNormal
);
return true;
}
return false;
}
var endPosCartographicScratch = new Cartographic_default();
var normalStartpointScratch = new Cartesian3_default();
var normalEndpointScratch = new Cartesian3_default();
function projectNormal(projection, cartographic2, normal2, projectedPosition2, result) {
const position = Cartographic_default.toCartesian(
cartographic2,
projection._ellipsoid,
normalStartpointScratch
);
let normalEndpoint = Cartesian3_default.add(position, normal2, normalEndpointScratch);
let flipNormal = false;
const ellipsoid = projection._ellipsoid;
let normalEndpointCartographic = ellipsoid.cartesianToCartographic(
normalEndpoint,
endPosCartographicScratch
);
if (Math.abs(cartographic2.longitude - normalEndpointCartographic.longitude) > Math_default.PI_OVER_TWO) {
flipNormal = true;
normalEndpoint = Cartesian3_default.subtract(
position,
normal2,
normalEndpointScratch
);
normalEndpointCartographic = ellipsoid.cartesianToCartographic(
normalEndpoint,
endPosCartographicScratch
);
}
normalEndpointCartographic.height = 0;
const normalEndpointProjected = projection.project(
normalEndpointCartographic,
result
);
result = Cartesian3_default.subtract(
normalEndpointProjected,
projectedPosition2,
result
);
result.z = 0;
result = Cartesian3_default.normalize(result, result);
if (flipNormal) {
Cartesian3_default.negate(result, result);
}
return result;
}
var adjustHeightNormalScratch = new Cartesian3_default();
var adjustHeightOffsetScratch = new Cartesian3_default();
function adjustHeights(bottom, top, minHeight, maxHeight, adjustHeightBottom, adjustHeightTop) {
const adjustHeightNormal = Cartesian3_default.subtract(
top,
bottom,
adjustHeightNormalScratch
);
Cartesian3_default.normalize(adjustHeightNormal, adjustHeightNormal);
const distanceForBottom = minHeight - WALL_INITIAL_MIN_HEIGHT;
let adjustHeightOffset = Cartesian3_default.multiplyByScalar(
adjustHeightNormal,
distanceForBottom,
adjustHeightOffsetScratch
);
Cartesian3_default.add(bottom, adjustHeightOffset, adjustHeightBottom);
const distanceForTop = maxHeight - WALL_INITIAL_MAX_HEIGHT;
adjustHeightOffset = Cartesian3_default.multiplyByScalar(
adjustHeightNormal,
distanceForTop,
adjustHeightOffsetScratch
);
Cartesian3_default.add(top, adjustHeightOffset, adjustHeightTop);
}
var nudgeDirectionScratch = new Cartesian3_default();
function nudgeXZ(start, end) {
const startToXZdistance = Plane_default.getPointDistance(XZ_PLANE, start);
const endToXZdistance = Plane_default.getPointDistance(XZ_PLANE, end);
let offset2 = nudgeDirectionScratch;
if (Math_default.equalsEpsilon(startToXZdistance, 0, Math_default.EPSILON2)) {
offset2 = direction(end, start, offset2);
Cartesian3_default.multiplyByScalar(offset2, Math_default.EPSILON2, offset2);
Cartesian3_default.add(start, offset2, start);
} else if (Math_default.equalsEpsilon(endToXZdistance, 0, Math_default.EPSILON2)) {
offset2 = direction(start, end, offset2);
Cartesian3_default.multiplyByScalar(offset2, Math_default.EPSILON2, offset2);
Cartesian3_default.add(end, offset2, end);
}
}
function nudgeCartographic(start, end) {
const absStartLon = Math.abs(start.longitude);
const absEndLon = Math.abs(end.longitude);
if (Math_default.equalsEpsilon(absStartLon, Math_default.PI, Math_default.EPSILON11)) {
const endSign = Math_default.sign(end.longitude);
start.longitude = endSign * (absStartLon - Math_default.EPSILON11);
return 1;
} else if (Math_default.equalsEpsilon(absEndLon, Math_default.PI, Math_default.EPSILON11)) {
const startSign = Math_default.sign(start.longitude);
end.longitude = startSign * (absEndLon - Math_default.EPSILON11);
return 2;
}
return 0;
}
var startCartographicScratch = new Cartographic_default();
var endCartographicScratch = new Cartographic_default();
var segmentStartTopScratch = new Cartesian3_default();
var segmentEndTopScratch = new Cartesian3_default();
var segmentStartBottomScratch = new Cartesian3_default();
var segmentEndBottomScratch = new Cartesian3_default();
var segmentStartNormalScratch = new Cartesian3_default();
var segmentEndNormalScratch = new Cartesian3_default();
var getHeightCartographics = [
startCartographicScratch,
endCartographicScratch
];
var getHeightRectangleScratch = new Rectangle_default();
var adjustHeightStartTopScratch = new Cartesian3_default();
var adjustHeightEndTopScratch = new Cartesian3_default();
var adjustHeightStartBottomScratch = new Cartesian3_default();
var adjustHeightEndBottomScratch = new Cartesian3_default();
var segmentStart2DScratch = new Cartesian3_default();
var segmentEnd2DScratch = new Cartesian3_default();
var segmentStartNormal2DScratch = new Cartesian3_default();
var segmentEndNormal2DScratch = new Cartesian3_default();
var offsetScratch3 = new Cartesian3_default();
var startUpScratch = new Cartesian3_default();
var endUpScratch = new Cartesian3_default();
var rightScratch2 = new Cartesian3_default();
var startPlaneNormalScratch = new Cartesian3_default();
var endPlaneNormalScratch = new Cartesian3_default();
var encodeScratch2 = new EncodedCartesian3_default();
var encodeScratch2D = new EncodedCartesian3_default();
var forwardOffset2DScratch = new Cartesian3_default();
var right2DScratch = new Cartesian3_default();
var normalNudgeScratch = new Cartesian3_default();
var scratchBoundingSpheres = [new BoundingSphere_default(), new BoundingSphere_default()];
var REFERENCE_INDICES = [
0,
2,
1,
0,
3,
2,
0,
7,
3,
0,
4,
7,
0,
5,
4,
0,
1,
5,
5,
7,
4,
5,
6,
7,
5,
2,
6,
5,
1,
2,
3,
6,
2,
3,
7,
6
];
var REFERENCE_INDICES_LENGTH = REFERENCE_INDICES.length;
function generateGeometryAttributes(loop, projection, bottomPositionsArray, topPositionsArray, normalsArray, cartographicsArray, compute2dAttributes) {
let i;
let index;
const ellipsoid = projection._ellipsoid;
const segmentCount = bottomPositionsArray.length / 3 - 1;
const vertexCount = segmentCount * 8;
const arraySizeVec4 = vertexCount * 4;
const indexCount = segmentCount * 36;
const indices2 = 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);
}
const cartographicsLength = cartographicsArray.length / 2;
let length2D = 0;
const startCartographic = startCartographicScratch;
startCartographic.height = 0;
const endCartographic = endCartographicScratch;
endCartographic.height = 0;
let segmentStartCartesian = segmentStartTopScratch;
let segmentEndCartesian = segmentEndTopScratch;
if (compute2dAttributes) {
index = 0;
for (i = 1; i < cartographicsLength; i++) {
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_default.distance(
segmentStartCartesian,
segmentEndCartesian
);
index += 2;
}
}
const positionsLength = topPositionsArray.length / 3;
segmentEndCartesian = Cartesian3_default.unpack(
topPositionsArray,
0,
segmentEndCartesian
);
let length3D = 0;
index = 3;
for (i = 1; i < positionsLength; i++) {
segmentStartCartesian = Cartesian3_default.clone(
segmentEndCartesian,
segmentStartCartesian
);
segmentEndCartesian = Cartesian3_default.unpack(
topPositionsArray,
index,
segmentEndCartesian
);
length3D += Cartesian3_default.distance(segmentStartCartesian, segmentEndCartesian);
index += 3;
}
let j;
index = 3;
let cartographicsIndex = 0;
let vec2sWriteIndex = 0;
let vec3sWriteIndex = 0;
let vec4sWriteIndex = 0;
let miterBroken = false;
let endBottom = Cartesian3_default.unpack(
bottomPositionsArray,
0,
segmentEndBottomScratch
);
let endTop = Cartesian3_default.unpack(topPositionsArray, 0, segmentEndTopScratch);
let endGeometryNormal = Cartesian3_default.unpack(
normalsArray,
0,
segmentEndNormalScratch
);
if (loop) {
const preEndBottom = Cartesian3_default.unpack(
bottomPositionsArray,
bottomPositionsArray.length - 6,
segmentStartBottomScratch
);
if (breakMiter(endGeometryNormal, preEndBottom, endBottom, endTop)) {
endGeometryNormal = Cartesian3_default.negate(
endGeometryNormal,
endGeometryNormal
);
}
}
let lengthSoFar3D = 0;
let lengthSoFar2D = 0;
let sumHeights = 0;
for (i = 0; i < segmentCount; i++) {
const startBottom = Cartesian3_default.clone(endBottom, segmentStartBottomScratch);
const startTop = Cartesian3_default.clone(endTop, segmentStartTopScratch);
let startGeometryNormal = Cartesian3_default.clone(
endGeometryNormal,
segmentStartNormalScratch
);
if (miterBroken) {
startGeometryNormal = Cartesian3_default.negate(
startGeometryNormal,
startGeometryNormal
);
}
endBottom = Cartesian3_default.unpack(
bottomPositionsArray,
index,
segmentEndBottomScratch
);
endTop = Cartesian3_default.unpack(topPositionsArray, index, segmentEndTopScratch);
endGeometryNormal = Cartesian3_default.unpack(
normalsArray,
index,
segmentEndNormalScratch
);
miterBroken = breakMiter(endGeometryNormal, startBottom, endBottom, endTop);
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_default.dot(direction2D, Cartesian3_default.UNIT_Y) > MITER_BREAK_SMALL) {
startGeometryNormal2D = projectNormal(
projection,
startCartographic,
startGeometryNormal,
start2D,
segmentStartNormal2DScratch
);
endGeometryNormal2D = projectNormal(
projection,
endCartographic,
endGeometryNormal,
end2D,
segmentEndNormal2DScratch
);
} else if (nudgeResult === 1) {
endGeometryNormal2D = projectNormal(
projection,
endCartographic,
endGeometryNormal,
end2D,
segmentEndNormal2DScratch
);
startGeometryNormal2D.x = 0;
startGeometryNormal2D.y = Math_default.sign(
startCartographic.longitude - Math.abs(endCartographic.longitude)
);
startGeometryNormal2D.z = 0;
} else {
startGeometryNormal2D = projectNormal(
projection,
startCartographic,
startGeometryNormal,
start2D,
segmentStartNormal2DScratch
);
endGeometryNormal2D.x = 0;
endGeometryNormal2D.y = Math_default.sign(
startCartographic.longitude - endCartographic.longitude
);
endGeometryNormal2D.z = 0;
}
}
const segmentLength3D = Cartesian3_default.distance(startTop, endTop);
const encodedStart = EncodedCartesian3_default.fromCartesian(
startBottom,
encodeScratch2
);
const forwardOffset = Cartesian3_default.subtract(
endBottom,
startBottom,
offsetScratch3
);
const forward = Cartesian3_default.normalize(forwardOffset, rightScratch2);
let startUp = Cartesian3_default.subtract(startTop, startBottom, startUpScratch);
startUp = Cartesian3_default.normalize(startUp, startUp);
let rightNormal = Cartesian3_default.cross(forward, startUp, rightScratch2);
rightNormal = Cartesian3_default.normalize(rightNormal, rightNormal);
let startPlaneNormal = Cartesian3_default.cross(
startUp,
startGeometryNormal,
startPlaneNormalScratch
);
startPlaneNormal = Cartesian3_default.normalize(startPlaneNormal, startPlaneNormal);
let endUp = Cartesian3_default.subtract(endTop, endBottom, endUpScratch);
endUp = Cartesian3_default.normalize(endUp, endUp);
let endPlaneNormal = Cartesian3_default.cross(
endGeometryNormal,
endUp,
endPlaneNormalScratch
);
endPlaneNormal = Cartesian3_default.normalize(endPlaneNormal, endPlaneNormal);
const texcoordNormalization3DX = segmentLength3D / length3D;
const texcoordNormalization3DY = lengthSoFar3D / length3D;
let segmentLength2D = 0;
let encodedStart2D;
let forwardOffset2D;
let right2D;
let texcoordNormalization2DX = 0;
let texcoordNormalization2DY = 0;
if (compute2dAttributes) {
segmentLength2D = Cartesian3_default.distance(start2D, end2D);
encodedStart2D = EncodedCartesian3_default.fromCartesian(
start2D,
encodeScratch2D
);
forwardOffset2D = Cartesian3_default.subtract(
end2D,
start2D,
forwardOffset2DScratch
);
right2D = Cartesian3_default.normalize(forwardOffset2D, right2DScratch);
const swap5 = right2D.x;
right2D.x = right2D.y;
right2D.y = -swap5;
texcoordNormalization2DX = segmentLength2D / length2D;
texcoordNormalization2DY = lengthSoFar2D / length2D;
}
for (j = 0; j < 8; j++) {
const vec4Index = vec4sWriteIndex + j * 4;
const vec2Index = vec2sWriteIndex + j * 2;
const wIndex = vec4Index + 3;
const rightPlaneSide = j < 4 ? 1 : -1;
const topBottomSide = j === 2 || j === 3 || j === 6 || j === 7 ? 1 : -1;
Cartesian3_default.pack(encodedStart.high, startHiAndForwardOffsetX, vec4Index);
startHiAndForwardOffsetX[wIndex] = forwardOffset.x;
Cartesian3_default.pack(encodedStart.low, startLoAndForwardOffsetY, vec4Index);
startLoAndForwardOffsetY[wIndex] = forwardOffset.y;
Cartesian3_default.pack(
startPlaneNormal,
startNormalAndForwardOffsetZ,
vec4Index
);
startNormalAndForwardOffsetZ[wIndex] = forwardOffset.z;
Cartesian3_default.pack(
endPlaneNormal,
endNormalAndTextureCoordinateNormalizationX,
vec4Index
);
endNormalAndTextureCoordinateNormalizationX[wIndex] = texcoordNormalization3DX * rightPlaneSide;
Cartesian3_default.pack(
rightNormal,
rightNormalAndTextureCoordinateNormalizationY,
vec4Index
);
let texcoordNormalization = texcoordNormalization3DY * topBottomSide;
if (texcoordNormalization === 0 && topBottomSide < 0) {
texcoordNormalization = 9;
}
rightNormalAndTextureCoordinateNormalizationY[wIndex] = texcoordNormalization;
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 && topBottomSide < 0) {
texcoordNormalization = 9;
}
texcoordNormalization2D[vec2Index + 1] = texcoordNormalization;
}
}
const adjustHeightStartBottom = adjustHeightStartBottomScratch;
const adjustHeightEndBottom = adjustHeightEndBottomScratch;
const adjustHeightStartTop = adjustHeightStartTopScratch;
const adjustHeightEndTop = adjustHeightEndTopScratch;
const getHeightsRectangle = Rectangle_default.fromCartographicArray(
getHeightCartographics,
getHeightRectangleScratch
);
const minMaxHeights = ApproximateTerrainHeights_default.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
);
let normalNudge = Cartesian3_default.multiplyByScalar(
rightNormal,
Math_default.EPSILON5,
normalNudgeScratch
);
Cartesian3_default.add(
adjustHeightStartBottom,
normalNudge,
adjustHeightStartBottom
);
Cartesian3_default.add(adjustHeightEndBottom, normalNudge, adjustHeightEndBottom);
Cartesian3_default.add(adjustHeightStartTop, normalNudge, adjustHeightStartTop);
Cartesian3_default.add(adjustHeightEndTop, normalNudge, adjustHeightEndTop);
nudgeXZ(adjustHeightStartBottom, adjustHeightEndBottom);
nudgeXZ(adjustHeightStartTop, adjustHeightEndTop);
Cartesian3_default.pack(adjustHeightStartBottom, positionsArray, vec3sWriteIndex);
Cartesian3_default.pack(adjustHeightEndBottom, positionsArray, vec3sWriteIndex + 3);
Cartesian3_default.pack(adjustHeightEndTop, positionsArray, vec3sWriteIndex + 6);
Cartesian3_default.pack(adjustHeightStartTop, positionsArray, vec3sWriteIndex + 9);
normalNudge = Cartesian3_default.multiplyByScalar(
rightNormal,
-2 * Math_default.EPSILON5,
normalNudgeScratch
);
Cartesian3_default.add(
adjustHeightStartBottom,
normalNudge,
adjustHeightStartBottom
);
Cartesian3_default.add(adjustHeightEndBottom, normalNudge, adjustHeightEndBottom);
Cartesian3_default.add(adjustHeightStartTop, normalNudge, adjustHeightStartTop);
Cartesian3_default.add(adjustHeightEndTop, normalNudge, adjustHeightEndTop);
nudgeXZ(adjustHeightStartBottom, adjustHeightEndBottom);
nudgeXZ(adjustHeightStartTop, adjustHeightEndTop);
Cartesian3_default.pack(
adjustHeightStartBottom,
positionsArray,
vec3sWriteIndex + 12
);
Cartesian3_default.pack(
adjustHeightEndBottom,
positionsArray,
vec3sWriteIndex + 15
);
Cartesian3_default.pack(adjustHeightEndTop, positionsArray, vec3sWriteIndex + 18);
Cartesian3_default.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++) {
indices2[index + j] = REFERENCE_INDICES[j] + indexOffset;
}
indexOffset += 8;
index += REFERENCE_INDICES_LENGTH;
}
const boundingSpheres = scratchBoundingSpheres;
BoundingSphere_default.fromVertices(
bottomPositionsArray,
Cartesian3_default.ZERO,
3,
boundingSpheres[0]
);
BoundingSphere_default.fromVertices(
topPositionsArray,
Cartesian3_default.ZERO,
3,
boundingSpheres[1]
);
const boundingSphere = BoundingSphere_default.fromBoundingSpheres(boundingSpheres);
boundingSphere.radius += sumHeights / (segmentCount * 2);
const attributes = {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.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_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
normalize: false,
values: texcoordNormalization2D
});
}
return new Geometry_default({
attributes,
indices: indices2,
boundingSphere
});
}
function getVec4GeometryAttribute(typedArray) {
return new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4,
normalize: false,
values: typedArray
});
}
GroundPolylineGeometry._projectNormal = projectNormal;
var GroundPolylineGeometry_default = GroundPolylineGeometry;
// node_modules/@cesium/engine/Source/Shaders/PolylineShadowVolumeFS.js
var PolylineShadowVolumeFS_default = 'in vec4 v_startPlaneNormalEcAndHalfWidth;\nin vec4 v_endPlaneNormalEcAndBatchId;\nin vec4 v_rightPlaneEC; // Technically can compute distance for this here\nin vec4 v_endEcAndStartEcX;\nin vec4 v_texcoordNormalizationAndStartEcYZ;\n\n#ifdef PER_INSTANCE_COLOR\nin vec4 v_color;\n#endif\n\nvoid main(void)\n{\n float logDepthOrDepth = czm_branchFreeTernary(czm_sceneMode == czm_sceneMode2D, gl_FragCoord.z, czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw)));\n vec3 ecStart = vec3(v_endEcAndStartEcX.w, v_texcoordNormalizationAndStartEcYZ.zw);\n\n // Discard for sky\n if (logDepthOrDepth == 0.0) {\n#ifdef DEBUG_SHOW_VOLUME\n out_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\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n eyeCoordinate /= eyeCoordinate.w;\n\n float halfMaxWidth = v_startPlaneNormalEcAndHalfWidth.w * czm_metersPerPixel(eyeCoordinate);\n // Check distance of the eye coordinate against the right-facing plane\n float widthwiseDistance = czm_planeDistance(v_rightPlaneEC, eyeCoordinate.xyz);\n\n // Check eye coordinate against the mitering planes\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\n if (abs(widthwiseDistance) > halfMaxWidth || distanceFromStart < 0.0 || distanceFromEnd < 0.0) {\n#ifdef DEBUG_SHOW_VOLUME\n out_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\n // Check distance of the eye coordinate against start and end planes with normals in the right plane.\n // For computing unskewed lengthwise texture coordinate.\n // Can also be used for clipping extremely pointy miters, but in practice unnecessary because of miter breaking.\n\n // aligned plane: cross the right plane normal with miter plane normal, then cross the result with right again to point it more "forward"\n vec3 alignedPlaneNormal;\n\n // start aligned plane\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\n // end aligned plane\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\n#ifdef PER_INSTANCE_COLOR\n out_FragColor = czm_gammaCorrect(v_color);\n#else // PER_INSTANCE_COLOR\n // Clamp - distance to aligned planes may be negative due to mitering,\n // so fragment texture coordinate might be out-of-bounds.\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\n czm_materialInput materialInput;\n\n materialInput.s = s;\n materialInput.st = vec2(s, t);\n materialInput.str = vec3(s, t, 0.0);\n\n czm_material material = czm_getMaterial(materialInput);\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#endif // PER_INSTANCE_COLOR\n\n // Premultiply alpha. Required for classification primitives on translucent globe.\n out_FragColor.rgb *= out_FragColor.a;\n\n czm_writeDepthClamp();\n}\n';
// node_modules/@cesium/engine/Source/Shaders/PolylineShadowVolumeMorphFS.js
var PolylineShadowVolumeMorphFS_default = "in vec3 v_forwardDirectionEC;\nin vec3 v_texcoordNormalizationAndHalfWidth;\nin float v_batchId;\n\n#ifdef PER_INSTANCE_COLOR\nin vec4 v_color;\n#else\nin vec2 v_alignedPlaneDistances;\nin float v_texcoordT;\n#endif\n\nfloat rayPlaneDistanceUnsafe(vec3 origin, vec3 direction, vec3 planeNormal, float planeDistance) {\n // We don't expect the ray to ever be parallel to the plane\n return (-planeDistance - dot(planeNormal, origin)) / dot(planeNormal, direction);\n}\n\nvoid main(void)\n{\n vec4 eyeCoordinate = gl_FragCoord;\n eyeCoordinate /= eyeCoordinate.w;\n\n#ifdef PER_INSTANCE_COLOR\n out_FragColor = czm_gammaCorrect(v_color);\n#else // PER_INSTANCE_COLOR\n // Use distances for planes aligned with segment to prevent skew in dashing\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\n // Clamp - distance to aligned planes may be negative due to mitering\n distanceFromStart = max(0.0, distanceFromStart);\n distanceFromEnd = max(0.0, distanceFromEnd);\n\n float s = distanceFromStart / (distanceFromStart + distanceFromEnd);\n s = (s * v_texcoordNormalizationAndHalfWidth.x) + v_texcoordNormalizationAndHalfWidth.y;\n\n czm_materialInput materialInput;\n\n materialInput.s = s;\n materialInput.st = vec2(s, v_texcoordT);\n materialInput.str = vec3(s, v_texcoordT, 0.0);\n\n czm_material material = czm_getMaterial(materialInput);\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#endif // PER_INSTANCE_COLOR\n}\n";
// node_modules/@cesium/engine/Source/Shaders/PolylineShadowVolumeMorphVS.js
var PolylineShadowVolumeMorphVS_default = `in vec3 position3DHigh;
in vec3 position3DLow;
in vec4 startHiAndForwardOffsetX;
in vec4 startLoAndForwardOffsetY;
in vec4 startNormalAndForwardOffsetZ;
in vec4 endNormalAndTextureCoordinateNormalizationX;
in vec4 rightNormalAndTextureCoordinateNormalizationY;
in vec4 startHiLo2D;
in vec4 offsetAndRight2D;
in vec4 startEndNormals2D;
in vec2 texcoordNormalization2D;
in float batchId;
out vec3 v_forwardDirectionEC;
out vec3 v_texcoordNormalizationAndHalfWidth;
out float v_batchId;
// For materials
#ifdef WIDTH_VARYING
out float v_width;
#endif
#ifdef ANGLE_VARYING
out float v_polylineAngle;
#endif
#ifdef PER_INSTANCE_COLOR
out vec4 v_color;
#else
out vec2 v_alignedPlaneDistances;
out float v_texcoordT;
#endif
// Morphing planes using SLERP or NLERP doesn't seem to work, so instead draw the material directly on the shadow volume.
// Morph views are from very far away and aren't meant to be used precisely, so this should be sufficient.
void main()
{
v_batchId = batchId;
// Start position
vec4 posRelativeToEye2D = czm_translateRelativeToEye(vec3(0.0, startHiLo2D.xy), vec3(0.0, startHiLo2D.zw));
vec4 posRelativeToEye3D = czm_translateRelativeToEye(startHiAndForwardOffsetX.xyz, startLoAndForwardOffsetY.xyz);
vec4 posRelativeToEye = czm_columbusViewMorph(posRelativeToEye2D, posRelativeToEye3D, czm_morphTime);
vec3 posEc2D = (czm_modelViewRelativeToEye * posRelativeToEye2D).xyz;
vec3 posEc3D = (czm_modelViewRelativeToEye * posRelativeToEye3D).xyz;
vec3 startEC = (czm_modelViewRelativeToEye * posRelativeToEye).xyz;
// Start plane
vec4 startPlane2D;
vec4 startPlane3D;
startPlane2D.xyz = czm_normal * vec3(0.0, startEndNormals2D.xy);
startPlane3D.xyz = czm_normal * startNormalAndForwardOffsetZ.xyz;
startPlane2D.w = -dot(startPlane2D.xyz, posEc2D);
startPlane3D.w = -dot(startPlane3D.xyz, posEc3D);
// Right plane
vec4 rightPlane2D;
vec4 rightPlane3D;
rightPlane2D.xyz = czm_normal * vec3(0.0, offsetAndRight2D.zw);
rightPlane3D.xyz = czm_normal * rightNormalAndTextureCoordinateNormalizationY.xyz;
rightPlane2D.w = -dot(rightPlane2D.xyz, posEc2D);
rightPlane3D.w = -dot(rightPlane3D.xyz, posEc3D);
// End position
posRelativeToEye2D = posRelativeToEye2D + vec4(0.0, offsetAndRight2D.xy, 0.0);
posRelativeToEye3D = posRelativeToEye3D + vec4(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w, 0.0);
posRelativeToEye = czm_columbusViewMorph(posRelativeToEye2D, posRelativeToEye3D, czm_morphTime);
posEc2D = (czm_modelViewRelativeToEye * posRelativeToEye2D).xyz;
posEc3D = (czm_modelViewRelativeToEye * posRelativeToEye3D).xyz;
vec3 endEC = (czm_modelViewRelativeToEye * posRelativeToEye).xyz;
vec3 forwardEc3D = czm_normal * normalize(vec3(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w));
vec3 forwardEc2D = czm_normal * normalize(vec3(0.0, offsetAndRight2D.xy));
// End plane
vec4 endPlane2D;
vec4 endPlane3D;
endPlane2D.xyz = czm_normal * vec3(0.0, startEndNormals2D.zw);
endPlane3D.xyz = czm_normal * endNormalAndTextureCoordinateNormalizationX.xyz;
endPlane2D.w = -dot(endPlane2D.xyz, posEc2D);
endPlane3D.w = -dot(endPlane3D.xyz, posEc3D);
// Forward direction
v_forwardDirectionEC = normalize(endEC - startEC);
vec2 cleanTexcoordNormalization2D;
cleanTexcoordNormalization2D.x = abs(texcoordNormalization2D.x);
cleanTexcoordNormalization2D.y = czm_branchFreeTernary(texcoordNormalization2D.y > 1.0, 0.0, abs(texcoordNormalization2D.y));
vec2 cleanTexcoordNormalization3D;
cleanTexcoordNormalization3D.x = abs(endNormalAndTextureCoordinateNormalizationX.w);
cleanTexcoordNormalization3D.y = rightNormalAndTextureCoordinateNormalizationY.w;
cleanTexcoordNormalization3D.y = czm_branchFreeTernary(cleanTexcoordNormalization3D.y > 1.0, 0.0, abs(cleanTexcoordNormalization3D.y));
v_texcoordNormalizationAndHalfWidth.xy = mix(cleanTexcoordNormalization2D, cleanTexcoordNormalization3D, czm_morphTime);
#ifdef PER_INSTANCE_COLOR
v_color = czm_batchTable_color(batchId);
#else // PER_INSTANCE_COLOR
// For computing texture coordinates
v_alignedPlaneDistances.x = -dot(v_forwardDirectionEC, startEC);
v_alignedPlaneDistances.y = -dot(-v_forwardDirectionEC, endEC);
#endif // PER_INSTANCE_COLOR
#ifdef WIDTH_VARYING
float width = czm_batchTable_width(batchId);
float halfWidth = width * 0.5;
v_width = width;
v_texcoordNormalizationAndHalfWidth.z = halfWidth;
#else
float halfWidth = 0.5 * czm_batchTable_width(batchId);
v_texcoordNormalizationAndHalfWidth.z = halfWidth;
#endif
// Compute a normal along which to "push" the position out, extending the miter depending on view distance.
// Position has already been "pushed" by unit length along miter normal, and miter normals are encoded in the planes.
// Decode the normal to use at this specific vertex, push the position back, and then push to where it needs to be.
// Since this is morphing, compute both 3D and 2D positions and then blend.
// ****** 3D ******
// Check distance to the end plane and start plane, pick the plane that is closer
vec4 positionEc3D = czm_modelViewRelativeToEye * czm_translateRelativeToEye(position3DHigh, position3DLow); // w = 1.0, see czm_computePosition
float absStartPlaneDistance = abs(czm_planeDistance(startPlane3D, positionEc3D.xyz));
float absEndPlaneDistance = abs(czm_planeDistance(endPlane3D, positionEc3D.xyz));
vec3 planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlane3D.xyz, endPlane3D.xyz);
vec3 upOrDown = normalize(cross(rightPlane3D.xyz, planeDirection)); // Points "up" for start plane, "down" at end plane.
vec3 normalEC = normalize(cross(planeDirection, upOrDown)); // In practice, the opposite seems to work too.
// Nudge the top vertex upwards to prevent flickering
vec3 geodeticSurfaceNormal = normalize(cross(normalEC, forwardEc3D));
geodeticSurfaceNormal *= float(0.0 <= rightNormalAndTextureCoordinateNormalizationY.w && rightNormalAndTextureCoordinateNormalizationY.w <= 1.0);
geodeticSurfaceNormal *= MAX_TERRAIN_HEIGHT;
positionEc3D.xyz += geodeticSurfaceNormal;
// Determine if this vertex is on the "left" or "right"
normalEC *= sign(endNormalAndTextureCoordinateNormalizationX.w);
// A "perfect" implementation would push along normals according to the angle against forward.
// In practice, just pushing the normal out by halfWidth is sufficient for morph views.
positionEc3D.xyz += halfWidth * max(0.0, czm_metersPerPixel(positionEc3D)) * normalEC; // prevent artifacts when czm_metersPerPixel is negative (behind camera)
// ****** 2D ******
// Check distance to the end plane and start plane, pick the plane that is closer
vec4 positionEc2D = czm_modelViewRelativeToEye * czm_translateRelativeToEye(position2DHigh.zxy, position2DLow.zxy); // w = 1.0, see czm_computePosition
absStartPlaneDistance = abs(czm_planeDistance(startPlane2D, positionEc2D.xyz));
absEndPlaneDistance = abs(czm_planeDistance(endPlane2D, positionEc2D.xyz));
planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlane2D.xyz, endPlane2D.xyz);
upOrDown = normalize(cross(rightPlane2D.xyz, planeDirection)); // Points "up" for start plane, "down" at end plane.
normalEC = normalize(cross(planeDirection, upOrDown)); // In practice, the opposite seems to work too.
// Nudge the top vertex upwards to prevent flickering
geodeticSurfaceNormal = normalize(cross(normalEC, forwardEc2D));
geodeticSurfaceNormal *= float(0.0 <= texcoordNormalization2D.y && texcoordNormalization2D.y <= 1.0);
geodeticSurfaceNormal *= MAX_TERRAIN_HEIGHT;
positionEc2D.xyz += geodeticSurfaceNormal;
// Determine if this vertex is on the "left" or "right"
normalEC *= sign(texcoordNormalization2D.x);
#ifndef PER_INSTANCE_COLOR
// Use vertex's sidedness to compute its texture coordinate.
v_texcoordT = clamp(sign(texcoordNormalization2D.x), 0.0, 1.0);
#endif
// A "perfect" implementation would push along normals according to the angle against forward.
// In practice, just pushing the normal out by halfWidth is sufficient for morph views.
positionEc2D.xyz += halfWidth * max(0.0, czm_metersPerPixel(positionEc2D)) * normalEC; // prevent artifacts when czm_metersPerPixel is negative (behind camera)
// Blend for actual position
gl_Position = czm_projection * mix(positionEc2D, positionEc3D, czm_morphTime);
#ifdef ANGLE_VARYING
// Approximate relative screen space direction of the line.
vec2 approxLineDirection = normalize(vec2(v_forwardDirectionEC.x, -v_forwardDirectionEC.y));
approxLineDirection.y = czm_branchFreeTernary(approxLineDirection.x == 0.0 && approxLineDirection.y == 0.0, -1.0, approxLineDirection.y);
v_polylineAngle = czm_fastApproximateAtan(approxLineDirection.x, approxLineDirection.y);
#endif
}
`;
// node_modules/@cesium/engine/Source/Shaders/PolylineShadowVolumeVS.js
var PolylineShadowVolumeVS_default = 'in vec3 position3DHigh;\nin vec3 position3DLow;\n\n// In 2D and in 3D, texture coordinate normalization component signs encodes:\n// * X sign - sidedness relative to right plane\n// * Y sign - is negative OR magnitude is greater than 1.0 if vertex is on bottom of volume\n#ifndef COLUMBUS_VIEW_2D\nin vec4 startHiAndForwardOffsetX;\nin vec4 startLoAndForwardOffsetY;\nin vec4 startNormalAndForwardOffsetZ;\nin vec4 endNormalAndTextureCoordinateNormalizationX;\nin vec4 rightNormalAndTextureCoordinateNormalizationY;\n#else\nin vec4 startHiLo2D;\nin vec4 offsetAndRight2D;\nin vec4 startEndNormals2D;\nin vec2 texcoordNormalization2D;\n#endif\n\nin float batchId;\n\nout vec4 v_startPlaneNormalEcAndHalfWidth;\nout vec4 v_endPlaneNormalEcAndBatchId;\nout vec4 v_rightPlaneEC;\nout vec4 v_endEcAndStartEcX;\nout vec4 v_texcoordNormalizationAndStartEcYZ;\n\n// For materials\n#ifdef WIDTH_VARYING\nout float v_width;\n#endif\n#ifdef ANGLE_VARYING\nout float v_polylineAngle;\n#endif\n\n#ifdef PER_INSTANCE_COLOR\nout vec4 v_color;\n#endif\n\nvoid 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\n vec3 forwardDirectionEC = czm_normal * vec3(0.0, offsetAndRight2D.xy);\n vec3 ecEnd = forwardDirectionEC + ecStart;\n forwardDirectionEC = normalize(forwardDirectionEC);\n\n // Right plane\n v_rightPlaneEC.xyz = czm_normal * vec3(0.0, offsetAndRight2D.zw);\n v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);\n\n // start plane\n vec4 startPlaneEC;\n startPlaneEC.xyz = czm_normal * vec3(0.0, startEndNormals2D.xy);\n startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);\n\n // end plane\n vec4 endPlaneEC;\n endPlaneEC.xyz = czm_normal * vec3(0.0, startEndNormals2D.zw);\n endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);\n\n v_texcoordNormalizationAndStartEcYZ.x = abs(texcoordNormalization2D.x);\n v_texcoordNormalizationAndStartEcYZ.y = texcoordNormalization2D.y;\n\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\n vec3 forwardDirectionEC = normalize(offset);\n\n // start plane\n vec4 startPlaneEC;\n startPlaneEC.xyz = czm_normal * startNormalAndForwardOffsetZ.xyz;\n startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);\n\n // end plane\n vec4 endPlaneEC;\n endPlaneEC.xyz = czm_normal * endNormalAndTextureCoordinateNormalizationX.xyz;\n endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);\n\n // Right plane\n v_rightPlaneEC.xyz = czm_normal * rightNormalAndTextureCoordinateNormalizationY.xyz;\n v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);\n\n v_texcoordNormalizationAndStartEcYZ.x = abs(endNormalAndTextureCoordinateNormalizationX.w);\n v_texcoordNormalizationAndStartEcYZ.y = rightNormalAndTextureCoordinateNormalizationY.w;\n\n#endif // COLUMBUS_VIEW_2D\n\n v_endEcAndStartEcX.xyz = ecEnd;\n v_endEcAndStartEcX.w = ecStart.x;\n v_texcoordNormalizationAndStartEcYZ.zw = ecStart.yz;\n\n#ifdef PER_INSTANCE_COLOR\n v_color = czm_batchTable_color(batchId);\n#endif // PER_INSTANCE_COLOR\n\n // Compute a normal along which to "push" the position out, extending the miter depending on view distance.\n // Position has already been "pushed" by unit length along miter normal, and miter normals are encoded in the planes.\n // Decode the normal to use at this specific vertex, push the position back, and then push to where it needs to be.\n vec4 positionRelativeToEye = czm_computePosition();\n\n // Check distance to the end plane and start plane, pick the plane that is closer\n vec4 positionEC = czm_modelViewRelativeToEye * positionRelativeToEye; // w = 1.0, see czm_computePosition\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)); // Points "up" for start plane, "down" at end plane.\n vec3 normalEC = normalize(cross(planeDirection, upOrDown)); // In practice, the opposite seems to work too.\n\n // Extrude bottom vertices downward for far view distances, like for GroundPrimitives\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\n v_texcoordNormalizationAndStartEcYZ.y = czm_branchFreeTernary(v_texcoordNormalizationAndStartEcYZ.y > 1.0, 0.0, abs(v_texcoordNormalizationAndStartEcYZ.y));\n\n // Determine distance along normalEC to push for a volume of appropriate width.\n // Make volumes about double pixel width for a conservative fit - in practice the\n // extra cost here is minimal compared to the loose volume heights.\n //\n // N = normalEC (guaranteed "right-facing")\n // R = rightEC\n // p = angle between N and R\n // w = distance to push along R if R == N\n // d = distance to push along N\n //\n // N R\n // { p| } * cos(p) = dot(N, R) = w / d\n // d | |w * d = w / dot(N, R)\n // { | }\n // o---------- polyline segment ---->\n //\n float width = czm_batchTable_width(batchId);\n#ifdef WIDTH_VARYING\n v_width = width;\n#endif\n\n v_startPlaneNormalEcAndHalfWidth.xyz = startPlaneEC.xyz;\n v_startPlaneNormalEcAndHalfWidth.w = width * 0.5;\n\n v_endPlaneNormalEcAndBatchId.xyz = endPlaneEC.xyz;\n v_endPlaneNormalEcAndBatchId.w = batchId;\n\n width = width * max(0.0, czm_metersPerPixel(positionEC)); // width = distance to push along R\n width = width / dot(normalEC, v_rightPlaneEC.xyz); // width = distance to push along N\n\n // Determine if this vertex is on the "left" or "right"\n#ifdef COLUMBUS_VIEW_2D\n normalEC *= sign(texcoordNormalization2D.x);\n#else\n normalEC *= sign(endNormalAndTextureCoordinateNormalizationX.w);\n#endif\n\n positionEC.xyz += width * normalEC;\n gl_Position = czm_depthClamp(czm_projection * positionEC);\n\n#ifdef ANGLE_VARYING\n // Approximate relative screen space direction of the line.\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';
// node_modules/@cesium/engine/Source/Shaders/Appearances/PolylineColorAppearanceVS.js
var PolylineColorAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 prevPosition3DHigh;\nin vec3 prevPosition3DLow;\nin vec3 nextPosition3DHigh;\nin vec3 nextPosition3DLow;\nin vec2 expandAndWidth;\nin vec4 color;\nin float batchId;\n\nout vec4 v_color;\n\nvoid main()\n{\n float expandDir = expandAndWidth.x;\n float width = abs(expandAndWidth.y) + 0.5;\n bool usePrev = expandAndWidth.y < 0.0;\n\n vec4 p = czm_computePosition();\n vec4 prev = czm_computePrevPosition();\n vec4 next = czm_computeNextPosition();\n\n float angle;\n vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);\n gl_Position = czm_viewportOrthographic * positionWC;\n\n v_color = color;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/PolylineCommon.js
var PolylineCommon_default = "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\n vec3 p0ToP1 = p1 - p0;\n float magnitude = length(p0ToP1);\n vec3 direction = normalize(p0ToP1);\n\n // Distance that p0 is behind the near plane. Negative means p0 is\n // in front of the near plane.\n float endPoint0Distance = czm_currentFrustum.x + p0.z;\n\n // Camera looks down -Z.\n // When moving a point along +Z: LESS VISIBLE\n // * Points in front of the camera move closer to the camera.\n // * Points behind the camrea move farther away from the camera.\n // When moving a point along -Z: MORE VISIBLE\n // * Points in front of the camera move farther away from the camera.\n // * Points behind the camera move closer to the camera.\n\n // Positive denominator: -Z, becoming more visible\n // Negative denominator: +Z, becoming less visible\n // Nearly zero: parallel to near plane\n float denominator = -direction.z;\n\n if (endPoint0Distance > 0.0 && abs(denominator) < czm_epsilon7)\n {\n // p0 is behind the near plane and the line to p1 is nearly parallel to\n // the near plane, so cull the segment completely.\n culledByNearPlane = true;\n }\n else if (endPoint0Distance > 0.0)\n {\n // p0 is behind the near plane, and the line to p1 is moving distinctly\n // toward or away from it.\n\n // t = (-plane distance - dot(plane normal, ray origin)) / dot(plane normal, ray direction)\n float t = endPoint0Distance / denominator;\n if (t < 0.0 || t > magnitude)\n {\n // Near plane intersection is not between the two points.\n // We already confirmed p0 is behind the naer plane, so now\n // we know the entire segment is behind it.\n culledByNearPlane = true;\n }\n else\n {\n // Segment crosses the near plane, update p0 to lie exactly on it.\n p0 = p0 + t * direction;\n\n // Numerical noise might put us a bit on the wrong side of the near plane.\n // Don't let that happen.\n p0.z = min(p0.z, -czm_currentFrustum.x);\n\n clipped = true;\n }\n }\n\n clippedPositionEC = vec4(p0, 1.0);\n positionWC = czm_eyeToWindowCoordinates(clippedPositionEC);\n}\n\nvec4 getPolylineWindowCoordinatesEC(vec4 positionEC, vec4 prevEC, vec4 nextEC, float expandDirection, float width, bool usePrevious, out float angle)\n{\n // expandDirection +1 is to the _left_ when looking from positionEC toward nextEC.\n\n#ifdef POLYLINE_DASH\n // Compute the window coordinates of the points.\n vec4 positionWindow = czm_eyeToWindowCoordinates(positionEC);\n vec4 previousWindow = czm_eyeToWindowCoordinates(prevEC);\n vec4 nextWindow = czm_eyeToWindowCoordinates(nextEC);\n\n // Determine the relative screen space direction of the line.\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; // precomputed atan(1,0)\n\n // Quantize the angle so it doesn't change rapidly between segments.\n angle = floor(angle / czm_piOverFour + 0.5) * czm_piOverFour;\n#endif\n\n vec4 clippedPrevWC, clippedPrevEC;\n bool prevSegmentClipped, prevSegmentCulled;\n clipLineSegmentToNearPlane(prevEC.xyz, positionEC.xyz, clippedPrevWC, prevSegmentClipped, prevSegmentCulled, clippedPrevEC);\n\n vec4 clippedNextWC, clippedNextEC;\n bool nextSegmentClipped, nextSegmentCulled;\n clipLineSegmentToNearPlane(nextEC.xyz, positionEC.xyz, clippedNextWC, nextSegmentClipped, nextSegmentCulled, clippedNextEC);\n\n bool segmentClipped, segmentCulled;\n vec4 clippedPositionWC, clippedPositionEC;\n clipLineSegmentToNearPlane(positionEC.xyz, usePrevious ? prevEC.xyz : nextEC.xyz, clippedPositionWC, segmentClipped, segmentCulled, clippedPositionEC);\n\n if (segmentCulled)\n {\n return vec4(0.0, 0.0, 0.0, 1.0);\n }\n\n vec2 directionToPrevWC = normalize(clippedPrevWC.xy - clippedPositionWC.xy);\n vec2 directionToNextWC = normalize(clippedNextWC.xy - clippedPositionWC.xy);\n\n // If a segment was culled, we can't use the corresponding direction\n // computed above. We should never see both of these be true without\n // `segmentCulled` above also being true.\n if (prevSegmentCulled)\n {\n directionToPrevWC = -directionToNextWC;\n }\n else if (nextSegmentCulled)\n {\n directionToNextWC = -directionToPrevWC;\n }\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\n vec2 thisSegmentLeftWC = vec2(-thisSegmentForwardWC.y, thisSegmentForwardWC.x);\n\n vec2 leftWC = thisSegmentLeftWC;\n float expandWidth = width * 0.5;\n\n // When lines are split at the anti-meridian, the position may be at the\n // same location as the next or previous position, and we need to handle\n // that to avoid producing NaNs.\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\n vec2 leftSumWC = thisSegmentLeftWC + otherSegmentLeftWC;\n float leftSumLength = length(leftSumWC);\n leftWC = leftSumLength < czm_epsilon6 ? thisSegmentLeftWC : (leftSumWC / leftSumLength);\n\n // The sine of the angle between the two vectors is given by the formula\n // |a x b| = |a||b|sin(theta)\n // which is\n // float sinAngle = length(cross(vec3(leftWC, 0.0), vec3(-thisSegmentForwardWC, 0.0)));\n // Because the z components of both vectors are zero, the x and y coordinate will be zero.\n // Therefore, the sine of the angle is just the z component of the cross product.\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\n vec2 offset = leftWC * expandDirection * expandWidth * czm_pixelRatio;\n return vec4(clippedPositionWC.xy + offset, -clippedPositionWC.z, 1.0) * (czm_projection * clippedPositionEC).w;\n}\n\nvec4 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";
// node_modules/@cesium/engine/Source/Scene/PolylineColorAppearance.js
var defaultVertexShaderSource = `${PolylineCommon_default}
${PolylineColorAppearanceVS_default}`;
var defaultFragmentShaderSource = PerInstanceFlatColorAppearanceFS_default;
if (!FeatureDetection_default.isInternetExplorer()) {
defaultVertexShaderSource = `#define CLIP_POLYLINE
${defaultVertexShaderSource}`;
}
function PolylineColorAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const closed = false;
const vertexFormat = PolylineColorAppearance.VERTEX_FORMAT;
this.material = void 0;
this.translucent = translucent;
this._vertexShaderSource = defaultValue_default(
options.vertexShaderSource,
defaultVertexShaderSource
);
this._fragmentShaderSource = defaultValue_default(
options.fragmentShaderSource,
defaultFragmentShaderSource
);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._vertexFormat = vertexFormat;
}
Object.defineProperties(PolylineColorAppearance.prototype, {
vertexShaderSource: {
get: function() {
return this._vertexShaderSource;
}
},
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
renderState: {
get: function() {
return this._renderState;
}
},
closed: {
get: function() {
return this._closed;
}
},
vertexFormat: {
get: function() {
return this._vertexFormat;
}
}
});
PolylineColorAppearance.VERTEX_FORMAT = VertexFormat_default.POSITION_ONLY;
PolylineColorAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
PolylineColorAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
PolylineColorAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var PolylineColorAppearance_default = PolylineColorAppearance;
// node_modules/@cesium/engine/Source/Shaders/Appearances/PolylineMaterialAppearanceVS.js
var PolylineMaterialAppearanceVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 prevPosition3DHigh;\nin vec3 prevPosition3DLow;\nin vec3 nextPosition3DHigh;\nin vec3 nextPosition3DLow;\nin vec2 expandAndWidth;\nin vec2 st;\nin float batchId;\n\nout float v_width;\nout vec2 v_st;\nout float v_polylineAngle;\n\nvoid main()\n{\n float expandDir = expandAndWidth.x;\n float width = abs(expandAndWidth.y) + 0.5;\n bool usePrev = expandAndWidth.y < 0.0;\n\n vec4 p = czm_computePosition();\n vec4 prev = czm_computePrevPosition();\n vec4 next = czm_computeNextPosition();\n\n float angle;\n vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);\n gl_Position = czm_viewportOrthographic * positionWC;\n\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";
// node_modules/@cesium/engine/Source/Shaders/PolylineFS.js
var PolylineFS_default = "#ifdef VECTOR_TILE\nuniform vec4 u_highlightColor;\n#endif\n\nin vec2 v_st;\n\nvoid main()\n{\n czm_materialInput materialInput;\n\n vec2 st = v_st;\n st.t = czm_readNonPerspective(st.t, gl_FragCoord.w);\n\n materialInput.s = st.s;\n materialInput.st = st;\n materialInput.str = vec3(st, 0.0);\n\n czm_material material = czm_getMaterial(materialInput);\n out_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#ifdef VECTOR_TILE\n out_FragColor *= u_highlightColor;\n#endif\n\n czm_writeLogDepth();\n}\n";
// node_modules/@cesium/engine/Source/Scene/PolylineMaterialAppearance.js
var defaultVertexShaderSource2 = `${PolylineCommon_default}
${PolylineMaterialAppearanceVS_default}`;
var defaultFragmentShaderSource2 = PolylineFS_default;
if (!FeatureDetection_default.isInternetExplorer()) {
defaultVertexShaderSource2 = `#define CLIP_POLYLINE
${defaultVertexShaderSource2}`;
}
function PolylineMaterialAppearance(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const translucent = defaultValue_default(options.translucent, true);
const closed = false;
const vertexFormat = PolylineMaterialAppearance.VERTEX_FORMAT;
this.material = defined_default(options.material) ? options.material : Material_default.fromType(Material_default.ColorType);
this.translucent = translucent;
this._vertexShaderSource = defaultValue_default(
options.vertexShaderSource,
defaultVertexShaderSource2
);
this._fragmentShaderSource = defaultValue_default(
options.fragmentShaderSource,
defaultFragmentShaderSource2
);
this._renderState = Appearance_default.getDefaultRenderState(
translucent,
closed,
options.renderState
);
this._closed = closed;
this._vertexFormat = vertexFormat;
}
Object.defineProperties(PolylineMaterialAppearance.prototype, {
vertexShaderSource: {
get: function() {
let vs = this._vertexShaderSource;
if (this.material.shaderSource.search(/in\s+float\s+v_polylineAngle;/g) !== -1) {
vs = `#define POLYLINE_DASH
${vs}`;
}
return vs;
}
},
fragmentShaderSource: {
get: function() {
return this._fragmentShaderSource;
}
},
renderState: {
get: function() {
return this._renderState;
}
},
closed: {
get: function() {
return this._closed;
}
},
vertexFormat: {
get: function() {
return this._vertexFormat;
}
}
});
PolylineMaterialAppearance.VERTEX_FORMAT = VertexFormat_default.POSITION_AND_ST;
PolylineMaterialAppearance.prototype.getFragmentShaderSource = Appearance_default.prototype.getFragmentShaderSource;
PolylineMaterialAppearance.prototype.isTranslucent = Appearance_default.prototype.isTranslucent;
PolylineMaterialAppearance.prototype.getRenderState = Appearance_default.prototype.getRenderState;
var PolylineMaterialAppearance_default = PolylineMaterialAppearance;
// node_modules/@cesium/engine/Source/Scene/GroundPolylinePrimitive.js
function GroundPolylinePrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.geometryInstances = options.geometryInstances;
this._hasPerInstanceColors = true;
let appearance = options.appearance;
if (!defined_default(appearance)) {
appearance = new PolylineMaterialAppearance_default();
}
this.appearance = appearance;
this.show = defaultValue_default(options.show, true);
this.classificationType = defaultValue_default(
options.classificationType,
ClassificationType_default.BOTH
);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this._debugShowShadowVolume = defaultValue_default(
options.debugShowShadowVolume,
false
);
this._primitiveOptions = {
geometryInstances: void 0,
appearance: void 0,
vertexCacheOptimize: false,
interleave: defaultValue_default(options.interleave, false),
releaseGeometryInstances: defaultValue_default(
options.releaseGeometryInstances,
true
),
allowPicking: defaultValue_default(options.allowPicking, true),
asynchronous: defaultValue_default(options.asynchronous, true),
compressVertices: false,
_createShaderProgramFunction: void 0,
_createCommandsFunction: void 0,
_updateAndQueueCommandsFunction: void 0
};
this._zIndex = void 0;
this._ready = false;
const groundPolylinePrimitive = this;
this._readyPromise = new Promise((resolve2, reject) => {
groundPolylinePrimitive._completeLoad = () => {
this._ready = true;
if (this.releaseGeometryInstances) {
this.geometryInstances = void 0;
}
const error = this._error;
if (!defined_default(error)) {
resolve2(this);
} else {
reject(error);
}
};
});
this._primitive = void 0;
this._sp = void 0;
this._sp2D = void 0;
this._spMorph = void 0;
this._renderState = getRenderState(false);
this._renderState3DTiles = getRenderState(true);
this._renderStateMorph = RenderState_default.fromCache({
cull: {
enabled: true,
face: CullFace_default.FRONT
},
depthTest: {
enabled: true
},
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND,
depthMask: false
});
}
Object.defineProperties(GroundPolylinePrimitive.prototype, {
interleave: {
get: function() {
return this._primitiveOptions.interleave;
}
},
releaseGeometryInstances: {
get: function() {
return this._primitiveOptions.releaseGeometryInstances;
}
},
allowPicking: {
get: function() {
return this._primitiveOptions.allowPicking;
}
},
asynchronous: {
get: function() {
return this._primitiveOptions.asynchronous;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"GroundPolylinePrimitive.readyPromise",
"GroundPolylinePrimitive.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for GroundPolylinePrimitive.ready to return true instead."
);
return this._readyPromise;
}
},
debugShowShadowVolume: {
get: function() {
return this._debugShowShadowVolume;
}
}
});
GroundPolylinePrimitive.initializeTerrainHeights = function() {
return ApproximateTerrainHeights_default.initialize();
};
function createShaderProgram3(groundPolylinePrimitive, frameState, appearance) {
const context = frameState.context;
const primitive = groundPolylinePrimitive._primitive;
const attributeLocations8 = primitive._attributeLocations;
let vs = primitive._batchTable.getVertexShaderCallback()(
PolylineShadowVolumeVS_default
);
vs = Primitive_default._appendShowToShader(primitive, vs);
vs = Primitive_default._appendDistanceDisplayConditionToShader(primitive, vs);
vs = Primitive_default._modifyShaderPosition(
groundPolylinePrimitive,
vs,
frameState.scene3DOnly
);
let vsMorph = primitive._batchTable.getVertexShaderCallback()(
PolylineShadowVolumeMorphVS_default
);
vsMorph = Primitive_default._appendShowToShader(primitive, vsMorph);
vsMorph = Primitive_default._appendDistanceDisplayConditionToShader(
primitive,
vsMorph
);
vsMorph = Primitive_default._modifyShaderPosition(
groundPolylinePrimitive,
vsMorph,
frameState.scene3DOnly
);
let fs = primitive._batchTable.getVertexShaderCallback()(
PolylineShadowVolumeFS_default
);
const vsDefines = [
`GLOBE_MINIMUM_ALTITUDE ${frameState.mapProjection.ellipsoid.minimumRadius.toFixed(
1
)}`
];
let colorDefine = "";
let materialShaderSource = "";
if (defined_default(appearance.material)) {
materialShaderSource = defined_default(appearance.material) ? appearance.material.shaderSource : "";
if (materialShaderSource.search(/in\s+float\s+v_polylineAngle;/g) !== -1) {
vsDefines.push("ANGLE_VARYING");
}
if (materialShaderSource.search(/in\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_default({
defines: vsDefines,
sources: [vs]
});
const fsColor3D = new ShaderSource_default({
defines: fsDefines,
sources: [materialShaderSource, fs]
});
groundPolylinePrimitive._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: primitive._sp,
vertexShaderSource: vsColor3D,
fragmentShaderSource: fsColor3D,
attributeLocations: attributeLocations8
});
let colorProgram2D = context.shaderCache.getDerivedShaderProgram(
groundPolylinePrimitive._sp,
"2dColor"
);
if (!defined_default(colorProgram2D)) {
const vsColor2D = new ShaderSource_default({
defines: vsDefines.concat(["COLUMBUS_VIEW_2D"]),
sources: [vs]
});
colorProgram2D = context.shaderCache.createDerivedShaderProgram(
groundPolylinePrimitive._sp,
"2dColor",
{
context,
shaderProgram: groundPolylinePrimitive._sp2D,
vertexShaderSource: vsColor2D,
fragmentShaderSource: fsColor3D,
attributeLocations: attributeLocations8
}
);
}
groundPolylinePrimitive._sp2D = colorProgram2D;
let colorProgramMorph = context.shaderCache.getDerivedShaderProgram(
groundPolylinePrimitive._sp,
"MorphColor"
);
if (!defined_default(colorProgramMorph)) {
const vsColorMorph = new ShaderSource_default({
defines: vsDefines.concat([
`MAX_TERRAIN_HEIGHT ${ApproximateTerrainHeights_default._defaultMaxTerrainHeight.toFixed(
1
)}`
]),
sources: [vsMorph]
});
fs = primitive._batchTable.getVertexShaderCallback()(
PolylineShadowVolumeMorphFS_default
);
const fsColorMorph = new ShaderSource_default({
defines: fsDefines,
sources: [materialShaderSource, fs]
});
colorProgramMorph = context.shaderCache.createDerivedShaderProgram(
groundPolylinePrimitive._sp,
"MorphColor",
{
context,
shaderProgram: groundPolylinePrimitive._spMorph,
vertexShaderSource: vsColorMorph,
fragmentShaderSource: fsColorMorph,
attributeLocations: attributeLocations8
}
);
}
groundPolylinePrimitive._spMorph = colorProgramMorph;
}
function getRenderState(mask3DTiles) {
return RenderState_default.fromCache({
cull: {
enabled: true
},
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND,
depthMask: false,
stencilTest: {
enabled: mask3DTiles,
frontFunction: StencilFunction_default.EQUAL,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.KEEP
},
backFunction: StencilFunction_default.EQUAL,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.KEEP
},
reference: StencilConstants_default.CESIUM_3D_TILE_MASK,
mask: StencilConstants_default.CESIUM_3D_TILE_MASK
}
});
}
function createCommands3(groundPolylinePrimitive, appearance, material, translucent, colorCommands, pickCommands) {
const primitive = groundPolylinePrimitive._primitive;
const length3 = primitive._va.length;
colorCommands.length = length3;
pickCommands.length = length3;
const isPolylineColorAppearance = appearance instanceof PolylineColorAppearance_default;
const materialUniforms = isPolylineColorAppearance ? {} : material._uniforms;
const uniformMap2 = primitive._batchTable.getUniformMapCallback()(
materialUniforms
);
for (let i = 0; i < length3; i++) {
const vertexArray = primitive._va[i];
let command = colorCommands[i];
if (!defined_default(command)) {
command = colorCommands[i] = new DrawCommand_default({
owner: groundPolylinePrimitive,
primitiveType: primitive._primitiveType
});
}
command.vertexArray = vertexArray;
command.renderState = groundPolylinePrimitive._renderState;
command.shaderProgram = groundPolylinePrimitive._sp;
command.uniformMap = uniformMap2;
command.pass = Pass_default.TERRAIN_CLASSIFICATION;
command.pickId = "czm_batchTable_pickColor(v_endPlaneNormalEcAndBatchId.w)";
const derivedTilesetCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedTilesetCommand.renderState = groundPolylinePrimitive._renderState3DTiles;
derivedTilesetCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedTilesetCommand;
const derived2DCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.color2D
);
derived2DCommand.shaderProgram = groundPolylinePrimitive._sp2D;
command.derivedCommands.color2D = derived2DCommand;
const derived2DTilesetCommand = DrawCommand_default.shallowClone(
derivedTilesetCommand,
derivedTilesetCommand.derivedCommands.color2D
);
derived2DTilesetCommand.shaderProgram = groundPolylinePrimitive._sp2D;
derivedTilesetCommand.derivedCommands.color2D = derived2DTilesetCommand;
const derivedMorphCommand = DrawCommand_default.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, debugShowBoundingVolume2) {
if (frameState.mode === SceneMode_default.MORPHING) {
command = command.derivedCommands.colorMorph;
} else if (frameState.mode !== SceneMode_default.SCENE3D) {
command = command.derivedCommands.color2D;
}
command.modelMatrix = modelMatrix;
command.boundingVolume = boundingVolume;
command.cull = cull;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
frameState.commandList.push(command);
}
function updateAndQueueCommands4(groundPolylinePrimitive, frameState, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2) {
const primitive = groundPolylinePrimitive._primitive;
Primitive_default._updateBoundingVolumes(primitive, frameState, modelMatrix);
let boundingSpheres;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingSpheres = primitive._boundingSphereWC;
} else if (frameState.mode === SceneMode_default.COLUMBUS_VIEW) {
boundingSpheres = primitive._boundingSphereCV;
} else if (frameState.mode === SceneMode_default.SCENE2D && defined_default(primitive._boundingSphere2D)) {
boundingSpheres = primitive._boundingSphere2D;
} else if (defined_default(primitive._boundingSphereMorph)) {
boundingSpheres = primitive._boundingSphereMorph;
}
const morphing = frameState.mode === SceneMode_default.MORPHING;
const classificationType = groundPolylinePrimitive.classificationType;
const queueTerrainCommands = classificationType !== ClassificationType_default.CESIUM_3D_TILE;
const queue3DTilesCommands = classificationType !== ClassificationType_default.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,
debugShowBoundingVolume2
);
}
if (queue3DTilesCommands) {
command = colorCommands[j].derivedCommands.tileset;
updateAndQueueCommand(
groundPolylinePrimitive,
command,
frameState,
modelMatrix,
cull,
boundingVolume,
debugShowBoundingVolume2
);
}
}
}
}
GroundPolylinePrimitive.prototype.update = function(frameState) {
if (!defined_default(this._primitive) && !defined_default(this.geometryInstances)) {
return;
}
if (!ApproximateTerrainHeights_default.initialized) {
if (!this.asynchronous) {
throw new DeveloperError_default(
"For synchronous GroundPolylinePrimitives, you must call GroundPolylinePrimitives.initializeTerrainHeights() and wait for the returned promise to resolve."
);
}
GroundPolylinePrimitive.initializeTerrainHeights();
return;
}
let i;
const that = this;
const primitiveOptions = this._primitiveOptions;
if (!defined_default(this._primitive)) {
const geometryInstances = Array.isArray(this.geometryInstances) ? this.geometryInstances : [this.geometryInstances];
const geometryInstancesLength = geometryInstances.length;
const groundInstances = new Array(geometryInstancesLength);
let attributes;
for (i = 0; i < geometryInstancesLength; ++i) {
attributes = geometryInstances[i].attributes;
if (!defined_default(attributes) || !defined_default(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];
}
}
if (!defined_default(attributes.width)) {
attributes.width = new GeometryInstanceAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
value: [geometryInstance.geometry.width]
});
}
geometryInstance.geometry._scene3DOnly = frameState.scene3DOnly;
GroundPolylineGeometry_default.setProjectionAndEllipsoid(
geometryInstance.geometry,
frameState.mapProjection
);
groundInstances[i] = new GeometryInstance_default({
geometry: geometryInstance.geometry,
attributes,
id: geometryInstance.id,
pickPrimitive: that
});
}
primitiveOptions.geometryInstances = groundInstances;
primitiveOptions.appearance = this.appearance;
primitiveOptions._createShaderProgramFunction = function(primitive, frameState2, appearance) {
createShaderProgram3(that, frameState2, appearance);
};
primitiveOptions._createCommandsFunction = function(primitive, appearance, material, translucent, twoPasses, colorCommands, pickCommands) {
createCommands3(
that,
appearance,
material,
translucent,
colorCommands,
pickCommands
);
};
primitiveOptions._updateAndQueueCommandsFunction = function(primitive, frameState2, colorCommands, pickCommands, modelMatrix, cull, debugShowBoundingVolume2, twoPasses) {
updateAndQueueCommands4(
that,
frameState2,
colorCommands,
pickCommands,
modelMatrix,
cull,
debugShowBoundingVolume2
);
};
this._primitive = new Primitive_default(primitiveOptions);
}
if (this.appearance instanceof PolylineColorAppearance_default && !this._hasPerInstanceColors) {
throw new DeveloperError_default(
"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);
frameState.afterRender.push(() => {
if (!this._ready && defined_default(this._primitive) && this._primitive.ready) {
this._completeLoad();
}
});
};
GroundPolylinePrimitive.prototype.getGeometryInstanceAttributes = function(id) {
if (!defined_default(this._primitive)) {
throw new DeveloperError_default(
"must call update before calling getGeometryInstanceAttributes"
);
}
return this._primitive.getGeometryInstanceAttributes(id);
};
GroundPolylinePrimitive.isSupported = function(scene) {
return scene.frameState.context.depthTexture;
};
GroundPolylinePrimitive.prototype.isDestroyed = function() {
return false;
};
GroundPolylinePrimitive.prototype.destroy = function() {
this._primitive = this._primitive && this._primitive.destroy();
this._sp = this._sp && this._sp.destroy();
this._sp2D = void 0;
this._spMorph = void 0;
return destroyObject_default(this);
};
var GroundPolylinePrimitive_default = GroundPolylinePrimitive;
// node_modules/@cesium/engine/Source/DataSources/ImageMaterialProperty.js
var defaultRepeat = new Cartesian2_default(1, 1);
var defaultTransparent = false;
var defaultColor2 = Color_default.WHITE;
function ImageMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._image = void 0;
this._imageSubscription = void 0;
this._repeat = void 0;
this._repeatSubscription = void 0;
this._color = void 0;
this._colorSubscription = void 0;
this._transparent = void 0;
this._transparentSubscription = void 0;
this.image = options.image;
this.repeat = options.repeat;
this.color = options.color;
this.transparent = options.transparent;
}
Object.defineProperties(ImageMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._image) && Property_default.isConstant(this._repeat);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
image: createPropertyDescriptor_default("image"),
repeat: createPropertyDescriptor_default("repeat"),
color: createPropertyDescriptor_default("color"),
transparent: createPropertyDescriptor_default("transparent")
});
ImageMaterialProperty.prototype.getType = function(time) {
return "Image";
};
ImageMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.image = Property_default.getValueOrUndefined(this._image, time);
result.repeat = Property_default.getValueOrClonedDefault(
this._repeat,
time,
defaultRepeat,
result.repeat
);
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
defaultColor2,
result.color
);
if (Property_default.getValueOrDefault(this._transparent, time, defaultTransparent)) {
result.color.alpha = Math.min(0.99, result.color.alpha);
}
return result;
};
ImageMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof ImageMaterialProperty && Property_default.equals(this._image, other._image) && Property_default.equals(this._repeat, other._repeat) && Property_default.equals(this._color, other._color) && Property_default.equals(this._transparent, other._transparent);
};
var ImageMaterialProperty_default = ImageMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/createMaterialPropertyDescriptor.js
function createMaterialProperty(value) {
if (value instanceof Color_default) {
return new ColorMaterialProperty_default(value);
}
if (typeof value === "string" || value instanceof Resource_default || value instanceof HTMLCanvasElement || value instanceof HTMLVideoElement) {
const result = new ImageMaterialProperty_default();
result.image = value;
return result;
}
throw new DeveloperError_default(`Unable to infer material type: ${value}`);
}
function createMaterialPropertyDescriptor(name, configurable) {
return createPropertyDescriptor_default(name, configurable, createMaterialProperty);
}
var createMaterialPropertyDescriptor_default = createMaterialPropertyDescriptor;
// node_modules/@cesium/engine/Source/DataSources/BoxGraphics.js
function BoxGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._dimensions = void 0;
this._dimensionsSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(BoxGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
dimensions: createPropertyDescriptor_default("dimensions"),
heightReference: createPropertyDescriptor_default("heightReference"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
BoxGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
BoxGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.dimensions = defaultValue_default(this.dimensions, source.dimensions);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var BoxGraphics_default = BoxGraphics;
// node_modules/@cesium/engine/Source/Core/ReferenceFrame.js
var ReferenceFrame = {
FIXED: 0,
INERTIAL: 1
};
var ReferenceFrame_default = Object.freeze(ReferenceFrame);
// node_modules/@cesium/engine/Source/DataSources/PositionProperty.js
function PositionProperty() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(PositionProperty.prototype, {
isConstant: {
get: DeveloperError_default.throwInstantiationError
},
definitionChanged: {
get: DeveloperError_default.throwInstantiationError
},
referenceFrame: {
get: DeveloperError_default.throwInstantiationError
}
});
PositionProperty.prototype.getValue = DeveloperError_default.throwInstantiationError;
PositionProperty.prototype.getValueInReferenceFrame = DeveloperError_default.throwInstantiationError;
PositionProperty.prototype.equals = DeveloperError_default.throwInstantiationError;
var scratchMatrix3 = new Matrix3_default();
PositionProperty.convertToReferenceFrame = function(time, value, inputFrame, outputFrame, result) {
if (!defined_default(value)) {
return value;
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
if (inputFrame === outputFrame) {
return Cartesian3_default.clone(value, result);
}
let icrfToFixed2 = Transforms_default.computeIcrfToFixedMatrix(time, scratchMatrix3);
if (!defined_default(icrfToFixed2)) {
icrfToFixed2 = Transforms_default.computeTemeToPseudoFixedMatrix(
time,
scratchMatrix3
);
}
if (inputFrame === ReferenceFrame_default.INERTIAL) {
return Matrix3_default.multiplyByVector(icrfToFixed2, value, result);
}
if (inputFrame === ReferenceFrame_default.FIXED) {
return Matrix3_default.multiplyByVector(
Matrix3_default.transpose(icrfToFixed2, scratchMatrix3),
value,
result
);
}
};
var PositionProperty_default = PositionProperty;
// node_modules/@cesium/engine/Source/DataSources/ConstantPositionProperty.js
function ConstantPositionProperty(value, referenceFrame) {
this._definitionChanged = new Event_default();
this._value = Cartesian3_default.clone(value);
this._referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
}
Object.defineProperties(ConstantPositionProperty.prototype, {
isConstant: {
get: function() {
return !defined_default(this._value) || this._referenceFrame === ReferenceFrame_default.FIXED;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
referenceFrame: {
get: function() {
return this._referenceFrame;
}
}
});
ConstantPositionProperty.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
ConstantPositionProperty.prototype.setValue = function(value, referenceFrame) {
let definitionChanged = false;
if (!Cartesian3_default.equals(this._value, value)) {
definitionChanged = true;
this._value = Cartesian3_default.clone(value);
}
if (defined_default(referenceFrame) && this._referenceFrame !== referenceFrame) {
definitionChanged = true;
this._referenceFrame = referenceFrame;
}
if (definitionChanged) {
this._definitionChanged.raiseEvent(this);
}
};
ConstantPositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!defined_default(referenceFrame)) {
throw new DeveloperError_default("referenceFrame is required.");
}
return PositionProperty_default.convertToReferenceFrame(
time,
this._value,
this._referenceFrame,
referenceFrame,
result
);
};
ConstantPositionProperty.prototype.equals = function(other) {
return this === other || other instanceof ConstantPositionProperty && Cartesian3_default.equals(this._value, other._value) && this._referenceFrame === other._referenceFrame;
};
var ConstantPositionProperty_default = ConstantPositionProperty;
// node_modules/@cesium/engine/Source/DataSources/CorridorGraphics.js
function CorridorGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._positions = void 0;
this._positionsSubscription = void 0;
this._width = void 0;
this._widthSubscription = void 0;
this._height = void 0;
this._heightSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._extrudedHeight = void 0;
this._extrudedHeightSubscription = void 0;
this._extrudedHeightReference = void 0;
this._extrudedHeightReferenceSubscription = void 0;
this._cornerType = void 0;
this._cornerTypeSubscription = void 0;
this._granularity = void 0;
this._granularitySubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._classificationType = void 0;
this._classificationTypeSubscription = void 0;
this._zIndex = void 0;
this._zIndexSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(CorridorGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
positions: createPropertyDescriptor_default("positions"),
width: createPropertyDescriptor_default("width"),
height: createPropertyDescriptor_default("height"),
heightReference: createPropertyDescriptor_default("heightReference"),
extrudedHeight: createPropertyDescriptor_default("extrudedHeight"),
extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"),
cornerType: createPropertyDescriptor_default("cornerType"),
granularity: createPropertyDescriptor_default("granularity"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
classificationType: createPropertyDescriptor_default("classificationType"),
zIndex: createPropertyDescriptor_default("zIndex")
});
CorridorGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
CorridorGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.positions = defaultValue_default(this.positions, source.positions);
this.width = defaultValue_default(this.width, source.width);
this.height = defaultValue_default(this.height, source.height);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.extrudedHeight = defaultValue_default(
this.extrudedHeight,
source.extrudedHeight
);
this.extrudedHeightReference = defaultValue_default(
this.extrudedHeightReference,
source.extrudedHeightReference
);
this.cornerType = defaultValue_default(this.cornerType, source.cornerType);
this.granularity = defaultValue_default(this.granularity, source.granularity);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.classificationType = defaultValue_default(
this.classificationType,
source.classificationType
);
this.zIndex = defaultValue_default(this.zIndex, source.zIndex);
};
var CorridorGraphics_default = CorridorGraphics;
// node_modules/@cesium/engine/Source/DataSources/createRawPropertyDescriptor.js
function createRawProperty(value) {
return value;
}
function createRawPropertyDescriptor(name, configurable) {
return createPropertyDescriptor_default(name, configurable, createRawProperty);
}
var createRawPropertyDescriptor_default = createRawPropertyDescriptor;
// node_modules/@cesium/engine/Source/DataSources/CylinderGraphics.js
function CylinderGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._length = void 0;
this._lengthSubscription = void 0;
this._topRadius = void 0;
this._topRadiusSubscription = void 0;
this._bottomRadius = void 0;
this._bottomRadiusSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._numberOfVerticalLines = void 0;
this._numberOfVerticalLinesSubscription = void 0;
this._slices = void 0;
this._slicesSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(CylinderGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
length: createPropertyDescriptor_default("length"),
topRadius: createPropertyDescriptor_default("topRadius"),
bottomRadius: createPropertyDescriptor_default("bottomRadius"),
heightReference: createPropertyDescriptor_default("heightReference"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
numberOfVerticalLines: createPropertyDescriptor_default("numberOfVerticalLines"),
slices: createPropertyDescriptor_default("slices"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
CylinderGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
CylinderGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.length = defaultValue_default(this.length, source.length);
this.topRadius = defaultValue_default(this.topRadius, source.topRadius);
this.bottomRadius = defaultValue_default(this.bottomRadius, source.bottomRadius);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.numberOfVerticalLines = defaultValue_default(
this.numberOfVerticalLines,
source.numberOfVerticalLines
);
this.slices = defaultValue_default(this.slices, source.slices);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var CylinderGraphics_default = CylinderGraphics;
// node_modules/@cesium/engine/Source/DataSources/EllipseGraphics.js
function EllipseGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._semiMajorAxis = void 0;
this._semiMajorAxisSubscription = void 0;
this._semiMinorAxis = void 0;
this._semiMinorAxisSubscription = void 0;
this._height = void 0;
this._heightSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._extrudedHeight = void 0;
this._extrudedHeightSubscription = void 0;
this._extrudedHeightReference = void 0;
this._extrudedHeightReferenceSubscription = void 0;
this._rotation = void 0;
this._rotationSubscription = void 0;
this._stRotation = void 0;
this._stRotationSubscription = void 0;
this._granularity = void 0;
this._granularitySubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._numberOfVerticalLines = void 0;
this._numberOfVerticalLinesSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._classificationType = void 0;
this._classificationTypeSubscription = void 0;
this._zIndex = void 0;
this._zIndexSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(EllipseGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
semiMajorAxis: createPropertyDescriptor_default("semiMajorAxis"),
semiMinorAxis: createPropertyDescriptor_default("semiMinorAxis"),
height: createPropertyDescriptor_default("height"),
heightReference: createPropertyDescriptor_default("heightReference"),
extrudedHeight: createPropertyDescriptor_default("extrudedHeight"),
extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"),
rotation: createPropertyDescriptor_default("rotation"),
stRotation: createPropertyDescriptor_default("stRotation"),
granularity: createPropertyDescriptor_default("granularity"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
numberOfVerticalLines: createPropertyDescriptor_default("numberOfVerticalLines"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
classificationType: createPropertyDescriptor_default("classificationType"),
zIndex: createPropertyDescriptor_default("zIndex")
});
EllipseGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
EllipseGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.semiMajorAxis = defaultValue_default(this.semiMajorAxis, source.semiMajorAxis);
this.semiMinorAxis = defaultValue_default(this.semiMinorAxis, source.semiMinorAxis);
this.height = defaultValue_default(this.height, source.height);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.extrudedHeight = defaultValue_default(
this.extrudedHeight,
source.extrudedHeight
);
this.extrudedHeightReference = defaultValue_default(
this.extrudedHeightReference,
source.extrudedHeightReference
);
this.rotation = defaultValue_default(this.rotation, source.rotation);
this.stRotation = defaultValue_default(this.stRotation, source.stRotation);
this.granularity = defaultValue_default(this.granularity, source.granularity);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.numberOfVerticalLines = defaultValue_default(
this.numberOfVerticalLines,
source.numberOfVerticalLines
);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.classificationType = defaultValue_default(
this.classificationType,
source.classificationType
);
this.zIndex = defaultValue_default(this.zIndex, source.zIndex);
};
var EllipseGraphics_default = EllipseGraphics;
// node_modules/@cesium/engine/Source/DataSources/EllipsoidGraphics.js
function EllipsoidGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._radii = void 0;
this._radiiSubscription = void 0;
this._innerRadii = void 0;
this._innerRadiiSubscription = void 0;
this._minimumClock = void 0;
this._minimumClockSubscription = void 0;
this._maximumClock = void 0;
this._maximumClockSubscription = void 0;
this._minimumCone = void 0;
this._minimumConeSubscription = void 0;
this._maximumCone = void 0;
this._maximumConeSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._stackPartitions = void 0;
this._stackPartitionsSubscription = void 0;
this._slicePartitions = void 0;
this._slicePartitionsSubscription = void 0;
this._subdivisions = void 0;
this._subdivisionsSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(EllipsoidGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
radii: createPropertyDescriptor_default("radii"),
innerRadii: createPropertyDescriptor_default("innerRadii"),
minimumClock: createPropertyDescriptor_default("minimumClock"),
maximumClock: createPropertyDescriptor_default("maximumClock"),
minimumCone: createPropertyDescriptor_default("minimumCone"),
maximumCone: createPropertyDescriptor_default("maximumCone"),
heightReference: createPropertyDescriptor_default("heightReference"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
stackPartitions: createPropertyDescriptor_default("stackPartitions"),
slicePartitions: createPropertyDescriptor_default("slicePartitions"),
subdivisions: createPropertyDescriptor_default("subdivisions"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
EllipsoidGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
EllipsoidGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.radii = defaultValue_default(this.radii, source.radii);
this.innerRadii = defaultValue_default(this.innerRadii, source.innerRadii);
this.minimumClock = defaultValue_default(this.minimumClock, source.minimumClock);
this.maximumClock = defaultValue_default(this.maximumClock, source.maximumClock);
this.minimumCone = defaultValue_default(this.minimumCone, source.minimumCone);
this.maximumCone = defaultValue_default(this.maximumCone, source.maximumCone);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.stackPartitions = defaultValue_default(
this.stackPartitions,
source.stackPartitions
);
this.slicePartitions = defaultValue_default(
this.slicePartitions,
source.slicePartitions
);
this.subdivisions = defaultValue_default(this.subdivisions, source.subdivisions);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var EllipsoidGraphics_default = EllipsoidGraphics;
// node_modules/@cesium/engine/Source/DataSources/LabelGraphics.js
function LabelGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._text = void 0;
this._textSubscription = void 0;
this._font = void 0;
this._fontSubscription = void 0;
this._style = void 0;
this._styleSubscription = void 0;
this._scale = void 0;
this._scaleSubscription = void 0;
this._showBackground = void 0;
this._showBackgroundSubscription = void 0;
this._backgroundColor = void 0;
this._backgroundColorSubscription = void 0;
this._backgroundPadding = void 0;
this._backgroundPaddingSubscription = void 0;
this._pixelOffset = void 0;
this._pixelOffsetSubscription = void 0;
this._eyeOffset = void 0;
this._eyeOffsetSubscription = void 0;
this._horizontalOrigin = void 0;
this._horizontalOriginSubscription = void 0;
this._verticalOrigin = void 0;
this._verticalOriginSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._fillColor = void 0;
this._fillColorSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._translucencyByDistance = void 0;
this._translucencyByDistanceSubscription = void 0;
this._pixelOffsetScaleByDistance = void 0;
this._pixelOffsetScaleByDistanceSubscription = void 0;
this._scaleByDistance = void 0;
this._scaleByDistanceSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._disableDepthTestDistance = void 0;
this._disableDepthTestDistanceSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(LabelGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
text: createPropertyDescriptor_default("text"),
font: createPropertyDescriptor_default("font"),
style: createPropertyDescriptor_default("style"),
scale: createPropertyDescriptor_default("scale"),
showBackground: createPropertyDescriptor_default("showBackground"),
backgroundColor: createPropertyDescriptor_default("backgroundColor"),
backgroundPadding: createPropertyDescriptor_default("backgroundPadding"),
pixelOffset: createPropertyDescriptor_default("pixelOffset"),
eyeOffset: createPropertyDescriptor_default("eyeOffset"),
horizontalOrigin: createPropertyDescriptor_default("horizontalOrigin"),
verticalOrigin: createPropertyDescriptor_default("verticalOrigin"),
heightReference: createPropertyDescriptor_default("heightReference"),
fillColor: createPropertyDescriptor_default("fillColor"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
translucencyByDistance: createPropertyDescriptor_default("translucencyByDistance"),
pixelOffsetScaleByDistance: createPropertyDescriptor_default(
"pixelOffsetScaleByDistance"
),
scaleByDistance: createPropertyDescriptor_default("scaleByDistance"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
disableDepthTestDistance: createPropertyDescriptor_default(
"disableDepthTestDistance"
)
});
LabelGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
LabelGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.text = defaultValue_default(this.text, source.text);
this.font = defaultValue_default(this.font, source.font);
this.style = defaultValue_default(this.style, source.style);
this.scale = defaultValue_default(this.scale, source.scale);
this.showBackground = defaultValue_default(
this.showBackground,
source.showBackground
);
this.backgroundColor = defaultValue_default(
this.backgroundColor,
source.backgroundColor
);
this.backgroundPadding = defaultValue_default(
this.backgroundPadding,
source.backgroundPadding
);
this.pixelOffset = defaultValue_default(this.pixelOffset, source.pixelOffset);
this.eyeOffset = defaultValue_default(this.eyeOffset, source.eyeOffset);
this.horizontalOrigin = defaultValue_default(
this.horizontalOrigin,
source.horizontalOrigin
);
this.verticalOrigin = defaultValue_default(
this.verticalOrigin,
source.verticalOrigin
);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.fillColor = defaultValue_default(this.fillColor, source.fillColor);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.translucencyByDistance = defaultValue_default(
this.translucencyByDistance,
source.translucencyByDistance
);
this.pixelOffsetScaleByDistance = defaultValue_default(
this.pixelOffsetScaleByDistance,
source.pixelOffsetScaleByDistance
);
this.scaleByDistance = defaultValue_default(
this.scaleByDistance,
source.scaleByDistance
);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.disableDepthTestDistance = defaultValue_default(
this.disableDepthTestDistance,
source.disableDepthTestDistance
);
};
var LabelGraphics_default = LabelGraphics;
// node_modules/@cesium/engine/Source/Core/TranslationRotationScale.js
var defaultScale2 = new Cartesian3_default(1, 1, 1);
var defaultTranslation = Cartesian3_default.ZERO;
var defaultRotation2 = Quaternion_default.IDENTITY;
function TranslationRotationScale(translation3, rotation, scale) {
this.translation = Cartesian3_default.clone(
defaultValue_default(translation3, defaultTranslation)
);
this.rotation = Quaternion_default.clone(defaultValue_default(rotation, defaultRotation2));
this.scale = Cartesian3_default.clone(defaultValue_default(scale, defaultScale2));
}
TranslationRotationScale.prototype.equals = function(right) {
return this === right || defined_default(right) && Cartesian3_default.equals(this.translation, right.translation) && Quaternion_default.equals(this.rotation, right.rotation) && Cartesian3_default.equals(this.scale, right.scale);
};
var TranslationRotationScale_default = TranslationRotationScale;
// node_modules/@cesium/engine/Source/DataSources/NodeTransformationProperty.js
var defaultNodeTransformation = new TranslationRotationScale_default();
function NodeTransformationProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._translation = void 0;
this._translationSubscription = void 0;
this._rotation = void 0;
this._rotationSubscription = void 0;
this._scale = void 0;
this._scaleSubscription = void 0;
this.translation = options.translation;
this.rotation = options.rotation;
this.scale = options.scale;
}
Object.defineProperties(NodeTransformationProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._translation) && Property_default.isConstant(this._rotation) && Property_default.isConstant(this._scale);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
translation: createPropertyDescriptor_default("translation"),
rotation: createPropertyDescriptor_default("rotation"),
scale: createPropertyDescriptor_default("scale")
});
NodeTransformationProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = new TranslationRotationScale_default();
}
result.translation = Property_default.getValueOrClonedDefault(
this._translation,
time,
defaultNodeTransformation.translation,
result.translation
);
result.rotation = Property_default.getValueOrClonedDefault(
this._rotation,
time,
defaultNodeTransformation.rotation,
result.rotation
);
result.scale = Property_default.getValueOrClonedDefault(
this._scale,
time,
defaultNodeTransformation.scale,
result.scale
);
return result;
};
NodeTransformationProperty.prototype.equals = function(other) {
return this === other || other instanceof NodeTransformationProperty && Property_default.equals(this._translation, other._translation) && Property_default.equals(this._rotation, other._rotation) && Property_default.equals(this._scale, other._scale);
};
var NodeTransformationProperty_default = NodeTransformationProperty;
// node_modules/@cesium/engine/Source/DataSources/PropertyBag.js
function PropertyBag(value, createPropertyCallback) {
this._propertyNames = [];
this._definitionChanged = new Event_default();
if (defined_default(value)) {
this.merge(value, createPropertyCallback);
}
}
Object.defineProperties(PropertyBag.prototype, {
propertyNames: {
get: function() {
return this._propertyNames;
}
},
isConstant: {
get: function() {
const propertyNames = this._propertyNames;
for (let i = 0, len = propertyNames.length; i < len; i++) {
if (!Property_default.isConstant(this[propertyNames[i]])) {
return false;
}
}
return true;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
}
});
PropertyBag.prototype.hasProperty = function(propertyName) {
return this._propertyNames.indexOf(propertyName) !== -1;
};
function createConstantProperty2(value) {
return new ConstantProperty_default(value);
}
PropertyBag.prototype.addProperty = function(propertyName, value, createPropertyCallback) {
const propertyNames = this._propertyNames;
if (!defined_default(propertyName)) {
throw new DeveloperError_default("propertyName is required.");
}
if (propertyNames.indexOf(propertyName) !== -1) {
throw new DeveloperError_default(
`${propertyName} is already a registered property.`
);
}
propertyNames.push(propertyName);
Object.defineProperty(
this,
propertyName,
createPropertyDescriptor_default(
propertyName,
true,
defaultValue_default(createPropertyCallback, createConstantProperty2)
)
);
if (defined_default(value)) {
this[propertyName] = value;
}
this._definitionChanged.raiseEvent(this);
};
PropertyBag.prototype.removeProperty = function(propertyName) {
const propertyNames = this._propertyNames;
const index = propertyNames.indexOf(propertyName);
if (!defined_default(propertyName)) {
throw new DeveloperError_default("propertyName is required.");
}
if (index === -1) {
throw new DeveloperError_default(`${propertyName} is not a registered property.`);
}
this._propertyNames.splice(index, 1);
delete this[propertyName];
this._definitionChanged.raiseEvent(this);
};
PropertyBag.prototype.getValue = function(time, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!defined_default(result)) {
result = {};
}
const propertyNames = this._propertyNames;
for (let i = 0, len = propertyNames.length; i < len; i++) {
const propertyName = propertyNames[i];
result[propertyName] = Property_default.getValueOrUndefined(
this[propertyName],
time,
result[propertyName]
);
}
return result;
};
PropertyBag.prototype.merge = function(source, createPropertyCallback) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
const propertyNames = this._propertyNames;
const sourcePropertyNames = defined_default(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];
if (targetProperty === void 0 && propertyNames.indexOf(name) === -1) {
this.addProperty(name, void 0, createPropertyCallback);
}
if (sourceProperty !== void 0) {
if (targetProperty !== void 0) {
if (defined_default(targetProperty) && defined_default(targetProperty.merge)) {
targetProperty.merge(sourceProperty);
}
} else if (defined_default(sourceProperty) && defined_default(sourceProperty.merge) && defined_default(sourceProperty.clone)) {
this[name] = sourceProperty.clone();
} else {
this[name] = sourceProperty;
}
}
}
};
function propertiesEqual(a3, b) {
const aPropertyNames = a3._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_default.equals(a3[name], b[name])) {
return false;
}
}
return true;
}
PropertyBag.prototype.equals = function(other) {
return this === other || other instanceof PropertyBag && propertiesEqual(this, other);
};
var PropertyBag_default = PropertyBag;
// node_modules/@cesium/engine/Source/DataSources/ModelGraphics.js
function createNodeTransformationProperty(value) {
return new NodeTransformationProperty_default(value);
}
function createNodeTransformationPropertyBag(value) {
return new PropertyBag_default(value, createNodeTransformationProperty);
}
function createArticulationStagePropertyBag(value) {
return new PropertyBag_default(value);
}
function ModelGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._uri = void 0;
this._uriSubscription = void 0;
this._scale = void 0;
this._scaleSubscription = void 0;
this._minimumPixelSize = void 0;
this._minimumPixelSizeSubscription = void 0;
this._maximumScale = void 0;
this._maximumScaleSubscription = void 0;
this._incrementallyLoadTextures = void 0;
this._incrementallyLoadTexturesSubscription = void 0;
this._runAnimations = void 0;
this._runAnimationsSubscription = void 0;
this._clampAnimations = void 0;
this._clampAnimationsSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._silhouetteColor = void 0;
this._silhouetteColorSubscription = void 0;
this._silhouetteSize = void 0;
this._silhouetteSizeSubscription = void 0;
this._color = void 0;
this._colorSubscription = void 0;
this._colorBlendMode = void 0;
this._colorBlendModeSubscription = void 0;
this._colorBlendAmount = void 0;
this._colorBlendAmountSubscription = void 0;
this._imageBasedLightingFactor = void 0;
this._imageBasedLightingFactorSubscription = void 0;
this._lightColor = void 0;
this._lightColorSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._nodeTransformations = void 0;
this._nodeTransformationsSubscription = void 0;
this._articulations = void 0;
this._articulationsSubscription = void 0;
this._clippingPlanes = void 0;
this._clippingPlanesSubscription = void 0;
this._customShader = void 0;
this._customShaderSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(ModelGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
uri: createPropertyDescriptor_default("uri"),
scale: createPropertyDescriptor_default("scale"),
minimumPixelSize: createPropertyDescriptor_default("minimumPixelSize"),
maximumScale: createPropertyDescriptor_default("maximumScale"),
incrementallyLoadTextures: createPropertyDescriptor_default(
"incrementallyLoadTextures"
),
runAnimations: createPropertyDescriptor_default("runAnimations"),
clampAnimations: createPropertyDescriptor_default("clampAnimations"),
shadows: createPropertyDescriptor_default("shadows"),
heightReference: createPropertyDescriptor_default("heightReference"),
silhouetteColor: createPropertyDescriptor_default("silhouetteColor"),
silhouetteSize: createPropertyDescriptor_default("silhouetteSize"),
color: createPropertyDescriptor_default("color"),
colorBlendMode: createPropertyDescriptor_default("colorBlendMode"),
colorBlendAmount: createPropertyDescriptor_default("colorBlendAmount"),
imageBasedLightingFactor: createPropertyDescriptor_default(
"imageBasedLightingFactor"
),
lightColor: createPropertyDescriptor_default("lightColor"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
nodeTransformations: createPropertyDescriptor_default(
"nodeTransformations",
void 0,
createNodeTransformationPropertyBag
),
articulations: createPropertyDescriptor_default(
"articulations",
void 0,
createArticulationStagePropertyBag
),
clippingPlanes: createPropertyDescriptor_default("clippingPlanes"),
customShader: createPropertyDescriptor_default("customShader")
});
ModelGraphics.prototype.clone = function(result) {
if (!defined_default(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;
result.customShader = this.customShader;
return result;
};
ModelGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.uri = defaultValue_default(this.uri, source.uri);
this.scale = defaultValue_default(this.scale, source.scale);
this.minimumPixelSize = defaultValue_default(
this.minimumPixelSize,
source.minimumPixelSize
);
this.maximumScale = defaultValue_default(this.maximumScale, source.maximumScale);
this.incrementallyLoadTextures = defaultValue_default(
this.incrementallyLoadTextures,
source.incrementallyLoadTextures
);
this.runAnimations = defaultValue_default(this.runAnimations, source.runAnimations);
this.clampAnimations = defaultValue_default(
this.clampAnimations,
source.clampAnimations
);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.silhouetteColor = defaultValue_default(
this.silhouetteColor,
source.silhouetteColor
);
this.silhouetteSize = defaultValue_default(
this.silhouetteSize,
source.silhouetteSize
);
this.color = defaultValue_default(this.color, source.color);
this.colorBlendMode = defaultValue_default(
this.colorBlendMode,
source.colorBlendMode
);
this.colorBlendAmount = defaultValue_default(
this.colorBlendAmount,
source.colorBlendAmount
);
this.imageBasedLightingFactor = defaultValue_default(
this.imageBasedLightingFactor,
source.imageBasedLightingFactor
);
this.lightColor = defaultValue_default(this.lightColor, source.lightColor);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.clippingPlanes = defaultValue_default(
this.clippingPlanes,
source.clippingPlanes
);
this.customShader = defaultValue_default(this.customShader, source.customShader);
const sourceNodeTransformations = source.nodeTransformations;
if (defined_default(sourceNodeTransformations)) {
const targetNodeTransformations = this.nodeTransformations;
if (defined_default(targetNodeTransformations)) {
targetNodeTransformations.merge(sourceNodeTransformations);
} else {
this.nodeTransformations = new PropertyBag_default(
sourceNodeTransformations,
createNodeTransformationProperty
);
}
}
const sourceArticulations = source.articulations;
if (defined_default(sourceArticulations)) {
const targetArticulations = this.articulations;
if (defined_default(targetArticulations)) {
targetArticulations.merge(sourceArticulations);
} else {
this.articulations = new PropertyBag_default(sourceArticulations);
}
}
};
var ModelGraphics_default = ModelGraphics;
// node_modules/@cesium/engine/Source/DataSources/Cesium3DTilesetGraphics.js
function Cesium3DTilesetGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._uri = void 0;
this._uriSubscription = void 0;
this._maximumScreenSpaceError = void 0;
this._maximumScreenSpaceErrorSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(Cesium3DTilesetGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
uri: createPropertyDescriptor_default("uri"),
maximumScreenSpaceError: createPropertyDescriptor_default("maximumScreenSpaceError")
});
Cesium3DTilesetGraphics.prototype.clone = function(result) {
if (!defined_default(result)) {
return new Cesium3DTilesetGraphics(this);
}
result.show = this.show;
result.uri = this.uri;
result.maximumScreenSpaceError = this.maximumScreenSpaceError;
return result;
};
Cesium3DTilesetGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.uri = defaultValue_default(this.uri, source.uri);
this.maximumScreenSpaceError = defaultValue_default(
this.maximumScreenSpaceError,
source.maximumScreenSpaceError
);
};
var Cesium3DTilesetGraphics_default = Cesium3DTilesetGraphics;
// node_modules/@cesium/engine/Source/DataSources/PathGraphics.js
function PathGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._leadTime = void 0;
this._leadTimeSubscription = void 0;
this._trailTime = void 0;
this._trailTimeSubscription = void 0;
this._width = void 0;
this._widthSubscription = void 0;
this._resolution = void 0;
this._resolutionSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PathGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
leadTime: createPropertyDescriptor_default("leadTime"),
trailTime: createPropertyDescriptor_default("trailTime"),
width: createPropertyDescriptor_default("width"),
resolution: createPropertyDescriptor_default("resolution"),
material: createMaterialPropertyDescriptor_default("material"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
PathGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
PathGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.leadTime = defaultValue_default(this.leadTime, source.leadTime);
this.trailTime = defaultValue_default(this.trailTime, source.trailTime);
this.width = defaultValue_default(this.width, source.width);
this.resolution = defaultValue_default(this.resolution, source.resolution);
this.material = defaultValue_default(this.material, source.material);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var PathGraphics_default = PathGraphics;
// node_modules/@cesium/engine/Source/DataSources/PlaneGraphics.js
function PlaneGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._plane = void 0;
this._planeSubscription = void 0;
this._dimensions = void 0;
this._dimensionsSubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PlaneGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
plane: createPropertyDescriptor_default("plane"),
dimensions: createPropertyDescriptor_default("dimensions"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
PlaneGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
PlaneGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.plane = defaultValue_default(this.plane, source.plane);
this.dimensions = defaultValue_default(this.dimensions, source.dimensions);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var PlaneGraphics_default = PlaneGraphics;
// node_modules/@cesium/engine/Source/DataSources/PointGraphics.js
function PointGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._pixelSize = void 0;
this._pixelSizeSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._color = void 0;
this._colorSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._scaleByDistance = void 0;
this._scaleByDistanceSubscription = void 0;
this._translucencyByDistance = void 0;
this._translucencyByDistanceSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._disableDepthTestDistance = void 0;
this._disableDepthTestDistanceSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PointGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
pixelSize: createPropertyDescriptor_default("pixelSize"),
heightReference: createPropertyDescriptor_default("heightReference"),
color: createPropertyDescriptor_default("color"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
scaleByDistance: createPropertyDescriptor_default("scaleByDistance"),
translucencyByDistance: createPropertyDescriptor_default("translucencyByDistance"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
disableDepthTestDistance: createPropertyDescriptor_default(
"disableDepthTestDistance"
)
});
PointGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
PointGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.pixelSize = defaultValue_default(this.pixelSize, source.pixelSize);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.color = defaultValue_default(this.color, source.color);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.scaleByDistance = defaultValue_default(
this.scaleByDistance,
source.scaleByDistance
);
this.translucencyByDistance = defaultValue_default(
this._translucencyByDistance,
source.translucencyByDistance
);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.disableDepthTestDistance = defaultValue_default(
this.disableDepthTestDistance,
source.disableDepthTestDistance
);
};
var PointGraphics_default = PointGraphics;
// node_modules/@cesium/engine/Source/Core/PolygonHierarchy.js
function PolygonHierarchy(positions, holes) {
this.positions = defined_default(positions) ? positions : [];
this.holes = defined_default(holes) ? holes : [];
}
var PolygonHierarchy_default = PolygonHierarchy;
// node_modules/@cesium/engine/Source/DataSources/PolygonGraphics.js
function createPolygonHierarchyProperty(value) {
if (Array.isArray(value)) {
value = new PolygonHierarchy_default(value);
}
return new ConstantProperty_default(value);
}
function PolygonGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._hierarchy = void 0;
this._hierarchySubscription = void 0;
this._height = void 0;
this._heightSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._extrudedHeight = void 0;
this._extrudedHeightSubscription = void 0;
this._extrudedHeightReference = void 0;
this._extrudedHeightReferenceSubscription = void 0;
this._stRotation = void 0;
this._stRotationSubscription = void 0;
this._granularity = void 0;
this._granularitySubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._perPositionHeight = void 0;
this._perPositionHeightSubscription = void 0;
this._closeTop = void 0;
this._closeTopSubscription = void 0;
this._closeBottom = void 0;
this._closeBottomSubscription = void 0;
this._arcType = void 0;
this._arcTypeSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._classificationType = void 0;
this._classificationTypeSubscription = void 0;
this._zIndex = void 0;
this._zIndexSubscription = void 0;
this._textureCoordinates = void 0;
this._textureCoordinatesSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PolygonGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
hierarchy: createPropertyDescriptor_default(
"hierarchy",
void 0,
createPolygonHierarchyProperty
),
height: createPropertyDescriptor_default("height"),
heightReference: createPropertyDescriptor_default("heightReference"),
extrudedHeight: createPropertyDescriptor_default("extrudedHeight"),
extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"),
stRotation: createPropertyDescriptor_default("stRotation"),
granularity: createPropertyDescriptor_default("granularity"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
perPositionHeight: createPropertyDescriptor_default("perPositionHeight"),
closeTop: createPropertyDescriptor_default("closeTop"),
closeBottom: createPropertyDescriptor_default("closeBottom"),
arcType: createPropertyDescriptor_default("arcType"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
classificationType: createPropertyDescriptor_default("classificationType"),
zIndex: createPropertyDescriptor_default("zIndex"),
textureCoordinates: createPropertyDescriptor_default("textureCoordinates")
});
PolygonGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
PolygonGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.hierarchy = defaultValue_default(this.hierarchy, source.hierarchy);
this.height = defaultValue_default(this.height, source.height);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.extrudedHeight = defaultValue_default(
this.extrudedHeight,
source.extrudedHeight
);
this.extrudedHeightReference = defaultValue_default(
this.extrudedHeightReference,
source.extrudedHeightReference
);
this.stRotation = defaultValue_default(this.stRotation, source.stRotation);
this.granularity = defaultValue_default(this.granularity, source.granularity);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.perPositionHeight = defaultValue_default(
this.perPositionHeight,
source.perPositionHeight
);
this.closeTop = defaultValue_default(this.closeTop, source.closeTop);
this.closeBottom = defaultValue_default(this.closeBottom, source.closeBottom);
this.arcType = defaultValue_default(this.arcType, source.arcType);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.classificationType = defaultValue_default(
this.classificationType,
source.classificationType
);
this.zIndex = defaultValue_default(this.zIndex, source.zIndex);
this.textureCoordinates = defaultValue_default(
this.textureCoordinates,
source.textureCoordinates
);
};
var PolygonGraphics_default = PolygonGraphics;
// node_modules/@cesium/engine/Source/DataSources/PolylineGraphics.js
function PolylineGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._positions = void 0;
this._positionsSubscription = void 0;
this._width = void 0;
this._widthSubscription = void 0;
this._granularity = void 0;
this._granularitySubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._depthFailMaterial = void 0;
this._depthFailMaterialSubscription = void 0;
this._arcType = void 0;
this._arcTypeSubscription = void 0;
this._clampToGround = void 0;
this._clampToGroundSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this._classificationType = void 0;
this._classificationTypeSubscription = void 0;
this._zIndex = void 0;
this._zIndexSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PolylineGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
positions: createPropertyDescriptor_default("positions"),
width: createPropertyDescriptor_default("width"),
granularity: createPropertyDescriptor_default("granularity"),
material: createMaterialPropertyDescriptor_default("material"),
depthFailMaterial: createMaterialPropertyDescriptor_default("depthFailMaterial"),
arcType: createPropertyDescriptor_default("arcType"),
clampToGround: createPropertyDescriptor_default("clampToGround"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
classificationType: createPropertyDescriptor_default("classificationType"),
zIndex: createPropertyDescriptor_default("zIndex")
});
PolylineGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
PolylineGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.positions = defaultValue_default(this.positions, source.positions);
this.width = defaultValue_default(this.width, source.width);
this.granularity = defaultValue_default(this.granularity, source.granularity);
this.material = defaultValue_default(this.material, source.material);
this.depthFailMaterial = defaultValue_default(
this.depthFailMaterial,
source.depthFailMaterial
);
this.arcType = defaultValue_default(this.arcType, source.arcType);
this.clampToGround = defaultValue_default(this.clampToGround, source.clampToGround);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.classificationType = defaultValue_default(
this.classificationType,
source.classificationType
);
this.zIndex = defaultValue_default(this.zIndex, source.zIndex);
};
var PolylineGraphics_default = PolylineGraphics;
// node_modules/@cesium/engine/Source/DataSources/PolylineVolumeGraphics.js
function PolylineVolumeGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._positions = void 0;
this._positionsSubscription = void 0;
this._shape = void 0;
this._shapeSubscription = void 0;
this._cornerType = void 0;
this._cornerTypeSubscription = void 0;
this._granularity = void 0;
this._granularitySubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubsription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(PolylineVolumeGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
positions: createPropertyDescriptor_default("positions"),
shape: createPropertyDescriptor_default("shape"),
cornerType: createPropertyDescriptor_default("cornerType"),
granularity: createPropertyDescriptor_default("granularity"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
PolylineVolumeGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
PolylineVolumeGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.positions = defaultValue_default(this.positions, source.positions);
this.shape = defaultValue_default(this.shape, source.shape);
this.cornerType = defaultValue_default(this.cornerType, source.cornerType);
this.granularity = defaultValue_default(this.granularity, source.granularity);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var PolylineVolumeGraphics_default = PolylineVolumeGraphics;
// node_modules/@cesium/engine/Source/DataSources/RectangleGraphics.js
function RectangleGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._coordinates = void 0;
this._coordinatesSubscription = void 0;
this._height = void 0;
this._heightSubscription = void 0;
this._heightReference = void 0;
this._heightReferenceSubscription = void 0;
this._extrudedHeight = void 0;
this._extrudedHeightSubscription = void 0;
this._extrudedHeightReference = void 0;
this._extrudedHeightReferenceSubscription = void 0;
this._rotation = void 0;
this._rotationSubscription = void 0;
this._stRotation = void 0;
this._stRotationSubscription = void 0;
this._granularity = void 0;
this._granularitySubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distancedisplayConditionSubscription = void 0;
this._classificationType = void 0;
this._classificationTypeSubscription = void 0;
this._zIndex = void 0;
this._zIndexSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(RectangleGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
coordinates: createPropertyDescriptor_default("coordinates"),
height: createPropertyDescriptor_default("height"),
heightReference: createPropertyDescriptor_default("heightReference"),
extrudedHeight: createPropertyDescriptor_default("extrudedHeight"),
extrudedHeightReference: createPropertyDescriptor_default("extrudedHeightReference"),
rotation: createPropertyDescriptor_default("rotation"),
stRotation: createPropertyDescriptor_default("stRotation"),
granularity: createPropertyDescriptor_default("granularity"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
),
classificationType: createPropertyDescriptor_default("classificationType"),
zIndex: createPropertyDescriptor_default("zIndex")
});
RectangleGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
RectangleGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.coordinates = defaultValue_default(this.coordinates, source.coordinates);
this.height = defaultValue_default(this.height, source.height);
this.heightReference = defaultValue_default(
this.heightReference,
source.heightReference
);
this.extrudedHeight = defaultValue_default(
this.extrudedHeight,
source.extrudedHeight
);
this.extrudedHeightReference = defaultValue_default(
this.extrudedHeightReference,
source.extrudedHeightReference
);
this.rotation = defaultValue_default(this.rotation, source.rotation);
this.stRotation = defaultValue_default(this.stRotation, source.stRotation);
this.granularity = defaultValue_default(this.granularity, source.granularity);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
this.classificationType = defaultValue_default(
this.classificationType,
source.classificationType
);
this.zIndex = defaultValue_default(this.zIndex, source.zIndex);
};
var RectangleGraphics_default = RectangleGraphics;
// node_modules/@cesium/engine/Source/DataSources/WallGraphics.js
function WallGraphics(options) {
this._definitionChanged = new Event_default();
this._show = void 0;
this._showSubscription = void 0;
this._positions = void 0;
this._positionsSubscription = void 0;
this._minimumHeights = void 0;
this._minimumHeightsSubscription = void 0;
this._maximumHeights = void 0;
this._maximumHeightsSubscription = void 0;
this._granularity = void 0;
this._granularitySubscription = void 0;
this._fill = void 0;
this._fillSubscription = void 0;
this._material = void 0;
this._materialSubscription = void 0;
this._outline = void 0;
this._outlineSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this._shadows = void 0;
this._shadowsSubscription = void 0;
this._distanceDisplayCondition = void 0;
this._distanceDisplayConditionSubscription = void 0;
this.merge(defaultValue_default(options, defaultValue_default.EMPTY_OBJECT));
}
Object.defineProperties(WallGraphics.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
show: createPropertyDescriptor_default("show"),
positions: createPropertyDescriptor_default("positions"),
minimumHeights: createPropertyDescriptor_default("minimumHeights"),
maximumHeights: createPropertyDescriptor_default("maximumHeights"),
granularity: createPropertyDescriptor_default("granularity"),
fill: createPropertyDescriptor_default("fill"),
material: createMaterialPropertyDescriptor_default("material"),
outline: createPropertyDescriptor_default("outline"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth"),
shadows: createPropertyDescriptor_default("shadows"),
distanceDisplayCondition: createPropertyDescriptor_default(
"distanceDisplayCondition"
)
});
WallGraphics.prototype.clone = function(result) {
if (!defined_default(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;
};
WallGraphics.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.show = defaultValue_default(this.show, source.show);
this.positions = defaultValue_default(this.positions, source.positions);
this.minimumHeights = defaultValue_default(
this.minimumHeights,
source.minimumHeights
);
this.maximumHeights = defaultValue_default(
this.maximumHeights,
source.maximumHeights
);
this.granularity = defaultValue_default(this.granularity, source.granularity);
this.fill = defaultValue_default(this.fill, source.fill);
this.material = defaultValue_default(this.material, source.material);
this.outline = defaultValue_default(this.outline, source.outline);
this.outlineColor = defaultValue_default(this.outlineColor, source.outlineColor);
this.outlineWidth = defaultValue_default(this.outlineWidth, source.outlineWidth);
this.shadows = defaultValue_default(this.shadows, source.shadows);
this.distanceDisplayCondition = defaultValue_default(
this.distanceDisplayCondition,
source.distanceDisplayCondition
);
};
var WallGraphics_default = WallGraphics;
// node_modules/@cesium/engine/Source/DataSources/Entity.js
var cartoScratch = new Cartographic_default();
function createConstantPositionProperty(value) {
return new ConstantPositionProperty_default(value);
}
function createPositionPropertyDescriptor(name) {
return createPropertyDescriptor_default(
name,
void 0,
createConstantPositionProperty
);
}
function createPropertyTypeDescriptor(name, Type) {
return createPropertyDescriptor_default(name, void 0, function(value) {
if (value instanceof Type) {
return value;
}
return new Type(value);
});
}
function Entity(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let id = options.id;
if (!defined_default(id)) {
id = createGuid_default();
}
this._availability = void 0;
this._id = id;
this._definitionChanged = new Event_default();
this._name = options.name;
this._show = defaultValue_default(options.show, true);
this._parent = void 0;
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 = void 0;
this._billboardSubscription = void 0;
this._box = void 0;
this._boxSubscription = void 0;
this._corridor = void 0;
this._corridorSubscription = void 0;
this._cylinder = void 0;
this._cylinderSubscription = void 0;
this._description = void 0;
this._descriptionSubscription = void 0;
this._ellipse = void 0;
this._ellipseSubscription = void 0;
this._ellipsoid = void 0;
this._ellipsoidSubscription = void 0;
this._label = void 0;
this._labelSubscription = void 0;
this._model = void 0;
this._modelSubscription = void 0;
this._tileset = void 0;
this._tilesetSubscription = void 0;
this._orientation = void 0;
this._orientationSubscription = void 0;
this._path = void 0;
this._pathSubscription = void 0;
this._plane = void 0;
this._planeSubscription = void 0;
this._point = void 0;
this._pointSubscription = void 0;
this._polygon = void 0;
this._polygonSubscription = void 0;
this._polyline = void 0;
this._polylineSubscription = void 0;
this._polylineVolume = void 0;
this._polylineVolumeSubscription = void 0;
this._position = void 0;
this._positionSubscription = void 0;
this._properties = void 0;
this._propertiesSubscription = void 0;
this._rectangle = void 0;
this._rectangleSubscription = void 0;
this._viewFrom = void 0;
this._viewFromSubscription = void 0;
this._wall = void 0;
this._wallSubscription = void 0;
this._children = [];
this.entityCollection = void 0;
this.parent = options.parent;
this.merge(options);
}
function updateShow(entity, children, isShowing) {
const length3 = children.length;
for (let i = 0; i < length3; i++) {
const child = children[i];
const childShow = child._show;
const oldValue2 = !isShowing && childShow;
const newValue = isShowing && childShow;
if (oldValue2 !== newValue) {
updateShow(child, child._children, isShowing);
}
}
entity._definitionChanged.raiseEvent(
entity,
"isShowing",
isShowing,
!isShowing
);
}
Object.defineProperties(Entity.prototype, {
availability: createRawPropertyDescriptor_default("availability"),
id: {
get: function() {
return this._id;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
name: createRawPropertyDescriptor_default("name"),
show: {
get: function() {
return this._show;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
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);
}
},
isShowing: {
get: function() {
return this._show && (!defined_default(this.entityCollection) || this.entityCollection.show) && (!defined_default(this._parent) || this._parent.isShowing);
}
},
parent: {
get: function() {
return this._parent;
},
set: function(value) {
const oldValue2 = this._parent;
if (oldValue2 === value) {
return;
}
const wasShowing = this.isShowing;
if (defined_default(oldValue2)) {
const index = oldValue2._children.indexOf(this);
oldValue2._children.splice(index, 1);
}
this._parent = value;
if (defined_default(value)) {
value._children.push(this);
}
const isShowing = this.isShowing;
if (wasShowing !== isShowing) {
updateShow(this, this._children, isShowing);
}
this._definitionChanged.raiseEvent(this, "parent", value, oldValue2);
}
},
propertyNames: {
get: function() {
return this._propertyNames;
}
},
billboard: createPropertyTypeDescriptor("billboard", BillboardGraphics_default),
box: createPropertyTypeDescriptor("box", BoxGraphics_default),
corridor: createPropertyTypeDescriptor("corridor", CorridorGraphics_default),
cylinder: createPropertyTypeDescriptor("cylinder", CylinderGraphics_default),
description: createPropertyDescriptor_default("description"),
ellipse: createPropertyTypeDescriptor("ellipse", EllipseGraphics_default),
ellipsoid: createPropertyTypeDescriptor("ellipsoid", EllipsoidGraphics_default),
label: createPropertyTypeDescriptor("label", LabelGraphics_default),
model: createPropertyTypeDescriptor("model", ModelGraphics_default),
tileset: createPropertyTypeDescriptor("tileset", Cesium3DTilesetGraphics_default),
orientation: createPropertyDescriptor_default("orientation"),
path: createPropertyTypeDescriptor("path", PathGraphics_default),
plane: createPropertyTypeDescriptor("plane", PlaneGraphics_default),
point: createPropertyTypeDescriptor("point", PointGraphics_default),
polygon: createPropertyTypeDescriptor("polygon", PolygonGraphics_default),
polyline: createPropertyTypeDescriptor("polyline", PolylineGraphics_default),
polylineVolume: createPropertyTypeDescriptor(
"polylineVolume",
PolylineVolumeGraphics_default
),
properties: createPropertyTypeDescriptor("properties", PropertyBag_default),
position: createPositionPropertyDescriptor("position"),
rectangle: createPropertyTypeDescriptor("rectangle", RectangleGraphics_default),
viewFrom: createPropertyDescriptor_default("viewFrom"),
wall: createPropertyTypeDescriptor("wall", WallGraphics_default)
});
Entity.prototype.isAvailable = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
const availability = this._availability;
return !defined_default(availability) || availability.contains(time);
};
Entity.prototype.addProperty = function(propertyName) {
const propertyNames = this._propertyNames;
if (!defined_default(propertyName)) {
throw new DeveloperError_default("propertyName is required.");
}
if (propertyNames.indexOf(propertyName) !== -1) {
throw new DeveloperError_default(
`${propertyName} is already a registered property.`
);
}
if (propertyName in this) {
throw new DeveloperError_default(`${propertyName} is a reserved property name.`);
}
propertyNames.push(propertyName);
Object.defineProperty(
this,
propertyName,
createRawPropertyDescriptor_default(propertyName, true)
);
};
Entity.prototype.removeProperty = function(propertyName) {
const propertyNames = this._propertyNames;
const index = propertyNames.indexOf(propertyName);
if (!defined_default(propertyName)) {
throw new DeveloperError_default("propertyName is required.");
}
if (index === -1) {
throw new DeveloperError_default(`${propertyName} is not a registered property.`);
}
this._propertyNames.splice(index, 1);
delete this[propertyName];
};
Entity.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.name = defaultValue_default(this.name, source.name);
this.availability = defaultValue_default(this.availability, source.availability);
const propertyNames = this._propertyNames;
const sourcePropertyNames = defined_default(source._propertyNames) ? source._propertyNames : Object.keys(source);
const propertyNamesLength = sourcePropertyNames.length;
for (let i = 0; i < propertyNamesLength; i++) {
const name = sourcePropertyNames[i];
if (name === "parent" || name === "name" || name === "availability" || name === "children") {
continue;
}
const targetProperty = this[name];
const sourceProperty = source[name];
if (!defined_default(targetProperty) && propertyNames.indexOf(name) === -1) {
this.addProperty(name);
}
if (defined_default(sourceProperty)) {
if (defined_default(targetProperty)) {
if (defined_default(targetProperty.merge)) {
targetProperty.merge(sourceProperty);
}
} else if (defined_default(sourceProperty.merge) && defined_default(sourceProperty.clone)) {
this[name] = sourceProperty.clone();
} else {
this[name] = sourceProperty;
}
}
}
};
var matrix3Scratch2 = new Matrix3_default();
var positionScratch2 = new Cartesian3_default();
var orientationScratch = new Quaternion_default();
Entity.prototype.computeModelMatrix = function(time, result) {
Check_default.typeOf.object("time", time);
const position = Property_default.getValueOrUndefined(
this._position,
time,
positionScratch2
);
if (!defined_default(position)) {
return void 0;
}
const orientation = Property_default.getValueOrUndefined(
this._orientation,
time,
orientationScratch
);
if (!defined_default(orientation)) {
result = Transforms_default.eastNorthUpToFixedFrame(position, void 0, result);
} else {
result = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromQuaternion(orientation, matrix3Scratch2),
position,
result
);
}
return result;
};
Entity.prototype.computeModelMatrixForHeightReference = function(time, heightReferenceProperty, heightOffset, ellipsoid, result) {
Check_default.typeOf.object("time", time);
const heightReference = Property_default.getValueOrDefault(
heightReferenceProperty,
time,
HeightReference_default.NONE
);
let position = Property_default.getValueOrUndefined(
this._position,
time,
positionScratch2
);
if (heightReference === HeightReference_default.NONE || !defined_default(position) || Cartesian3_default.equalsEpsilon(position, Cartesian3_default.ZERO, Math_default.EPSILON8)) {
return this.computeModelMatrix(time, result);
}
const carto = ellipsoid.cartesianToCartographic(position, cartoScratch);
if (heightReference === HeightReference_default.CLAMP_TO_GROUND) {
carto.height = heightOffset;
} else {
carto.height += heightOffset;
}
position = ellipsoid.cartographicToCartesian(carto, position);
const orientation = Property_default.getValueOrUndefined(
this._orientation,
time,
orientationScratch
);
if (!defined_default(orientation)) {
result = Transforms_default.eastNorthUpToFixedFrame(position, void 0, result);
} else {
result = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromQuaternion(orientation, matrix3Scratch2),
position,
result
);
}
return result;
};
Entity.supportsMaterialsforEntitiesOnTerrain = function(scene) {
return GroundPrimitive_default.supportsMaterials(scene);
};
Entity.supportsPolylinesOnTerrain = function(scene) {
return GroundPolylinePrimitive_default.isSupported(scene);
};
var Entity_default = Entity;
// node_modules/@cesium/engine/Source/DataSources/GeometryUpdater.js
var defaultMaterial = new ColorMaterialProperty_default(Color_default.WHITE);
var defaultShow = new ConstantProperty_default(true);
var defaultFill = new ConstantProperty_default(true);
var defaultOutline = new ConstantProperty_default(false);
var defaultOutlineColor = new ConstantProperty_default(Color_default.BLACK);
var defaultShadows = new ConstantProperty_default(ShadowMode_default.DISABLED);
var defaultDistanceDisplayCondition = new ConstantProperty_default(
new DistanceDisplayCondition_default()
);
var defaultClassificationType = new ConstantProperty_default(ClassificationType_default.BOTH);
function GeometryUpdater(options) {
Check_default.defined("options.entity", options.entity);
Check_default.defined("options.scene", options.scene);
Check_default.defined("options.geometryOptions", options.geometryOptions);
Check_default.defined("options.geometryPropertyName", options.geometryPropertyName);
Check_default.defined("options.observedPropertyNames", options.observedPropertyNames);
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_default();
this._showProperty = void 0;
this._materialProperty = void 0;
this._showOutlineProperty = void 0;
this._outlineColorProperty = void 0;
this._outlineWidth = 1;
this._shadowsProperty = void 0;
this._distanceDisplayConditionProperty = void 0;
this._classificationTypeProperty = void 0;
this._options = options.geometryOptions;
this._geometryPropertyName = geometryPropertyName;
this._id = `${geometryPropertyName}-${entity.id}`;
this._observedPropertyNames = options.observedPropertyNames;
this._supportsMaterialsforEntitiesOnTerrain = Entity_default.supportsMaterialsforEntitiesOnTerrain(
options.scene
);
}
Object.defineProperties(GeometryUpdater.prototype, {
id: {
get: function() {
return this._id;
}
},
entity: {
get: function() {
return this._entity;
}
},
fillEnabled: {
get: function() {
return this._fillEnabled;
}
},
hasConstantFill: {
get: function() {
return !this._fillEnabled || !defined_default(this._entity.availability) && Property_default.isConstant(this._showProperty) && Property_default.isConstant(this._fillProperty);
}
},
fillMaterialProperty: {
get: function() {
return this._materialProperty;
}
},
outlineEnabled: {
get: function() {
return this._outlineEnabled;
}
},
hasConstantOutline: {
get: function() {
return !this._outlineEnabled || !defined_default(this._entity.availability) && Property_default.isConstant(this._showProperty) && Property_default.isConstant(this._showOutlineProperty);
}
},
outlineColorProperty: {
get: function() {
return this._outlineColorProperty;
}
},
outlineWidth: {
get: function() {
return this._outlineWidth;
}
},
shadowsProperty: {
get: function() {
return this._shadowsProperty;
}
},
distanceDisplayConditionProperty: {
get: function() {
return this._distanceDisplayConditionProperty;
}
},
classificationTypeProperty: {
get: function() {
return this._classificationTypeProperty;
}
},
isDynamic: {
get: function() {
return this._dynamic;
}
},
isClosed: {
get: function() {
return this._isClosed;
}
},
onTerrain: {
get: function() {
return this._onTerrain;
}
},
geometryChanged: {
get: function() {
return this._geometryChanged;
}
}
});
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_default(visible, false);
};
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_default(visible, false);
};
GeometryUpdater.prototype.createFillGeometryInstance = DeveloperError_default.throwInstantiationError;
GeometryUpdater.prototype.createOutlineGeometryInstance = DeveloperError_default.throwInstantiationError;
GeometryUpdater.prototype.isDestroyed = function() {
return false;
};
GeometryUpdater.prototype.destroy = function() {
destroyObject_default(this);
};
GeometryUpdater.prototype._isHidden = function(entity, geometry) {
const show = geometry.show;
return defined_default(show) && show.isConstant && !show.getValue(Iso8601_default.MINIMUM_VALUE);
};
GeometryUpdater.prototype._isOnTerrain = function(entity, geometry) {
return false;
};
GeometryUpdater.prototype._getIsClosed = function(options) {
return true;
};
GeometryUpdater.prototype._isDynamic = DeveloperError_default.throwInstantiationError;
GeometryUpdater.prototype._setStaticOptions = DeveloperError_default.throwInstantiationError;
GeometryUpdater.prototype._onEntityPropertyChanged = function(entity, propertyName, newValue, oldValue2) {
if (this._observedPropertyNames.indexOf(propertyName) === -1) {
return;
}
const geometry = this._entity[this._geometryPropertyName];
if (!defined_default(geometry)) {
if (this._fillEnabled || this._outlineEnabled) {
this._fillEnabled = false;
this._outlineEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
const fillProperty = geometry.fill;
const fillEnabled = defined_default(fillProperty) && fillProperty.isConstant ? fillProperty.getValue(Iso8601_default.MINIMUM_VALUE) : true;
const outlineProperty = geometry.outline;
let outlineEnabled = defined_default(outlineProperty);
if (outlineEnabled && outlineProperty.isConstant) {
outlineEnabled = outlineProperty.getValue(Iso8601_default.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_default(geometry.material, defaultMaterial);
this._fillProperty = defaultValue_default(fillProperty, defaultFill);
this._showProperty = defaultValue_default(show, defaultShow);
this._showOutlineProperty = defaultValue_default(geometry.outline, defaultOutline);
this._outlineColorProperty = outlineEnabled ? defaultValue_default(geometry.outlineColor, defaultOutlineColor) : void 0;
this._shadowsProperty = defaultValue_default(geometry.shadows, defaultShadows);
this._distanceDisplayConditionProperty = defaultValue_default(
geometry.distanceDisplayCondition,
defaultDistanceDisplayCondition
);
this._classificationTypeProperty = defaultValue_default(
geometry.classificationType,
defaultClassificationType
);
this._fillEnabled = fillEnabled;
const onTerrain = this._isOnTerrain(entity, geometry) && (this._supportsMaterialsforEntitiesOnTerrain || this._materialProperty instanceof ColorMaterialProperty_default);
if (outlineEnabled && onTerrain) {
oneTimeWarning_default(oneTimeWarning_default.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_default(outlineWidth) ? outlineWidth.getValue(Iso8601_default.MINIMUM_VALUE) : 1;
this._dynamic = false;
this._geometryChanged.raiseEvent(this);
}
};
GeometryUpdater.prototype.createDynamicUpdater = function(primitives, groundPrimitives) {
Check_default.defined("primitives", primitives);
Check_default.defined("groundPrimitives", groundPrimitives);
if (!this._dynamic) {
throw new DeveloperError_default(
"This instance does not represent dynamic geometry."
);
}
return new this.constructor.DynamicGeometryUpdater(
this,
primitives,
groundPrimitives
);
};
var GeometryUpdater_default = GeometryUpdater;
// node_modules/@cesium/engine/Source/DataSources/CallbackProperty.js
function CallbackProperty(callback, isConstant) {
this._callback = void 0;
this._isConstant = void 0;
this._definitionChanged = new Event_default();
this.setCallback(callback, isConstant);
}
Object.defineProperties(CallbackProperty.prototype, {
isConstant: {
get: function() {
return this._isConstant;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
}
});
CallbackProperty.prototype.getValue = function(time, result) {
return this._callback(time, result);
};
CallbackProperty.prototype.setCallback = function(callback, isConstant) {
if (!defined_default(callback)) {
throw new DeveloperError_default("callback is required.");
}
if (!defined_default(isConstant)) {
throw new DeveloperError_default("isConstant is required.");
}
const changed = this._callback !== callback || this._isConstant !== isConstant;
this._callback = callback;
this._isConstant = isConstant;
if (changed) {
this._definitionChanged.raiseEvent(this);
}
};
CallbackProperty.prototype.equals = function(other) {
return this === other || other instanceof CallbackProperty && this._callback === other._callback && this._isConstant === other._isConstant;
};
var CallbackProperty_default = CallbackProperty;
// node_modules/@cesium/engine/Source/DataSources/TerrainOffsetProperty.js
var scratchPosition = new Cartesian3_default();
var scratchCarto = new Cartographic_default();
function TerrainOffsetProperty(scene, positionProperty, heightReferenceProperty, extrudedHeightReferenceProperty) {
Check_default.defined("scene", scene);
Check_default.defined("positionProperty", positionProperty);
this._scene = scene;
this._heightReference = heightReferenceProperty;
this._extrudedHeightReference = extrudedHeightReferenceProperty;
this._positionProperty = positionProperty;
this._position = new Cartesian3_default();
this._cartographicPosition = new Cartographic_default();
this._normal = new Cartesian3_default();
this._definitionChanged = new Event_default();
this._terrainHeight = 0;
this._removeCallbackFunc = void 0;
this._removeEventListener = void 0;
this._removeModeListener = void 0;
const that = this;
if (defined_default(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_default.MINIMUM_VALUE,
scratchPosition
);
if (!defined_default(position) || Cartesian3_default.equals(position, Cartesian3_default.ZERO) || !defined_default(scene.globe)) {
return;
}
this._position = Cartesian3_default.clone(position, this._position);
this._updateClamping();
this._normal = scene.globe.ellipsoid.geodeticSurfaceNormal(
position,
this._normal
);
}
}
Object.defineProperties(TerrainOffsetProperty.prototype, {
isConstant: {
get: function() {
return false;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
}
});
TerrainOffsetProperty.prototype._updateClamping = function() {
if (defined_default(this._removeCallbackFunc)) {
this._removeCallbackFunc();
}
const scene = this._scene;
const globe = scene.globe;
const position = this._position;
if (!defined_default(globe) || Cartesian3_default.equals(position, Cartesian3_default.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_default(height)) {
this._terrainHeight = height;
} else {
this._terrainHeight = 0;
}
function updateFunction(clampedPosition) {
if (scene.mode === SceneMode_default.SCENE3D) {
const carto = ellipsoid.cartesianToCartographic(
clampedPosition,
scratchCarto
);
that._terrainHeight = carto.height;
} else {
that._terrainHeight = clampedPosition.x;
}
that.definitionChanged.raiseEvent();
}
this._removeCallbackFunc = surface.updateHeight(
cartographicPosition,
updateFunction
);
};
TerrainOffsetProperty.prototype.getValue = function(time, result) {
const heightReference = Property_default.getValueOrDefault(
this._heightReference,
time,
HeightReference_default.NONE
);
const extrudedHeightReference = Property_default.getValueOrDefault(
this._extrudedHeightReference,
time,
HeightReference_default.NONE
);
if (heightReference === HeightReference_default.NONE && extrudedHeightReference !== HeightReference_default.RELATIVE_TO_GROUND) {
this._position = Cartesian3_default.clone(Cartesian3_default.ZERO, this._position);
return Cartesian3_default.clone(Cartesian3_default.ZERO, result);
}
if (this._positionProperty.isConstant) {
return Cartesian3_default.multiplyByScalar(
this._normal,
this._terrainHeight,
result
);
}
const scene = this._scene;
const position = this._positionProperty.getValue(time, scratchPosition);
if (!defined_default(position) || Cartesian3_default.equals(position, Cartesian3_default.ZERO) || !defined_default(scene.globe)) {
return Cartesian3_default.clone(Cartesian3_default.ZERO, result);
}
if (Cartesian3_default.equalsEpsilon(this._position, position, Math_default.EPSILON10)) {
return Cartesian3_default.multiplyByScalar(
this._normal,
this._terrainHeight,
result
);
}
this._position = Cartesian3_default.clone(position, this._position);
this._updateClamping();
const normal2 = scene.globe.ellipsoid.geodeticSurfaceNormal(
position,
this._normal
);
return Cartesian3_default.multiplyByScalar(normal2, this._terrainHeight, result);
};
TerrainOffsetProperty.prototype.isDestroyed = function() {
return false;
};
TerrainOffsetProperty.prototype.destroy = function() {
if (defined_default(this._removeEventListener)) {
this._removeEventListener();
}
if (defined_default(this._removeModeListener)) {
this._removeModeListener();
}
if (defined_default(this._removeCallbackFunc)) {
this._removeCallbackFunc();
}
return destroyObject_default(this);
};
var TerrainOffsetProperty_default = TerrainOffsetProperty;
// node_modules/@cesium/engine/Source/DataSources/heightReferenceOnEntityPropertyChanged.js
function heightReferenceOnEntityPropertyChanged(entity, propertyName, newValue, oldValue2) {
GeometryUpdater_default.prototype._onEntityPropertyChanged.call(
this,
entity,
propertyName,
newValue,
oldValue2
);
if (this._observedPropertyNames.indexOf(propertyName) === -1) {
return;
}
const geometry = this._entity[this._geometryPropertyName];
if (!defined_default(geometry)) {
return;
}
if (defined_default(this._terrainOffsetProperty)) {
this._terrainOffsetProperty.destroy();
this._terrainOffsetProperty = void 0;
}
const heightReferenceProperty = geometry.heightReference;
if (defined_default(heightReferenceProperty)) {
const centerPosition = new CallbackProperty_default(
this._computeCenter.bind(this),
!this._dynamic
);
this._terrainOffsetProperty = new TerrainOffsetProperty_default(
this._scene,
centerPosition,
heightReferenceProperty
);
}
}
var heightReferenceOnEntityPropertyChanged_default = heightReferenceOnEntityPropertyChanged;
// node_modules/@cesium/engine/Source/DataSources/BoxGeometryUpdater.js
var defaultOffset = Cartesian3_default.ZERO;
var offsetScratch4 = new Cartesian3_default();
var positionScratch3 = new Cartesian3_default();
var scratchColor = new Color_default();
function BoxGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.dimensions = void 0;
this.offsetAttribute = void 0;
}
function BoxGeometryUpdater(entity, scene) {
GeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new BoxGeometryOptions(entity),
geometryPropertyName: "box",
observedPropertyNames: ["availability", "position", "orientation", "box"]
});
this._onEntityPropertyChanged(entity, "box", entity.box, void 0);
}
if (defined_default(Object.create)) {
BoxGeometryUpdater.prototype = Object.create(GeometryUpdater_default.prototype);
BoxGeometryUpdater.prototype.constructor = BoxGeometryUpdater;
}
Object.defineProperties(BoxGeometryUpdater.prototype, {
terrainOffsetProperty: {
get: function() {
return this._terrainOffsetProperty;
}
}
});
BoxGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const show = new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
);
const attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: void 0,
offset: void 0
};
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
}
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch4
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: BoxGeometry_default.fromDimensions(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.box.heightReference,
this._options.dimensions.z * 0.5,
this._scene.mapProjection.ellipsoid
),
attributes
});
};
BoxGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
),
offset: void 0
};
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset,
offsetScratch4
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: BoxOutlineGeometry_default.fromDimensions(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.box.heightReference,
this._options.dimensions.z * 0.5,
this._scene.mapProjection.ellipsoid
),
attributes
});
};
BoxGeometryUpdater.prototype._computeCenter = function(time, result) {
return Property_default.getValueOrUndefined(this._entity.position, time, result);
};
BoxGeometryUpdater.prototype._isHidden = function(entity, box) {
return !defined_default(box.dimensions) || !defined_default(entity.position) || GeometryUpdater_default.prototype._isHidden.call(this, entity, box);
};
BoxGeometryUpdater.prototype._isDynamic = function(entity, box) {
return !entity.position.isConstant || !Property_default.isConstant(entity.orientation) || !box.dimensions.isConstant || !Property_default.isConstant(box.outlineWidth);
};
BoxGeometryUpdater.prototype._setStaticOptions = function(entity, box) {
const heightReference = Property_default.getValueOrDefault(
box.heightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
const options = this._options;
options.vertexFormat = this._materialProperty instanceof ColorMaterialProperty_default ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.dimensions = box.dimensions.getValue(
Iso8601_default.MINIMUM_VALUE,
options.dimensions
);
options.offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0;
};
BoxGeometryUpdater.prototype._onEntityPropertyChanged = heightReferenceOnEntityPropertyChanged_default;
BoxGeometryUpdater.DynamicGeometryUpdater = DynamicBoxGeometryUpdater;
function DynamicBoxGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicBoxGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicBoxGeometryUpdater.prototype.constructor = DynamicBoxGeometryUpdater;
}
DynamicBoxGeometryUpdater.prototype._isHidden = function(entity, box, time) {
const position = Property_default.getValueOrUndefined(
entity.position,
time,
positionScratch3
);
const dimensions = this._options.dimensions;
return !defined_default(position) || !defined_default(dimensions) || DynamicGeometryUpdater_default.prototype._isHidden.call(this, entity, box, time);
};
DynamicBoxGeometryUpdater.prototype._setOptions = function(entity, box, time) {
const heightReference = Property_default.getValueOrDefault(
box.heightReference,
time,
HeightReference_default.NONE
);
const options = this._options;
options.dimensions = Property_default.getValueOrUndefined(
box.dimensions,
time,
options.dimensions
);
options.offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0;
};
var BoxGeometryUpdater_default = BoxGeometryUpdater;
// node_modules/dompurify/dist/purify.es.js
var {
entries,
setPrototypeOf,
isFrozen,
getPrototypeOf,
getOwnPropertyDescriptor
} = Object;
var {
freeze,
seal,
create
} = Object;
var {
apply,
construct
} = typeof Reflect !== "undefined" && Reflect;
if (!apply) {
apply = function apply2(fun, thisValue, args) {
return fun.apply(thisValue, args);
};
}
if (!freeze) {
freeze = function freeze2(x) {
return x;
};
}
if (!seal) {
seal = function seal2(x) {
return x;
};
}
if (!construct) {
construct = function construct2(Func, args) {
return new Func(...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 stringToString = unapply(String.prototype.toString);
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);
};
}
function addToSet(set2, array, transformCaseFunc) {
transformCaseFunc = transformCaseFunc ? transformCaseFunc : stringToLowerCase;
if (setPrototypeOf) {
setPrototypeOf(set2, null);
}
let l = array.length;
while (l--) {
let element = array[l];
if (typeof element === "string") {
const lcElement = transformCaseFunc(element);
if (lcElement !== element) {
if (!isFrozen(array)) {
array[l] = lcElement;
}
element = lcElement;
}
}
set2[element] = true;
}
return set2;
}
function clone2(object) {
const newObject = create(null);
for (const [property, value] of entries(object)) {
newObject[property] = value;
}
return newObject;
}
function lookupGetter(object, prop) {
while (object !== null) {
const 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"]);
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"]);
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", "mprescripts"]);
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);
var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
var TMPLIT_EXPR = seal(/\${[\w\W]*}/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
var IS_ALLOWED_URI = seal(
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
);
var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
var ATTR_WHITESPACE = seal(
/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
);
var DOCTYPE_NAME = seal(/^html$/i);
var EXPRESSIONS = Object.freeze({
__proto__: null,
MUSTACHE_EXPR,
ERB_EXPR,
TMPLIT_EXPR,
DATA_ATTR,
ARIA_ATTR,
IS_ALLOWED_URI,
IS_SCRIPT_OR_DATA,
ATTR_WHITESPACE,
DOCTYPE_NAME
});
var getGlobal = () => typeof window === "undefined" ? null : window;
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, document2) {
if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") {
return null;
}
let suffix = null;
const ATTR_NAME = "data-tt-policy-suffix";
if (document2.currentScript && document2.currentScript.hasAttribute(ATTR_NAME)) {
suffix = document2.currentScript.getAttribute(ATTR_NAME);
}
const policyName = "dompurify" + (suffix ? "#" + suffix : "");
try {
return trustedTypes.createPolicy(policyName, {
createHTML(html2) {
return html2;
},
createScriptURL(scriptUrl) {
return scriptUrl;
}
});
} catch (_) {
console.warn("TrustedTypes policy " + policyName + " could not be created.");
return null;
}
};
function createDOMPurify() {
let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
const DOMPurify = (root) => createDOMPurify(root);
DOMPurify.version = "3.0.2";
DOMPurify.removed = [];
if (!window2 || !window2.document || window2.document.nodeType !== 9) {
DOMPurify.isSupported = false;
return DOMPurify;
}
const originalDocument = window2.document;
let {
document: document2
} = window2;
const {
DocumentFragment: DocumentFragment2,
HTMLTemplateElement,
Node: Node6,
Element: Element2,
NodeFilter,
NamedNodeMap = window2.NamedNodeMap || window2.MozNamedAttrMap,
HTMLFormElement,
DOMParser: DOMParser2,
trustedTypes
} = window2;
const ElementPrototype = Element2.prototype;
const cloneNode = lookupGetter(ElementPrototype, "cloneNode");
const getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
const getChildNodes = lookupGetter(ElementPrototype, "childNodes");
const getParentNode = lookupGetter(ElementPrototype, "parentNode");
if (typeof HTMLTemplateElement === "function") {
const template = document2.createElement("template");
if (template.content && template.content.ownerDocument) {
document2 = template.content.ownerDocument;
}
}
const trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
const emptyHTML = trustedTypesPolicy ? trustedTypesPolicy.createHTML("") : "";
const {
implementation: implementation2,
createNodeIterator,
createDocumentFragment,
getElementsByTagName
} = document2;
const {
importNode
} = originalDocument;
let hooks2 = {};
DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation2 && typeof implementation2.createHTMLDocument !== "undefined";
const {
MUSTACHE_EXPR: MUSTACHE_EXPR2,
ERB_EXPR: ERB_EXPR2,
TMPLIT_EXPR: TMPLIT_EXPR2,
DATA_ATTR: DATA_ATTR2,
ARIA_ATTR: ARIA_ATTR2,
IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2,
ATTR_WHITESPACE: ATTR_WHITESPACE2
} = EXPRESSIONS;
let {
IS_ALLOWED_URI: IS_ALLOWED_URI$1
} = EXPRESSIONS;
let ALLOWED_TAGS = null;
const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
let ALLOWED_ATTR = null;
const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
let 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
}
}));
let FORBID_TAGS = null;
let FORBID_ATTR = null;
let ALLOW_ARIA_ATTR = true;
let ALLOW_DATA_ATTR = true;
let ALLOW_UNKNOWN_PROTOCOLS = false;
let ALLOW_SELF_CLOSE_IN_ATTR = true;
let SAFE_FOR_TEMPLATES = false;
let WHOLE_DOCUMENT = false;
let SET_CONFIG = false;
let FORCE_BODY = false;
let RETURN_DOM = false;
let RETURN_DOM_FRAGMENT = false;
let RETURN_TRUSTED_TYPE = false;
let SANITIZE_DOM = true;
let SANITIZE_NAMED_PROPS = false;
const SANITIZE_NAMED_PROPS_PREFIX = "user-content-";
let KEEP_CONTENT = true;
let IN_PLACE = false;
let USE_PROFILES = {};
let FORBID_CONTENTS = null;
const 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"]);
let DATA_URI_TAGS = null;
const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]);
let URI_SAFE_ATTRIBUTES = null;
const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]);
const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
let NAMESPACE = HTML_NAMESPACE;
let IS_EMPTY_INPUT = false;
let ALLOWED_NAMESPACES = null;
const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
let PARSER_MEDIA_TYPE;
const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"];
const DEFAULT_PARSER_MEDIA_TYPE = "text/html";
let transformCaseFunc;
let CONFIG = null;
const formElement = document2.createElement("form");
const isRegexOrFunction = function isRegexOrFunction2(testValue) {
return testValue instanceof RegExp || testValue instanceof Function;
};
const _parseConfig = function _parseConfig2(cfg) {
if (CONFIG && CONFIG === cfg) {
return;
}
if (!cfg || typeof cfg !== "object") {
cfg = {};
}
cfg = clone2(cfg);
PARSER_MEDIA_TYPE = SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? PARSER_MEDIA_TYPE = DEFAULT_PARSER_MEDIA_TYPE : PARSER_MEDIA_TYPE = cfg.PARSER_MEDIA_TYPE;
transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase;
ALLOWED_TAGS = "ALLOWED_TAGS" in cfg ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
ALLOWED_ATTR = "ALLOWED_ATTR" in cfg ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
ALLOWED_NAMESPACES = "ALLOWED_NAMESPACES" in cfg ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
URI_SAFE_ATTRIBUTES = "ADD_URI_SAFE_ATTR" in cfg ? addToSet(
clone2(DEFAULT_URI_SAFE_ATTRIBUTES),
cfg.ADD_URI_SAFE_ATTR,
transformCaseFunc
) : DEFAULT_URI_SAFE_ATTRIBUTES;
DATA_URI_TAGS = "ADD_DATA_URI_TAGS" in cfg ? addToSet(
clone2(DEFAULT_DATA_URI_TAGS),
cfg.ADD_DATA_URI_TAGS,
transformCaseFunc
) : DEFAULT_DATA_URI_TAGS;
FORBID_CONTENTS = "FORBID_CONTENTS" in cfg ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
FORBID_TAGS = "FORBID_TAGS" in cfg ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : {};
FORBID_ATTR = "FORBID_ATTR" in cfg ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : {};
USE_PROFILES = "USE_PROFILES" in cfg ? cfg.USE_PROFILES : false;
ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false;
SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
RETURN_DOM = cfg.RETURN_DOM || false;
RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
FORCE_BODY = cfg.FORCE_BODY || false;
SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false;
KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
IN_PLACE = cfg.IN_PLACE || false;
IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
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;
}
if (SAFE_FOR_TEMPLATES) {
ALLOW_DATA_ATTR = false;
}
if (RETURN_DOM_FRAGMENT) {
RETURN_DOM = true;
}
if (USE_PROFILES) {
ALLOWED_TAGS = addToSet({}, [...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);
}
}
if (cfg.ADD_TAGS) {
if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
ALLOWED_TAGS = clone2(ALLOWED_TAGS);
}
addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
}
if (cfg.ADD_ATTR) {
if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
ALLOWED_ATTR = clone2(ALLOWED_ATTR);
}
addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
}
if (cfg.ADD_URI_SAFE_ATTR) {
addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
}
if (cfg.FORBID_CONTENTS) {
if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
FORBID_CONTENTS = clone2(FORBID_CONTENTS);
}
addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
}
if (KEEP_CONTENT) {
ALLOWED_TAGS["#text"] = true;
}
if (WHOLE_DOCUMENT) {
addToSet(ALLOWED_TAGS, ["html", "head", "body"]);
}
if (ALLOWED_TAGS.table) {
addToSet(ALLOWED_TAGS, ["tbody"]);
delete FORBID_TAGS.tbody;
}
if (freeze) {
freeze(cfg);
}
CONFIG = cfg;
};
const MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]);
const HTML_INTEGRATION_POINTS = addToSet({}, ["foreignobject", "desc", "title", "annotation-xml"]);
const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]);
const ALL_SVG_TAGS = addToSet({}, svg$1);
addToSet(ALL_SVG_TAGS, svgFilters);
addToSet(ALL_SVG_TAGS, svgDisallowed);
const ALL_MATHML_TAGS = addToSet({}, mathMl$1);
addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
const _checkValidNamespace = function _checkValidNamespace2(element) {
let parent = getParentNode(element);
if (!parent || !parent.tagName) {
parent = {
namespaceURI: NAMESPACE,
tagName: "template"
};
}
const tagName = stringToLowerCase(element.tagName);
const parentTagName = stringToLowerCase(parent.tagName);
if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
return false;
}
if (element.namespaceURI === SVG_NAMESPACE) {
if (parent.namespaceURI === HTML_NAMESPACE) {
return tagName === "svg";
}
if (parent.namespaceURI === MATHML_NAMESPACE) {
return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
}
return Boolean(ALL_SVG_TAGS[tagName]);
}
if (element.namespaceURI === MATHML_NAMESPACE) {
if (parent.namespaceURI === HTML_NAMESPACE) {
return tagName === "math";
}
if (parent.namespaceURI === SVG_NAMESPACE) {
return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
}
return Boolean(ALL_MATHML_TAGS[tagName]);
}
if (element.namespaceURI === HTML_NAMESPACE) {
if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
return false;
}
if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
return false;
}
return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
}
if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) {
return true;
}
return false;
};
const _forceRemove = function _forceRemove2(node) {
arrayPush(DOMPurify.removed, {
element: node
});
try {
node.parentNode.removeChild(node);
} catch (_) {
node.remove();
}
};
const _removeAttribute = function _removeAttribute2(name, node) {
try {
arrayPush(DOMPurify.removed, {
attribute: node.getAttributeNode(name),
from: node
});
} catch (_) {
arrayPush(DOMPurify.removed, {
attribute: null,
from: node
});
}
node.removeAttribute(name);
if (name === "is" && !ALLOWED_ATTR[name]) {
if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
try {
_forceRemove(node);
} catch (_) {
}
} else {
try {
node.setAttribute(name, "");
} catch (_) {
}
}
}
};
const _initDocument = function _initDocument2(dirty) {
let doc;
let leadingWhitespace;
if (FORCE_BODY) {
dirty = "" + dirty;
} else {
const matches = stringMatch(dirty, /^[\r\n\t ]+/);
leadingWhitespace = matches && matches[0];
}
if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) {
dirty = '' + dirty + "";
}
const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
if (NAMESPACE === HTML_NAMESPACE) {
try {
doc = new DOMParser2().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
} catch (_) {
}
}
if (!doc || !doc.documentElement) {
doc = implementation2.createDocument(NAMESPACE, "template", null);
try {
doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
} catch (_) {
}
}
const body = doc.body || doc.documentElement;
if (dirty && leadingWhitespace) {
body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null);
}
if (NAMESPACE === HTML_NAMESPACE) {
return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0];
}
return WHOLE_DOCUMENT ? doc.documentElement : body;
};
const _createIterator = function _createIterator2(root) {
return createNodeIterator.call(
root.ownerDocument || root,
root,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT,
null,
false
);
};
const _isClobbered = function _isClobbered2(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" || typeof elm.hasChildNodes !== "function");
};
const _isNode = function _isNode2(object) {
return typeof Node6 === "object" ? object instanceof Node6 : object && typeof object === "object" && typeof object.nodeType === "number" && typeof object.nodeName === "string";
};
const _executeHook = function _executeHook2(entryPoint, currentNode, data) {
if (!hooks2[entryPoint]) {
return;
}
arrayForEach(hooks2[entryPoint], (hook) => {
hook.call(DOMPurify, currentNode, data, CONFIG);
});
};
const _sanitizeElements = function _sanitizeElements2(currentNode) {
let content;
_executeHook("beforeSanitizeElements", currentNode, null);
if (_isClobbered(currentNode)) {
_forceRemove(currentNode);
return true;
}
const tagName = transformCaseFunc(currentNode.nodeName);
_executeHook("uponSanitizeElement", currentNode, {
tagName,
allowedTags: ALLOWED_TAGS
});
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;
}
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
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;
}
if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
const parentNode = getParentNode(currentNode) || currentNode.parentNode;
const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
if (childNodes && parentNode) {
const childCount = childNodes.length;
for (let i = childCount - 1; i >= 0; --i) {
parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));
}
}
}
_forceRemove(currentNode);
return true;
}
if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
_forceRemove(currentNode);
return true;
}
if ((tagName === "noscript" || tagName === "noembed") && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
_forceRemove(currentNode);
return true;
}
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
content = currentNode.textContent;
content = stringReplace(content, MUSTACHE_EXPR2, " ");
content = stringReplace(content, ERB_EXPR2, " ");
content = stringReplace(content, TMPLIT_EXPR2, " ");
if (currentNode.textContent !== content) {
arrayPush(DOMPurify.removed, {
element: currentNode.cloneNode()
});
currentNode.textContent = content;
}
}
_executeHook("afterSanitizeElements", currentNode, null);
return false;
};
const _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) {
if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) {
return false;
}
if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName))
;
else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName))
;
else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
if (_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)) || 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;
}
} else if (URI_SAFE_ATTRIBUTES[lcName])
;
else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, "")))
;
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_DATA2, stringReplace(value, ATTR_WHITESPACE2, "")))
;
else if (!value)
;
else {
return false;
}
return true;
};
const _basicCustomElementTest = function _basicCustomElementTest2(tagName) {
return tagName.indexOf("-") > 0;
};
const _sanitizeAttributes = function _sanitizeAttributes2(currentNode) {
let attr;
let value;
let lcName;
let l;
_executeHook("beforeSanitizeAttributes", currentNode, null);
const {
attributes
} = currentNode;
if (!attributes) {
return;
}
const hookEvent = {
attrName: "",
attrValue: "",
keepAttr: true,
allowedAttributes: ALLOWED_ATTR
};
l = attributes.length;
while (l--) {
attr = attributes[l];
const {
name,
namespaceURI
} = attr;
value = name === "value" ? attr.value : stringTrim(attr.value);
lcName = transformCaseFunc(name);
hookEvent.attrName = lcName;
hookEvent.attrValue = value;
hookEvent.keepAttr = true;
hookEvent.forceKeepAttr = void 0;
_executeHook("uponSanitizeAttribute", currentNode, hookEvent);
value = hookEvent.attrValue;
if (hookEvent.forceKeepAttr) {
continue;
}
_removeAttribute(name, currentNode);
if (!hookEvent.keepAttr) {
continue;
}
if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
_removeAttribute(name, currentNode);
continue;
}
if (SAFE_FOR_TEMPLATES) {
value = stringReplace(value, MUSTACHE_EXPR2, " ");
value = stringReplace(value, ERB_EXPR2, " ");
value = stringReplace(value, TMPLIT_EXPR2, " ");
}
const lcTag = transformCaseFunc(currentNode.nodeName);
if (!_isValidAttribute(lcTag, lcName, value)) {
continue;
}
if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) {
_removeAttribute(name, currentNode);
value = SANITIZE_NAMED_PROPS_PREFIX + value;
}
if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") {
if (namespaceURI)
;
else {
switch (trustedTypes.getAttributeType(lcTag, lcName)) {
case "TrustedHTML":
value = trustedTypesPolicy.createHTML(value);
break;
case "TrustedScriptURL":
value = trustedTypesPolicy.createScriptURL(value);
break;
}
}
}
try {
if (namespaceURI) {
currentNode.setAttributeNS(namespaceURI, name, value);
} else {
currentNode.setAttribute(name, value);
}
arrayPop(DOMPurify.removed);
} catch (_) {
}
}
_executeHook("afterSanitizeAttributes", currentNode, null);
};
const _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) {
let shadowNode;
const shadowIterator = _createIterator(fragment);
_executeHook("beforeSanitizeShadowDOM", fragment, null);
while (shadowNode = shadowIterator.nextNode()) {
_executeHook("uponSanitizeShadowNode", shadowNode, null);
if (_sanitizeElements(shadowNode)) {
continue;
}
if (shadowNode.content instanceof DocumentFragment2) {
_sanitizeShadowDOM2(shadowNode.content);
}
_sanitizeAttributes(shadowNode);
}
_executeHook("afterSanitizeShadowDOM", fragment, null);
};
DOMPurify.sanitize = function(dirty) {
let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
let body;
let importedNode;
let currentNode;
let returnNode;
IS_EMPTY_INPUT = !dirty;
if (IS_EMPTY_INPUT) {
dirty = "";
}
if (typeof dirty !== "string" && !_isNode(dirty)) {
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");
}
}
}
if (!DOMPurify.isSupported) {
return dirty;
}
if (!SET_CONFIG) {
_parseConfig(cfg);
}
DOMPurify.removed = [];
if (typeof dirty === "string") {
IN_PLACE = false;
}
if (IN_PLACE) {
if (dirty.nodeName) {
const 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 Node6) {
body = _initDocument("");
importedNode = body.ownerDocument.importNode(dirty, true);
if (importedNode.nodeType === 1 && importedNode.nodeName === "BODY") {
body = importedNode;
} else if (importedNode.nodeName === "HTML") {
body = importedNode;
} else {
body.appendChild(importedNode);
}
} else {
if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && dirty.indexOf("<") === -1) {
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
}
body = _initDocument(dirty);
if (!body) {
return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : "";
}
}
if (body && FORCE_BODY) {
_forceRemove(body.firstChild);
}
const nodeIterator = _createIterator(IN_PLACE ? dirty : body);
while (currentNode = nodeIterator.nextNode()) {
if (_sanitizeElements(currentNode)) {
continue;
}
if (currentNode.content instanceof DocumentFragment2) {
_sanitizeShadowDOM(currentNode.content);
}
_sanitizeAttributes(currentNode);
}
if (IN_PLACE) {
return dirty;
}
if (RETURN_DOM) {
if (RETURN_DOM_FRAGMENT) {
returnNode = createDocumentFragment.call(body.ownerDocument);
while (body.firstChild) {
returnNode.appendChild(body.firstChild);
}
} else {
returnNode = body;
}
if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmod) {
returnNode = importNode.call(originalDocument, returnNode, true);
}
return returnNode;
}
let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
serializedHTML = "\n" + serializedHTML;
}
if (SAFE_FOR_TEMPLATES) {
serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR2, " ");
serializedHTML = stringReplace(serializedHTML, ERB_EXPR2, " ");
serializedHTML = stringReplace(serializedHTML, TMPLIT_EXPR2, " ");
}
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
};
DOMPurify.setConfig = function(cfg) {
_parseConfig(cfg);
SET_CONFIG = true;
};
DOMPurify.clearConfig = function() {
CONFIG = null;
SET_CONFIG = false;
};
DOMPurify.isValidAttribute = function(tag, attr, value) {
if (!CONFIG) {
_parseConfig({});
}
const lcTag = transformCaseFunc(tag);
const lcName = transformCaseFunc(attr);
return _isValidAttribute(lcTag, lcName, value);
};
DOMPurify.addHook = function(entryPoint, hookFunction) {
if (typeof hookFunction !== "function") {
return;
}
hooks2[entryPoint] = hooks2[entryPoint] || [];
arrayPush(hooks2[entryPoint], hookFunction);
};
DOMPurify.removeHook = function(entryPoint) {
if (hooks2[entryPoint]) {
return arrayPop(hooks2[entryPoint]);
}
};
DOMPurify.removeHooks = function(entryPoint) {
if (hooks2[entryPoint]) {
hooks2[entryPoint] = [];
}
};
DOMPurify.removeAllHooks = function() {
hooks2 = {};
};
return DOMPurify;
}
var purify = createDOMPurify();
// node_modules/@cesium/engine/Source/Core/Credit.js
var nextCreditId = 0;
var creditToId = {};
function Credit(html2, showOnScreen) {
Check_default.typeOf.string("html", html2);
let id;
const key = html2;
if (defined_default(creditToId[key])) {
id = creditToId[key];
} else {
id = nextCreditId++;
creditToId[key] = id;
}
showOnScreen = defaultValue_default(showOnScreen, false);
this._id = id;
this._html = html2;
this._showOnScreen = showOnScreen;
this._element = void 0;
}
Object.defineProperties(Credit.prototype, {
html: {
get: function() {
return this._html;
}
},
id: {
get: function() {
return this._id;
}
},
showOnScreen: {
get: function() {
return this._showOnScreen;
},
set: function(value) {
this._showOnScreen = value;
}
},
element: {
get: function() {
if (!defined_default(this._element)) {
const html2 = purify.sanitize(this._html);
const div = document.createElement("div");
div._creditId = this._id;
div.style.display = "inline";
div.innerHTML = html2;
const links = div.querySelectorAll("a");
for (let i = 0; i < links.length; i++) {
links[i].setAttribute("target", "_blank");
}
this._element = div;
}
return this._element;
}
}
});
Credit.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left._id === right._id && left._showOnScreen === right._showOnScreen;
};
Credit.prototype.equals = function(credit) {
return Credit.equals(this, credit);
};
Credit.getIonCredit = function(attribution) {
const showOnScreen = defined_default(attribution.collapsible) && !attribution.collapsible;
const credit = new Credit(attribution.html, showOnScreen);
credit._isIon = credit.html.indexOf("ion-credit.png") !== -1;
return credit;
};
Credit.clone = function(credit) {
if (defined_default(credit)) {
return new Credit(credit.html, credit.showOnScreen);
}
};
var Credit_default = Credit;
// node_modules/@cesium/engine/Source/Shaders/OctahedralProjectionAtlasFS.js
var OctahedralProjectionAtlasFS_default = "in vec2 v_textureCoordinates;\n\nuniform float originalSize;\nuniform sampler2D texture0;\nuniform sampler2D texture1;\nuniform sampler2D texture2;\nuniform sampler2D texture3;\nuniform sampler2D texture4;\nuniform sampler2D texture5;\n\nconst float yMipLevel1 = 1.0 - (1.0 / pow(2.0, 1.0));\nconst float yMipLevel2 = 1.0 - (1.0 / pow(2.0, 2.0));\nconst float yMipLevel3 = 1.0 - (1.0 / pow(2.0, 3.0));\nconst float yMipLevel4 = 1.0 - (1.0 / pow(2.0, 4.0));\n\nvoid main()\n{\n vec2 uv = v_textureCoordinates;\n vec2 textureSize = vec2(originalSize * 1.5 + 2.0, originalSize);\n vec2 pixel = 1.0 / textureSize;\n\n float mipLevel = 0.0;\n\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\n if (mipLevel > 0.0)\n {\n float scale = pow(2.0, mipLevel);\n\n uv.y -= (pixel.y * (mipLevel - 1.0) * 2.0);\n uv.x *= ((textureSize.x - 2.0) / textureSize.y);\n\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\n if(mipLevel == 0.0)\n {\n out_FragColor = texture(texture0, uv);\n }\n else if(mipLevel == 1.0)\n {\n out_FragColor = texture(texture1, uv);\n }\n else if(mipLevel == 2.0)\n {\n out_FragColor = texture(texture2, uv);\n }\n else if(mipLevel == 3.0)\n {\n out_FragColor = texture(texture3, uv);\n }\n else if(mipLevel == 4.0)\n {\n out_FragColor = texture(texture4, uv);\n }\n else if(mipLevel == 5.0)\n {\n out_FragColor = texture(texture5, uv);\n }\n else\n {\n out_FragColor = vec4(0.0);\n }\n}\n";
// node_modules/@cesium/engine/Source/Shaders/OctahedralProjectionFS.js
var OctahedralProjectionFS_default = "in vec3 v_cubeMapCoordinates;\nuniform samplerCube cubeMap;\n\nvoid main()\n{\n vec4 rgba = czm_textureCube(cubeMap, v_cubeMapCoordinates);\n #ifdef RGBA_NORMALIZED\n out_FragColor = vec4(rgba.rgb, 1.0);\n #else\n float m = rgba.a * 16.0;\n vec3 r = rgba.rgb * m;\n out_FragColor = vec4(r * r, 1.0);\n #endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/OctahedralProjectionVS.js
var OctahedralProjectionVS_default = "in vec4 position;\nin vec3 cubeMapCoordinates;\n\nout vec3 v_cubeMapCoordinates;\n\nvoid main()\n{\n gl_Position = position;\n v_cubeMapCoordinates = cubeMapCoordinates;\n}\n";
// node_modules/@cesium/engine/Source/Scene/OctahedralProjectedCubeMap.js
function OctahedralProjectedCubeMap(url2) {
this._url = url2;
this._cubeMapBuffers = void 0;
this._cubeMaps = void 0;
this._texture = void 0;
this._mipTextures = void 0;
this._va = void 0;
this._sp = void 0;
this._maximumMipmapLevel = void 0;
this._loading = false;
this._ready = false;
this._errorEvent = new Event_default();
}
Object.defineProperties(OctahedralProjectedCubeMap.prototype, {
url: {
get: function() {
return this._url;
}
},
errorEvent: {
get: function() {
return this._errorEvent;
}
},
texture: {
get: function() {
return this._texture;
}
},
maximumMipmapLevel: {
get: function() {
return this._maximumMipmapLevel;
}
},
ready: {
get: function() {
return this._ready;
}
}
});
OctahedralProjectedCubeMap.isSupported = function(context) {
return context.colorBufferHalfFloat && context.halfFloatingPointTexture || context.floatingPointTexture && context.colorBufferFloat;
};
var v12 = new Cartesian3_default(1, 0, 0);
var v22 = new Cartesian3_default(0, 0, 1);
var v3 = new Cartesian3_default(-1, 0, 0);
var v4 = new Cartesian3_default(0, 0, -1);
var v5 = new Cartesian3_default(0, 1, 0);
var v6 = new Cartesian3_default(0, -1, 0);
var cubeMapCoordinates = [v5, v3, v22, v6, v12, v5, v4, v5, v5];
var length = cubeMapCoordinates.length;
var flatCubeMapCoordinates = new Float32Array(length * 3);
var offset = 0;
for (let i = 0; i < length; ++i, offset += 3) {
Cartesian3_default.pack(cubeMapCoordinates[i], flatCubeMapCoordinates, offset);
}
var flatPositions = new Float32Array([
-1,
1,
-1,
0,
0,
1,
0,
0,
1,
0,
1,
1,
0,
-1,
-1,
-1,
1,
-1
]);
var indices = new Uint16Array([
0,
1,
2,
2,
3,
1,
7,
6,
1,
3,
6,
1,
2,
5,
4,
3,
4,
2,
4,
8,
6,
3,
4,
6
]);
function createVertexArray2(context) {
const positionBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: flatPositions,
usage: BufferUsage_default.STATIC_DRAW
});
const cubeMapCoordinatesBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: flatCubeMapCoordinates,
usage: BufferUsage_default.STATIC_DRAW
});
const indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: indices,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
const attributes = [
{
index: 0,
vertexBuffer: positionBuffer,
componentsPerAttribute: 2,
componentDatatype: ComponentDatatype_default.FLOAT
},
{
index: 1,
vertexBuffer: cubeMapCoordinatesBuffer,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT
}
];
return new VertexArray_default({
context,
attributes,
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 length3;
const cubeMaps = map._cubeMaps;
if (defined_default(cubeMaps)) {
length3 = cubeMaps.length;
for (i = 0; i < length3; ++i) {
cubeMaps[i].destroy();
}
}
const mipTextures = map._mipTextures;
if (defined_default(mipTextures)) {
length3 = mipTextures.length;
for (i = 0; i < length3; ++i) {
mipTextures[i].destroy();
}
}
map._va = void 0;
map._sp = void 0;
map._cubeMaps = void 0;
map._cubeMapBuffers = void 0;
map._mipTextures = void 0;
}
OctahedralProjectedCubeMap.prototype.update = function(frameState) {
const context = frameState.context;
if (!OctahedralProjectedCubeMap.isSupported(context)) {
return;
}
if (defined_default(this._texture) && defined_default(this._va)) {
cleanupResources(this);
}
if (defined_default(this._texture)) {
return;
}
if (!defined_default(this._texture) && !this._loading) {
const cachedTexture = frameState.context.textureCache.getTexture(this._url);
if (defined_default(cachedTexture)) {
cleanupResources(this);
this._texture = cachedTexture;
this._maximumMipmapLevel = this._texture.maximumMipmapLevel;
this._ready = true;
}
}
const cubeMapBuffers = this._cubeMapBuffers;
if (!defined_default(cubeMapBuffers) && !this._loading) {
const that = this;
loadKTX2_default(this._url).then(function(buffers) {
that._cubeMapBuffers = buffers;
that._loading = false;
}).catch(function(error) {
if (that.isDestroyed()) {
return;
}
that._errorEvent.raiseEvent(error);
});
this._loading = true;
}
if (!defined_default(this._cubeMapBuffers)) {
return;
}
const defines = [];
let pixelDatatype = cubeMapBuffers[0].positiveX.pixelDatatype;
if (!defined_default(pixelDatatype)) {
pixelDatatype = context.halfFloatingPointTexture ? PixelDatatype_default.HALF_FLOAT : PixelDatatype_default.FLOAT;
} else {
defines.push("RGBA_NORMALIZED");
}
const pixelFormat = PixelFormat_default.RGBA;
const fs = new ShaderSource_default({
defines,
sources: [OctahedralProjectionFS_default]
});
this._va = createVertexArray2(context);
this._sp = ShaderProgram_default.fromCache({
context,
vertexShaderSource: OctahedralProjectionVS_default,
fragmentShaderSource: fs,
attributeLocations: {
position: 0,
cubeMapCoordinates: 1
}
});
const length3 = Math.min(cubeMapBuffers.length, 6);
this._maximumMipmapLevel = length3 - 1;
const cubeMaps = this._cubeMaps = new Array(length3);
const mipTextures = this._mipTextures = new Array(length3);
const originalSize = cubeMapBuffers[0].positiveX.width * 2;
const uniformMap2 = {
originalSize: function() {
return originalSize;
}
};
for (let i = 0; i < length3; ++i) {
const positiveY = cubeMapBuffers[i].positiveY;
cubeMapBuffers[i].positiveY = cubeMapBuffers[i].negativeY;
cubeMapBuffers[i].negativeY = positiveY;
const cubeMap = cubeMaps[i] = new CubeMap_default({
context,
source: cubeMapBuffers[i],
pixelDatatype
});
const size = cubeMaps[i].width * 2;
const mipTexture = mipTextures[i] = new Texture_default({
context,
width: size,
height: size,
pixelDatatype,
pixelFormat
});
const command = new ComputeCommand_default({
vertexArray: this._va,
shaderProgram: this._sp,
uniformMap: {
cubeMap: createUniformTexture(cubeMap)
},
outputTexture: mipTexture,
persists: true,
owner: this
});
frameState.commandList.push(command);
uniformMap2[`texture${i}`] = createUniformTexture(mipTexture);
}
this._texture = new Texture_default({
context,
width: originalSize * 1.5 + 2,
height: originalSize,
pixelDatatype,
pixelFormat
});
this._texture.maximumMipmapLevel = this._maximumMipmapLevel;
context.textureCache.addTexture(this._url, this._texture);
const atlasCommand = new ComputeCommand_default({
fragmentShaderSource: OctahedralProjectionAtlasFS_default,
uniformMap: uniformMap2,
outputTexture: this._texture,
persists: false,
owner: this
});
frameState.commandList.push(atlasCommand);
this._ready = true;
};
OctahedralProjectedCubeMap.prototype.isDestroyed = function() {
return false;
};
OctahedralProjectedCubeMap.prototype.destroy = function() {
cleanupResources(this);
this._texture = this._texture && this._texture.destroy();
return destroyObject_default(this);
};
var OctahedralProjectedCubeMap_default = OctahedralProjectedCubeMap;
// node_modules/@cesium/engine/Source/Scene/ImageBasedLighting.js
function ImageBasedLighting(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const imageBasedLightingFactor = defined_default(options.imageBasedLightingFactor) ? Cartesian2_default.clone(options.imageBasedLightingFactor) : new Cartesian2_default(1, 1);
Check_default.typeOf.object(
"options.imageBasedLightingFactor",
imageBasedLightingFactor
);
Check_default.typeOf.number.greaterThanOrEquals(
"options.imageBasedLightingFactor.x",
imageBasedLightingFactor.x,
0
);
Check_default.typeOf.number.lessThanOrEquals(
"options.imageBasedLightingFactor.x",
imageBasedLightingFactor.x,
1
);
Check_default.typeOf.number.greaterThanOrEquals(
"options.imageBasedLightingFactor.y",
imageBasedLightingFactor.y,
0
);
Check_default.typeOf.number.lessThanOrEquals(
"options.imageBasedLightingFactor.y",
imageBasedLightingFactor.y,
1
);
this._imageBasedLightingFactor = imageBasedLightingFactor;
const luminanceAtZenith = defaultValue_default(options.luminanceAtZenith, 0.2);
Check_default.typeOf.number("options.luminanceAtZenith", luminanceAtZenith);
this._luminanceAtZenith = luminanceAtZenith;
const sphericalHarmonicCoefficients = options.sphericalHarmonicCoefficients;
if (defined_default(sphericalHarmonicCoefficients) && (!Array.isArray(sphericalHarmonicCoefficients) || sphericalHarmonicCoefficients.length !== 9)) {
throw new DeveloperError_default(
"options.sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values."
);
}
this._sphericalHarmonicCoefficients = sphericalHarmonicCoefficients;
this._specularEnvironmentMaps = options.specularEnvironmentMaps;
this._specularEnvironmentMapAtlas = void 0;
this._specularEnvironmentMapAtlasDirty = true;
this._specularEnvironmentMapLoaded = false;
this._previousSpecularEnvironmentMapLoaded = false;
this._useDefaultSpecularMaps = false;
this._useDefaultSphericalHarmonics = false;
this._shouldRegenerateShaders = false;
this._previousFrameNumber = void 0;
this._previousImageBasedLightingFactor = Cartesian2_default.clone(
imageBasedLightingFactor
);
this._previousLuminanceAtZenith = luminanceAtZenith;
this._previousSphericalHarmonicCoefficients = sphericalHarmonicCoefficients;
this._removeErrorListener = void 0;
}
Object.defineProperties(ImageBasedLighting.prototype, {
imageBasedLightingFactor: {
get: function() {
return this._imageBasedLightingFactor;
},
set: function(value) {
Check_default.typeOf.object("imageBasedLightingFactor", value);
Check_default.typeOf.number.greaterThanOrEquals(
"imageBasedLightingFactor.x",
value.x,
0
);
Check_default.typeOf.number.lessThanOrEquals(
"imageBasedLightingFactor.x",
value.x,
1
);
Check_default.typeOf.number.greaterThanOrEquals(
"imageBasedLightingFactor.y",
value.y,
0
);
Check_default.typeOf.number.lessThanOrEquals(
"imageBasedLightingFactor.y",
value.y,
1
);
this._previousImageBasedLightingFactor = Cartesian2_default.clone(
this._imageBasedLightingFactor,
this._previousImageBasedLightingFactor
);
this._imageBasedLightingFactor = Cartesian2_default.clone(
value,
this._imageBasedLightingFactor
);
}
},
luminanceAtZenith: {
get: function() {
return this._luminanceAtZenith;
},
set: function(value) {
this._previousLuminanceAtZenith = this._luminanceAtZenith;
this._luminanceAtZenith = value;
}
},
sphericalHarmonicCoefficients: {
get: function() {
return this._sphericalHarmonicCoefficients;
},
set: function(value) {
if (defined_default(value) && (!Array.isArray(value) || value.length !== 9)) {
throw new DeveloperError_default(
"sphericalHarmonicCoefficients must be an array of 9 Cartesian3 values."
);
}
this._previousSphericalHarmonicCoefficients = this._sphericalHarmonicCoefficients;
this._sphericalHarmonicCoefficients = value;
}
},
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;
}
},
enabled: {
get: function() {
return this._imageBasedLightingFactor.x > 0 || this._imageBasedLightingFactor.y > 0;
}
},
shouldRegenerateShaders: {
get: function() {
return this._shouldRegenerateShaders;
}
},
useDefaultSphericalHarmonics: {
get: function() {
return this._useDefaultSphericalHarmonics;
}
},
useSphericalHarmonicCoefficients: {
get: function() {
return defined_default(this._sphericalHarmonicCoefficients) || this._useDefaultSphericalHarmonics;
}
},
specularEnvironmentMapAtlas: {
get: function() {
return this._specularEnvironmentMapAtlas;
}
},
useDefaultSpecularMaps: {
get: function() {
return this._useDefaultSpecularMaps;
}
},
useSpecularEnvironmentMaps: {
get: function() {
return defined_default(this._specularEnvironmentMapAtlas) && this._specularEnvironmentMapAtlas.ready || this._useDefaultSpecularMaps;
}
}
});
function createSpecularEnvironmentMapAtlas(imageBasedLighting, context) {
if (!OctahedralProjectedCubeMap_default.isSupported(context)) {
return;
}
imageBasedLighting._specularEnvironmentMapAtlas = imageBasedLighting._specularEnvironmentMapAtlas && imageBasedLighting._specularEnvironmentMapAtlas.destroy();
if (defined_default(imageBasedLighting._specularEnvironmentMaps)) {
const atlas = new OctahedralProjectedCubeMap_default(
imageBasedLighting._specularEnvironmentMaps
);
imageBasedLighting._specularEnvironmentMapAtlas = atlas;
imageBasedLighting._removeErrorListener = atlas.errorEvent.addEventListener(
(error) => {
console.error(`Error loading specularEnvironmentMaps: ${error}`);
}
);
}
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_default.equals(iblFactor, previousIBLFactor)) {
this._shouldRegenerateShaders = iblFactor.x > 0 && previousIBLFactor.x === 0 || iblFactor.x === 0 && previousIBLFactor.x > 0;
this._shouldRegenerateShaders = this._shouldRegenerateShaders || iblFactor.y > 0 && previousIBLFactor.y === 0 || iblFactor.y === 0 && previousIBLFactor.y > 0;
this._previousImageBasedLightingFactor = Cartesian2_default.clone(
this._imageBasedLightingFactor,
this._previousImageBasedLightingFactor
);
}
if (this._luminanceAtZenith !== this._previousLuminanceAtZenith) {
this._shouldRegenerateShaders = this._shouldRegenerateShaders || defined_default(this._luminanceAtZenith) !== defined_default(this._previousLuminanceAtZenith);
this._previousLuminanceAtZenith = this._luminanceAtZenith;
}
if (this._previousSphericalHarmonicCoefficients !== this._sphericalHarmonicCoefficients) {
this._shouldRegenerateShaders = this._shouldRegenerateShaders || defined_default(this._previousSphericalHarmonicCoefficients) !== defined_default(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_default(this._specularEnvironmentMapAtlas)) {
this._specularEnvironmentMapAtlas.update(frameState);
if (this._specularEnvironmentMapAtlas.ready) {
this._specularEnvironmentMapLoaded = true;
}
}
const recompileWithDefaultAtlas = !defined_default(this._specularEnvironmentMapAtlas) && defined_default(frameState.specularEnvironmentMaps) && !this._useDefaultSpecularMaps;
const recompileWithoutDefaultAtlas = !defined_default(frameState.specularEnvironmentMaps) && this._useDefaultSpecularMaps;
const recompileWithDefaultSHCoeffs = !defined_default(this._sphericalHarmonicCoefficients) && defined_default(frameState.sphericalHarmonicCoefficients) && !this._useDefaultSphericalHarmonics;
const recompileWithoutDefaultSHCoeffs = !defined_default(frameState.sphericalHarmonicCoefficients) && this._useDefaultSphericalHarmonics;
this._shouldRegenerateShaders = this._shouldRegenerateShaders || recompileWithDefaultAtlas || recompileWithoutDefaultAtlas || recompileWithDefaultSHCoeffs || recompileWithoutDefaultSHCoeffs;
this._useDefaultSpecularMaps = !defined_default(this._specularEnvironmentMapAtlas) && defined_default(frameState.specularEnvironmentMaps);
this._useDefaultSphericalHarmonics = !defined_default(this._sphericalHarmonicCoefficients) && defined_default(frameState.sphericalHarmonicCoefficients);
};
ImageBasedLighting.prototype.isDestroyed = function() {
return false;
};
ImageBasedLighting.prototype.destroy = function() {
this._specularEnvironmentMapAtlas = this._specularEnvironmentMapAtlas && this._specularEnvironmentMapAtlas.destroy();
this._removeErrorListener = this._removeErrorListener && this._removeErrorListener();
return destroyObject_default(this);
};
var ImageBasedLighting_default = ImageBasedLighting;
// node_modules/@cesium/engine/Source/Core/IonResource.js
var import_urijs8 = __toESM(require_URI(), 1);
// node_modules/@cesium/engine/Source/Core/Ion.js
var defaultTokenCredit;
var defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwZWQ3OWFlZC1kOTg3LTRlZjctYTAyYy0xNjFmODE1MWE2NGUiLCJpZCI6MjU5LCJpYXQiOjE2ODI5NDYzODh9.DEH4GpqliH-xsDE7h-ZCICtHgnGu32wdSjt4hFqw7lU";
var Ion = {};
Ion.defaultAccessToken = defaultAccessToken;
Ion.defaultServer = new Resource_default({ url: "https://api.cesium.com/" });
Ion.getDefaultTokenCredit = function(providedKey) {
if (providedKey !== defaultAccessToken) {
return void 0;
}
if (!defined_default(defaultTokenCredit)) {
const defaultTokenMessage = ` This application is using Cesium's default ion access token. Please assign Cesium.Ion.defaultAccessToken with an access token from your ion account before making any Cesium API calls. You can sign up for a free ion account at https://cesium.com.`;
defaultTokenCredit = new Credit_default(defaultTokenMessage, true);
}
return defaultTokenCredit;
};
var Ion_default = Ion;
// node_modules/@cesium/engine/Source/Core/IonResource.js
function IonResource(endpoint, endpointResource) {
Check_default.defined("endpoint", endpoint);
Check_default.defined("endpointResource", endpointResource);
let options;
const externalType = endpoint.externalType;
const isExternal = defined_default(externalType);
if (!isExternal) {
options = {
url: endpoint.url,
retryAttempts: 1,
retryCallback
};
} else if (externalType === "3DTILES" || externalType === "STK_TERRAIN_SERVER") {
options = { url: endpoint.options.url };
} else {
throw new RuntimeError_default(
"Ion.createResource does not support external imagery assets; use IonImageryProvider instead."
);
}
Resource_default.call(this, options);
this._ionEndpoint = endpoint;
this._ionEndpointDomain = isExternal ? void 0 : new import_urijs8.default(endpoint.url).authority();
this._ionEndpointResource = endpointResource;
this._ionRoot = void 0;
this._pendingPromise = void 0;
this._credits = void 0;
this._isExternal = isExternal;
}
if (defined_default(Object.create)) {
IonResource.prototype = Object.create(Resource_default.prototype);
IonResource.prototype.constructor = IonResource;
}
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, {
credits: {
get: function() {
if (defined_default(this._ionRoot)) {
return this._ionRoot.credits;
}
if (defined_default(this._credits)) {
return this._credits;
}
this._credits = IonResource.getCreditsFromEndpoint(
this._ionEndpoint,
this._ionEndpointResource
);
return this._credits;
}
}
});
IonResource.getCreditsFromEndpoint = function(endpoint, endpointResource) {
const credits = endpoint.attributions.map(Credit_default.getIonCredit);
const defaultTokenCredit3 = Ion_default.getDefaultTokenCredit(
endpointResource.queryParameters.access_token
);
if (defined_default(defaultTokenCredit3)) {
credits.push(Credit_default.clone(defaultTokenCredit3));
}
return credits;
};
IonResource.prototype.clone = function(result) {
const ionRoot = defaultValue_default(this._ionRoot, this);
if (!defined_default(result)) {
result = new IonResource(
ionRoot._ionEndpoint,
ionRoot._ionEndpointResource
);
}
result = Resource_default.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_default(userOptions)) {
options.flipY = userOptions.flipY;
options.preferImageBitmap = userOptions.preferImageBitmap;
}
}
return Resource_default.prototype.fetchImage.call(this, options);
};
IonResource.prototype._makeRequest = function(options) {
if (this._isExternal || new import_urijs8.default(this.url).authority() !== this._ionEndpointDomain) {
return Resource_default.prototype._makeRequest.call(this, options);
}
if (!defined_default(options.headers)) {
options.headers = {};
}
options.headers.Authorization = `Bearer ${this._ionEndpoint.accessToken}`;
options.headers["X-Cesium-Client"] = "CesiumJS";
if (typeof CESIUM_VERSION !== "undefined") {
options.headers["X-Cesium-Client-Version"] = CESIUM_VERSION;
}
return Resource_default.prototype._makeRequest.call(this, options);
};
IonResource._createEndpointResource = function(assetId, options) {
Check_default.defined("assetId", assetId);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let server = defaultValue_default(options.server, Ion_default.defaultServer);
const accessToken = defaultValue_default(options.accessToken, Ion_default.defaultAccessToken);
server = Resource_default.createIfNeeded(server);
const resourceOptions = {
url: `v1/assets/${assetId}/endpoint`
};
if (defined_default(accessToken)) {
resourceOptions.queryParameters = { access_token: accessToken };
}
return server.getDerivedResource(resourceOptions);
};
function retryCallback(that, error) {
const ionRoot = defaultValue_default(that._ionRoot, that);
const endpointResource = ionRoot._ionEndpointResource;
const imageDefined = typeof Image !== "undefined";
if (!defined_default(error) || error.statusCode !== 401 && !(imageDefined && error.target instanceof Image)) {
return Promise.resolve(false);
}
if (!defined_default(ionRoot._pendingPromise)) {
ionRoot._pendingPromise = endpointResource.fetchJson().then(function(newEndpoint) {
ionRoot._ionEndpoint = newEndpoint;
return newEndpoint;
}).finally(function(newEndpoint) {
ionRoot._pendingPromise = void 0;
return newEndpoint;
});
}
return ionRoot._pendingPromise.then(function(newEndpoint) {
that._ionEndpoint = newEndpoint;
return true;
});
}
var IonResource_default = IonResource;
// node_modules/@cesium/engine/Source/Core/ManagedArray.js
function ManagedArray(length3) {
length3 = defaultValue_default(length3, 0);
this._array = new Array(length3);
this._length = length3;
}
Object.defineProperties(ManagedArray.prototype, {
length: {
get: function() {
return this._length;
},
set: function(length3) {
Check_default.typeOf.number.greaterThanOrEquals("length", length3, 0);
const array = this._array;
const originalLength = this._length;
if (length3 < originalLength) {
for (let i = length3; i < originalLength; ++i) {
array[i] = void 0;
}
} else if (length3 > array.length) {
array.length = length3;
}
this._length = length3;
}
},
values: {
get: function() {
return this._array;
}
}
});
ManagedArray.prototype.get = function(index) {
Check_default.typeOf.number.lessThan("index", index, this._array.length);
return this._array[index];
};
ManagedArray.prototype.set = function(index, element) {
Check_default.typeOf.number("index", index);
if (index >= this._length) {
this.length = index + 1;
}
this._array[index] = element;
};
ManagedArray.prototype.peek = function() {
return this._array[this._length - 1];
};
ManagedArray.prototype.push = function(element) {
const index = this.length++;
this._array[index] = element;
};
ManagedArray.prototype.pop = function() {
if (this._length === 0) {
return void 0;
}
const element = this._array[this._length - 1];
--this.length;
return element;
};
ManagedArray.prototype.reserve = function(length3) {
Check_default.typeOf.number.greaterThanOrEquals("length", length3, 0);
if (length3 > this._array.length) {
this._array.length = length3;
}
};
ManagedArray.prototype.resize = function(length3) {
Check_default.typeOf.number.greaterThanOrEquals("length", length3, 0);
this.length = length3;
};
ManagedArray.prototype.trim = function(length3) {
length3 = defaultValue_default(length3, this._length);
this._array.length = length3;
};
var ManagedArray_default = ManagedArray;
// node_modules/@cesium/engine/Source/Scene/Axis.js
var Axis = {
X: 0,
Y: 1,
Z: 2
};
Axis.Y_UP_TO_Z_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationX(Math_default.PI_OVER_TWO)
);
Axis.Z_UP_TO_Y_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationX(-Math_default.PI_OVER_TWO)
);
Axis.X_UP_TO_Z_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationY(-Math_default.PI_OVER_TWO)
);
Axis.Z_UP_TO_X_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationY(Math_default.PI_OVER_TWO)
);
Axis.X_UP_TO_Y_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationZ(Math_default.PI_OVER_TWO)
);
Axis.Y_UP_TO_X_UP = Matrix4_default.fromRotationTranslation(
Matrix3_default.fromRotationZ(-Math_default.PI_OVER_TWO)
);
Axis.fromName = function(name) {
Check_default.typeOf.string("name", name);
return Axis[name];
};
var Axis_default = Object.freeze(Axis);
// node_modules/@cesium/engine/Source/Scene/Cesium3DContentGroup.js
function Cesium3DContentGroup(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.metadata", options.metadata);
this._metadata = options.metadata;
}
Object.defineProperties(Cesium3DContentGroup.prototype, {
metadata: {
get: function() {
return this._metadata;
}
}
});
var Cesium3DContentGroup_default = Cesium3DContentGroup;
// node_modules/@cesium/engine/Source/Core/getStringFromTypedArray.js
function getStringFromTypedArray(uint8Array, byteOffset, byteLength) {
if (!defined_default(uint8Array)) {
throw new DeveloperError_default("uint8Array is required.");
}
if (byteOffset < 0) {
throw new DeveloperError_default("byteOffset cannot be negative.");
}
if (byteLength < 0) {
throw new DeveloperError_default("byteLength cannot be negative.");
}
if (byteOffset + byteLength > uint8Array.byteLength) {
throw new DeveloperError_default("sub-region exceeds array bounds.");
}
byteOffset = defaultValue_default(byteOffset, 0);
byteLength = defaultValue_default(byteLength, uint8Array.byteLength - byteOffset);
uint8Array = uint8Array.subarray(byteOffset, byteOffset + byteLength);
return getStringFromTypedArray.decode(uint8Array);
}
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 length3 = codePoints.length;
for (let i = 0; i < length3; ++i) {
let cp = codePoints[i];
if (cp <= 65535) {
result += String.fromCharCode(cp);
} else {
cp -= 65536;
result += String.fromCharCode((cp >> 10) + 55296, (cp & 1023) + 56320);
}
}
return result;
};
function inRange(a3, min3, max3) {
return min3 <= a3 && a3 <= max3;
}
function utf8Handler(utfBytes) {
let codePoint = 0;
let bytesSeen = 0;
let bytesNeeded = 0;
let lowerBoundary = 128;
let upperBoundary = 191;
const codePoints = [];
const length3 = utfBytes.length;
for (let i = 0; i < length3; ++i) {
const currentByte = utfBytes[i];
if (bytesNeeded === 0) {
if (inRange(currentByte, 0, 127)) {
codePoints.push(currentByte);
continue;
}
if (inRange(currentByte, 194, 223)) {
bytesNeeded = 1;
codePoint = currentByte & 31;
continue;
}
if (inRange(currentByte, 224, 239)) {
if (currentByte === 224) {
lowerBoundary = 160;
}
if (currentByte === 237) {
upperBoundary = 159;
}
bytesNeeded = 2;
codePoint = currentByte & 15;
continue;
}
if (inRange(currentByte, 240, 244)) {
if (currentByte === 240) {
lowerBoundary = 144;
}
if (currentByte === 244) {
upperBoundary = 143;
}
bytesNeeded = 3;
codePoint = currentByte & 7;
continue;
}
throw new RuntimeError_default("String decoding failed.");
}
if (!inRange(currentByte, lowerBoundary, upperBoundary)) {
codePoint = bytesNeeded = bytesSeen = 0;
lowerBoundary = 128;
upperBoundary = 191;
--i;
continue;
}
lowerBoundary = 128;
upperBoundary = 191;
codePoint = codePoint << 6 | currentByte & 63;
++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;
}
var getStringFromTypedArray_default = getStringFromTypedArray;
// node_modules/@cesium/engine/Source/Core/getMagic.js
function getMagic(uint8Array, byteOffset) {
byteOffset = defaultValue_default(byteOffset, 0);
return getStringFromTypedArray_default(
uint8Array,
byteOffset,
Math.min(4, uint8Array.length)
);
}
var getMagic_default = getMagic;
// node_modules/@cesium/engine/Source/Scene/Composite3DTileContent.js
function Composite3DTileContent(tileset, tile, resource, contents) {
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
if (!defined_default(contents)) {
contents = [];
}
this._contents = contents;
this._metadata = void 0;
this._group = void 0;
this._ready = false;
this._resolveContent = void 0;
this._readyPromise = new Promise((resolve2) => {
this._resolveContent = resolve2;
});
}
Object.defineProperties(Composite3DTileContent.prototype, {
featurePropertiesDirty: {
get: function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
if (contents[i].featurePropertiesDirty) {
return true;
}
}
return false;
},
set: function(value) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].featurePropertiesDirty = value;
}
}
},
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 this._contents;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Composite3DTileContent.readyPromise",
"Composite3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Composite3DTileContent.ready to return true instead."
);
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;
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].metadata = value;
}
}
},
batchTable: {
get: function() {
return void 0;
}
},
group: {
get: function() {
return this._group;
},
set: function(value) {
this._group = value;
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].group = value;
}
}
}
});
var sizeOfUint32 = Uint32Array.BYTES_PER_ELEMENT;
Composite3DTileContent.fromTileType = async function(tileset, tile, resource, arrayBuffer, byteOffset, factory) {
byteOffset = defaultValue_default(byteOffset, 0);
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint32;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Composite Tile version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint32;
byteOffset += sizeOfUint32;
const tilesLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint32;
let prefix = resource.queryParameters.compositeIndex;
if (defined_default(prefix)) {
prefix = `${prefix}_`;
} else {
prefix = "";
}
const promises = [];
promises.length = tilesLength;
for (let i = 0; i < tilesLength; ++i) {
const tileType = getMagic_default(uint8Array, byteOffset);
const tileByteLength = view.getUint32(byteOffset + sizeOfUint32 * 2, true);
const contentFactory = factory[tileType];
const compositeIndex = `${prefix}${i}`;
const childResource = resource.getDerivedResource({
queryParameters: {
compositeIndex
}
});
if (defined_default(contentFactory)) {
promises[i] = Promise.resolve(
contentFactory(tileset, tile, childResource, arrayBuffer, byteOffset)
);
} else {
throw new RuntimeError_default(
`Unknown tile content type, ${tileType}, inside Composite tile`
);
}
byteOffset += tileByteLength;
}
const innerContents = await Promise.all(promises);
const content = new Composite3DTileContent(
tileset,
tile,
resource,
innerContents
);
return content;
};
Composite3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Composite3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
Composite3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyDebugSettings(enabled, color);
}
};
Composite3DTileContent.prototype.applyStyle = function(style) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyStyle(style);
}
};
Composite3DTileContent.prototype.update = function(tileset, frameState) {
const contents = this._contents;
const length3 = contents.length;
let ready = true;
for (let i = 0; i < length3; ++i) {
contents[i].update(tileset, frameState);
ready = ready && contents[i].ready;
}
if (!this._ready && ready) {
this._ready = true;
this._resolveContent(this);
}
};
Composite3DTileContent.prototype.isDestroyed = function() {
return false;
};
Composite3DTileContent.prototype.destroy = function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].destroy();
}
return destroyObject_default(this);
};
var Composite3DTileContent_default = Composite3DTileContent;
// node_modules/@cesium/engine/Source/Core/getJsonFromTypedArray.js
function getJsonFromTypedArray(uint8Array, byteOffset, byteLength) {
return JSON.parse(
getStringFromTypedArray_default(uint8Array, byteOffset, byteLength)
);
}
var getJsonFromTypedArray_default = getJsonFromTypedArray;
// node_modules/@cesium/engine/Source/Scene/BatchTexture.js
function BatchTexture(options) {
Check_default.typeOf.number("options.featuresLength", options.featuresLength);
Check_default.typeOf.object("options.owner", options.owner);
this._id = createGuid_default();
const featuresLength = options.featuresLength;
this._showAlphaProperties = void 0;
this._batchValues = void 0;
this._batchValuesDirty = false;
this._batchTexture = void 0;
this._defaultTexture = void 0;
this._pickTexture = void 0;
this._pickIds = [];
let textureDimensions;
let textureStep;
if (featuresLength > 0) {
const width = Math.min(featuresLength, ContextLimits_default.maximumTextureSize);
const height = Math.ceil(featuresLength / ContextLimits_default.maximumTextureSize);
const stepX = 1 / width;
const centerX = stepX * 0.5;
const stepY = 1 / height;
const centerY = stepY * 0.5;
textureDimensions = new Cartesian2_default(width, height);
textureStep = new Cartesian4_default(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, {
translucentFeaturesLength: {
get: function() {
return this._translucentFeaturesLength;
}
},
byteLength: {
get: function() {
let memory = 0;
if (defined_default(this._pickTexture)) {
memory += this._pickTexture.sizeInBytes;
}
if (defined_default(this._batchTexture)) {
memory += this._batchTexture.sizeInBytes;
}
return memory;
}
},
textureDimensions: {
get: function() {
return this._textureDimensions;
}
},
textureStep: {
get: function() {
return this._textureStep;
}
},
batchTexture: {
get: function() {
return this._batchTexture;
}
},
defaultTexture: {
get: function() {
return this._defaultTexture;
}
},
pickTexture: {
get: function() {
return this._pickTexture;
}
}
});
BatchTexture.DEFAULT_COLOR_VALUE = Color_default.WHITE;
BatchTexture.DEFAULT_SHOW_VALUE = true;
function getByteLength(batchTexture) {
const dimensions = batchTexture._textureDimensions;
return dimensions.x * dimensions.y * 4;
}
function getBatchValues(batchTexture) {
if (!defined_default(batchTexture._batchValues)) {
const byteLength = getByteLength(batchTexture);
const bytes = new Uint8Array(byteLength).fill(255);
batchTexture._batchValues = bytes;
}
return batchTexture._batchValues;
}
function getShowAlphaProperties(batchTexture) {
if (!defined_default(batchTexture._showAlphaProperties)) {
const byteLength = 2 * batchTexture._featuresLength;
const bytes = new Uint8Array(byteLength).fill(255);
batchTexture._showAlphaProperties = bytes;
}
return batchTexture._showAlphaProperties;
}
function checkBatchId(batchId, featuresLength) {
if (!defined_default(batchId) || batchId < 0 || batchId >= featuresLength) {
throw new DeveloperError_default(
`batchId is required and between zero and featuresLength - 1 (${featuresLength}` - +")."
);
}
}
BatchTexture.prototype.setShow = function(batchId, show) {
checkBatchId(batchId, this._featuresLength);
Check_default.typeOf.bool("show", show);
if (show && !defined_default(this._showAlphaProperties)) {
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);
const offset2 = batchId * 4 + 3;
batchValues[offset2] = show ? showAlphaProperties[propertyOffset + 1] : 0;
this._batchValuesDirty = true;
}
};
BatchTexture.prototype.setAllShow = function(show) {
Check_default.typeOf.bool("show", show);
const featuresLength = this._featuresLength;
for (let i = 0; i < featuresLength; ++i) {
this.setShow(i, show);
}
};
BatchTexture.prototype.getShow = function(batchId) {
checkBatchId(batchId, this._featuresLength);
if (!defined_default(this._showAlphaProperties)) {
return true;
}
const offset2 = batchId * 2;
return this._showAlphaProperties[offset2] === 255;
};
var scratchColorBytes = new Array(4);
BatchTexture.prototype.setColor = function(batchId, color) {
checkBatchId(batchId, this._featuresLength);
Check_default.typeOf.object("color", color);
if (Color_default.equals(color, BatchTexture.DEFAULT_COLOR_VALUE) && !defined_default(this._batchValues)) {
return;
}
const newColor = color.toBytes(scratchColorBytes);
const newAlpha = newColor[3];
const batchValues = getBatchValues(this);
const offset2 = batchId * 4;
const showAlphaProperties = getShowAlphaProperties(this);
const propertyOffset = batchId * 2;
if (batchValues[offset2] !== newColor[0] || batchValues[offset2 + 1] !== newColor[1] || batchValues[offset2 + 2] !== newColor[2] || showAlphaProperties[propertyOffset + 1] !== newAlpha) {
batchValues[offset2] = newColor[0];
batchValues[offset2 + 1] = newColor[1];
batchValues[offset2 + 2] = newColor[2];
const wasTranslucent = showAlphaProperties[propertyOffset + 1] !== 255;
const show = showAlphaProperties[propertyOffset] !== 0;
batchValues[offset2 + 3] = show ? newAlpha : 0;
showAlphaProperties[propertyOffset + 1] = newAlpha;
const isTranslucent = newAlpha !== 255;
if (isTranslucent && !wasTranslucent) {
++this._translucentFeaturesLength;
} else if (!isTranslucent && wasTranslucent) {
--this._translucentFeaturesLength;
}
this._batchValuesDirty = true;
if (defined_default(this._colorChangedCallback)) {
this._colorChangedCallback(batchId, color);
}
}
};
BatchTexture.prototype.setAllColor = function(color) {
Check_default.typeOf.object("color", color);
const featuresLength = this._featuresLength;
for (let i = 0; i < featuresLength; ++i) {
this.setColor(i, color);
}
};
BatchTexture.prototype.getColor = function(batchId, result) {
checkBatchId(batchId, this._featuresLength);
Check_default.typeOf.object("result", result);
if (!defined_default(this._batchValues)) {
return Color_default.clone(BatchTexture.DEFAULT_COLOR_VALUE, result);
}
const batchValues = this._batchValues;
const offset2 = batchId * 4;
const showAlphaProperties = this._showAlphaProperties;
const propertyOffset = batchId * 2;
return Color_default.fromBytes(
batchValues[offset2],
batchValues[offset2 + 1],
batchValues[offset2 + 2],
showAlphaProperties[propertyOffset + 1],
result
);
};
BatchTexture.prototype.getPickColor = function(batchId) {
checkBatchId(batchId, this._featuresLength);
return this._pickIds[batchId];
};
function createTexture2(batchTexture, context, bytes) {
const dimensions = batchTexture._textureDimensions;
return new Texture_default({
context,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: PixelDatatype_default.UNSIGNED_BYTE,
source: {
width: dimensions.x,
height: dimensions.y,
arrayBufferView: bytes
},
flipY: false,
sampler: Sampler_default.NEAREST
});
}
function createPickTexture(batchTexture, context) {
const featuresLength = batchTexture._featuresLength;
if (!defined_default(batchTexture._pickTexture) && featuresLength > 0) {
const pickIds = batchTexture._pickIds;
const byteLength = getByteLength(batchTexture);
const bytes = new Uint8Array(byteLength);
const owner = batchTexture._owner;
const statistics2 = batchTexture._statistics;
for (let i = 0; i < featuresLength; ++i) {
const pickId = context.createPickId(owner.getFeature(i));
pickIds.push(pickId);
const pickColor = pickId.color;
const offset2 = i * 4;
bytes[offset2] = Color_default.floatToByte(pickColor.red);
bytes[offset2 + 1] = Color_default.floatToByte(pickColor.green);
bytes[offset2 + 2] = Color_default.floatToByte(pickColor.blue);
bytes[offset2 + 3] = Color_default.floatToByte(pickColor.alpha);
}
batchTexture._pickTexture = createTexture2(batchTexture, context, bytes);
if (defined_default(statistics2)) {
statistics2.batchTableByteLength += batchTexture._pickTexture.sizeInBytes;
}
}
}
function updateBatchTexture(batchTexture) {
const dimensions = batchTexture._textureDimensions;
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;
if (!defined_default(this._batchTexture)) {
this._batchTexture = createTexture2(this, context, this._batchValues);
if (defined_default(this._statistics)) {
this._statistics.batchTableByteLength += this._batchTexture.sizeInBytes;
}
}
updateBatchTexture(this);
}
};
BatchTexture.prototype.isDestroyed = function() {
return false;
};
BatchTexture.prototype.destroy = function() {
this._batchTexture = this._batchTexture && this._batchTexture.destroy();
this._pickTexture = this._pickTexture && this._pickTexture.destroy();
const pickIds = this._pickIds;
const length3 = pickIds.length;
for (let i = 0; i < length3; ++i) {
pickIds[i].destroy();
}
return destroyObject_default(this);
};
var BatchTexture_default = BatchTexture;
// node_modules/@cesium/engine/Source/Scene/getBinaryAccessor.js
var ComponentsPerAttribute = {
SCALAR: 1,
VEC2: 2,
VEC3: 3,
VEC4: 4,
MAT2: 4,
MAT3: 9,
MAT4: 16
};
var ClassPerType = {
SCALAR: void 0,
VEC2: Cartesian2_default,
VEC3: Cartesian3_default,
VEC4: Cartesian4_default,
MAT2: Matrix2_default,
MAT3: Matrix3_default,
MAT4: Matrix4_default
};
function getBinaryAccessor(accessor) {
const componentType = accessor.componentType;
let componentDatatype;
if (typeof componentType === "string") {
componentDatatype = ComponentDatatype_default.fromName(componentType);
} else {
componentDatatype = componentType;
}
const componentsPerAttribute = ComponentsPerAttribute[accessor.type];
const classType = ClassPerType[accessor.type];
return {
componentsPerAttribute,
classType,
createArrayBufferView: function(buffer, byteOffset, length3) {
return ComponentDatatype_default.createArrayBufferView(
componentDatatype,
buffer,
byteOffset,
componentsPerAttribute * length3
);
}
};
}
var getBinaryAccessor_default = getBinaryAccessor;
// node_modules/@cesium/engine/Source/Scene/BatchTableHierarchy.js
function BatchTableHierarchy(options) {
this._classes = void 0;
this._classIds = void 0;
this._classIndexes = void 0;
this._parentCounts = void 0;
this._parentIndexes = void 0;
this._parentIds = void 0;
this._byteLength = 0;
Check_default.typeOf.object("options.extension", options.extension);
initialize3(this, options.extension, options.binaryBody);
validateHierarchy(this);
}
Object.defineProperties(BatchTableHierarchy.prototype, {
byteLength: {
get: function() {
return this._byteLength;
}
}
});
function initialize3(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_default(classIds.byteOffset)) {
classIds.componentType = defaultValue_default(
classIds.componentType,
ComponentDatatype_default.UNSIGNED_SHORT
);
classIds.type = AttributeType_default.SCALAR;
binaryAccessor = getBinaryAccessor_default(classIds);
classIds = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + classIds.byteOffset,
instancesLength
);
byteLength += classIds.byteLength;
}
let parentIndexes;
if (defined_default(parentCounts)) {
if (defined_default(parentCounts.byteOffset)) {
parentCounts.componentType = defaultValue_default(
parentCounts.componentType,
ComponentDatatype_default.UNSIGNED_SHORT
);
parentCounts.type = AttributeType_default.SCALAR;
binaryAccessor = getBinaryAccessor_default(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_default(parentIds) && defined_default(parentIds.byteOffset)) {
parentIds.componentType = defaultValue_default(
parentIds.componentType,
ComponentDatatype_default.UNSIGNED_SHORT
);
parentIds.type = AttributeType_default.SCALAR;
binaryAccessor = getBinaryAccessor_default(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(
classInstancesLength,
properties,
binaryBody
);
byteLength += countBinaryPropertyMemory(binaryProperties);
classes[i].instances = combine_default(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(featuresLength, properties, binaryBody) {
let binaryProperties;
for (const name in properties) {
if (properties.hasOwnProperty(name)) {
const property = properties[name];
const byteOffset = property.byteOffset;
if (defined_default(byteOffset)) {
const componentType = property.componentType;
const type = property.type;
if (!defined_default(componentType)) {
throw new RuntimeError_default("componentType is required.");
}
if (!defined_default(type)) {
throw new RuntimeError_default("type is required.");
}
if (!defined_default(binaryBody)) {
throw new RuntimeError_default(
`Property ${name} requires a batch table binary.`
);
}
const binaryAccessor = getBinaryAccessor_default(property);
const componentCount = binaryAccessor.componentsPerAttribute;
const classType = binaryAccessor.classType;
const typedArray = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + byteOffset,
featuresLength
);
if (!defined_default(binaryProperties)) {
binaryProperties = {};
}
binaryProperties[name] = {
typedArray,
componentCount,
type: classType
};
}
}
}
return binaryProperties;
}
function countBinaryPropertyMemory(binaryProperties) {
let byteLength = 0;
for (const name in binaryProperties) {
if (binaryProperties.hasOwnProperty(name)) {
byteLength += binaryProperties[name].typedArray.byteLength;
}
}
return byteLength;
}
var 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_default(parentIds)) {
return;
}
if (instanceIndex >= instancesLength) {
throw new DeveloperError_default(
`Parent index ${instanceIndex} exceeds the total number of instances: ${instancesLength}`
);
}
if (stack.indexOf(instanceIndex) > -1) {
throw new DeveloperError_default(
"Circular dependency detected in the batch table hierarchy."
);
}
stack.push(instanceIndex);
const parentCount = defined_default(parentCounts) ? parentCounts[instanceIndex] : 1;
const parentIndex = defined_default(parentCounts) ? parentIndexes[instanceIndex] : instanceIndex;
for (let i = 0; i < parentCount; ++i) {
const parentId = parentIds[parentIndex + i];
if (parentId !== instanceIndex) {
validateInstance(hierarchy, parentId, stack);
}
}
stack.pop(instanceIndex);
}
var scratchVisited = [];
var scratchStack = [];
var 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;
const visited = scratchVisited;
visited.length = Math.max(visited.length, instancesLength);
const visitedMarker = ++marker;
const stack = scratchStack;
stack.length = 0;
stack.push(instanceIndex);
while (stack.length > 0) {
instanceIndex = stack.pop();
if (visited[instanceIndex] === visitedMarker) {
continue;
}
visited[instanceIndex] = visitedMarker;
const result = endConditionCallback(hierarchy, instanceIndex);
if (defined_default(result)) {
return result;
}
const parentCount = parentCounts[instanceIndex];
const parentIndex = parentIndexes[instanceIndex];
for (let i = 0; i < parentCount; ++i) {
const parentId = parentIds[parentIndex + i];
if (parentId !== instanceIndex) {
stack.push(parentId);
}
}
}
}
function traverseHierarchySingleParent(hierarchy, instanceIndex, endConditionCallback) {
let hasParent = true;
while (hasParent) {
const result = endConditionCallback(hierarchy, instanceIndex);
if (defined_default(result)) {
return result;
}
const parentId = hierarchy._parentIds[instanceIndex];
hasParent = parentId !== instanceIndex;
instanceIndex = parentId;
}
}
function traverseHierarchy(hierarchy, instanceIndex, endConditionCallback) {
const parentCounts = hierarchy._parentCounts;
const parentIds = hierarchy._parentIds;
if (!defined_default(parentIds)) {
return endConditionCallback(hierarchy, instanceIndex);
} else if (defined_default(parentCounts)) {
return traverseHierarchyMultipleParents(
hierarchy,
instanceIndex,
endConditionCallback
);
}
return traverseHierarchySingleParent(
hierarchy,
instanceIndex,
endConditionCallback
);
}
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_default(instances[propertyId])) {
return true;
}
});
return defined_default(result);
};
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_default(instances[propertyId])) {
return true;
}
}
return false;
};
BatchTableHierarchy.prototype.getPropertyIds = function(batchId, results) {
results = defined_default(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;
};
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_default(propertyValues)) {
if (defined_default(propertyValues.typedArray)) {
return getBinaryProperty(propertyValues, indexInClass);
}
return clone_default(propertyValues[indexInClass], true);
}
});
};
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);
}
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_default(propertyValues)) {
if (instanceIndex !== batchId) {
throw new DeveloperError_default(
`Inherited property "${propertyId}" is read-only.`
);
}
if (defined_default(propertyValues.typedArray)) {
setBinaryProperty(propertyValues, indexInClass, value);
} else {
propertyValues[indexInClass] = clone_default(value, true);
}
return true;
}
});
return defined_default(result);
};
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);
}
}
BatchTableHierarchy.prototype.isClass = function(batchId, className) {
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_default(result);
};
BatchTableHierarchy.prototype.getClassName = function(batchId) {
const classId = this._classIds[batchId];
const instanceClass = this._classes[classId];
return instanceClass.name;
};
var BatchTableHierarchy_default = BatchTableHierarchy;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileColorBlendMode.js
var Cesium3DTileColorBlendMode = {
HIGHLIGHT: 0,
REPLACE: 1,
MIX: 2
};
var Cesium3DTileColorBlendMode_default = Object.freeze(Cesium3DTileColorBlendMode);
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileBatchTable.js
var DEFAULT_COLOR_VALUE = BatchTexture_default.DEFAULT_COLOR_VALUE;
var DEFAULT_SHOW_VALUE = BatchTexture_default.DEFAULT_SHOW_VALUE;
function Cesium3DTileBatchTable(content, featuresLength, batchTableJson, batchTableBinary, colorChangedCallback) {
this.featuresLength = featuresLength;
let extensions;
if (defined_default(batchTableJson)) {
extensions = batchTableJson.extensions;
}
this._extensions = defaultValue_default(extensions, {});
const properties = initializeProperties(batchTableJson);
this._properties = properties;
this._batchTableHierarchy = initializeHierarchy(
this,
batchTableJson,
batchTableBinary
);
const binaryProperties = getBinaryProperties2(
featuresLength,
properties,
batchTableBinary
);
this._binaryPropertiesByteLength = countBinaryPropertyMemory2(
binaryProperties
);
this._batchTableBinaryProperties = binaryProperties;
this._content = content;
this._batchTexture = new BatchTexture_default({
featuresLength,
colorChangedCallback,
owner: content,
statistics: content.tileset.statistics
});
}
Cesium3DTileBatchTable._deprecationWarning = deprecationWarning_default;
Object.defineProperties(Cesium3DTileBatchTable.prototype, {
batchTableByteLength: {
get: function() {
let totalByteLength = this._binaryPropertiesByteLength;
if (defined_default(this._batchTableHierarchy)) {
totalByteLength += this._batchTableHierarchy.byteLength;
}
totalByteLength += this._batchTexture.byteLength;
return totalByteLength;
}
}
});
function initializeProperties(jsonHeader) {
const properties = {};
if (!defined_default(jsonHeader)) {
return properties;
}
for (const propertyName in jsonHeader) {
if (jsonHeader.hasOwnProperty(propertyName) && propertyName !== "HIERARCHY" && propertyName !== "extensions" && propertyName !== "extras") {
properties[propertyName] = clone_default(jsonHeader[propertyName], true);
}
}
return properties;
}
function initializeHierarchy(batchTable, jsonHeader, binaryBody) {
if (!defined_default(jsonHeader)) {
return;
}
let hierarchy = batchTable._extensions["3DTILES_batch_table_hierarchy"];
const legacyHierarchy = jsonHeader.HIERARCHY;
if (defined_default(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_default(hierarchy)) {
return;
}
return new BatchTableHierarchy_default({
extension: hierarchy,
binaryBody
});
}
function getBinaryProperties2(featuresLength, properties, binaryBody) {
let binaryProperties;
for (const name in properties) {
if (properties.hasOwnProperty(name)) {
const property = properties[name];
const byteOffset = property.byteOffset;
if (defined_default(byteOffset)) {
const componentType = property.componentType;
const type = property.type;
if (!defined_default(componentType)) {
throw new RuntimeError_default("componentType is required.");
}
if (!defined_default(type)) {
throw new RuntimeError_default("type is required.");
}
if (!defined_default(binaryBody)) {
throw new RuntimeError_default(
`Property ${name} requires a batch table binary.`
);
}
const binaryAccessor = getBinaryAccessor_default(property);
const componentCount = binaryAccessor.componentsPerAttribute;
const classType = binaryAccessor.classType;
const typedArray = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + byteOffset,
featuresLength
);
if (!defined_default(binaryProperties)) {
binaryProperties = {};
}
binaryProperties[name] = {
typedArray,
componentCount,
type: classType
};
}
}
}
return binaryProperties;
}
function countBinaryPropertyMemory2(binaryProperties) {
if (!defined_default(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 getBinaryProperties2(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);
};
var scratchColor2 = new Color_default();
Cesium3DTileBatchTable.prototype.applyStyle = function(style) {
if (!defined_default(style)) {
this.setAllColor(DEFAULT_COLOR_VALUE);
this.setAllShow(DEFAULT_SHOW_VALUE);
return;
}
const content = this._content;
const length3 = this.featuresLength;
for (let i = 0; i < length3; ++i) {
const feature = content.getFeature(i);
const color = defined_default(style.color) ? defaultValue_default(
style.color.evaluateColor(feature, scratchColor2),
DEFAULT_COLOR_VALUE
) : DEFAULT_COLOR_VALUE;
const show = defined_default(style.show) ? defaultValue_default(style.show.evaluate(feature), DEFAULT_SHOW_VALUE) : DEFAULT_SHOW_VALUE;
this.setColor(i, color);
this.setShow(i, show);
}
};
function getBinaryProperty2(binaryProperty, index) {
const typedArray = binaryProperty.typedArray;
const componentCount = binaryProperty.componentCount;
if (componentCount === 1) {
return typedArray[index];
}
return binaryProperty.type.unpack(typedArray, index * componentCount);
}
function setBinaryProperty2(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 checkBatchId2(batchId, featuresLength) {
if (!defined_default(batchId) || batchId < 0 || batchId >= featuresLength) {
throw new DeveloperError_default(
`batchId is required and must be between zero and featuresLength - 1 (${featuresLength}` - +")."
);
}
}
Cesium3DTileBatchTable.prototype.isClass = function(batchId, className) {
checkBatchId2(batchId, this.featuresLength);
Check_default.typeOf.string("className", className);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return false;
}
return hierarchy.isClass(batchId, className);
};
Cesium3DTileBatchTable.prototype.isExactClass = function(batchId, className) {
Check_default.typeOf.string("className", className);
return this.getExactClassName(batchId) === className;
};
Cesium3DTileBatchTable.prototype.getExactClassName = function(batchId) {
checkBatchId2(batchId, this.featuresLength);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return void 0;
}
return hierarchy.getClassName(batchId);
};
Cesium3DTileBatchTable.prototype.hasProperty = function(batchId, name) {
checkBatchId2(batchId, this.featuresLength);
Check_default.typeOf.string("name", name);
return defined_default(this._properties[name]) || defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.hasProperty(batchId, name);
};
Cesium3DTileBatchTable.prototype.hasPropertyBySemantic = function() {
return false;
};
Cesium3DTileBatchTable.prototype.getPropertyIds = function(batchId, results) {
checkBatchId2(batchId, this.featuresLength);
results = defined_default(results) ? results : [];
results.length = 0;
const scratchPropertyIds = Object.keys(this._properties);
results.push.apply(results, scratchPropertyIds);
if (defined_default(this._batchTableHierarchy)) {
results.push.apply(
results,
this._batchTableHierarchy.getPropertyIds(batchId, scratchPropertyIds)
);
}
return results;
};
Cesium3DTileBatchTable.prototype.getPropertyBySemantic = function(batchId, name) {
return void 0;
};
Cesium3DTileBatchTable.prototype.getProperty = function(batchId, name) {
checkBatchId2(batchId, this.featuresLength);
Check_default.typeOf.string("name", name);
if (defined_default(this._batchTableBinaryProperties)) {
const binaryProperty = this._batchTableBinaryProperties[name];
if (defined_default(binaryProperty)) {
return getBinaryProperty2(binaryProperty, batchId);
}
}
const propertyValues = this._properties[name];
if (defined_default(propertyValues)) {
return clone_default(propertyValues[batchId], true);
}
if (defined_default(this._batchTableHierarchy)) {
const hierarchyProperty = this._batchTableHierarchy.getProperty(
batchId,
name
);
if (defined_default(hierarchyProperty)) {
return hierarchyProperty;
}
}
return void 0;
};
Cesium3DTileBatchTable.prototype.setProperty = function(batchId, name, value) {
const featuresLength = this.featuresLength;
checkBatchId2(batchId, featuresLength);
Check_default.typeOf.string("name", name);
if (defined_default(this._batchTableBinaryProperties)) {
const binaryProperty = this._batchTableBinaryProperties[name];
if (defined_default(binaryProperty)) {
setBinaryProperty2(binaryProperty, batchId, value);
return;
}
}
if (defined_default(this._batchTableHierarchy)) {
if (this._batchTableHierarchy.setProperty(batchId, name, value)) {
return;
}
}
let propertyValues = this._properties[name];
if (!defined_default(propertyValues)) {
this._properties[name] = new Array(featuresLength);
propertyValues = this._properties[name];
}
propertyValues[batchId] = clone_default(value, true);
};
function getGlslComputeSt2(batchTable) {
if (batchTable._batchTexture.textureDimensions.y === 1) {
return "uniform vec4 tile_textureStep; \nvec2 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; \nuniform vec2 tile_textureDimensions; \nvec2 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) {
const renamedSource = modifyDiffuse(
source,
diffuseAttributeOrUniformName,
false
);
let newMain;
if (ContextLimits_default.maximumVertexTextureImageUnits > 0) {
newMain = "";
if (handleTranslucent) {
newMain += "uniform bool tile_translucentCommand; \n";
}
newMain += `${"uniform sampler2D tile_batchTexture; \nout vec4 tile_featureColor; \nout vec2 tile_featureSt; \nvoid main() \n{ \n vec2 st = computeSt("}${batchIdAttributeName});
vec4 featureProperties = texture(tile_batchTexture, st);
tile_color(featureProperties);
float show = ceil(featureProperties.a);
gl_Position *= show;
`;
if (handleTranslucent) {
newMain += " bool isStyleTranslucent = (featureProperties.a != 1.0); \n if (czm_pass == czm_passTranslucent) \n { \n if (!isStyleTranslucent && !tile_translucentCommand) \n { \n gl_Position *= 0.0; \n } \n } \n else \n { \n if (isStyleTranslucent) \n { \n gl_Position *= 0.0; \n } \n } \n";
}
newMain += " tile_featureColor = featureProperties; \n tile_featureSt = st; \n}";
} else {
newMain = `${"out vec2 tile_featureSt; \nvoid main() \n{ \n tile_color(vec4(1.0)); \n tile_featureSt = computeSt("}${batchIdAttributeName});
}`;
}
return `${renamedSource}
${getGlslComputeSt2(that)}${newMain}`;
};
};
function getDefaultShader(source, applyHighlight) {
source = ShaderSource_default.replaceMain(source, "tile_main");
if (!applyHighlight) {
return `${source}void tile_color(vec4 tile_featureColor)
{
tile_main();
}
`;
}
return `${source}uniform float tile_colorBlend;
void tile_color(vec4 tile_featureColor)
{
tile_main();
tile_featureColor = czm_gammaCorrect(tile_featureColor);
out_FragColor.a *= tile_featureColor.a;
float highlight = ceil(tile_colorBlend);
out_FragColor.rgb *= mix(tile_featureColor.rgb, vec3(1.0), highlight);
}
`;
}
function replaceDiffuseTextureCalls(source, diffuseAttributeOrUniformName) {
const functionCall = `texture(${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 (!defined_default(diffuseAttributeOrUniformName)) {
return getDefaultShader(source, applyHighlight);
}
let regex = new RegExp(
`(uniform|attribute|in)\\s+(vec[34]|sampler2D)\\s+${diffuseAttributeOrUniformName};`
);
const uniformMatch = source.match(regex);
if (!defined_default(uniformMatch)) {
return getDefaultShader(source, applyHighlight);
}
const declaration = uniformMatch[0];
const type = uniformMatch[2];
source = ShaderSource_default.replaceMain(source, "tile_main");
source = source.replace(declaration, "");
const finalDiffuseFunction = "bool isWhite(vec3 color) \n{ \n return all(greaterThan(color, vec3(1.0 - czm_epsilon3))); \n} \nvec4 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";
const highlight = " tile_featureColor = czm_gammaCorrect(tile_featureColor); \n out_FragColor.a *= tile_featureColor.a; \n float highlight = ceil(tile_colorBlend); \n out_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};
tile_diffuse = tile_diffuse_final(source, tile_featureColor);
tile_main();
`;
} else if (type === "sampler2D") {
source = replaceDiffuseTextureCalls(source, diffuseAttributeOrUniformName);
setColor = " tile_diffuse = tile_featureColor; \n tile_main(); \n";
}
source = `${"uniform float tile_colorBlend; \nvec4 tile_diffuse = vec4(1.0); \n"}${finalDiffuseFunction}${declaration}
${source}
void tile_color(vec4 tile_featureColor)
{
${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_default.maximumVertexTextureImageUnits > 0) {
source += "uniform sampler2D tile_pickTexture; \nin vec2 tile_featureSt; \nin vec4 tile_featureColor; \nvoid main() \n{ \n tile_color(tile_featureColor); \n";
if (hasPremultipliedAlpha) {
source += " out_FragColor.rgb *= out_FragColor.a; \n";
}
source += "}";
} else {
if (handleTranslucent) {
source += "uniform bool tile_translucentCommand; \n";
}
source += "uniform sampler2D tile_pickTexture; \nuniform sampler2D tile_batchTexture; \nin vec2 tile_featureSt; \nvoid main() \n{ \n vec4 featureProperties = texture(tile_batchTexture, tile_featureSt); \n if (featureProperties.a == 0.0) { \n 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 { \n discard; \n } \n } \n else \n { \n if (isStyleTranslucent) \n { \n discard; \n } \n } \n";
}
source += " tile_color(featureProperties); \n";
if (hasPremultipliedAlpha) {
source += " out_FragColor.rgb *= out_FragColor.a; \n";
}
source += "} \n";
}
return source;
};
};
Cesium3DTileBatchTable.prototype.getClassificationFragmentShaderCallback = function() {
if (this.featuresLength === 0) {
return;
}
return function(source) {
source = ShaderSource_default.replaceMain(source, "tile_main");
if (ContextLimits_default.maximumVertexTextureImageUnits > 0) {
source += "uniform sampler2D tile_pickTexture;\nin vec2 tile_featureSt; \nin vec4 tile_featureColor; \nvoid main() \n{ \n tile_main(); \n out_FragColor = tile_featureColor; \n out_FragColor.rgb *= out_FragColor.a; \n}";
} else {
source += "uniform sampler2D tile_batchTexture; \nuniform sampler2D tile_pickTexture;\nin vec2 tile_featureSt; \nvoid main() \n{ \n tile_main(); \n vec4 featureProperties = texture(tile_batchTexture, tile_featureSt); \n if (featureProperties.a == 0.0) { \n discard; \n } \n out_FragColor = featureProperties; \n out_FragColor.rgb *= out_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_default.HIGHLIGHT) {
return 0;
}
if (colorBlendMode === Cesium3DTileColorBlendMode_default.REPLACE) {
return 1;
}
if (colorBlendMode === Cesium3DTileColorBlendMode_default.MIX) {
return Math_default.clamp(colorBlendAmount, Math_default.EPSILON4, 1);
}
throw new DeveloperError_default(`Invalid color blend mode "${colorBlendMode}".`);
}
Cesium3DTileBatchTable.prototype.getUniformMapCallback = function() {
if (this.featuresLength === 0) {
return;
}
const that = this;
return function(uniformMap2) {
const batchUniformMap = {
tile_batchTexture: function() {
return defaultValue_default(
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_default(uniformMap2, batchUniformMap);
};
};
Cesium3DTileBatchTable.prototype.getPickId = function() {
return "texture(tile_pickTexture, tile_featureSt)";
};
var StyleCommandsNeeded = {
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.isSkippingLevelOfDetail && tileset.hasMixedContent && frameState.context.stencilBuffer;
const styleCommandsNeeded = getStyleCommandsNeeded(this);
for (let i = commandStart; i < commandEnd; ++i) {
const command = commandList[i];
if (command.pass === Pass_default.COMPUTE) {
continue;
}
let derivedCommands = command.derivedCommands.tileset;
if (!defined_default(derivedCommands) || command.dirty) {
derivedCommands = {};
command.derivedCommands.tileset = derivedCommands;
derivedCommands.originalCommand = deriveCommand(command);
command.dirty = false;
}
const originalCommand = derivedCommands.originalCommand;
if (styleCommandsNeeded !== StyleCommandsNeeded.ALL_OPAQUE && command.pass !== Pass_default.TRANSLUCENT) {
if (!defined_default(derivedCommands.translucent)) {
derivedCommands.translucent = deriveTranslucentCommand(originalCommand);
}
}
if (styleCommandsNeeded !== StyleCommandsNeeded.ALL_TRANSLUCENT && command.pass !== Pass_default.TRANSLUCENT) {
if (!defined_default(derivedCommands.opaque)) {
derivedCommands.opaque = deriveOpaqueCommand(originalCommand);
}
if (bivariateVisibilityTest) {
if (!finalResolution) {
if (!defined_default(derivedCommands.zback)) {
derivedCommands.zback = deriveZBackfaceCommand(
frameState.context,
originalCommand
);
}
tileset._backfaceCommands.push(derivedCommands.zback);
}
if (!defined_default(derivedCommands.stencil) || tile._selectionDepth !== getLastSelectionDepth(derivedCommands.stencil)) {
if (command.renderState.depthMask) {
derivedCommands.stencil = deriveStencilCommand(
originalCommand,
tile._selectionDepth
);
} else {
derivedCommands.stencil = derivedCommands.opaque;
}
}
}
}
const opaqueCommand = bivariateVisibilityTest ? derivedCommands.stencil : derivedCommands.opaque;
const translucentCommand = derivedCommands.translucent;
if (command.pass !== Pass_default.TRANSLUCENT) {
if (styleCommandsNeeded === StyleCommandsNeeded.ALL_OPAQUE) {
commandList[i] = opaqueCommand;
}
if (styleCommandsNeeded === StyleCommandsNeeded.ALL_TRANSLUCENT) {
commandList[i] = translucentCommand;
}
if (styleCommandsNeeded === StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT) {
commandList[i] = opaqueCommand;
commandList.push(translucentCommand);
}
} else {
commandList[i] = originalCommand;
}
}
};
function getStyleCommandsNeeded(batchTable) {
const translucentFeaturesLength = batchTable._batchTexture.translucentFeaturesLength;
if (translucentFeaturesLength === 0) {
return StyleCommandsNeeded.ALL_OPAQUE;
} else if (translucentFeaturesLength === batchTable.featuresLength) {
return StyleCommandsNeeded.ALL_TRANSLUCENT;
}
return StyleCommandsNeeded.OPAQUE_AND_TRANSLUCENT;
}
function deriveCommand(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
const translucentCommand = derivedCommand.pass === Pass_default.TRANSLUCENT;
derivedCommand.uniformMap = defined_default(derivedCommand.uniformMap) ? derivedCommand.uniformMap : {};
derivedCommand.uniformMap.tile_translucentCommand = function() {
return translucentCommand;
};
return derivedCommand;
}
function deriveTranslucentCommand(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
derivedCommand.pass = Pass_default.TRANSLUCENT;
derivedCommand.renderState = getTranslucentRenderState(command.renderState);
return derivedCommand;
}
function deriveOpaqueCommand(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
derivedCommand.renderState = getOpaqueRenderState(command.renderState);
return derivedCommand;
}
function getLogDepthPolygonOffsetFragmentShaderProgram(context, shaderProgram) {
let shader = context.shaderCache.getDerivedShaderProgram(
shaderProgram,
"zBackfaceLogDepth"
);
if (!defined_default(shader)) {
const fs = shaderProgram.fragmentShaderSource.clone();
fs.defines = defined_default(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) {
const derivedCommand = DrawCommand_default.shallowClone(command);
const rs = clone_default(derivedCommand.renderState, true);
rs.cull.enabled = true;
rs.cull.face = CullFace_default.FRONT;
rs.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
rs.polygonOffset = {
enabled: true,
factor: 5,
units: 5
};
rs.stencilTest = StencilConstants_default.setCesium3DTileBit();
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
derivedCommand.renderState = RenderState_default.fromCache(rs);
derivedCommand.castShadows = false;
derivedCommand.receiveShadows = false;
derivedCommand.uniformMap = clone_default(command.uniformMap);
const polygonOffset = new Cartesian2_default(5, 5);
derivedCommand.uniformMap.u_polygonOffset = function() {
return polygonOffset;
};
derivedCommand.shaderProgram = getLogDepthPolygonOffsetFragmentShaderProgram(
context,
command.shaderProgram
);
return derivedCommand;
}
function deriveStencilCommand(command, reference) {
const derivedCommand = DrawCommand_default.shallowClone(command);
const rs = clone_default(derivedCommand.renderState, true);
rs.stencilTest.enabled = true;
rs.stencilTest.mask = StencilConstants_default.SKIP_LOD_MASK;
rs.stencilTest.reference = StencilConstants_default.CESIUM_3D_TILE_MASK | reference << StencilConstants_default.SKIP_LOD_BIT_SHIFT;
rs.stencilTest.frontFunction = StencilFunction_default.GREATER_OR_EQUAL;
rs.stencilTest.frontOperation.zPass = StencilOperation_default.REPLACE;
rs.stencilTest.backFunction = StencilFunction_default.GREATER_OR_EQUAL;
rs.stencilTest.backOperation.zPass = StencilOperation_default.REPLACE;
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK | StencilConstants_default.SKIP_LOD_MASK;
derivedCommand.renderState = RenderState_default.fromCache(rs);
return derivedCommand;
}
function getLastSelectionDepth(stencilCommand) {
const reference = stencilCommand.renderState.stencilTest.reference;
return (reference & StencilConstants_default.SKIP_LOD_MASK) >>> StencilConstants_default.SKIP_LOD_BIT_SHIFT;
}
function getTranslucentRenderState(renderState) {
const rs = clone_default(renderState, true);
rs.cull.enabled = false;
rs.depthTest.enabled = true;
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
rs.stencilTest = StencilConstants_default.setCesium3DTileBit();
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
return RenderState_default.fromCache(rs);
}
function getOpaqueRenderState(renderState) {
const rs = clone_default(renderState, true);
rs.stencilTest = StencilConstants_default.setCesium3DTileBit();
rs.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
return RenderState_default.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_default(this);
};
var Cesium3DTileBatchTable_default = Cesium3DTileBatchTable;
// node_modules/@cesium/engine/Source/Scene/Vector3DTileBatch.js
function Vector3DTileBatch(options) {
this.offset = options.offset;
this.count = options.count;
this.color = options.color;
this.batchIds = options.batchIds;
}
var Vector3DTileBatch_default = Vector3DTileBatch;
// node_modules/@cesium/engine/Source/Shaders/VectorTileVS.js
var VectorTileVS_default = "in vec3 position;\nin float a_batchId;\n\nuniform mat4 u_modifiedModelViewProjection;\n\nvoid main()\n{\n gl_Position = czm_depthClamp(u_modifiedModelViewProjection * vec4(position, 1.0));\n}\n";
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileFeature.js
function Cesium3DTileFeature(content, batchId) {
this._content = content;
this._batchId = batchId;
this._color = void 0;
}
Object.defineProperties(Cesium3DTileFeature.prototype, {
show: {
get: function() {
return this._content.batchTable.getShow(this._batchId);
},
set: function(value) {
this._content.batchTable.setShow(this._batchId, value);
}
},
color: {
get: function() {
if (!defined_default(this._color)) {
this._color = new Color_default();
}
return this._content.batchTable.getColor(this._batchId, this._color);
},
set: function(value) {
this._content.batchTable.setColor(this._batchId, value);
}
},
polylinePositions: {
get: function() {
if (!defined_default(this._content.getPolylinePositions)) {
return void 0;
}
return this._content.getPolylinePositions(this._batchId);
}
},
content: {
get: function() {
return this._content;
}
},
tileset: {
get: function() {
return this._content.tileset;
}
},
primitive: {
get: function() {
return this._content.tileset;
}
},
featureId: {
get: function() {
return this._batchId;
}
},
pickId: {
get: function() {
return this._content.batchTable.getPickColor(this._batchId);
}
}
});
Cesium3DTileFeature.prototype.hasProperty = function(name) {
return this._content.batchTable.hasProperty(this._batchId, name);
};
Cesium3DTileFeature.prototype.getPropertyIds = function(results) {
return this._content.batchTable.getPropertyIds(this._batchId, results);
};
Cesium3DTileFeature.prototype.getProperty = function(name) {
return this._content.batchTable.getProperty(this._batchId, name);
};
Cesium3DTileFeature.getPropertyInherited = function(content, batchId, name) {
const batchTable = content.batchTable;
if (defined_default(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_default(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_default(tileMetadata)) {
if (tileMetadata.hasPropertyBySemantic(name)) {
return tileMetadata.getPropertyBySemantic(name);
}
if (tileMetadata.hasProperty(name)) {
return tileMetadata.getProperty(name);
}
}
let subtreeMetadata;
if (defined_default(tile.implicitSubtree)) {
subtreeMetadata = tile.implicitSubtree.metadata;
}
if (defined_default(subtreeMetadata)) {
if (subtreeMetadata.hasPropertyBySemantic(name)) {
return subtreeMetadata.getPropertyBySemantic(name);
}
if (subtreeMetadata.hasProperty(name)) {
return subtreeMetadata.getProperty(name);
}
}
const groupMetadata = defined_default(content.group) ? content.group.metadata : void 0;
if (defined_default(groupMetadata)) {
if (groupMetadata.hasPropertyBySemantic(name)) {
return groupMetadata.getPropertyBySemantic(name);
}
if (groupMetadata.hasProperty(name)) {
return groupMetadata.getProperty(name);
}
}
const tilesetMetadata = content.tileset.metadata;
if (defined_default(tilesetMetadata)) {
if (tilesetMetadata.hasPropertyBySemantic(name)) {
return tilesetMetadata.getPropertyBySemantic(name);
}
if (tilesetMetadata.hasProperty(name)) {
return tilesetMetadata.getProperty(name);
}
}
return void 0;
};
Cesium3DTileFeature.prototype.getPropertyInherited = function(name) {
return Cesium3DTileFeature.getPropertyInherited(
this._content,
this._batchId,
name
);
};
Cesium3DTileFeature.prototype.setProperty = function(name, value) {
this._content.batchTable.setProperty(this._batchId, name, value);
this._content.featurePropertiesDirty = true;
};
Cesium3DTileFeature.prototype.isExactClass = function(className) {
return this._content.batchTable.isExactClass(this._batchId, className);
};
Cesium3DTileFeature.prototype.isClass = function(className) {
return this._content.batchTable.isClass(this._batchId, className);
};
Cesium3DTileFeature.prototype.getExactClassName = function() {
return this._content.batchTable.getExactClassName(this._batchId);
};
var Cesium3DTileFeature_default = Cesium3DTileFeature;
// node_modules/jsep/dist/jsep.js
var Hooks = class {
add(name, callback, first) {
if (typeof arguments[0] != "string") {
for (let name2 in arguments[0]) {
this.add(name2, arguments[0][name2], arguments[1]);
}
} else {
(Array.isArray(name) ? name : [name]).forEach(function(name2) {
this[name2] = this[name2] || [];
if (callback) {
this[name2][first ? "unshift" : "push"](callback);
}
}, this);
}
}
run(name, env) {
this[name] = this[name] || [];
this[name].forEach(function(callback) {
callback.call(env && env.context ? env.context : env, env);
});
}
};
var Plugins = class {
constructor(jsep2) {
this.jsep = jsep2;
this.registered = {};
}
register(...plugins) {
plugins.forEach((plugin) => {
if (typeof plugin !== "object" || !plugin.name || !plugin.init) {
throw new Error("Invalid JSEP plugin format");
}
if (this.registered[plugin.name]) {
return;
}
plugin.init(this.jsep);
this.registered[plugin.name] = plugin;
});
}
};
var Jsep = class {
static get version() {
return "1.3.8";
}
static toString() {
return "JavaScript Expression Parser (JSEP) v" + Jsep.version;
}
static addUnaryOp(op_name) {
Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);
Jsep.unary_ops[op_name] = 1;
return Jsep;
}
static addBinaryOp(op_name, precedence, isRightAssociative) {
Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);
Jsep.binary_ops[op_name] = precedence;
if (isRightAssociative) {
Jsep.right_associative.add(op_name);
} else {
Jsep.right_associative.delete(op_name);
}
return Jsep;
}
static addIdentifierChar(char) {
Jsep.additional_identifier_chars.add(char);
return Jsep;
}
static addLiteral(literal_name, literal_value) {
Jsep.literals[literal_name] = literal_value;
return Jsep;
}
static removeUnaryOp(op_name) {
delete Jsep.unary_ops[op_name];
if (op_name.length === Jsep.max_unop_len) {
Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
}
return Jsep;
}
static removeAllUnaryOps() {
Jsep.unary_ops = {};
Jsep.max_unop_len = 0;
return Jsep;
}
static removeIdentifierChar(char) {
Jsep.additional_identifier_chars.delete(char);
return Jsep;
}
static removeBinaryOp(op_name) {
delete Jsep.binary_ops[op_name];
if (op_name.length === Jsep.max_binop_len) {
Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
}
Jsep.right_associative.delete(op_name);
return Jsep;
}
static removeAllBinaryOps() {
Jsep.binary_ops = {};
Jsep.max_binop_len = 0;
return Jsep;
}
static removeLiteral(literal_name) {
delete Jsep.literals[literal_name];
return Jsep;
}
static removeAllLiterals() {
Jsep.literals = {};
return Jsep;
}
get char() {
return this.expr.charAt(this.index);
}
get code() {
return this.expr.charCodeAt(this.index);
}
constructor(expr) {
this.expr = expr;
this.index = 0;
}
static parse(expr) {
return new Jsep(expr).parse();
}
static getMaxKeyLen(obj) {
return Math.max(0, ...Object.keys(obj).map((k) => k.length));
}
static isDecimalDigit(ch) {
return ch >= 48 && ch <= 57;
}
static binaryPrecedence(op_val) {
return Jsep.binary_ops[op_val] || 0;
}
static isIdentifierStart(ch) {
return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] || Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
}
static isIdentifierPart(ch) {
return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);
}
throwError(message) {
const error = new Error(message + " at character " + this.index);
error.index = this.index;
error.description = message;
throw error;
}
runHook(name, node) {
if (Jsep.hooks[name]) {
const env = { context: this, node };
Jsep.hooks.run(name, env);
return env.node;
}
return node;
}
searchHook(name) {
if (Jsep.hooks[name]) {
const env = { context: this };
Jsep.hooks[name].find(function(callback) {
callback.call(env.context, env);
return env.node;
});
return env.node;
}
}
gobbleSpaces() {
let ch = this.code;
while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {
ch = this.expr.charCodeAt(++this.index);
}
this.runHook("gobble-spaces");
}
parse() {
this.runHook("before-all");
const nodes = this.gobbleExpressions();
const node = nodes.length === 1 ? nodes[0] : {
type: Jsep.COMPOUND,
body: nodes
};
return this.runHook("after-all", node);
}
gobbleExpressions(untilICode) {
let nodes = [], ch_i, node;
while (this.index < this.expr.length) {
ch_i = this.code;
if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {
this.index++;
} else {
if (node = this.gobbleExpression()) {
nodes.push(node);
} else if (this.index < this.expr.length) {
if (ch_i === untilICode) {
break;
}
this.throwError('Unexpected "' + this.char + '"');
}
}
}
return nodes;
}
gobbleExpression() {
const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
this.gobbleSpaces();
return this.runHook("after-expression", node);
}
gobbleBinaryOp() {
this.gobbleSpaces();
let to_check = this.expr.substr(this.index, Jsep.max_binop_len);
let tc_len = to_check.length;
while (tc_len > 0) {
if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
this.index += tc_len;
return to_check;
}
to_check = to_check.substr(0, --tc_len);
}
return false;
}
gobbleBinaryExpression() {
let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
left = this.gobbleToken();
if (!left) {
return left;
}
biop = this.gobbleBinaryOp();
if (!biop) {
return left;
}
biop_info = { value: biop, prec: Jsep.binaryPrecedence(biop), right_a: Jsep.right_associative.has(biop) };
right = this.gobbleToken();
if (!right) {
this.throwError("Expected expression after " + biop);
}
stack = [left, biop_info, right];
while (biop = this.gobbleBinaryOp()) {
prec = Jsep.binaryPrecedence(biop);
if (prec === 0) {
this.index -= biop.length;
break;
}
biop_info = { value: biop, prec, right_a: Jsep.right_associative.has(biop) };
cur_biop = biop;
const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
right = stack.pop();
biop = stack.pop().value;
left = stack.pop();
node = {
type: Jsep.BINARY_EXP,
operator: biop,
left,
right
};
stack.push(node);
}
node = this.gobbleToken();
if (!node) {
this.throwError("Expected expression after " + cur_biop);
}
stack.push(biop_info, node);
}
i = stack.length - 1;
node = stack[i];
while (i > 1) {
node = {
type: Jsep.BINARY_EXP,
operator: stack[i - 1].value,
left: stack[i - 2],
right: node
};
i -= 2;
}
return node;
}
gobbleToken() {
let ch, to_check, tc_len, node;
this.gobbleSpaces();
node = this.searchHook("gobble-token");
if (node) {
return this.runHook("after-token", node);
}
ch = this.code;
if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {
return this.gobbleNumericLiteral();
}
if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {
node = this.gobbleStringLiteral();
} else if (ch === Jsep.OBRACK_CODE) {
node = this.gobbleArray();
} else {
to_check = this.expr.substr(this.index, Jsep.max_unop_len);
tc_len = to_check.length;
while (tc_len > 0) {
if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
this.index += tc_len;
const argument = this.gobbleToken();
if (!argument) {
this.throwError("missing unaryOp argument");
}
return this.runHook("after-token", {
type: Jsep.UNARY_EXP,
operator: to_check,
argument,
prefix: true
});
}
to_check = to_check.substr(0, --tc_len);
}
if (Jsep.isIdentifierStart(ch)) {
node = this.gobbleIdentifier();
if (Jsep.literals.hasOwnProperty(node.name)) {
node = {
type: Jsep.LITERAL,
value: Jsep.literals[node.name],
raw: node.name
};
} else if (node.name === Jsep.this_str) {
node = { type: Jsep.THIS_EXP };
}
} else if (ch === Jsep.OPAREN_CODE) {
node = this.gobbleGroup();
}
}
if (!node) {
return this.runHook("after-token", false);
}
node = this.gobbleTokenProperty(node);
return this.runHook("after-token", node);
}
gobbleTokenProperty(node) {
this.gobbleSpaces();
let ch = this.code;
while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {
let optional;
if (ch === Jsep.QUMARK_CODE) {
if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {
break;
}
optional = true;
this.index += 2;
this.gobbleSpaces();
ch = this.code;
}
this.index++;
if (ch === Jsep.OBRACK_CODE) {
node = {
type: Jsep.MEMBER_EXP,
computed: true,
object: node,
property: this.gobbleExpression()
};
this.gobbleSpaces();
ch = this.code;
if (ch !== Jsep.CBRACK_CODE) {
this.throwError("Unclosed [");
}
this.index++;
} else if (ch === Jsep.OPAREN_CODE) {
node = {
type: Jsep.CALL_EXP,
"arguments": this.gobbleArguments(Jsep.CPAREN_CODE),
callee: node
};
} else if (ch === Jsep.PERIOD_CODE || optional) {
if (optional) {
this.index--;
}
this.gobbleSpaces();
node = {
type: Jsep.MEMBER_EXP,
computed: false,
object: node,
property: this.gobbleIdentifier()
};
}
if (optional) {
node.optional = true;
}
this.gobbleSpaces();
ch = this.code;
}
return node;
}
gobbleNumericLiteral() {
let number = "", ch, chCode;
while (Jsep.isDecimalDigit(this.code)) {
number += this.expr.charAt(this.index++);
}
if (this.code === Jsep.PERIOD_CODE) {
number += this.expr.charAt(this.index++);
while (Jsep.isDecimalDigit(this.code)) {
number += this.expr.charAt(this.index++);
}
}
ch = this.char;
if (ch === "e" || ch === "E") {
number += this.expr.charAt(this.index++);
ch = this.char;
if (ch === "+" || ch === "-") {
number += this.expr.charAt(this.index++);
}
while (Jsep.isDecimalDigit(this.code)) {
number += this.expr.charAt(this.index++);
}
if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
this.throwError("Expected exponent (" + number + this.char + ")");
}
}
chCode = this.code;
if (Jsep.isIdentifierStart(chCode)) {
this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
} else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {
this.throwError("Unexpected period");
}
return {
type: Jsep.LITERAL,
value: parseFloat(number),
raw: number
};
}
gobbleStringLiteral() {
let str = "";
const startIndex = this.index;
const quote = this.expr.charAt(this.index++);
let closed = false;
while (this.index < this.expr.length) {
let ch = this.expr.charAt(this.index++);
if (ch === quote) {
closed = true;
break;
} else if (ch === "\\") {
ch = this.expr.charAt(this.index++);
switch (ch) {
case "n":
str += "\n";
break;
case "r":
str += "\r";
break;
case "t":
str += " ";
break;
case "b":
str += "\b";
break;
case "f":
str += "\f";
break;
case "v":
str += "\v";
break;
default:
str += ch;
}
} else {
str += ch;
}
}
if (!closed) {
this.throwError('Unclosed quote after "' + str + '"');
}
return {
type: Jsep.LITERAL,
value: str,
raw: this.expr.substring(startIndex, this.index)
};
}
gobbleIdentifier() {
let ch = this.code, start = this.index;
if (Jsep.isIdentifierStart(ch)) {
this.index++;
} else {
this.throwError("Unexpected " + this.char);
}
while (this.index < this.expr.length) {
ch = this.code;
if (Jsep.isIdentifierPart(ch)) {
this.index++;
} else {
break;
}
}
return {
type: Jsep.IDENTIFIER,
name: this.expr.slice(start, this.index)
};
}
gobbleArguments(termination) {
const args = [];
let closed = false;
let separator_count = 0;
while (this.index < this.expr.length) {
this.gobbleSpaces();
let ch_i = this.code;
if (ch_i === termination) {
closed = true;
this.index++;
if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
this.throwError("Unexpected token " + String.fromCharCode(termination));
}
break;
} else if (ch_i === Jsep.COMMA_CODE) {
this.index++;
separator_count++;
if (separator_count !== args.length) {
if (termination === Jsep.CPAREN_CODE) {
this.throwError("Unexpected token ,");
} else if (termination === Jsep.CBRACK_CODE) {
for (let arg = args.length; arg < separator_count; arg++) {
args.push(null);
}
}
}
} else if (args.length !== separator_count && separator_count !== 0) {
this.throwError("Expected comma");
} else {
const node = this.gobbleExpression();
if (!node || node.type === Jsep.COMPOUND) {
this.throwError("Expected comma");
}
args.push(node);
}
}
if (!closed) {
this.throwError("Expected " + String.fromCharCode(termination));
}
return args;
}
gobbleGroup() {
this.index++;
let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);
if (this.code === Jsep.CPAREN_CODE) {
this.index++;
if (nodes.length === 1) {
return nodes[0];
} else if (!nodes.length) {
return false;
} else {
return {
type: Jsep.SEQUENCE_EXP,
expressions: nodes
};
}
} else {
this.throwError("Unclosed (");
}
}
gobbleArray() {
this.index++;
return {
type: Jsep.ARRAY_EXP,
elements: this.gobbleArguments(Jsep.CBRACK_CODE)
};
}
};
var hooks = new Hooks();
Object.assign(Jsep, {
hooks,
plugins: new Plugins(Jsep),
COMPOUND: "Compound",
SEQUENCE_EXP: "SequenceExpression",
IDENTIFIER: "Identifier",
MEMBER_EXP: "MemberExpression",
LITERAL: "Literal",
THIS_EXP: "ThisExpression",
CALL_EXP: "CallExpression",
UNARY_EXP: "UnaryExpression",
BINARY_EXP: "BinaryExpression",
ARRAY_EXP: "ArrayExpression",
TAB_CODE: 9,
LF_CODE: 10,
CR_CODE: 13,
SPACE_CODE: 32,
PERIOD_CODE: 46,
COMMA_CODE: 44,
SQUOTE_CODE: 39,
DQUOTE_CODE: 34,
OPAREN_CODE: 40,
CPAREN_CODE: 41,
OBRACK_CODE: 91,
CBRACK_CODE: 93,
QUMARK_CODE: 63,
SEMCOL_CODE: 59,
COLON_CODE: 58,
unary_ops: {
"-": 1,
"!": 1,
"~": 1,
"+": 1
},
binary_ops: {
"||": 1,
"&&": 2,
"|": 3,
"^": 4,
"&": 5,
"==": 6,
"!=": 6,
"===": 6,
"!==": 6,
"<": 7,
">": 7,
"<=": 7,
">=": 7,
"<<": 8,
">>": 8,
">>>": 8,
"+": 9,
"-": 9,
"*": 10,
"/": 10,
"%": 10
},
right_associative: /* @__PURE__ */ new Set(),
additional_identifier_chars: /* @__PURE__ */ new Set(["$", "_"]),
literals: {
"true": true,
"false": false,
"null": null
},
this_str: "this"
});
Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
var jsep = (expr) => new Jsep(expr).parse();
var staticMethods = Object.getOwnPropertyNames(Jsep);
staticMethods.forEach((m) => {
if (jsep[m] === void 0 && m !== "prototype") {
jsep[m] = Jsep[m];
}
});
jsep.Jsep = Jsep;
var CONDITIONAL_EXP = "ConditionalExpression";
var ternary = {
name: "ternary",
init(jsep2) {
jsep2.hooks.add("after-expression", function gobbleTernary(env) {
if (env.node && this.code === jsep2.QUMARK_CODE) {
this.index++;
const test = env.node;
const consequent = this.gobbleExpression();
if (!consequent) {
this.throwError("Expected expression");
}
this.gobbleSpaces();
if (this.code === jsep2.COLON_CODE) {
this.index++;
const alternate = this.gobbleExpression();
if (!alternate) {
this.throwError("Expected expression");
}
env.node = {
type: CONDITIONAL_EXP,
test,
consequent,
alternate
};
if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
let newTest = test;
while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
newTest = newTest.right;
}
env.node.test = newTest.right;
newTest.right = env.node;
env.node = test;
}
} else {
this.throwError("Expected :");
}
}
});
}
};
jsep.plugins.register(ternary);
// node_modules/@cesium/engine/Source/Scene/ExpressionNodeType.js
var 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_default = Object.freeze(ExpressionNodeType);
// node_modules/@cesium/engine/Source/Scene/Expression.js
function Expression(expression, defines) {
Check_default.typeOf.string("expression", expression);
this._expression = expression;
expression = replaceDefines(expression, defines);
expression = replaceVariables(removeBackslashes(expression));
jsep.addBinaryOp("=~", 0);
jsep.addBinaryOp("!~", 0);
let ast;
try {
ast = jsep(expression);
} catch (e) {
throw new RuntimeError_default(e);
}
this._runtimeAst = createRuntimeAst(this, ast);
}
Object.defineProperties(Expression.prototype, {
expression: {
get: function() {
return this._expression;
}
}
});
var scratchStorage = {
arrayIndex: 0,
arrayArray: [[]],
cartesian2Index: 0,
cartesian3Index: 0,
cartesian4Index: 0,
cartesian2Array: [new Cartesian2_default()],
cartesian3Array: [new Cartesian3_default()],
cartesian4Array: [new Cartesian4_default()],
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_default());
}
return this.cartesian2Array[this.cartesian2Index++];
},
getCartesian3: function() {
if (this.cartesian3Index >= this.cartesian3Array.length) {
this.cartesian3Array.push(new Cartesian3_default());
}
return this.cartesian3Array[this.cartesian3Index++];
},
getCartesian4: function() {
if (this.cartesian4Index >= this.cartesian4Array.length) {
this.cartesian4Array.push(new Cartesian4_default());
}
return this.cartesian4Array[this.cartesian4Index++];
}
};
Expression.prototype.evaluate = function(feature, result) {
scratchStorage.reset();
const value = this._runtimeAst.evaluate(feature);
if (result instanceof Color_default && value instanceof Cartesian4_default) {
return Color_default.fromCartesian4(value, result);
}
if (value instanceof Cartesian2_default || value instanceof Cartesian3_default || value instanceof Cartesian4_default) {
return value.clone(result);
}
return value;
};
Expression.prototype.evaluateColor = function(feature, result) {
scratchStorage.reset();
const color = this._runtimeAst.evaluate(feature);
return Color_default.fromCartesian4(color, result);
};
Expression.prototype.getShaderFunction = function(functionSignature, variableSubstitutionMap, shaderState, returnType) {
let shaderExpression = this.getShaderExpression(
variableSubstitutionMap,
shaderState
);
shaderExpression = `${returnType} ${functionSignature}
{
return ${shaderExpression};
}
`;
return shaderExpression;
};
Expression.prototype.getShaderExpression = function(variableSubstitutionMap, shaderState) {
return this._runtimeAst.getShaderExpression(
variableSubstitutionMap,
shaderState
);
};
Expression.prototype.getVariables = function() {
let variables = [];
this._runtimeAst.getVariables(variables);
variables = variables.filter(function(variable, index, variables2) {
return variables2.indexOf(variable) === index;
});
return variables;
};
var unaryOperators = ["!", "-", "+"];
var binaryOperators = [
"+",
"-",
"*",
"/",
"%",
"===",
"!==",
">",
">=",
"<",
"<=",
"&&",
"||",
"!~",
"=~"
];
var variableRegex = /\${(.*?)}/g;
var backslashRegex = /\\/g;
var backslashReplacement = "@#%";
var replacementRegex = /@#%/g;
var scratchColor3 = new Color_default();
var 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(Math_default.toRadians),
degrees: getEvaluateUnaryComponentwise(Math_default.toDegrees),
sign: getEvaluateUnaryComponentwise(Math_default.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(log22),
fract: getEvaluateUnaryComponentwise(fract),
length: length2,
normalize
};
var binaryFunctions = {
atan2: getEvaluateBinaryComponentwise(Math.atan2, false),
pow: getEvaluateBinaryComponentwise(Math.pow, false),
min: getEvaluateBinaryComponentwise(Math.min, true),
max: getEvaluateBinaryComponentwise(Math.max, true),
distance,
dot,
cross
};
var ternaryFunctions = {
clamp: getEvaluateTernaryComponentwise(Math_default.clamp, true),
mix: getEvaluateTernaryComponentwise(Math_default.lerp, true)
};
function fract(number) {
return number - Math.floor(number);
}
function exp2(exponent) {
return Math.pow(2, exponent);
}
function log22(number) {
return Math_default.log2(number);
}
function getEvaluateUnaryComponentwise(operation) {
return function(call, left) {
if (typeof left === "number") {
return operation(left);
} else if (left instanceof Cartesian2_default) {
return Cartesian2_default.fromElements(
operation(left.x),
operation(left.y),
scratchStorage.getCartesian2()
);
} else if (left instanceof Cartesian3_default) {
return Cartesian3_default.fromElements(
operation(left.x),
operation(left.y),
operation(left.z),
scratchStorage.getCartesian3()
);
} else if (left instanceof Cartesian4_default) {
return Cartesian4_default.fromElements(
operation(left.x),
operation(left.y),
operation(left.z),
operation(left.w),
scratchStorage.getCartesian4()
);
}
throw new RuntimeError_default(
`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_default) {
return Cartesian2_default.fromElements(
operation(left.x, right),
operation(left.y, right),
scratchStorage.getCartesian2()
);
} else if (left instanceof Cartesian3_default) {
return Cartesian3_default.fromElements(
operation(left.x, right),
operation(left.y, right),
operation(left.z, right),
scratchStorage.getCartesian3()
);
} else if (left instanceof Cartesian4_default) {
return Cartesian4_default.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_default && right instanceof Cartesian2_default) {
return Cartesian2_default.fromElements(
operation(left.x, right.x),
operation(left.y, right.y),
scratchStorage.getCartesian2()
);
} else if (left instanceof Cartesian3_default && right instanceof Cartesian3_default) {
return Cartesian3_default.fromElements(
operation(left.x, right.x),
operation(left.y, right.y),
operation(left.z, right.z),
scratchStorage.getCartesian3()
);
} else if (left instanceof Cartesian4_default && right instanceof Cartesian4_default) {
return Cartesian4_default.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_default(
`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_default && right instanceof Cartesian2_default) {
return Cartesian2_default.fromElements(
operation(left.x, right.x, test),
operation(left.y, right.y, test),
scratchStorage.getCartesian2()
);
} else if (left instanceof Cartesian3_default && right instanceof Cartesian3_default) {
return Cartesian3_default.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_default && right instanceof Cartesian4_default) {
return Cartesian4_default.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_default && right instanceof Cartesian2_default && test instanceof Cartesian2_default) {
return Cartesian2_default.fromElements(
operation(left.x, right.x, test.x),
operation(left.y, right.y, test.y),
scratchStorage.getCartesian2()
);
} else if (left instanceof Cartesian3_default && right instanceof Cartesian3_default && test instanceof Cartesian3_default) {
return Cartesian3_default.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_default && right instanceof Cartesian4_default && test instanceof Cartesian4_default) {
return Cartesian4_default.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_default(
`Function "${call}" requires vector or number arguments of matching types. Arguments are ${left}, ${right}, and ${test}.`
);
};
}
function length2(call, left) {
if (typeof left === "number") {
return Math.abs(left);
} else if (left instanceof Cartesian2_default) {
return Cartesian2_default.magnitude(left);
} else if (left instanceof Cartesian3_default) {
return Cartesian3_default.magnitude(left);
} else if (left instanceof Cartesian4_default) {
return Cartesian4_default.magnitude(left);
}
throw new RuntimeError_default(
`Function "${call}" requires a vector or number argument. Argument is ${left}.`
);
}
function normalize(call, left) {
if (typeof left === "number") {
return 1;
} else if (left instanceof Cartesian2_default) {
return Cartesian2_default.normalize(left, scratchStorage.getCartesian2());
} else if (left instanceof Cartesian3_default) {
return Cartesian3_default.normalize(left, scratchStorage.getCartesian3());
} else if (left instanceof Cartesian4_default) {
return Cartesian4_default.normalize(left, scratchStorage.getCartesian4());
}
throw new RuntimeError_default(
`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_default && right instanceof Cartesian2_default) {
return Cartesian2_default.distance(left, right);
} else if (left instanceof Cartesian3_default && right instanceof Cartesian3_default) {
return Cartesian3_default.distance(left, right);
} else if (left instanceof Cartesian4_default && right instanceof Cartesian4_default) {
return Cartesian4_default.distance(left, right);
}
throw new RuntimeError_default(
`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_default && right instanceof Cartesian2_default) {
return Cartesian2_default.dot(left, right);
} else if (left instanceof Cartesian3_default && right instanceof Cartesian3_default) {
return Cartesian3_default.dot(left, right);
} else if (left instanceof Cartesian4_default && right instanceof Cartesian4_default) {
return Cartesian4_default.dot(left, right);
}
throw new RuntimeError_default(
`Function "${call}" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
);
}
function cross(call, left, right) {
if (left instanceof Cartesian3_default && right instanceof Cartesian3_default) {
return Cartesian3_default.cross(left, right, scratchStorage.getCartesian3());
}
throw new RuntimeError_default(
`Function "${call}" requires vec3 arguments. Arguments are ${left} and ${right}.`
);
}
function Node2(type, value, left, right, test) {
this._type = type;
this._value = value;
this._left = left;
this._right = right;
this._test = test;
this.evaluate = void 0;
setEvaluateFunction(this);
}
function replaceDefines(expression, defines) {
if (!defined_default(defines)) {
return expression;
}
for (const key in defines) {
if (defines.hasOwnProperty(key)) {
const definePlaceholder = new RegExp(`\\$\\{${key}\\}`, "g");
const defineReplace = `(${defines[key]})`;
if (defined_default(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) {
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_default("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 Node2(ExpressionNodeType_default.LITERAL_NULL, null);
} else if (type === "boolean") {
return new Node2(ExpressionNodeType_default.LITERAL_BOOLEAN, ast.value);
} else if (type === "number") {
return new Node2(ExpressionNodeType_default.LITERAL_NUMBER, ast.value);
} else if (type === "string") {
if (ast.value.indexOf("${") >= 0) {
return new Node2(ExpressionNodeType_default.VARIABLE_IN_STRING, ast.value);
}
return new Node2(
ExpressionNodeType_default.LITERAL_STRING,
replaceBackslashes(ast.value)
);
}
}
function parseCall(expression, ast) {
const args = ast.arguments;
const argsLength = args.length;
let call;
let val, left, right;
if (ast.callee.type === "MemberExpression") {
call = ast.callee.property.name;
const object = ast.callee.object;
if (call === "test" || call === "exec") {
if (!defined_default(object.callee) || object.callee.name !== "regExp") {
throw new RuntimeError_default(`${call} is not a function.`);
}
if (argsLength === 0) {
if (call === "test") {
return new Node2(ExpressionNodeType_default.LITERAL_BOOLEAN, false);
}
return new Node2(ExpressionNodeType_default.LITERAL_NULL, null);
}
left = createRuntimeAst(expression, object);
right = createRuntimeAst(expression, args[0]);
return new Node2(ExpressionNodeType_default.FUNCTION_CALL, call, left, right);
} else if (call === "toString") {
val = createRuntimeAst(expression, object);
return new Node2(ExpressionNodeType_default.FUNCTION_CALL, call, val);
}
throw new RuntimeError_default(`Unexpected function call "${call}".`);
}
call = ast.callee.name;
if (call === "color") {
if (argsLength === 0) {
return new Node2(ExpressionNodeType_default.LITERAL_COLOR, call);
}
val = createRuntimeAst(expression, args[0]);
if (defined_default(args[1])) {
const alpha = createRuntimeAst(expression, args[1]);
return new Node2(ExpressionNodeType_default.LITERAL_COLOR, call, [val, alpha]);
}
return new Node2(ExpressionNodeType_default.LITERAL_COLOR, call, [val]);
} else if (call === "rgb" || call === "hsl") {
if (argsLength < 3) {
throw new RuntimeError_default(`${call} requires three arguments.`);
}
val = [
createRuntimeAst(expression, args[0]),
createRuntimeAst(expression, args[1]),
createRuntimeAst(expression, args[2])
];
return new Node2(ExpressionNodeType_default.LITERAL_COLOR, call, val);
} else if (call === "rgba" || call === "hsla") {
if (argsLength < 4) {
throw new RuntimeError_default(`${call} requires four arguments.`);
}
val = [
createRuntimeAst(expression, args[0]),
createRuntimeAst(expression, args[1]),
createRuntimeAst(expression, args[2]),
createRuntimeAst(expression, args[3])
];
return new Node2(ExpressionNodeType_default.LITERAL_COLOR, call, val);
} else if (call === "vec2" || call === "vec3" || call === "vec4") {
val = new Array(argsLength);
for (let i = 0; i < argsLength; ++i) {
val[i] = createRuntimeAst(expression, args[i]);
}
return new Node2(ExpressionNodeType_default.LITERAL_VECTOR, call, val);
} else if (call === "isNaN" || call === "isFinite") {
if (argsLength === 0) {
if (call === "isNaN") {
return new Node2(ExpressionNodeType_default.LITERAL_BOOLEAN, true);
}
return new Node2(ExpressionNodeType_default.LITERAL_BOOLEAN, false);
}
val = createRuntimeAst(expression, args[0]);
return new Node2(ExpressionNodeType_default.UNARY, call, val);
} else if (call === "isExactClass" || call === "isClass") {
if (argsLength < 1 || argsLength > 1) {
throw new RuntimeError_default(`${call} requires exactly one argument.`);
}
val = createRuntimeAst(expression, args[0]);
return new Node2(ExpressionNodeType_default.UNARY, call, val);
} else if (call === "getExactClassName") {
if (argsLength > 0) {
throw new RuntimeError_default(`${call} does not take any argument.`);
}
return new Node2(ExpressionNodeType_default.UNARY, call);
} else if (defined_default(unaryFunctions[call])) {
if (argsLength !== 1) {
throw new RuntimeError_default(`${call} requires exactly one argument.`);
}
val = createRuntimeAst(expression, args[0]);
return new Node2(ExpressionNodeType_default.UNARY, call, val);
} else if (defined_default(binaryFunctions[call])) {
if (argsLength !== 2) {
throw new RuntimeError_default(`${call} requires exactly two arguments.`);
}
left = createRuntimeAst(expression, args[0]);
right = createRuntimeAst(expression, args[1]);
return new Node2(ExpressionNodeType_default.BINARY, call, left, right);
} else if (defined_default(ternaryFunctions[call])) {
if (argsLength !== 3) {
throw new RuntimeError_default(`${call} requires exactly three arguments.`);
}
left = createRuntimeAst(expression, args[0]);
right = createRuntimeAst(expression, args[1]);
const test = createRuntimeAst(expression, args[2]);
return new Node2(ExpressionNodeType_default.TERNARY, call, left, right, test);
} else if (call === "Boolean") {
if (argsLength === 0) {
return new Node2(ExpressionNodeType_default.LITERAL_BOOLEAN, false);
}
val = createRuntimeAst(expression, args[0]);
return new Node2(ExpressionNodeType_default.UNARY, call, val);
} else if (call === "Number") {
if (argsLength === 0) {
return new Node2(ExpressionNodeType_default.LITERAL_NUMBER, 0);
}
val = createRuntimeAst(expression, args[0]);
return new Node2(ExpressionNodeType_default.UNARY, call, val);
} else if (call === "String") {
if (argsLength === 0) {
return new Node2(ExpressionNodeType_default.LITERAL_STRING, "");
}
val = createRuntimeAst(expression, args[0]);
return new Node2(ExpressionNodeType_default.UNARY, call, val);
} else if (call === "regExp") {
return parseRegex(expression, ast);
}
throw new RuntimeError_default(`Unexpected function call "${call}".`);
}
function parseRegex(expression, ast) {
const args = ast.arguments;
if (args.length === 0) {
return new Node2(ExpressionNodeType_default.LITERAL_REGEX, new RegExp());
}
const pattern = createRuntimeAst(expression, args[0]);
let exp;
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_default(e);
}
return new Node2(ExpressionNodeType_default.LITERAL_REGEX, exp);
}
return new Node2(ExpressionNodeType_default.REGEX, pattern, flags);
}
if (isLiteralType(pattern)) {
try {
exp = new RegExp(replaceBackslashes(String(pattern._value)));
} catch (e) {
throw new RuntimeError_default(e);
}
return new Node2(ExpressionNodeType_default.LITERAL_REGEX, exp);
}
return new Node2(ExpressionNodeType_default.REGEX, pattern);
}
function parseKeywordsAndVariables(ast) {
if (isVariable(ast.name)) {
const name = getPropertyName(ast.name);
if (name.substr(0, 8) === "tiles3d_") {
return new Node2(ExpressionNodeType_default.BUILTIN_VARIABLE, name);
}
return new Node2(ExpressionNodeType_default.VARIABLE, name);
} else if (ast.name === "NaN") {
return new Node2(ExpressionNodeType_default.LITERAL_NUMBER, NaN);
} else if (ast.name === "Infinity") {
return new Node2(ExpressionNodeType_default.LITERAL_NUMBER, Infinity);
} else if (ast.name === "undefined") {
return new Node2(ExpressionNodeType_default.LITERAL_UNDEFINED, void 0);
}
throw new RuntimeError_default(`${ast.name} is not defined.`);
}
function parseMathConstant(ast) {
const name = ast.property.name;
if (name === "PI") {
return new Node2(ExpressionNodeType_default.LITERAL_NUMBER, Math.PI);
} else if (name === "E") {
return new Node2(ExpressionNodeType_default.LITERAL_NUMBER, Math.E);
}
}
function parseNumberConstant(ast) {
const name = ast.property.name;
if (name === "POSITIVE_INFINITY") {
return new Node2(
ExpressionNodeType_default.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 Node2(ExpressionNodeType_default.MEMBER, "brackets", obj, val);
}
val = new Node2(ExpressionNodeType_default.LITERAL_STRING, ast.property.name);
return new Node2(ExpressionNodeType_default.MEMBER, "dot", obj, val);
}
function isLiteralType(node) {
return node._type >= ExpressionNodeType_default.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 Node2(ExpressionNodeType_default.UNARY, op, child);
} else {
throw new RuntimeError_default(`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 Node2(ExpressionNodeType_default.BINARY, op, left, right);
} else {
throw new RuntimeError_default(`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 Node2(ExpressionNodeType_default.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 Node2(ExpressionNodeType_default.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 Node2(ExpressionNodeType_default.ARRAY, val);
} else if (ast.type === "Compound") {
throw new RuntimeError_default("Provide exactly one expression.");
} else {
throw new RuntimeError_default("Cannot parse expression.");
}
return node;
}
function setEvaluateFunction(node) {
if (node._type === ExpressionNodeType_default.CONDITIONAL) {
node.evaluate = node._evaluateConditional;
} else if (node._type === ExpressionNodeType_default.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_default.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_default(unaryFunctions[node._value])) {
node.evaluate = getEvaluateUnaryFunction(node._value);
}
} else if (node._type === ExpressionNodeType_default.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_default(binaryFunctions[node._value])) {
node.evaluate = getEvaluateBinaryFunction(node._value);
}
} else if (node._type === ExpressionNodeType_default.TERNARY) {
node.evaluate = getEvaluateTernaryFunction(node._value);
} else if (node._type === ExpressionNodeType_default.MEMBER) {
if (node._value === "brackets") {
node.evaluate = node._evaluateMemberBrackets;
} else {
node.evaluate = node._evaluateMemberDot;
}
} else if (node._type === ExpressionNodeType_default.ARRAY) {
node.evaluate = node._evaluateArray;
} else if (node._type === ExpressionNodeType_default.VARIABLE) {
node.evaluate = node._evaluateVariable;
} else if (node._type === ExpressionNodeType_default.VARIABLE_IN_STRING) {
node.evaluate = node._evaluateVariableString;
} else if (node._type === ExpressionNodeType_default.LITERAL_COLOR) {
node.evaluate = node._evaluateLiteralColor;
} else if (node._type === ExpressionNodeType_default.LITERAL_VECTOR) {
node.evaluate = node._evaluateLiteralVector;
} else if (node._type === ExpressionNodeType_default.LITERAL_STRING) {
node.evaluate = node._evaluateLiteralString;
} else if (node._type === ExpressionNodeType_default.REGEX) {
node.evaluate = node._evaluateRegExp;
} else if (node._type === ExpressionNodeType_default.BUILTIN_VARIABLE) {
if (node._value === "tiles3d_tileset_time") {
node.evaluate = evaluateTilesetTime;
}
} else {
node.evaluate = node._evaluateLiteral;
}
}
function evaluateTilesetTime(feature) {
if (!defined_default(feature)) {
return 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) {
if (defined_default(feature)) {
return feature.getPropertyInherited(name);
}
}
Node2.prototype._evaluateLiteral = function() {
return this._value;
};
Node2.prototype._evaluateLiteralColor = function(feature) {
const color = scratchColor3;
const args = this._left;
if (this._value === "color") {
if (!defined_default(args)) {
Color_default.fromBytes(255, 255, 255, 255, color);
} else if (args.length > 1) {
Color_default.fromCssColorString(args[0].evaluate(feature), color);
color.alpha = args[1].evaluate(feature);
} else {
Color_default.fromCssColorString(args[0].evaluate(feature), color);
}
} else if (this._value === "rgb") {
Color_default.fromBytes(
args[0].evaluate(feature),
args[1].evaluate(feature),
args[2].evaluate(feature),
255,
color
);
} else if (this._value === "rgba") {
const a3 = args[3].evaluate(feature) * 255;
Color_default.fromBytes(
args[0].evaluate(feature),
args[1].evaluate(feature),
args[2].evaluate(feature),
a3,
color
);
} else if (this._value === "hsl") {
Color_default.fromHsl(
args[0].evaluate(feature),
args[1].evaluate(feature),
args[2].evaluate(feature),
1,
color
);
} else if (this._value === "hsla") {
Color_default.fromHsl(
args[0].evaluate(feature),
args[1].evaluate(feature),
args[2].evaluate(feature),
args[3].evaluate(feature),
color
);
}
return Cartesian4_default.fromColor(color, scratchStorage.getCartesian4());
};
Node2.prototype._evaluateLiteralVector = function(feature) {
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_default) {
components.push(value.x, value.y);
} else if (value instanceof Cartesian3_default) {
components.push(value.x, value.y, value.z);
} else if (value instanceof Cartesian4_default) {
components.push(value.x, value.y, value.z, value.w);
} else {
throw new RuntimeError_default(
`${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_default(`Invalid ${call} constructor. No valid arguments.`);
} else if (componentsLength < vectorLength && componentsLength > 1) {
throw new RuntimeError_default(
`Invalid ${call} constructor. Not enough arguments.`
);
} else if (componentsLength > vectorLength && argsLength > 1) {
throw new RuntimeError_default(`Invalid ${call} constructor. Too many arguments.`);
}
if (componentsLength === 1) {
const component = components[0];
components.push(component, component, component);
}
if (call === "vec2") {
return Cartesian2_default.fromArray(components, 0, scratchStorage.getCartesian2());
} else if (call === "vec3") {
return Cartesian3_default.fromArray(components, 0, scratchStorage.getCartesian3());
} else if (call === "vec4") {
return Cartesian4_default.fromArray(components, 0, scratchStorage.getCartesian4());
}
};
Node2.prototype._evaluateLiteralString = function() {
return this._value;
};
Node2.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_default(property)) {
property = "";
}
result = result.replace(placeholder, property);
match = variableRegex.exec(result);
}
return result;
};
Node2.prototype._evaluateVariable = function(feature) {
return getFeatureProperty(feature, this._value);
};
function checkFeature(ast) {
return ast._value === "feature";
}
Node2.prototype._evaluateMemberDot = function(feature) {
if (checkFeature(this._left)) {
return getFeatureProperty(feature, this._right.evaluate(feature));
}
const property = this._left.evaluate(feature);
if (!defined_default(property)) {
return void 0;
}
const member = this._right.evaluate(feature);
if (property instanceof Cartesian2_default || property instanceof Cartesian3_default || property instanceof Cartesian4_default) {
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];
};
Node2.prototype._evaluateMemberBrackets = function(feature) {
if (checkFeature(this._left)) {
return getFeatureProperty(feature, this._right.evaluate(feature));
}
const property = this._left.evaluate(feature);
if (!defined_default(property)) {
return void 0;
}
const member = this._right.evaluate(feature);
if (property instanceof Cartesian2_default || property instanceof Cartesian3_default || property instanceof Cartesian4_default) {
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];
};
Node2.prototype._evaluateArray = function(feature) {
const array = [];
for (let i = 0; i < this._value.length; i++) {
array[i] = this._value[i].evaluate(feature);
}
return array;
};
Node2.prototype._evaluateNot = function(feature) {
const left = this._left.evaluate(feature);
if (typeof left !== "boolean") {
throw new RuntimeError_default(
`Operator "!" requires a boolean argument. Argument is ${left}.`
);
}
return !left;
};
Node2.prototype._evaluateNegative = function(feature) {
const left = this._left.evaluate(feature);
if (left instanceof Cartesian2_default) {
return Cartesian2_default.negate(left, scratchStorage.getCartesian2());
} else if (left instanceof Cartesian3_default) {
return Cartesian3_default.negate(left, scratchStorage.getCartesian3());
} else if (left instanceof Cartesian4_default) {
return Cartesian4_default.negate(left, scratchStorage.getCartesian4());
} else if (typeof left === "number") {
return -left;
}
throw new RuntimeError_default(
`Operator "-" requires a vector or number argument. Argument is ${left}.`
);
};
Node2.prototype._evaluatePositive = function(feature) {
const left = this._left.evaluate(feature);
if (!(left instanceof Cartesian2_default || left instanceof Cartesian3_default || left instanceof Cartesian4_default || typeof left === "number")) {
throw new RuntimeError_default(
`Operator "+" requires a vector or number argument. Argument is ${left}.`
);
}
return left;
};
Node2.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_default(
`Operator "<" requires number arguments. Arguments are ${left} and ${right}.`
);
}
return left < right;
};
Node2.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_default(
`Operator "<=" requires number arguments. Arguments are ${left} and ${right}.`
);
}
return left <= right;
};
Node2.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_default(
`Operator ">" requires number arguments. Arguments are ${left} and ${right}.`
);
}
return left > right;
};
Node2.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_default(
`Operator ">=" requires number arguments. Arguments are ${left} and ${right}.`
);
}
return left >= right;
};
Node2.prototype._evaluateOr = function(feature) {
const left = this._left.evaluate(feature);
if (typeof left !== "boolean") {
throw new RuntimeError_default(
`Operator "||" requires boolean arguments. First argument is ${left}.`
);
}
if (left) {
return true;
}
const right = this._right.evaluate(feature);
if (typeof right !== "boolean") {
throw new RuntimeError_default(
`Operator "||" requires boolean arguments. Second argument is ${right}.`
);
}
return left || right;
};
Node2.prototype._evaluateAnd = function(feature) {
const left = this._left.evaluate(feature);
if (typeof left !== "boolean") {
throw new RuntimeError_default(
`Operator "&&" requires boolean arguments. First argument is ${left}.`
);
}
if (!left) {
return false;
}
const right = this._right.evaluate(feature);
if (typeof right !== "boolean") {
throw new RuntimeError_default(
`Operator "&&" requires boolean arguments. Second argument is ${right}.`
);
}
return left && right;
};
Node2.prototype._evaluatePlus = function(feature) {
const left = this._left.evaluate(feature);
const right = this._right.evaluate(feature);
if (right instanceof Cartesian2_default && left instanceof Cartesian2_default) {
return Cartesian2_default.add(left, right, scratchStorage.getCartesian2());
} else if (right instanceof Cartesian3_default && left instanceof Cartesian3_default) {
return Cartesian3_default.add(left, right, scratchStorage.getCartesian3());
} else if (right instanceof Cartesian4_default && left instanceof Cartesian4_default) {
return Cartesian4_default.add(left, right, scratchStorage.getCartesian4());
} else if (typeof left === "string" || typeof right === "string") {
return left + right;
} else if (typeof left === "number" && typeof right === "number") {
return left + right;
}
throw new RuntimeError_default(
`Operator "+" requires vector or number arguments of matching types, or at least one string argument. Arguments are ${left} and ${right}.`
);
};
Node2.prototype._evaluateMinus = function(feature) {
const left = this._left.evaluate(feature);
const right = this._right.evaluate(feature);
if (right instanceof Cartesian2_default && left instanceof Cartesian2_default) {
return Cartesian2_default.subtract(left, right, scratchStorage.getCartesian2());
} else if (right instanceof Cartesian3_default && left instanceof Cartesian3_default) {
return Cartesian3_default.subtract(left, right, scratchStorage.getCartesian3());
} else if (right instanceof Cartesian4_default && left instanceof Cartesian4_default) {
return Cartesian4_default.subtract(left, right, scratchStorage.getCartesian4());
} else if (typeof left === "number" && typeof right === "number") {
return left - right;
}
throw new RuntimeError_default(
`Operator "-" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
);
};
Node2.prototype._evaluateTimes = function(feature) {
const left = this._left.evaluate(feature);
const right = this._right.evaluate(feature);
if (right instanceof Cartesian2_default && left instanceof Cartesian2_default) {
return Cartesian2_default.multiplyComponents(
left,
right,
scratchStorage.getCartesian2()
);
} else if (right instanceof Cartesian2_default && typeof left === "number") {
return Cartesian2_default.multiplyByScalar(
right,
left,
scratchStorage.getCartesian2()
);
} else if (left instanceof Cartesian2_default && typeof right === "number") {
return Cartesian2_default.multiplyByScalar(
left,
right,
scratchStorage.getCartesian2()
);
} else if (right instanceof Cartesian3_default && left instanceof Cartesian3_default) {
return Cartesian3_default.multiplyComponents(
left,
right,
scratchStorage.getCartesian3()
);
} else if (right instanceof Cartesian3_default && typeof left === "number") {
return Cartesian3_default.multiplyByScalar(
right,
left,
scratchStorage.getCartesian3()
);
} else if (left instanceof Cartesian3_default && typeof right === "number") {
return Cartesian3_default.multiplyByScalar(
left,
right,
scratchStorage.getCartesian3()
);
} else if (right instanceof Cartesian4_default && left instanceof Cartesian4_default) {
return Cartesian4_default.multiplyComponents(
left,
right,
scratchStorage.getCartesian4()
);
} else if (right instanceof Cartesian4_default && typeof left === "number") {
return Cartesian4_default.multiplyByScalar(
right,
left,
scratchStorage.getCartesian4()
);
} else if (left instanceof Cartesian4_default && typeof right === "number") {
return Cartesian4_default.multiplyByScalar(
left,
right,
scratchStorage.getCartesian4()
);
} else if (typeof left === "number" && typeof right === "number") {
return left * right;
}
throw new RuntimeError_default(
`Operator "*" requires vector or number arguments. If both arguments are vectors they must be matching types. Arguments are ${left} and ${right}.`
);
};
Node2.prototype._evaluateDivide = function(feature) {
const left = this._left.evaluate(feature);
const right = this._right.evaluate(feature);
if (right instanceof Cartesian2_default && left instanceof Cartesian2_default) {
return Cartesian2_default.divideComponents(
left,
right,
scratchStorage.getCartesian2()
);
} else if (left instanceof Cartesian2_default && typeof right === "number") {
return Cartesian2_default.divideByScalar(
left,
right,
scratchStorage.getCartesian2()
);
} else if (right instanceof Cartesian3_default && left instanceof Cartesian3_default) {
return Cartesian3_default.divideComponents(
left,
right,
scratchStorage.getCartesian3()
);
} else if (left instanceof Cartesian3_default && typeof right === "number") {
return Cartesian3_default.divideByScalar(
left,
right,
scratchStorage.getCartesian3()
);
} else if (right instanceof Cartesian4_default && left instanceof Cartesian4_default) {
return Cartesian4_default.divideComponents(
left,
right,
scratchStorage.getCartesian4()
);
} else if (left instanceof Cartesian4_default && typeof right === "number") {
return Cartesian4_default.divideByScalar(
left,
right,
scratchStorage.getCartesian4()
);
} else if (typeof left === "number" && typeof right === "number") {
return left / right;
}
throw new RuntimeError_default(
`Operator "/" requires vector or number arguments of matching types, or a number as the second argument. Arguments are ${left} and ${right}.`
);
};
Node2.prototype._evaluateMod = function(feature) {
const left = this._left.evaluate(feature);
const right = this._right.evaluate(feature);
if (right instanceof Cartesian2_default && left instanceof Cartesian2_default) {
return Cartesian2_default.fromElements(
left.x % right.x,
left.y % right.y,
scratchStorage.getCartesian2()
);
} else if (right instanceof Cartesian3_default && left instanceof Cartesian3_default) {
return Cartesian3_default.fromElements(
left.x % right.x,
left.y % right.y,
left.z % right.z,
scratchStorage.getCartesian3()
);
} else if (right instanceof Cartesian4_default && left instanceof Cartesian4_default) {
return Cartesian4_default.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_default(
`Operator "%" requires vector or number arguments of matching types. Arguments are ${left} and ${right}.`
);
};
Node2.prototype._evaluateEqualsStrict = function(feature) {
const left = this._left.evaluate(feature);
const right = this._right.evaluate(feature);
if (right instanceof Cartesian2_default && left instanceof Cartesian2_default || right instanceof Cartesian3_default && left instanceof Cartesian3_default || right instanceof Cartesian4_default && left instanceof Cartesian4_default) {
return left.equals(right);
}
return left === right;
};
Node2.prototype._evaluateNotEqualsStrict = function(feature) {
const left = this._left.evaluate(feature);
const right = this._right.evaluate(feature);
if (right instanceof Cartesian2_default && left instanceof Cartesian2_default || right instanceof Cartesian3_default && left instanceof Cartesian3_default || right instanceof Cartesian4_default && left instanceof Cartesian4_default) {
return !left.equals(right);
}
return left !== right;
};
Node2.prototype._evaluateConditional = function(feature) {
const test = this._test.evaluate(feature);
if (typeof test !== "boolean") {
throw new RuntimeError_default(
`Conditional argument of conditional expression must be a boolean. Argument is ${test}.`
);
}
if (test) {
return this._left.evaluate(feature);
}
return this._right.evaluate(feature);
};
Node2.prototype._evaluateNaN = function(feature) {
return isNaN(this._left.evaluate(feature));
};
Node2.prototype._evaluateIsFinite = function(feature) {
return isFinite(this._left.evaluate(feature));
};
Node2.prototype._evaluateIsExactClass = function(feature) {
if (defined_default(feature)) {
return feature.isExactClass(this._left.evaluate(feature));
}
return false;
};
Node2.prototype._evaluateIsClass = function(feature) {
if (defined_default(feature)) {
return feature.isClass(this._left.evaluate(feature));
}
return false;
};
Node2.prototype._evaluateGetExactClassName = function(feature) {
if (defined_default(feature)) {
return feature.getExactClassName();
}
};
Node2.prototype._evaluateBooleanConversion = function(feature) {
return Boolean(this._left.evaluate(feature));
};
Node2.prototype._evaluateNumberConversion = function(feature) {
return Number(this._left.evaluate(feature));
};
Node2.prototype._evaluateStringConversion = function(feature) {
return String(this._left.evaluate(feature));
};
Node2.prototype._evaluateRegExp = function(feature) {
const pattern = this._value.evaluate(feature);
let flags = "";
if (defined_default(this._left)) {
flags = this._left.evaluate(feature);
}
let exp;
try {
exp = new RegExp(pattern, flags);
} catch (e) {
throw new RuntimeError_default(e);
}
return exp;
};
Node2.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_default(
`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);
};
Node2.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_default(
`Operator "=~" requires one RegExp argument and one string argument. Arguments are ${left} and ${right}.`
);
};
Node2.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_default(
`Operator "!~" requires one RegExp argument and one string argument. Arguments are ${left} and ${right}.`
);
};
Node2.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_default(
`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_default(exec)) {
return null;
}
return exec[1];
};
Node2.prototype._evaluateToString = function(feature) {
const left = this._left.evaluate(feature);
if (left instanceof RegExp || left instanceof Cartesian2_default || left instanceof Cartesian3_default || left instanceof Cartesian4_default) {
return String(left);
}
throw new RuntimeError_default(`Unexpected function call "${this._value}".`);
};
function convertHSLToRGB(ast) {
const channels = ast._left;
const length3 = channels.length;
for (let i = 0; i < length3; ++i) {
if (channels[i]._type !== ExpressionNodeType_default.LITERAL_NUMBER) {
return void 0;
}
}
const h = channels[0]._value;
const s = channels[1]._value;
const l = channels[2]._value;
const a3 = length3 === 4 ? channels[3]._value : 1;
return Color_default.fromHsl(h, s, l, a3, scratchColor3);
}
function convertRGBToColor(ast) {
const channels = ast._left;
const length3 = channels.length;
for (let i = 0; i < length3; ++i) {
if (channels[i]._type !== ExpressionNodeType_default.LITERAL_NUMBER) {
return void 0;
}
}
const color = scratchColor3;
color.red = channels[0]._value / 255;
color.green = channels[1]._value / 255;
color.blue = channels[2]._value / 255;
color.alpha = length3 === 4 ? channels[3]._value : 1;
return color;
}
function numberToString(number) {
if (number % 1 === 0) {
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 a3 = numberToString(color.alpha);
return `vec4(${r}, ${g}, ${b}, ${a3})`;
}
function getExpressionArray(array, variableSubstitutionMap, shaderState, parent) {
const length3 = array.length;
const expressions = new Array(length3);
for (let i = 0; i < length3; ++i) {
expressions[i] = array[i].getShaderExpression(
variableSubstitutionMap,
shaderState,
parent
);
}
return expressions;
}
function getVariableName(variableName, variableSubstitutionMap) {
if (!defined_default(variableSubstitutionMap[variableName])) {
return Expression.NULL_SENTINEL;
}
return variableSubstitutionMap[variableName];
}
Expression.NULL_SENTINEL = "czm_infinity";
Node2.prototype.getShaderExpression = function(variableSubstitutionMap, shaderState, parent) {
let color;
let left;
let right;
let test;
const type = this._type;
let value = this._value;
if (defined_default(this._left)) {
if (Array.isArray(this._left)) {
left = getExpressionArray(
this._left,
variableSubstitutionMap,
shaderState,
this
);
} else {
left = this._left.getShaderExpression(
variableSubstitutionMap,
shaderState,
this
);
}
}
if (defined_default(this._right)) {
right = this._right.getShaderExpression(
variableSubstitutionMap,
shaderState,
this
);
}
if (defined_default(this._test)) {
test = this._test.getShaderExpression(
variableSubstitutionMap,
shaderState,
this
);
}
if (Array.isArray(this._value)) {
value = getExpressionArray(
this._value,
variableSubstitutionMap,
shaderState,
this
);
}
let args;
let length3;
let vectorExpression;
switch (type) {
case ExpressionNodeType_default.VARIABLE:
if (checkFeature(this)) {
return void 0;
}
return getVariableName(value, variableSubstitutionMap);
case ExpressionNodeType_default.UNARY:
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_default(unaryFunctions[value])) {
return `${value}(${left})`;
} else if (value === "isNaN") {
return `(${left} != ${left})`;
} else if (value === "isFinite") {
return `(abs(${left}) < czm_infinity)`;
} else if (value === "String" || value === "isExactClass" || value === "isClass" || value === "getExactClassName") {
throw new RuntimeError_default(
`Error generating style shader: "${value}" is not supported.`
);
}
return value + left;
case ExpressionNodeType_default.BINARY:
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_default(binaryFunctions[value])) {
return `${value}(${left}, ${right})`;
}
return `(${left} ${value} ${right})`;
case ExpressionNodeType_default.TERNARY:
if (defined_default(ternaryFunctions[value])) {
return `${value}(${left}, ${right}, ${test})`;
}
break;
case ExpressionNodeType_default.CONDITIONAL:
return `(${test} ? ${left} : ${right})`;
case ExpressionNodeType_default.MEMBER:
if (checkFeature(this._left)) {
return getVariableName(right, variableSubstitutionMap);
}
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_default.FUNCTION_CALL:
throw new RuntimeError_default(
`Error generating style shader: "${value}" is not supported.`
);
case ExpressionNodeType_default.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_default(
"Error generating style shader: Invalid array length. Array length should be 2, 3, or 4."
);
case ExpressionNodeType_default.REGEX:
throw new RuntimeError_default(
"Error generating style shader: Regular expressions are not supported."
);
case ExpressionNodeType_default.VARIABLE_IN_STRING:
throw new RuntimeError_default(
"Error generating style shader: Converting a variable to a string is not supported."
);
case ExpressionNodeType_default.LITERAL_NULL:
return Expression.NULL_SENTINEL;
case ExpressionNodeType_default.LITERAL_BOOLEAN:
return value ? "true" : "false";
case ExpressionNodeType_default.LITERAL_NUMBER:
return numberToString(value);
case ExpressionNodeType_default.LITERAL_STRING:
if (defined_default(parent) && parent._type === ExpressionNodeType_default.MEMBER) {
if (value === "r" || value === "g" || value === "b" || value === "a" || value === "x" || value === "y" || value === "z" || value === "w" || checkFeature(parent._left)) {
return value;
}
}
color = Color_default.fromCssColorString(value, scratchColor3);
if (defined_default(color)) {
return colorToVec3(color);
}
throw new RuntimeError_default(
"Error generating style shader: String literals are not supported."
);
case ExpressionNodeType_default.LITERAL_COLOR:
args = left;
if (value === "color") {
if (!defined_default(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_default(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_default(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_default(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_default(color)) {
if (color.alpha !== 1) {
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_default.LITERAL_VECTOR:
if (!defined_default(left)) {
throw new DeveloperError_default(
"left should always be defined for type ExpressionNodeType.LITERAL_VECTOR"
);
}
length3 = left.length;
vectorExpression = `${value}(`;
for (let i = 0; i < length3; ++i) {
vectorExpression += left[i];
if (i < length3 - 1) {
vectorExpression += ", ";
}
}
vectorExpression += ")";
return vectorExpression;
case ExpressionNodeType_default.LITERAL_REGEX:
throw new RuntimeError_default(
"Error generating style shader: Regular expressions are not supported."
);
case ExpressionNodeType_default.LITERAL_UNDEFINED:
return Expression.NULL_SENTINEL;
case ExpressionNodeType_default.BUILTIN_VARIABLE:
if (value === "tiles3d_tileset_time") {
return value;
}
}
};
Node2.prototype.getVariables = function(variables, parent) {
let array;
let length3;
let i;
const type = this._type;
const value = this._value;
if (defined_default(this._left)) {
if (Array.isArray(this._left)) {
array = this._left;
length3 = array.length;
for (i = 0; i < length3; ++i) {
array[i].getVariables(variables, this);
}
} else {
this._left.getVariables(variables, this);
}
}
if (defined_default(this._right)) {
this._right.getVariables(variables, this);
}
if (defined_default(this._test)) {
this._test.getVariables(variables, this);
}
if (Array.isArray(this._value)) {
array = this._value;
length3 = array.length;
for (i = 0; i < length3; ++i) {
array[i].getVariables(variables, this);
}
}
let match;
switch (type) {
case ExpressionNodeType_default.VARIABLE:
if (!checkFeature(this)) {
variables.push(value);
}
break;
case ExpressionNodeType_default.VARIABLE_IN_STRING:
match = variableRegex.exec(value);
while (match !== null) {
variables.push(match[1]);
match = variableRegex.exec(value);
}
break;
case ExpressionNodeType_default.LITERAL_STRING:
if (defined_default(parent) && parent._type === ExpressionNodeType_default.MEMBER && checkFeature(parent._left)) {
variables.push(value);
}
break;
}
};
var Expression_default = Expression;
// node_modules/@cesium/engine/Source/Scene/Vector3DTilePrimitive.js
function Vector3DTilePrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._batchTable = options.batchTable;
this._batchIds = options.batchIds;
this._positions = options.positions;
this._vertexBatchIds = options.vertexBatchIds;
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_default(options.center, Cartesian3_default.ZERO);
this._va = void 0;
this._sp = void 0;
this._spStencil = void 0;
this._spPick = void 0;
this._uniformMap = void 0;
this._vaSwap = void 0;
this._rsStencilDepthPass = void 0;
this._rsStencilDepthPass3DTiles = void 0;
this._rsColorPass = void 0;
this._rsPickPass = void 0;
this._rsWireframe = void 0;
this._commands = [];
this._commandsIgnoreShow = [];
this._pickCommands = [];
this._constantColor = Color_default.clone(Color_default.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;
this.debugWireframe = false;
this._debugWireframe = this.debugWireframe;
this._wireframeDirty = false;
this.forceRebatch = false;
this.classificationType = defaultValue_default(
options.classificationType,
ClassificationType_default.BOTH
);
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 length3 = this._batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = this._batchIds[i];
this._batchIdLookUp[batchId] = i;
}
}
Object.defineProperties(Vector3DTilePrimitive.prototype, {
trianglesLength: {
get: function() {
return this._trianglesLength;
}
},
geometryByteLength: {
get: function() {
return this._geometryByteLength;
}
}
});
var defaultAttributeLocations = {
position: 0,
a_batchId: 1
};
function createVertexArray3(primitive, context) {
if (defined_default(primitive._va)) {
return;
}
const positionBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: primitive._positions,
usage: BufferUsage_default.STATIC_DRAW
});
const idBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: primitive._vertexBatchIds,
usage: BufferUsage_default.STATIC_DRAW
});
const indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: primitive._indices,
usage: BufferUsage_default.DYNAMIC_DRAW,
indexDatatype: primitive._indices.BYTES_PER_ELEMENT === 2 ? IndexDatatype_default.UNSIGNED_SHORT : IndexDatatype_default.UNSIGNED_INT
});
const vertexAttributes = [
{
index: 0,
vertexBuffer: positionBuffer,
componentDatatype: ComponentDatatype_default.fromTypedArray(primitive._positions),
componentsPerAttribute: 3
},
{
index: 1,
vertexBuffer: idBuffer,
componentDatatype: ComponentDatatype_default.fromTypedArray(
primitive._vertexBatchIds
),
componentsPerAttribute: 1
}
];
primitive._va = new VertexArray_default({
context,
attributes: vertexAttributes,
indexBuffer
});
if (context.webgl2) {
primitive._vaSwap = new VertexArray_default({
context,
attributes: vertexAttributes,
indexBuffer: Buffer_default.createIndexBuffer({
context,
sizeInBytes: indexBuffer.sizeInBytes,
usage: BufferUsage_default.DYNAMIC_DRAW,
indexDatatype: indexBuffer.indexDatatype
})
});
}
primitive._batchedPositions = void 0;
primitive._transferrableBatchIds = void 0;
primitive._vertexBatchIds = void 0;
}
function createShaders(primitive, context) {
if (defined_default(primitive._sp)) {
return;
}
const batchTable = primitive._batchTable;
const attributeLocations8 = defaultValue_default(
primitive._attributeLocations,
defaultAttributeLocations
);
let pickId = primitive._pickId;
const vertexShaderSource = primitive._vertexShaderSource;
let fragmentShaderSource = primitive._fragmentShaderSource;
if (defined_default(vertexShaderSource)) {
primitive._sp = ShaderProgram_default.fromCache({
context,
vertexShaderSource,
fragmentShaderSource,
attributeLocations: attributeLocations8
});
primitive._spStencil = primitive._sp;
fragmentShaderSource = ShaderSource_default.replaceMain(
fragmentShaderSource,
"czm_non_pick_main"
);
fragmentShaderSource = `${fragmentShaderSource}void main()
{
czm_non_pick_main();
out_FragColor = ${pickId};
}
`;
primitive._spPick = ShaderProgram_default.fromCache({
context,
vertexShaderSource,
fragmentShaderSource,
attributeLocations: attributeLocations8
});
return;
}
const vsSource = batchTable.getVertexShaderCallback(
false,
"a_batchId",
void 0
)(VectorTileVS_default);
let fsSource = batchTable.getFragmentShaderCallback(
false,
void 0,
true
)(ShadowVolumeFS_default);
pickId = batchTable.getPickId();
let vs = new ShaderSource_default({
sources: [vsSource]
});
let fs = new ShaderSource_default({
defines: ["VECTOR_TILE"],
sources: [fsSource]
});
primitive._sp = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
});
vs = new ShaderSource_default({
sources: [VectorTileVS_default]
});
fs = new ShaderSource_default({
defines: ["VECTOR_TILE"],
sources: [ShadowVolumeFS_default]
});
primitive._spStencil = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
});
fsSource = ShaderSource_default.replaceMain(fsSource, "czm_non_pick_main");
fsSource = `${fsSource}
void main()
{
czm_non_pick_main();
out_FragColor = ${pickId};
}
`;
const pickVS = new ShaderSource_default({
sources: [vsSource]
});
const pickFS = new ShaderSource_default({
defines: ["VECTOR_TILE"],
sources: [fsSource]
});
primitive._spPick = ShaderProgram_default.fromCache({
context,
vertexShaderSource: pickVS,
fragmentShaderSource: pickFS,
attributeLocations: attributeLocations8
});
}
function getStencilDepthRenderState2(mask3DTiles) {
const stencilFunction = mask3DTiles ? StencilFunction_default.EQUAL : StencilFunction_default.ALWAYS;
return {
colorMask: {
red: false,
green: false,
blue: false,
alpha: false
},
stencilTest: {
enabled: true,
frontFunction: stencilFunction,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.DECREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
backFunction: stencilFunction,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.INCREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
reference: StencilConstants_default.CESIUM_3D_TILE_MASK,
mask: StencilConstants_default.CESIUM_3D_TILE_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: true,
func: DepthFunction_default.LESS_OR_EQUAL
},
depthMask: false
};
}
var colorRenderState = {
stencilTest: {
enabled: true,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false,
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND
};
var pickRenderState2 = {
stencilTest: {
enabled: true,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false
};
function createRenderStates3(primitive) {
if (defined_default(primitive._rsStencilDepthPass)) {
return;
}
primitive._rsStencilDepthPass = RenderState_default.fromCache(
getStencilDepthRenderState2(false)
);
primitive._rsStencilDepthPass3DTiles = RenderState_default.fromCache(
getStencilDepthRenderState2(true)
);
primitive._rsColorPass = RenderState_default.fromCache(colorRenderState);
primitive._rsPickPass = RenderState_default.fromCache(pickRenderState2);
}
var modifiedModelViewScratch2 = new Matrix4_default();
var rtcScratch2 = new Cartesian3_default();
function createUniformMap(primitive, context) {
if (defined_default(primitive._uniformMap)) {
return;
}
const uniformMap2 = {
u_modifiedModelViewProjection: function() {
const viewMatrix = context.uniformState.view;
const projectionMatrix = context.uniformState.projection;
Matrix4_default.clone(viewMatrix, modifiedModelViewScratch2);
Matrix4_default.multiplyByPoint(
modifiedModelViewScratch2,
primitive._center,
rtcScratch2
);
Matrix4_default.setTranslation(
modifiedModelViewScratch2,
rtcScratch2,
modifiedModelViewScratch2
);
Matrix4_default.multiply(
projectionMatrix,
modifiedModelViewScratch2,
modifiedModelViewScratch2
);
return modifiedModelViewScratch2;
},
u_highlightColor: function() {
return primitive._highlightColor;
}
};
primitive._uniformMap = primitive._batchTable.getUniformMapCallback()(
uniformMap2
);
}
function copyIndicesCPU(indices2, newIndices, currentOffset, offsets, counts, batchIds, batchIdLookUp) {
const sizeInBytes = indices2.constructor.BYTES_PER_ELEMENT;
const batchedIdsLength = batchIds.length;
for (let j = 0; j < batchedIdsLength; ++j) {
const batchedId = batchIds[j];
const index = batchIdLookUp[batchedId];
const offset2 = offsets[index];
const count = counts[index];
const subarray2 = new indices2.constructor(
indices2.buffer,
sizeInBytes * offset2,
count
);
newIndices.set(subarray2, currentOffset);
offsets[index] = currentOffset;
currentOffset += count;
}
return currentOffset;
}
function rebatchCPU(primitive, batchedIndices) {
const indices2 = primitive._indices;
const indexOffsets = primitive._indexOffsets;
const indexCounts = primitive._indexCounts;
const batchIdLookUp = primitive._batchIdLookUp;
const newIndices = new indices2.constructor(indices2.length);
let current = batchedIndices.pop();
const newBatchedIndices = [current];
let currentOffset = copyIndicesCPU(
indices2,
newIndices,
0,
indexOffsets,
indexCounts,
current.batchIds,
batchIdLookUp
);
current.offset = 0;
current.count = currentOffset;
while (batchedIndices.length > 0) {
const next = batchedIndices.pop();
if (Color_default.equals(next.color, current.color)) {
currentOffset = copyIndicesCPU(
indices2,
newIndices,
currentOffset,
indexOffsets,
indexCounts,
next.batchIds,
batchIdLookUp
);
current.batchIds = current.batchIds.concat(next.batchIds);
current.count = currentOffset - current.offset;
} else {
const offset2 = currentOffset;
currentOffset = copyIndicesCPU(
indices2,
newIndices,
currentOffset,
indexOffsets,
indexCounts,
next.batchIds,
batchIdLookUp
);
next.offset = offset2;
next.count = currentOffset - offset2;
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 offset2 = offsets[index];
const count = counts[index];
writeBuffer.copyFromBuffer(
readBuffer,
offset2 * 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_default.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 offset2 = currentOffset;
currentOffset = copyIndicesGPU(
readBuffer,
writeBuffer,
currentOffset,
indexOffsets,
indexCounts,
next.batchIds,
batchIdLookUp
);
next.offset = offset2;
next.count = currentOffset - offset2;
newBatchedIndices.push(next);
current = next;
}
}
const temp = primitive._va;
primitive._va = primitive._vaSwap;
primitive._vaSwap = temp;
primitive._batchedIndices = newBatchedIndices;
}
function compareColors(a3, b) {
return b.color.toRgba() - a3.color.toRgba();
}
function rebatchCommands(primitive, context) {
if (!primitive._batchDirty) {
return false;
}
const batchedIndices = primitive._batchedIndices;
const length3 = batchedIndices.length;
let needToRebatch = false;
const colorCounts = {};
for (let i = 0; i < length3; ++i) {
const color = batchedIndices[i].color;
const rgba = color.toRgba();
if (defined_default(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 createColorCommands2(primitive, context) {
const needsRebatch = rebatchCommands(primitive, context);
const commands = primitive._commands;
const batchedIndices = primitive._batchedIndices;
const length3 = batchedIndices.length;
const commandsLength = length3 * 2;
if (defined_default(commands) && !needsRebatch && commands.length === commandsLength) {
return;
}
commands.length = commandsLength;
const vertexArray = primitive._va;
const sp = primitive._sp;
const modelMatrix = defaultValue_default(primitive._modelMatrix, Matrix4_default.IDENTITY);
const uniformMap2 = primitive._uniformMap;
const bv = primitive._boundingVolume;
for (let j = 0; j < length3; ++j) {
const offset2 = batchedIndices[j].offset;
const count = batchedIndices[j].count;
let stencilDepthCommand = commands[j * 2];
if (!defined_default(stencilDepthCommand)) {
stencilDepthCommand = commands[j * 2] = new DrawCommand_default({
owner: primitive
});
}
stencilDepthCommand.vertexArray = vertexArray;
stencilDepthCommand.modelMatrix = modelMatrix;
stencilDepthCommand.offset = offset2;
stencilDepthCommand.count = count;
stencilDepthCommand.renderState = primitive._rsStencilDepthPass;
stencilDepthCommand.shaderProgram = sp;
stencilDepthCommand.uniformMap = uniformMap2;
stencilDepthCommand.boundingVolume = bv;
stencilDepthCommand.cull = false;
stencilDepthCommand.pass = Pass_default.TERRAIN_CLASSIFICATION;
const stencilDepthDerivedCommand = DrawCommand_default.shallowClone(
stencilDepthCommand,
stencilDepthCommand.derivedCommands.tileset
);
stencilDepthDerivedCommand.renderState = primitive._rsStencilDepthPass3DTiles;
stencilDepthDerivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
stencilDepthCommand.derivedCommands.tileset = stencilDepthDerivedCommand;
let colorCommand = commands[j * 2 + 1];
if (!defined_default(colorCommand)) {
colorCommand = commands[j * 2 + 1] = new DrawCommand_default({
owner: primitive
});
}
colorCommand.vertexArray = vertexArray;
colorCommand.modelMatrix = modelMatrix;
colorCommand.offset = offset2;
colorCommand.count = count;
colorCommand.renderState = primitive._rsColorPass;
colorCommand.shaderProgram = sp;
colorCommand.uniformMap = uniformMap2;
colorCommand.boundingVolume = bv;
colorCommand.cull = false;
colorCommand.pass = Pass_default.TERRAIN_CLASSIFICATION;
const colorDerivedCommand = DrawCommand_default.shallowClone(
colorCommand,
colorCommand.derivedCommands.tileset
);
colorDerivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
colorCommand.derivedCommands.tileset = colorDerivedCommand;
}
primitive._commandsDirty = true;
}
function createColorCommandsIgnoreShow(primitive, frameState) {
if (primitive.classificationType === ClassificationType_default.TERRAIN || !frameState.invertClassification || defined_default(primitive._commandsIgnoreShow) && !primitive._commandsDirty) {
return;
}
const commands = primitive._commands;
const commandsIgnoreShow = primitive._commandsIgnoreShow;
const spStencil = primitive._spStencil;
const commandsLength = commands.length;
const length3 = commandsIgnoreShow.length = commandsLength / 2;
let commandIndex = 0;
for (let j = 0; j < length3; ++j) {
const commandIgnoreShow = commandsIgnoreShow[j] = DrawCommand_default.shallowClone(
commands[commandIndex],
commandsIgnoreShow[j]
);
commandIgnoreShow.shaderProgram = spStencil;
commandIgnoreShow.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;
commandIndex += 2;
}
primitive._commandsDirty = false;
}
function createPickCommands2(primitive) {
if (!primitive._pickCommandsDirty) {
return;
}
const length3 = primitive._indexOffsets.length;
const pickCommands = primitive._pickCommands;
pickCommands.length = length3 * 2;
const vertexArray = primitive._va;
const spStencil = primitive._spStencil;
const spPick = primitive._spPick;
const modelMatrix = defaultValue_default(primitive._modelMatrix, Matrix4_default.IDENTITY);
const uniformMap2 = primitive._uniformMap;
for (let j = 0; j < length3; ++j) {
const offset2 = primitive._indexOffsets[j];
const count = primitive._indexCounts[j];
const bv = defined_default(primitive._boundingVolumes) ? primitive._boundingVolumes[j] : primitive.boundingVolume;
let stencilDepthCommand = pickCommands[j * 2];
if (!defined_default(stencilDepthCommand)) {
stencilDepthCommand = pickCommands[j * 2] = new DrawCommand_default({
owner: primitive,
pickOnly: true
});
}
stencilDepthCommand.vertexArray = vertexArray;
stencilDepthCommand.modelMatrix = modelMatrix;
stencilDepthCommand.offset = offset2;
stencilDepthCommand.count = count;
stencilDepthCommand.renderState = primitive._rsStencilDepthPass;
stencilDepthCommand.shaderProgram = spStencil;
stencilDepthCommand.uniformMap = uniformMap2;
stencilDepthCommand.boundingVolume = bv;
stencilDepthCommand.pass = Pass_default.TERRAIN_CLASSIFICATION;
const stencilDepthDerivedCommand = DrawCommand_default.shallowClone(
stencilDepthCommand,
stencilDepthCommand.derivedCommands.tileset
);
stencilDepthDerivedCommand.renderState = primitive._rsStencilDepthPass3DTiles;
stencilDepthDerivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
stencilDepthCommand.derivedCommands.tileset = stencilDepthDerivedCommand;
let colorCommand = pickCommands[j * 2 + 1];
if (!defined_default(colorCommand)) {
colorCommand = pickCommands[j * 2 + 1] = new DrawCommand_default({
owner: primitive,
pickOnly: true
});
}
colorCommand.vertexArray = vertexArray;
colorCommand.modelMatrix = modelMatrix;
colorCommand.offset = offset2;
colorCommand.count = count;
colorCommand.renderState = primitive._rsPickPass;
colorCommand.shaderProgram = spPick;
colorCommand.uniformMap = uniformMap2;
colorCommand.boundingVolume = bv;
colorCommand.pass = Pass_default.TERRAIN_CLASSIFICATION;
const colorDerivedCommand = DrawCommand_default.shallowClone(
colorCommand,
colorCommand.derivedCommands.tileset
);
colorDerivedCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
colorCommand.derivedCommands.tileset = colorDerivedCommand;
}
primitive._pickCommandsDirty = false;
}
Vector3DTilePrimitive.prototype.createFeatures = function(content, features) {
const batchIds = this._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
features[batchId] = new Cesium3DTileFeature_default(content, batchId);
}
};
Vector3DTilePrimitive.prototype.applyDebugSettings = function(enabled, color) {
this._highlightColor = enabled ? color : this._constantColor;
};
function clearStyle(polygons, features) {
polygons._updatingAllCommands = true;
const batchIds = polygons._batchIds;
let length3 = batchIds.length;
let i;
for (i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
feature.show = true;
feature.color = Color_default.WHITE;
}
const batchedIndices = polygons._batchedIndices;
length3 = batchedIndices.length;
for (i = 0; i < length3; ++i) {
batchedIndices[i].color = Color_default.clone(Color_default.WHITE);
}
polygons._updatingAllCommands = false;
polygons._batchDirty = true;
}
var scratchColor4 = new Color_default();
var DEFAULT_COLOR_VALUE2 = Color_default.WHITE;
var DEFAULT_SHOW_VALUE2 = true;
var complexExpressionReg = /\$/;
Vector3DTilePrimitive.prototype.applyStyle = function(style, features) {
if (!defined_default(style)) {
clearStyle(this, features);
return;
}
const colorExpression = style.color;
const isSimpleStyle = colorExpression instanceof Expression_default && !complexExpressionReg.test(colorExpression.expression);
this._updatingAllCommands = isSimpleStyle;
const batchIds = this._batchIds;
let length3 = batchIds.length;
let i;
for (i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
feature.color = defined_default(style.color) ? style.color.evaluateColor(feature, scratchColor4) : DEFAULT_COLOR_VALUE2;
feature.show = defined_default(style.show) ? style.show.evaluate(feature) : DEFAULT_SHOW_VALUE2;
}
if (isSimpleStyle) {
const batchedIndices = this._batchedIndices;
length3 = batchedIndices.length;
for (i = 0; i < length3; ++i) {
batchedIndices[i].color = Color_default.clone(Color_default.WHITE);
}
this._updatingAllCommands = false;
this._batchDirty = true;
}
};
Vector3DTilePrimitive.prototype.updateCommands = function(batchId, color) {
if (this._updatingAllCommands) {
return;
}
const batchIdLookUp = this._batchIdLookUp;
const index = batchIdLookUp[batchId];
if (!defined_default(index)) {
return;
}
const indexOffsets = this._indexOffsets;
const indexCounts = this._indexCounts;
const offset2 = indexOffsets[index];
const count = indexCounts[index];
const batchedIndices = this._batchedIndices;
const length3 = batchedIndices.length;
let i;
for (i = 0; i < length3; ++i) {
const batchedOffset = batchedIndices[i].offset;
const batchedCount = batchedIndices[i].count;
if (offset2 >= batchedOffset && offset2 < batchedOffset + batchedCount) {
break;
}
}
batchedIndices.push(
new Vector3DTileBatch_default({
color: Color_default.clone(color),
offset: offset2,
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] < offset2) {
startIds.push(id);
} else {
endIds.push(id);
}
}
if (endIds.length !== 0) {
batchedIndices.push(
new Vector3DTileBatch_default({
color: Color_default.clone(batchedIndices[i].color),
offset: offset2 + count,
count: batchedIndices[i].offset + batchedIndices[i].count - (offset2 + count),
batchIds: endIds
})
);
}
if (startIds.length !== 0) {
batchedIndices[i].count = offset2 - batchedIndices[i].offset;
batchedIndices[i].batchIds = startIds;
} else {
batchedIndices.splice(i, 1);
}
this._batchDirty = true;
};
function queueCommands(primitive, frameState, commands, commandsIgnoreShow) {
const classificationType = primitive.classificationType;
const queueTerrainCommands = classificationType !== ClassificationType_default.CESIUM_3D_TILE;
const queue3DTilesCommands = classificationType !== ClassificationType_default.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_default.TERRAIN_CLASSIFICATION;
commandList.push(command);
}
if (queue3DTilesCommands) {
command = commands[i].derivedCommands.tileset;
command.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
commandList.push(command);
}
}
if (!frameState.invertClassification || !defined_default(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_default.OPAQUE;
commandList.push(command);
}
}
function updateWireframe(primitive) {
let earlyExit = primitive.debugWireframe === primitive._debugWireframe;
earlyExit = earlyExit && !(primitive.debugWireframe && primitive._wireframeDirty);
if (earlyExit) {
return;
}
if (!defined_default(primitive._rsWireframe)) {
primitive._rsWireframe = RenderState_default.fromCache({});
}
let rs;
let type;
if (primitive.debugWireframe) {
rs = primitive._rsWireframe;
type = PrimitiveType_default.LINES;
} else {
rs = primitive._rsColorPass;
type = PrimitiveType_default.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;
}
Vector3DTilePrimitive.prototype.update = function(frameState) {
const context = frameState.context;
createVertexArray3(this, context);
createShaders(this, context);
createRenderStates3(this);
createUniformMap(this, context);
const passes = frameState.passes;
if (passes.render) {
createColorCommands2(this, context);
createColorCommandsIgnoreShow(this, frameState);
updateWireframe(this);
if (this._debugWireframe) {
queueWireframeCommands(frameState, this._commands);
} else {
queueCommands(this, frameState, this._commands, this._commandsIgnoreShow);
}
}
if (passes.pick) {
createPickCommands2(this);
queueCommands(this, frameState, this._pickCommands);
}
};
Vector3DTilePrimitive.prototype.isDestroyed = function() {
return false;
};
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_default(this);
};
var Vector3DTilePrimitive_default = Vector3DTilePrimitive;
// node_modules/@cesium/engine/Source/Scene/Vector3DTileGeometry.js
function Vector3DTileGeometry(options) {
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_default(this._center)) {
if (defined_default(this._boundingVolume)) {
this._center = Cartesian3_default.clone(this._boundingVolume.center);
} else {
this._center = Cartesian3_default.clone(Cartesian3_default.ZERO);
}
}
this._boundingVolumes = void 0;
this._batchedIndices = void 0;
this._indices = void 0;
this._indexOffsets = void 0;
this._indexCounts = void 0;
this._positions = void 0;
this._vertexBatchIds = void 0;
this._batchIds = void 0;
this._batchTableColors = void 0;
this._packedBuffer = void 0;
this._ready = false;
this._promise = void 0;
this._error = void 0;
this._verticesPromise = void 0;
this._primitive = void 0;
this.debugWireframe = false;
this.forceRebatch = false;
this.classificationType = ClassificationType_default.BOTH;
}
Object.defineProperties(Vector3DTileGeometry.prototype, {
trianglesLength: {
get: function() {
if (defined_default(this._primitive)) {
return this._primitive.trianglesLength;
}
return 0;
}
},
geometryByteLength: {
get: function() {
if (defined_default(this._primitive)) {
return this._primitive.geometryByteLength;
}
return 0;
}
},
ready: {
get: function() {
return this._ready;
}
}
});
Vector3DTileGeometry.packedBoxLength = Matrix4_default.packedLength + Cartesian3_default.packedLength;
Vector3DTileGeometry.packedCylinderLength = Matrix4_default.packedLength + 2;
Vector3DTileGeometry.packedEllipsoidLength = Matrix4_default.packedLength + Cartesian3_default.packedLength;
Vector3DTileGeometry.packedSphereLength = Cartesian3_default.packedLength + 1;
function packBuffer(geometries) {
const packedBuffer = new Float64Array(
Matrix4_default.packedLength + Cartesian3_default.packedLength
);
let offset2 = 0;
Cartesian3_default.pack(geometries._center, packedBuffer, offset2);
offset2 += Cartesian3_default.packedLength;
Matrix4_default.pack(geometries._modelMatrix, packedBuffer, offset2);
return packedBuffer;
}
function unpackBuffer(geometries, packedBuffer) {
let offset2 = 0;
const indicesBytesPerElement = packedBuffer[offset2++];
const numBVS = packedBuffer[offset2++];
const bvs = geometries._boundingVolumes = new Array(numBVS);
for (let i = 0; i < numBVS; ++i) {
bvs[i] = BoundingSphere_default.unpack(packedBuffer, offset2);
offset2 += BoundingSphere_default.packedLength;
}
const numBatchedIndices = packedBuffer[offset2++];
const bis = geometries._batchedIndices = new Array(numBatchedIndices);
for (let j = 0; j < numBatchedIndices; ++j) {
const color = Color_default.unpack(packedBuffer, offset2);
offset2 += Color_default.packedLength;
const indexOffset = packedBuffer[offset2++];
const count = packedBuffer[offset2++];
const length3 = packedBuffer[offset2++];
const batchIds = new Array(length3);
for (let k = 0; k < length3; ++k) {
batchIds[k] = packedBuffer[offset2++];
}
bis[j] = new Vector3DTileBatch_default({
color,
offset: indexOffset,
count,
batchIds
});
}
return indicesBytesPerElement;
}
var createVerticesTaskProcessor = new TaskProcessor_default(
"createVectorTileGeometries",
5
);
var scratchColor5 = new Color_default();
function createPrimitive(geometries) {
if (defined_default(geometries._primitive)) {
return;
}
if (!defined_default(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_default(batchTableColors)) {
let length3 = 0;
if (defined_default(geometries._boxes)) {
boxes = geometries._boxes = boxes.slice();
boxBatchIds = geometries._boxBatchIds = boxBatchIds.slice();
length3 += boxBatchIds.length;
}
if (defined_default(geometries._cylinders)) {
cylinders = geometries._cylinders = cylinders.slice();
cylinderBatchIds = geometries._cylinderBatchIds = cylinderBatchIds.slice();
length3 += cylinderBatchIds.length;
}
if (defined_default(geometries._ellipsoids)) {
ellipsoids = geometries._ellipsoids = ellipsoids.slice();
ellipsoidBatchIds = geometries._ellipsoidBatchIds = ellipsoidBatchIds.slice();
length3 += ellipsoidBatchIds.length;
}
if (defined_default(geometries._spheres)) {
spheres = geometries._sphere = spheres.slice();
sphereBatchIds = geometries._sphereBatchIds = sphereBatchIds.slice();
length3 += sphereBatchIds.length;
}
batchTableColors = geometries._batchTableColors = new Uint32Array(length3);
const batchTable = geometries._batchTable;
for (let i = 0; i < length3; ++i) {
const color = batchTable.getColor(i, scratchColor5);
batchTableColors[i] = color.toRgba();
}
packedBuffer = geometries._packedBuffer = packBuffer(geometries);
}
const transferrableObjects = [];
if (defined_default(boxes)) {
transferrableObjects.push(boxes.buffer, boxBatchIds.buffer);
}
if (defined_default(cylinders)) {
transferrableObjects.push(cylinders.buffer, cylinderBatchIds.buffer);
}
if (defined_default(ellipsoids)) {
transferrableObjects.push(ellipsoids.buffer, ellipsoidBatchIds.buffer);
}
if (defined_default(spheres)) {
transferrableObjects.push(spheres.buffer, sphereBatchIds.buffer);
}
transferrableObjects.push(batchTableColors.buffer, packedBuffer.buffer);
const parameters = {
boxes: defined_default(boxes) ? boxes.buffer : void 0,
boxBatchIds: defined_default(boxes) ? boxBatchIds.buffer : void 0,
cylinders: defined_default(cylinders) ? cylinders.buffer : void 0,
cylinderBatchIds: defined_default(cylinders) ? cylinderBatchIds.buffer : void 0,
ellipsoids: defined_default(ellipsoids) ? ellipsoids.buffer : void 0,
ellipsoidBatchIds: defined_default(ellipsoids) ? ellipsoidBatchIds.buffer : void 0,
spheres: defined_default(spheres) ? spheres.buffer : void 0,
sphereBatchIds: defined_default(spheres) ? sphereBatchIds.buffer : void 0,
batchTableColors: batchTableColors.buffer,
packedBuffer: packedBuffer.buffer
};
const verticesPromise = geometries._verticesPromise = createVerticesTaskProcessor.scheduleTask(
parameters,
transferrableObjects
);
if (!defined_default(verticesPromise)) {
return;
}
return verticesPromise.then(function(result) {
if (geometries.isDestroyed()) {
return;
}
const packedBuffer2 = new Float64Array(result.packedBuffer);
const indicesBytesPerElement = unpackBuffer(geometries, packedBuffer2);
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);
finishPrimitive(geometries);
geometries._ready = true;
}).catch((error) => {
if (geometries.isDestroyed()) {
return;
}
geometries._error = error;
});
}
}
function finishPrimitive(geometries) {
if (!defined_default(geometries._primitive)) {
geometries._primitive = new Vector3DTilePrimitive_default({
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_default(geometries._pickObject, geometries)
});
geometries._boxes = void 0;
geometries._boxBatchIds = void 0;
geometries._cylinders = void 0;
geometries._cylinderBatchIds = void 0;
geometries._ellipsoids = void 0;
geometries._ellipsoidBatchIds = void 0;
geometries._spheres = void 0;
geometries._sphereBatchIds = void 0;
geometries._center = void 0;
geometries._modelMatrix = void 0;
geometries._batchTable = void 0;
geometries._boundingVolume = void 0;
geometries._boundingVolumes = void 0;
geometries._batchedIndices = void 0;
geometries._indices = void 0;
geometries._indexOffsets = void 0;
geometries._indexCounts = void 0;
geometries._positions = void 0;
geometries._vertexBatchIds = void 0;
geometries._batchIds = void 0;
geometries._batchTableColors = void 0;
geometries._packedBuffer = void 0;
geometries._verticesPromise = void 0;
}
}
Vector3DTileGeometry.prototype.createFeatures = function(content, features) {
this._primitive.createFeatures(content, features);
};
Vector3DTileGeometry.prototype.applyDebugSettings = function(enabled, color) {
this._primitive.applyDebugSettings(enabled, color);
};
Vector3DTileGeometry.prototype.applyStyle = function(style, features) {
this._primitive.applyStyle(style, features);
};
Vector3DTileGeometry.prototype.updateCommands = function(batchId, color) {
this._primitive.updateCommands(batchId, color);
};
Vector3DTileGeometry.prototype.update = function(frameState) {
if (!this._ready) {
if (!defined_default(this._promise)) {
this._promise = createPrimitive(this);
}
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
return;
}
this._primitive.debugWireframe = this.debugWireframe;
this._primitive.forceRebatch = this.forceRebatch;
this._primitive.classificationType = this.classificationType;
this._primitive.update(frameState);
};
Vector3DTileGeometry.prototype.isDestroyed = function() {
return false;
};
Vector3DTileGeometry.prototype.destroy = function() {
this._primitive = this._primitive && this._primitive.destroy();
return destroyObject_default(this);
};
var Vector3DTileGeometry_default = Vector3DTileGeometry;
// node_modules/@cesium/engine/Source/Scene/Geometry3DTileContent.js
function Geometry3DTileContent(tileset, tile, resource, arrayBuffer, byteOffset) {
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
this._geometries = void 0;
this._metadata = void 0;
this._batchTable = void 0;
this._features = void 0;
this.featurePropertiesDirty = false;
this._group = void 0;
this._ready = false;
this._resolveContent = void 0;
this._readyPromise = new Promise((resolve2) => {
this._resolveContent = resolve2;
});
initialize4(this, arrayBuffer, byteOffset);
}
Object.defineProperties(Geometry3DTileContent.prototype, {
featuresLength: {
get: function() {
return defined_default(this._batchTable) ? this._batchTable.featuresLength : 0;
}
},
pointsLength: {
get: function() {
return 0;
}
},
trianglesLength: {
get: function() {
if (defined_default(this._geometries)) {
return this._geometries.trianglesLength;
}
return 0;
}
},
geometryByteLength: {
get: function() {
if (defined_default(this._geometries)) {
return this._geometries.geometryByteLength;
}
return 0;
}
},
texturesByteLength: {
get: function() {
return 0;
}
},
batchTableByteLength: {
get: function() {
return defined_default(this._batchTable) ? this._batchTable.batchTableByteLength : 0;
}
},
innerContents: {
get: function() {
return void 0;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Geometry3DTileContent.readyPromise",
"Geometry3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Geometry3DTileContent.ready to return true instead."
);
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(content) {
return function(batchId, color) {
if (defined_default(content._geometries)) {
content._geometries.updateCommands(batchId, color);
}
};
}
function getBatchIds(featureTableJson, featureTableBinary) {
let boxBatchIds;
let cylinderBatchIds;
let ellipsoidBatchIds;
let sphereBatchIds;
let i;
const numberOfBoxes = defaultValue_default(featureTableJson.BOXES_LENGTH, 0);
const numberOfCylinders = defaultValue_default(featureTableJson.CYLINDERS_LENGTH, 0);
const numberOfEllipsoids = defaultValue_default(
featureTableJson.ELLIPSOIDS_LENGTH,
0
);
const numberOfSpheres = defaultValue_default(featureTableJson.SPHERES_LENGTH, 0);
if (numberOfBoxes > 0 && defined_default(featureTableJson.BOX_BATCH_IDS)) {
const boxBatchIdsByteOffset = featureTableBinary.byteOffset + featureTableJson.BOX_BATCH_IDS.byteOffset;
boxBatchIds = new Uint16Array(
featureTableBinary.buffer,
boxBatchIdsByteOffset,
numberOfBoxes
);
}
if (numberOfCylinders > 0 && defined_default(featureTableJson.CYLINDER_BATCH_IDS)) {
const cylinderBatchIdsByteOffset = featureTableBinary.byteOffset + featureTableJson.CYLINDER_BATCH_IDS.byteOffset;
cylinderBatchIds = new Uint16Array(
featureTableBinary.buffer,
cylinderBatchIdsByteOffset,
numberOfCylinders
);
}
if (numberOfEllipsoids > 0 && defined_default(featureTableJson.ELLIPSOID_BATCH_IDS)) {
const ellipsoidBatchIdsByteOffset = featureTableBinary.byteOffset + featureTableJson.ELLIPSOID_BATCH_IDS.byteOffset;
ellipsoidBatchIds = new Uint16Array(
featureTableBinary.buffer,
ellipsoidBatchIdsByteOffset,
numberOfEllipsoids
);
}
if (numberOfSpheres > 0 && defined_default(featureTableJson.SPHERE_BATCH_IDS)) {
const sphereBatchIdsByteOffset = featureTableBinary.byteOffset + featureTableJson.SPHERE_BATCH_IDS.byteOffset;
sphereBatchIds = new Uint16Array(
featureTableBinary.buffer,
sphereBatchIdsByteOffset,
numberOfSpheres
);
}
const atLeastOneDefined = defined_default(boxBatchIds) || defined_default(cylinderBatchIds) || defined_default(ellipsoidBatchIds) || defined_default(sphereBatchIds);
const atLeastOneUndefined = numberOfBoxes > 0 && !defined_default(boxBatchIds) || numberOfCylinders > 0 && !defined_default(cylinderBatchIds) || numberOfEllipsoids > 0 && !defined_default(ellipsoidBatchIds) || numberOfSpheres > 0 && !defined_default(sphereBatchIds);
if (atLeastOneDefined && atLeastOneUndefined) {
throw new RuntimeError_default(
"If one group of batch ids is defined, then all batch ids must be defined"
);
}
const allUndefinedBatchIds = !defined_default(boxBatchIds) && !defined_default(cylinderBatchIds) && !defined_default(ellipsoidBatchIds) && !defined_default(sphereBatchIds);
if (allUndefinedBatchIds) {
let id = 0;
if (!defined_default(boxBatchIds) && numberOfBoxes > 0) {
boxBatchIds = new Uint16Array(numberOfBoxes);
for (i = 0; i < numberOfBoxes; ++i) {
boxBatchIds[i] = id++;
}
}
if (!defined_default(cylinderBatchIds) && numberOfCylinders > 0) {
cylinderBatchIds = new Uint16Array(numberOfCylinders);
for (i = 0; i < numberOfCylinders; ++i) {
cylinderBatchIds[i] = id++;
}
}
if (!defined_default(ellipsoidBatchIds) && numberOfEllipsoids > 0) {
ellipsoidBatchIds = new Uint16Array(numberOfEllipsoids);
for (i = 0; i < numberOfEllipsoids; ++i) {
ellipsoidBatchIds[i] = id++;
}
}
if (!defined_default(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
};
}
var sizeOfUint322 = Uint32Array.BYTES_PER_ELEMENT;
function initialize4(content, arrayBuffer, byteOffset) {
byteOffset = defaultValue_default(byteOffset, 0);
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint322;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Geometry tile version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint322;
const byteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint322;
if (byteLength === 0) {
content._ready = true;
content._resolveContent(content);
return;
}
const featureTableJSONByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint322;
if (featureTableJSONByteLength === 0) {
throw new RuntimeError_default(
"Feature table must have a byte length greater than zero"
);
}
const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint322;
const batchTableJSONByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint322;
const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint322;
const featureTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
featureTableJSONByteLength
);
byteOffset += featureTableJSONByteLength;
const featureTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
featureTableBinaryByteLength
);
byteOffset += featureTableBinaryByteLength;
let batchTableJson;
let batchTableBinary;
if (batchTableJSONByteLength > 0) {
batchTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
batchTableJSONByteLength
);
byteOffset += batchTableJSONByteLength;
if (batchTableBinaryByteLength > 0) {
batchTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
batchTableBinaryByteLength
);
batchTableBinary = new Uint8Array(batchTableBinary);
}
}
const numberOfBoxes = defaultValue_default(featureTableJson.BOXES_LENGTH, 0);
const numberOfCylinders = defaultValue_default(featureTableJson.CYLINDERS_LENGTH, 0);
const numberOfEllipsoids = defaultValue_default(
featureTableJson.ELLIPSOIDS_LENGTH,
0
);
const numberOfSpheres = defaultValue_default(featureTableJson.SPHERES_LENGTH, 0);
const totalPrimitives = numberOfBoxes + numberOfCylinders + numberOfEllipsoids + numberOfSpheres;
const batchTable = new Cesium3DTileBatchTable_default(
content,
totalPrimitives,
batchTableJson,
batchTableBinary,
createColorChangedCallback(content)
);
content._batchTable = batchTable;
if (totalPrimitives === 0) {
return;
}
const modelMatrix = content.tile.computedTransform;
let center;
if (defined_default(featureTableJson.RTC_CENTER)) {
center = Cartesian3_default.unpack(featureTableJson.RTC_CENTER);
Matrix4_default.multiplyByPoint(modelMatrix, center, center);
}
const batchIds = getBatchIds(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_default.packedBoxLength * numberOfBoxes
);
}
if (numberOfCylinders > 0) {
const cylindersByteOffset = featureTableBinary.byteOffset + featureTableJson.CYLINDERS.byteOffset;
cylinders = new Float32Array(
featureTableBinary.buffer,
cylindersByteOffset,
Vector3DTileGeometry_default.packedCylinderLength * numberOfCylinders
);
}
if (numberOfEllipsoids > 0) {
const ellipsoidsByteOffset = featureTableBinary.byteOffset + featureTableJson.ELLIPSOIDS.byteOffset;
ellipsoids = new Float32Array(
featureTableBinary.buffer,
ellipsoidsByteOffset,
Vector3DTileGeometry_default.packedEllipsoidLength * numberOfEllipsoids
);
}
if (numberOfSpheres > 0) {
const spheresByteOffset = featureTableBinary.byteOffset + featureTableJson.SPHERES.byteOffset;
spheres = new Float32Array(
featureTableBinary.buffer,
spheresByteOffset,
Vector3DTileGeometry_default.packedSphereLength * numberOfSpheres
);
}
content._geometries = new Vector3DTileGeometry_default({
boxes,
boxBatchIds: batchIds.boxes,
cylinders,
cylinderBatchIds: batchIds.cylinders,
ellipsoids,
ellipsoidBatchIds: batchIds.ellipsoids,
spheres,
sphereBatchIds: batchIds.spheres,
center,
modelMatrix,
batchTable,
boundingVolume: content.tile.boundingVolume.boundingVolume
});
return content;
}
return Promise.resolve(content);
}
function createFeatures(content) {
const featuresLength = content.featuresLength;
if (!defined_default(content._features) && featuresLength > 0) {
const features = new Array(featuresLength);
if (defined_default(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) {
const featuresLength = this.featuresLength;
if (!defined_default(batchId) || batchId < 0 || batchId >= featuresLength) {
throw new DeveloperError_default(
`batchId is required and between zero and featuresLength - 1 (${featuresLength - 1}).`
);
}
createFeatures(this);
return this._features[batchId];
};
Geometry3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
if (defined_default(this._geometries)) {
this._geometries.applyDebugSettings(enabled, color);
}
};
Geometry3DTileContent.prototype.applyStyle = function(style) {
createFeatures(this);
if (defined_default(this._geometries)) {
this._geometries.applyStyle(style, this._features);
}
};
Geometry3DTileContent.prototype.update = function(tileset, frameState) {
if (defined_default(this._geometries)) {
this._geometries.classificationType = this._tileset.classificationType;
this._geometries.debugWireframe = this._tileset.debugWireframe;
this._geometries.update(frameState);
}
if (defined_default(this._batchTable) && this._geometries.ready) {
this._batchTable.update(tileset, frameState);
this._ready = true;
this._resolveContent(this);
}
};
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_default(this);
};
var Geometry3DTileContent_default = Geometry3DTileContent;
// node_modules/@cesium/engine/Source/Core/HilbertOrder.js
var HilbertOrder = {};
HilbertOrder.encode2D = function(level, x, y) {
const n = Math.pow(2, level);
Check_default.typeOf.number("level", level);
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (level < 1) {
throw new DeveloperError_default("Hilbert level cannot be less than 1.");
}
if (x < 0 || x >= n || y < 0 || y >= n) {
throw new DeveloperError_default("Invalid coordinates for given level.");
}
const p = {
x,
y
};
let rx, ry, s, 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;
index += BigInt((3 * rx ^ ry) * s * s);
rotate(n, p, rx, ry);
}
return index;
};
HilbertOrder.decode2D = function(level, index) {
Check_default.typeOf.number("level", level);
Check_default.typeOf.bigint("index", index);
if (level < 1) {
throw new DeveloperError_default("Hilbert level cannot be less than 1.");
}
if (index < BigInt(0) || index >= BigInt(Math.pow(4, level))) {
throw new DeveloperError_default(
"Hilbert index exceeds valid maximum for given level."
);
}
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) {
rx = 1 & Number(t / BigInt(2));
ry = 1 & Number(t ^ BigInt(rx));
rotate(s, p, rx, ry);
p.x += s * rx;
p.y += s * ry;
t /= BigInt(4);
}
return [p.x, p.y];
};
function rotate(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;
}
var HilbertOrder_default = HilbertOrder;
// node_modules/@cesium/engine/Source/Core/S2Cell.js
var S2_MAX_LEVEL = 30;
var S2_LIMIT_IJ = 1 << S2_MAX_LEVEL;
var S2_MAX_SITI = 1 << S2_MAX_LEVEL + 1 >>> 0;
var S2_POSITION_BITS = 2 * S2_MAX_LEVEL + 1;
var S2_LOOKUP_BITS = 4;
var S2_LOOKUP_POSITIONS = [];
var S2_LOOKUP_IJ = [];
var S2_POSITION_TO_IJ = [
[0, 1, 3, 2],
[0, 2, 3, 1],
[3, 2, 0, 1],
[3, 1, 0, 2]
];
var S2_SWAP_MASK = 1;
var S2_INVERT_MASK = 2;
var S2_POSITION_TO_ORIENTATION_MASK = [
S2_SWAP_MASK,
0,
0,
S2_SWAP_MASK | S2_INVERT_MASK
];
function S2Cell(cellId) {
if (!FeatureDetection_default.supportsBigInt()) {
throw new RuntimeError_default("S2 required BigInt support");
}
if (!defined_default(cellId)) {
throw new DeveloperError_default("cell ID is required.");
}
if (!S2Cell.isValidId(cellId)) {
throw new DeveloperError_default("cell ID is invalid.");
}
this._cellId = cellId;
this._level = S2Cell.getLevel(cellId);
}
S2Cell.fromToken = function(token) {
Check_default.typeOf.string("token", token);
if (!S2Cell.isValidToken(token)) {
throw new DeveloperError_default("token is invalid.");
}
return new S2Cell(S2Cell.getIdFromToken(token));
};
S2Cell.isValidId = function(cellId) {
Check_default.typeOf.bigint("cellId", cellId);
if (cellId <= 0) {
return false;
}
if (cellId >> BigInt(S2_POSITION_BITS) > 5) {
return false;
}
const lowestSetBit = cellId & ~cellId + BigInt(1);
if (!(lowestSetBit & BigInt("0x1555555555555555"))) {
return false;
}
return true;
};
S2Cell.isValidToken = function(token) {
Check_default.typeOf.string("token", token);
if (!/^[0-9a-fA-F]{1,16}$/.test(token)) {
return false;
}
return S2Cell.isValidId(S2Cell.getIdFromToken(token));
};
S2Cell.getIdFromToken = function(token) {
Check_default.typeOf.string("token", token);
return BigInt("0x" + token + "0".repeat(16 - token.length));
};
S2Cell.getTokenFromId = function(cellId) {
Check_default.typeOf.bigint("cellId", cellId);
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;
};
S2Cell.getLevel = function(cellId) {
Check_default.typeOf.bigint("cellId", cellId);
if (!S2Cell.isValidId(cellId)) {
throw new DeveloperError_default();
}
let lsbPosition = 0;
while (cellId !== BigInt(0)) {
if (cellId & BigInt(1)) {
break;
}
lsbPosition++;
cellId = cellId >> BigInt(1);
}
return S2_MAX_LEVEL - (lsbPosition >> 1);
};
S2Cell.prototype.getChild = function(index) {
Check_default.typeOf.number("index", index);
if (index < 0 || index > 3) {
throw new DeveloperError_default("child index must be in the range [0-3].");
}
if (this._level === 30) {
throw new DeveloperError_default("cannot get child of leaf cell.");
}
const newLsb = lsb(this._cellId) >> BigInt(2);
const childCellId = this._cellId + BigInt(2 * index + 1 - 4) * newLsb;
return new S2Cell(childCellId);
};
S2Cell.prototype.getParent = function() {
if (this._level === 0) {
throw new DeveloperError_default("cannot get parent of root cell.");
}
const newLsb = lsb(this._cellId) << BigInt(2);
return new S2Cell(this._cellId & ~newLsb + BigInt(1) | newLsb);
};
S2Cell.prototype.getParentAtLevel = function(level) {
if (this._level === 0 || level < 0 || this._level < level) {
throw new DeveloperError_default("cannot get parent at invalid level.");
}
const newLsb = lsbForLevel(level);
return new S2Cell(this._cellId & -newLsb | newLsb);
};
S2Cell.prototype.getCenter = function(ellipsoid) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
let center = getS2Center(this._cellId, this._level);
center = Cartesian3_default.normalize(center, center);
const cartographic2 = new Cartographic_default.fromCartesian(
center,
Ellipsoid_default.UNIT_SPHERE
);
return Cartographic_default.toCartesian(cartographic2, ellipsoid, new Cartesian3_default());
};
S2Cell.prototype.getVertex = function(index, ellipsoid) {
Check_default.typeOf.number("index", index);
if (index < 0 || index > 3) {
throw new DeveloperError_default("vertex index must be in the range [0-3].");
}
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
let vertex = getS2Vertex(this._cellId, this._level, index);
vertex = Cartesian3_default.normalize(vertex, vertex);
const cartographic2 = new Cartographic_default.fromCartesian(
vertex,
Ellipsoid_default.UNIT_SPHERE
);
return Cartographic_default.toCartesian(cartographic2, ellipsoid, new Cartesian3_default());
};
S2Cell.fromFacePositionLevel = function(face, position, level) {
Check_default.typeOf.bigint("position", position);
if (face < 0 || face > 5) {
throw new DeveloperError_default("Invalid S2 Face (must be within 0-5)");
}
if (level < 0 || level > S2_MAX_LEVEL) {
throw new DeveloperError_default("Invalid level (must be within 0-30)");
}
if (position < 0 || position >= Math.pow(4, level)) {
throw new DeveloperError_default("Invalid Hilbert position for level");
}
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");
const cellId = BigInt(
`0b${faceBitString}${positionPrefixPadding}${positionBitString}1${positionSuffixPadding}`
);
return new S2Cell(cellId);
};
function getS2Center(cellId, level) {
const faceSiTi = convertCellIdToFaceSiTi(cellId, level);
return convertFaceSiTitoXYZ(faceSiTi[0], faceSiTi[1], faceSiTi[2]);
}
function getS2Vertex(cellId, level, index) {
const faceIJ = convertCellIdToFaceIJ(cellId, level);
const uv = convertIJLeveltoBoundUV([faceIJ[1], faceIJ[2]], level);
const y = index >> 1 & 1;
return convertFaceUVtoXYZ(faceIJ[0], uv[0][y ^ index & 1], uv[1][y]);
}
function convertCellIdToFaceSiTi(cellId, level) {
const faceIJ = convertCellIdToFaceIJ(cellId);
const face = faceIJ[0];
const i = faceIJ[1];
const j = faceIJ[2];
const isLeaf = level === 30;
const shouldCorrect = !isLeaf && (BigInt(i) ^ cellId >> BigInt(2)) & BigInt(1);
const correction = isLeaf ? 1 : shouldCorrect ? 2 : 0;
const si = (i << 1) + correction;
const ti = (j << 1) + correction;
return [face, si, ti];
}
function convertCellIdToFaceIJ(cellId) {
if (S2_LOOKUP_POSITIONS.length === 0) {
generateLookupTable();
}
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)
) << 2;
bits = S2_LOOKUP_IJ[bits];
const offset2 = k * S2_LOOKUP_BITS;
i += bits >> S2_LOOKUP_BITS + 2 << offset2;
j += (bits >> 2 & lookupMask) << offset2;
bits &= S2_SWAP_MASK | S2_INVERT_MASK;
}
return [face, i, j];
}
function convertFaceSiTitoXYZ(face, si, ti) {
const s = convertSiTitoST(si);
const t = convertSiTitoST(ti);
const u3 = convertSTtoUV(s);
const v7 = convertSTtoUV(t);
return convertFaceUVtoXYZ(face, u3, v7);
}
function convertFaceUVtoXYZ(face, u3, v7) {
switch (face) {
case 0:
return new Cartesian3_default(1, u3, v7);
case 1:
return new Cartesian3_default(-u3, 1, v7);
case 2:
return new Cartesian3_default(-u3, -v7, 1);
case 3:
return new Cartesian3_default(-1, -v7, -u3);
case 4:
return new Cartesian3_default(v7, -1, -u3);
default:
return new Cartesian3_default(v7, u3, -1);
}
}
function convertSTtoUV(s) {
if (s >= 0.5) {
return 1 / 3 * (4 * s * s - 1);
}
return 1 / 3 * (1 - 4 * (1 - s) * (1 - s));
}
function convertSiTitoST(si) {
return 1 / S2_MAX_SITI * si;
}
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;
}
function getSizeIJ(level) {
return 1 << S2_MAX_LEVEL - level >>> 0;
}
function convertIJtoSTMinimum(i) {
return 1 / S2_LIMIT_IJ * i;
}
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]
);
}
}
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
);
}
function lsb(cellId) {
return cellId & ~cellId + BigInt(1);
}
function lsbForLevel(level) {
return BigInt(1) << BigInt(2 * (S2_MAX_LEVEL - level));
}
var 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
];
function countTrailingZeroBits(x) {
return Mod67BitPosition[(-x & x) % BigInt(67)];
}
var S2Cell_default = S2Cell;
// node_modules/@cesium/engine/Source/Scene/hasExtension.js
function hasExtension(json, extensionName) {
return defined_default(json) && defined_default(json.extensions) && defined_default(json.extensions[extensionName]);
}
var hasExtension_default = hasExtension;
// node_modules/@cesium/engine/Source/Scene/ImplicitAvailabilityBitstream.js
function ImplicitAvailabilityBitstream(options) {
const lengthBits = options.lengthBits;
let availableCount = options.availableCount;
Check_default.typeOf.number("options.lengthBits", lengthBits);
const constant = options.constant;
const bitstream = options.bitstream;
if (defined_default(constant)) {
availableCount = lengthBits;
} else {
const expectedLength = Math.ceil(lengthBits / 8);
if (bitstream.length !== expectedLength) {
throw new RuntimeError_default(
`Availability bitstream must be exactly ${expectedLength} bytes long to store ${lengthBits} bits. Actual bitstream was ${bitstream.length} bytes long.`
);
}
const computeAvailableCountEnabled = defaultValue_default(
options.computeAvailableCountEnabled,
false
);
if (!defined_default(availableCount) && computeAvailableCountEnabled) {
availableCount = count1Bits(bitstream, lengthBits);
}
}
this._lengthBits = lengthBits;
this._availableCount = availableCount;
this._constant = constant;
this._bitstream = bitstream;
}
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, {
lengthBits: {
get: function() {
return this._lengthBits;
}
},
availableCount: {
get: function() {
return this._availableCount;
}
}
});
ImplicitAvailabilityBitstream.prototype.getBit = function(index) {
if (index < 0 || index >= this._lengthBits) {
throw new DeveloperError_default("Bit index out of bounds.");
}
if (defined_default(this._constant)) {
return this._constant;
}
const byteIndex = index >> 3;
const bitIndex = index % 8;
return (this._bitstream[byteIndex] >> bitIndex & 1) === 1;
};
var ImplicitAvailabilityBitstream_default = ImplicitAvailabilityBitstream;
// node_modules/@cesium/engine/Source/Scene/ImplicitMetadataView.js
function ImplicitMetadataView(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const metadataTable = options.metadataTable;
const metadataClass = options.class;
const entityId = options.entityId;
const propertyTableJson = options.propertyTableJson;
Check_default.typeOf.object("options.metadataTable", metadataTable);
Check_default.typeOf.object("options.class", metadataClass);
Check_default.typeOf.number("options.entityId", entityId);
Check_default.typeOf.object("options.propertyTableJson", propertyTableJson);
this._class = metadataClass;
this._metadataTable = metadataTable;
this._entityId = entityId;
this._extensions = propertyTableJson.extensions;
this._extras = propertyTableJson.extras;
}
Object.defineProperties(ImplicitMetadataView.prototype, {
class: {
get: function() {
return this._class;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
ImplicitMetadataView.prototype.hasProperty = function(propertyId) {
return this._metadataTable.hasProperty(propertyId);
};
ImplicitMetadataView.prototype.hasPropertyBySemantic = function(semantic) {
return this._metadataTable.hasPropertyBySemantic(semantic);
};
ImplicitMetadataView.prototype.getPropertyIds = function(results) {
return this._metadataTable.getPropertyIds(results);
};
ImplicitMetadataView.prototype.getProperty = function(propertyId) {
return this._metadataTable.getProperty(this._entityId, propertyId);
};
ImplicitMetadataView.prototype.setProperty = function(propertyId, value) {
return this._metadataTable.setProperty(this._entityId, propertyId, value);
};
ImplicitMetadataView.prototype.getPropertyBySemantic = function(semantic) {
return this._metadataTable.getPropertyBySemantic(this._entityId, semantic);
};
ImplicitMetadataView.prototype.setPropertyBySemantic = function(semantic, value) {
return this._metadataTable.setPropertyBySemantic(
this._entityId,
semantic,
value
);
};
var ImplicitMetadataView_default = ImplicitMetadataView;
// node_modules/@cesium/engine/Source/Scene/ImplicitSubdivisionScheme.js
var ImplicitSubdivisionScheme = {
QUADTREE: "QUADTREE",
OCTREE: "OCTREE"
};
ImplicitSubdivisionScheme.getBranchingFactor = function(subdivisionScheme) {
switch (subdivisionScheme) {
case ImplicitSubdivisionScheme.OCTREE:
return 8;
case ImplicitSubdivisionScheme.QUADTREE:
return 4;
default:
throw new DeveloperError_default("subdivisionScheme is not a valid value.");
}
};
var ImplicitSubdivisionScheme_default = Object.freeze(ImplicitSubdivisionScheme);
// node_modules/@cesium/engine/Source/Scene/MetadataEntity.js
function MetadataEntity() {
}
Object.defineProperties(MetadataEntity.prototype, {
class: {
get: function() {
DeveloperError_default.throwInstantiationError();
}
}
});
MetadataEntity.prototype.hasProperty = function(propertyId) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.hasPropertyBySemantic = function(semantic) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.getPropertyIds = function(results) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.getProperty = function(propertyId) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.setProperty = function(propertyId, value) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.getPropertyBySemantic = function(semantic) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.prototype.setPropertyBySemantic = function(semantic, value) {
DeveloperError_default.throwInstantiationError();
};
MetadataEntity.hasProperty = function(propertyId, properties, classDefinition) {
Check_default.typeOf.string("propertyId", propertyId);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
if (defined_default(properties[propertyId])) {
return true;
}
const classProperties = classDefinition.properties;
if (!defined_default(classProperties)) {
return false;
}
const classProperty = classProperties[propertyId];
if (defined_default(classProperty) && defined_default(classProperty.default)) {
return true;
}
return false;
};
MetadataEntity.hasPropertyBySemantic = function(semantic, properties, classDefinition) {
Check_default.typeOf.string("semantic", semantic);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
const propertiesBySemantic = classDefinition.propertiesBySemantic;
if (!defined_default(propertiesBySemantic)) {
return false;
}
const property = propertiesBySemantic[semantic];
return defined_default(property);
};
MetadataEntity.getPropertyIds = function(properties, classDefinition, results) {
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
results = defined_default(results) ? results : [];
results.length = 0;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId) && defined_default(properties[propertyId])) {
results.push(propertyId);
}
}
const classProperties = classDefinition.properties;
if (defined_default(classProperties)) {
for (const classPropertyId in classProperties) {
if (classProperties.hasOwnProperty(classPropertyId) && !defined_default(properties[classPropertyId]) && defined_default(classProperties[classPropertyId].default)) {
results.push(classPropertyId);
}
}
}
return results;
};
MetadataEntity.getProperty = function(propertyId, properties, classDefinition) {
Check_default.typeOf.string("propertyId", propertyId);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
if (!defined_default(classDefinition.properties[propertyId])) {
throw new DeveloperError_default(`Class definition missing property ${propertyId}`);
}
const classProperty = classDefinition.properties[propertyId];
let value = properties[propertyId];
if (Array.isArray(value)) {
value = value.slice();
}
const enableNestedArrays = true;
value = classProperty.handleNoData(value);
if (!defined_default(value) && defined_default(classProperty.default)) {
value = clone_default(classProperty.default, true);
return classProperty.unpackVectorAndMatrixTypes(value, enableNestedArrays);
}
if (!defined_default(value)) {
return void 0;
}
value = classProperty.normalize(value);
value = classProperty.applyValueTransform(value);
return classProperty.unpackVectorAndMatrixTypes(value, enableNestedArrays);
};
MetadataEntity.setProperty = function(propertyId, value, properties, classDefinition) {
Check_default.typeOf.string("propertyId", propertyId);
Check_default.defined("value", value);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
if (!defined_default(properties[propertyId])) {
return false;
}
if (Array.isArray(value)) {
value = value.slice();
}
let classProperty;
const classProperties = classDefinition.properties;
if (defined_default(classProperties)) {
classProperty = classProperties[propertyId];
}
const enableNestedArrays = true;
if (defined_default(classProperty)) {
value = classProperty.packVectorAndMatrixTypes(value, enableNestedArrays);
value = classProperty.unapplyValueTransform(value);
value = classProperty.unnormalize(value);
}
properties[propertyId] = value;
return true;
};
MetadataEntity.getPropertyBySemantic = function(semantic, properties, classDefinition) {
Check_default.typeOf.string("semantic", semantic);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
const propertiesBySemantic = classDefinition.propertiesBySemantic;
if (!defined_default(propertiesBySemantic)) {
return void 0;
}
const property = propertiesBySemantic[semantic];
if (defined_default(property)) {
return MetadataEntity.getProperty(property.id, properties, classDefinition);
}
return void 0;
};
MetadataEntity.setPropertyBySemantic = function(semantic, value, properties, classDefinition) {
Check_default.typeOf.string("semantic", semantic);
Check_default.defined("value", value);
Check_default.typeOf.object("properties", properties);
Check_default.typeOf.object("classDefinition", classDefinition);
const propertiesBySemantic = classDefinition.propertiesBySemantic;
if (!defined_default(propertiesBySemantic)) {
return false;
}
const property = classDefinition.propertiesBySemantic[semantic];
if (defined_default(property)) {
return MetadataEntity.setProperty(
property.id,
value,
properties,
classDefinition
);
}
return false;
};
var MetadataEntity_default = MetadataEntity;
// node_modules/@cesium/engine/Source/Scene/ImplicitSubtreeMetadata.js
function ImplicitSubtreeMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const subtreeMetadata = options.subtreeMetadata;
const metadataClass = options.class;
Check_default.typeOf.object("options.subtreeMetadata", subtreeMetadata);
Check_default.typeOf.object("options.class", metadataClass);
const properties = defined_default(subtreeMetadata.properties) ? subtreeMetadata.properties : {};
this._class = metadataClass;
this._properties = properties;
this._extras = subtreeMetadata.extras;
this._extensions = subtreeMetadata.extensions;
}
Object.defineProperties(ImplicitSubtreeMetadata.prototype, {
class: {
get: function() {
return this._class;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
ImplicitSubtreeMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
ImplicitSubtreeMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
ImplicitSubtreeMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
ImplicitSubtreeMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
ImplicitSubtreeMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
ImplicitSubtreeMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
ImplicitSubtreeMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var ImplicitSubtreeMetadata_default = ImplicitSubtreeMetadata;
// node_modules/@cesium/engine/Source/Scene/MetadataComponentType.js
var MetadataComponentType = {
INT8: "INT8",
UINT8: "UINT8",
INT16: "INT16",
UINT16: "UINT16",
INT32: "INT32",
UINT32: "UINT32",
INT64: "INT64",
UINT64: "UINT64",
FLOAT32: "FLOAT32",
FLOAT64: "FLOAT64"
};
MetadataComponentType.getMinimum = function(type) {
Check_default.typeOf.string("type", type);
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_default.supportsBigInt()) {
return BigInt("-9223372036854775808");
}
return -Math.pow(2, 63);
case MetadataComponentType.UINT64:
if (FeatureDetection_default.supportsBigInt()) {
return BigInt(0);
}
return 0;
case MetadataComponentType.FLOAT32:
return -34028234663852886e22;
case MetadataComponentType.FLOAT64:
return -Number.MAX_VALUE;
}
};
MetadataComponentType.getMaximum = function(type) {
Check_default.typeOf.string("type", type);
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_default.supportsBigInt()) {
return BigInt("9223372036854775807");
}
return Math.pow(2, 63) - 1;
case MetadataComponentType.UINT64:
if (FeatureDetection_default.supportsBigInt()) {
return BigInt("18446744073709551615");
}
return Math.pow(2, 64) - 1;
case MetadataComponentType.FLOAT32:
return 34028234663852886e22;
case MetadataComponentType.FLOAT64:
return Number.MAX_VALUE;
}
};
MetadataComponentType.isIntegerType = function(type) {
Check_default.typeOf.string("type", type);
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;
}
};
MetadataComponentType.isUnsignedIntegerType = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.UINT8:
case MetadataComponentType.UINT16:
case MetadataComponentType.UINT32:
case MetadataComponentType.UINT64:
return true;
default:
return false;
}
};
MetadataComponentType.isVectorCompatible = function(type) {
Check_default.typeOf.string("type", type);
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;
}
};
MetadataComponentType.normalize = function(value, type) {
if (typeof value !== "number" && typeof value !== "bigint") {
throw new DeveloperError_default("value must be a number or a BigInt");
}
if (!MetadataComponentType.isIntegerType(type)) {
throw new DeveloperError_default("type must be an integer type");
}
return Math.max(
Number(value) / Number(MetadataComponentType.getMaximum(type)),
-1
);
};
MetadataComponentType.unnormalize = function(value, type) {
Check_default.typeOf.number("value", value);
if (!MetadataComponentType.isIntegerType(type)) {
throw new DeveloperError_default("type must be an integer type");
}
const max3 = MetadataComponentType.getMaximum(type);
const min3 = MetadataComponentType.isUnsignedIntegerType(type) ? 0 : -max3;
value = Math_default.sign(value) * Math.round(Math.abs(value) * Number(max3));
if ((type === MetadataComponentType.INT64 || type === MetadataComponentType.UINT64) && FeatureDetection_default.supportsBigInt()) {
value = BigInt(value);
}
if (value > max3) {
return max3;
}
if (value < min3) {
return min3;
}
return value;
};
MetadataComponentType.applyValueTransform = function(value, offset2, scale) {
return scale * value + offset2;
};
MetadataComponentType.unapplyValueTransform = function(value, offset2, scale) {
if (scale === 0) {
return 0;
}
return (value - offset2) / scale;
};
MetadataComponentType.getSizeInBytes = function(type) {
Check_default.typeOf.string("type", type);
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;
}
};
MetadataComponentType.fromComponentDatatype = function(componentDatatype) {
Check_default.typeOf.number("componentDatatype", componentDatatype);
switch (componentDatatype) {
case ComponentDatatype_default.BYTE:
return MetadataComponentType.INT8;
case ComponentDatatype_default.UNSIGNED_BYTE:
return MetadataComponentType.UINT8;
case ComponentDatatype_default.SHORT:
return MetadataComponentType.INT16;
case ComponentDatatype_default.UNSIGNED_SHORT:
return MetadataComponentType.UINT16;
case ComponentDatatype_default.INT:
return MetadataComponentType.INT32;
case ComponentDatatype_default.UNSIGNED_INT:
return MetadataComponentType.UINT32;
case ComponentDatatype_default.FLOAT:
return MetadataComponentType.FLOAT32;
case ComponentDatatype_default.DOUBLE:
return MetadataComponentType.FLOAT64;
}
};
MetadataComponentType.toComponentDatatype = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataComponentType.INT8:
return ComponentDatatype_default.BYTE;
case MetadataComponentType.UINT8:
return ComponentDatatype_default.UNSIGNED_BYTE;
case MetadataComponentType.INT16:
return ComponentDatatype_default.SHORT;
case MetadataComponentType.UINT16:
return ComponentDatatype_default.UNSIGNED_SHORT;
case MetadataComponentType.INT32:
return ComponentDatatype_default.INT;
case MetadataComponentType.UINT32:
return ComponentDatatype_default.UNSIGNED_INT;
case MetadataComponentType.FLOAT32:
return ComponentDatatype_default.FLOAT;
case MetadataComponentType.FLOAT64:
return ComponentDatatype_default.DOUBLE;
}
};
var MetadataComponentType_default = Object.freeze(MetadataComponentType);
// node_modules/@cesium/engine/Source/Scene/MetadataType.js
var MetadataType = {
SCALAR: "SCALAR",
VEC2: "VEC2",
VEC3: "VEC3",
VEC4: "VEC4",
MAT2: "MAT2",
MAT3: "MAT3",
MAT4: "MAT4",
BOOLEAN: "BOOLEAN",
STRING: "STRING",
ENUM: "ENUM"
};
MetadataType.isVectorType = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataType.VEC2:
case MetadataType.VEC3:
case MetadataType.VEC4:
return true;
default:
return false;
}
};
MetadataType.isMatrixType = function(type) {
Check_default.typeOf.string("type", type);
switch (type) {
case MetadataType.MAT2:
case MetadataType.MAT3:
case MetadataType.MAT4:
return true;
default:
return false;
}
};
MetadataType.getComponentCount = function(type) {
Check_default.typeOf.string("type", type);
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;
default:
throw new DeveloperError_default(`Invalid metadata type ${type}`);
}
};
MetadataType.getMathType = function(type) {
switch (type) {
case MetadataType.VEC2:
return Cartesian2_default;
case MetadataType.VEC3:
return Cartesian3_default;
case MetadataType.VEC4:
return Cartesian4_default;
case MetadataType.MAT2:
return Matrix2_default;
case MetadataType.MAT3:
return Matrix3_default;
case MetadataType.MAT4:
return Matrix4_default;
default:
return void 0;
}
};
var MetadataType_default = Object.freeze(MetadataType);
// node_modules/@cesium/engine/Source/Scene/MetadataClassProperty.js
function MetadataClassProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const type = options.type;
Check_default.typeOf.string("options.id", id);
Check_default.typeOf.string("options.type", type);
const componentType = options.componentType;
const enumType = options.enumType;
const normalized = defined_default(componentType) && MetadataComponentType_default.isIntegerType(componentType) && defaultValue_default(options.normalized, false);
this._id = id;
this._name = options.name;
this._description = options.description;
this._semantic = options.semantic;
this._isLegacyExtension = options.isLegacyExtension;
this._type = type;
this._componentType = componentType;
this._enumType = enumType;
this._valueType = defined_default(enumType) ? enumType.valueType : componentType;
this._isArray = defaultValue_default(options.isArray, false);
this._isVariableLengthArray = defaultValue_default(
options.isVariableLengthArray,
false
);
this._arrayLength = options.arrayLength;
this._min = clone_default(options.min, true);
this._max = clone_default(options.max, true);
this._normalized = normalized;
let offset2 = clone_default(options.offset, true);
let scale = clone_default(options.scale, true);
const hasValueTransform = defined_default(offset2) || defined_default(scale);
const enableNestedArrays = true;
if (!defined_default(offset2)) {
offset2 = this.expandConstant(0, enableNestedArrays);
}
if (!defined_default(scale)) {
scale = this.expandConstant(1, enableNestedArrays);
}
this._offset = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._noData = clone_default(options.noData, true);
this._default = clone_default(options.default, true);
this._required = defaultValue_default(options.required, true);
this._extras = clone_default(options.extras, true);
this._extensions = clone_default(options.extensions, true);
}
MetadataClassProperty.fromJson = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const property = options.property;
Check_default.typeOf.string("options.id", id);
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.string("options.property.type", property.type);
const isLegacyExtension = isLegacy(property);
const parsedType = parseType(property, options.enums);
let required;
if (!defined_default(isLegacyExtension)) {
required = false;
} else if (isLegacyExtension) {
required = defined_default(property.optional) ? !property.optional : true;
} else {
required = defaultValue_default(property.required, false);
}
return new MetadataClassProperty({
id,
type: parsedType.type,
componentType: parsedType.componentType,
enumType: parsedType.enumType,
isArray: parsedType.isArray,
isVariableLengthArray: parsedType.isVariableLengthArray,
arrayLength: parsedType.arrayLength,
normalized: property.normalized,
min: property.min,
max: property.max,
offset: property.offset,
scale: property.scale,
noData: property.noData,
default: property.default,
required,
name: property.name,
description: property.description,
semantic: property.semantic,
extras: property.extras,
extensions: property.extensions,
isLegacyExtension
});
};
Object.defineProperties(MetadataClassProperty.prototype, {
id: {
get: function() {
return this._id;
}
},
name: {
get: function() {
return this._name;
}
},
description: {
get: function() {
return this._description;
}
},
type: {
get: function() {
return this._type;
}
},
enumType: {
get: function() {
return this._enumType;
}
},
componentType: {
get: function() {
return this._componentType;
}
},
valueType: {
get: function() {
return this._valueType;
}
},
isArray: {
get: function() {
return this._isArray;
}
},
isVariableLengthArray: {
get: function() {
return this._isVariableLengthArray;
}
},
arrayLength: {
get: function() {
return this._arrayLength;
}
},
normalized: {
get: function() {
return this._normalized;
}
},
max: {
get: function() {
return this._max;
}
},
min: {
get: function() {
return this._min;
}
},
noData: {
get: function() {
return this._noData;
}
},
default: {
get: function() {
return this._default;
}
},
required: {
get: function() {
return this._required;
}
},
semantic: {
get: function() {
return this._semantic;
}
},
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
offset: {
get: function() {
return this._offset;
}
},
scale: {
get: function() {
return this._scale;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
function isLegacy(property) {
if (property.type === "ARRAY") {
return true;
}
const type = property.type;
if (type === MetadataType_default.SCALAR || MetadataType_default.isMatrixType(type) || MetadataType_default.isVectorType(type)) {
return false;
}
if (defined_default(MetadataComponentType_default[type])) {
return true;
}
if (defined_default(property.noData) || defined_default(property.scale) || defined_default(property.offset) || defined_default(property.required) || defined_default(property.count) || defined_default(property.array)) {
return false;
}
if (defined_default(property.optional)) {
return false;
}
return void 0;
}
function parseType(property, enums) {
const type = property.type;
const componentType = property.componentType;
const isLegacyArray = type === "ARRAY";
let isArray;
let arrayLength;
let isVariableLengthArray;
if (isLegacyArray) {
isArray = true;
arrayLength = property.componentCount;
isVariableLengthArray = !defined_default(arrayLength);
} else if (property.array) {
isArray = true;
arrayLength = property.count;
isVariableLengthArray = !defined_default(property.count);
} else {
isArray = false;
arrayLength = void 0;
isVariableLengthArray = false;
}
let enumType;
if (defined_default(property.enumType)) {
enumType = enums[property.enumType];
}
if (type === MetadataType_default.ENUM) {
return {
type,
componentType: void 0,
enumType,
valueType: enumType.valueType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (isLegacyArray && componentType === MetadataType_default.ENUM) {
return {
type: componentType,
componentType: void 0,
enumType,
valueType: enumType.valueType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (type === MetadataType_default.SCALAR || MetadataType_default.isMatrixType(type) || MetadataType_default.isVectorType(type)) {
return {
type,
componentType,
enumType: void 0,
valueType: componentType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (type === MetadataType_default.BOOLEAN || type === MetadataType_default.STRING) {
return {
type,
componentType: void 0,
enumType: void 0,
valueType: void 0,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (isLegacyArray && (componentType === MetadataType_default.BOOLEAN || componentType === MetadataType_default.STRING)) {
return {
type: componentType,
componentType: void 0,
enumType: void 0,
valueType: void 0,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (defined_default(componentType) && defined_default(MetadataComponentType_default[componentType])) {
return {
type: MetadataType_default.SCALAR,
componentType,
enumType: void 0,
valueType: componentType,
isArray,
isVariableLengthArray,
arrayLength
};
}
if (defined_default(MetadataComponentType_default[type])) {
return {
type: MetadataType_default.SCALAR,
componentType: type,
enumType: void 0,
valueType: type,
isArray,
isVariableLengthArray,
arrayLength
};
}
throw new DeveloperError_default(
`unknown metadata type {type: ${type}, componentType: ${componentType})`
);
}
MetadataClassProperty.prototype.normalize = function(value) {
if (!this._normalized) {
return value;
}
return normalizeInPlace(
value,
this._valueType,
MetadataComponentType_default.normalize
);
};
MetadataClassProperty.prototype.unnormalize = function(value) {
if (!this._normalized) {
return value;
}
return normalizeInPlace(
value,
this._valueType,
MetadataComponentType_default.unnormalize
);
};
MetadataClassProperty.prototype.applyValueTransform = function(value) {
if (!this._hasValueTransform || this._isVariableLengthArray) {
return value;
}
return MetadataClassProperty.valueTransformInPlace(
value,
this._offset,
this._scale,
MetadataComponentType_default.applyValueTransform
);
};
MetadataClassProperty.prototype.unapplyValueTransform = function(value) {
if (!this._hasValueTransform || this._isVariableLengthArray) {
return value;
}
return MetadataClassProperty.valueTransformInPlace(
value,
this._offset,
this._scale,
MetadataComponentType_default.unapplyValueTransform
);
};
MetadataClassProperty.prototype.expandConstant = function(constant, enableNestedArrays) {
enableNestedArrays = defaultValue_default(enableNestedArrays, false);
const isArray = this._isArray;
const arrayLength = this._arrayLength;
const componentCount = MetadataType_default.getComponentCount(this._type);
const isNested = isArray && componentCount > 1;
if (!isArray && componentCount === 1) {
return constant;
}
if (!isArray) {
return new Array(componentCount).fill(constant);
}
if (!isNested) {
return new Array(arrayLength).fill(constant);
}
if (!enableNestedArrays) {
return new Array(this._arrayLength * componentCount).fill(constant);
}
const innerConstant = new Array(componentCount).fill(constant);
return new Array(this._arrayLength).fill(innerConstant);
};
MetadataClassProperty.prototype.handleNoData = function(value) {
const sentinel = this._noData;
if (!defined_default(sentinel)) {
return value;
}
if (arrayEquals(value, sentinel)) {
return void 0;
}
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;
}
MetadataClassProperty.prototype.unpackVectorAndMatrixTypes = function(value, enableNestedArrays) {
enableNestedArrays = defaultValue_default(enableNestedArrays, false);
const MathType = MetadataType_default.getMathType(this._type);
const isArray = this._isArray;
const componentCount = MetadataType_default.getComponentCount(this._type);
const isNested = isArray && componentCount > 1;
if (!defined_default(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);
};
MetadataClassProperty.prototype.packVectorAndMatrixTypes = function(value, enableNestedArrays) {
enableNestedArrays = defaultValue_default(enableNestedArrays, false);
const MathType = MetadataType_default.getMathType(this._type);
const isArray = this._isArray;
const componentCount = MetadataType_default.getComponentCount(this._type);
const isNested = isArray && componentCount > 1;
if (!defined_default(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, []);
};
MetadataClassProperty.prototype.validate = function(value) {
if (!defined_default(value) && defined_default(this._default)) {
return void 0;
}
if (this._required && !defined_default(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 length3 = value.length;
if (!classProperty._isVariableLengthArray && length3 !== classProperty._arrayLength) {
return "Array length does not match property.arrayLength";
}
for (let i = 0; i < length3; i++) {
const message = validateSingleValue(classProperty, value[i]);
if (defined_default(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_default.isVectorType(type)) {
return validateVector(value, type, componentType);
} else if (MetadataType_default.isMatrixType(type)) {
return validateMatrix(value, type, componentType);
} else if (type === MetadataType_default.STRING) {
return validateString(value);
} else if (type === MetadataType_default.BOOLEAN) {
return validateBoolean(value);
} else if (type === MetadataType_default.ENUM) {
return validateEnum(value, enumType);
}
return validateScalar(value, componentType, normalized);
}
function validateVector(value, type, componentType) {
if (!MetadataComponentType_default.isVectorCompatible(componentType)) {
return `componentType ${componentType} is incompatible with vector type ${type}`;
}
if (type === MetadataType_default.VEC2 && !(value instanceof Cartesian2_default)) {
return `vector value ${value} must be a Cartesian2`;
}
if (type === MetadataType_default.VEC3 && !(value instanceof Cartesian3_default)) {
return `vector value ${value} must be a Cartesian3`;
}
if (type === MetadataType_default.VEC4 && !(value instanceof Cartesian4_default)) {
return `vector value ${value} must be a Cartesian4`;
}
}
function validateMatrix(value, type, componentType) {
if (!MetadataComponentType_default.isVectorCompatible(componentType)) {
return `componentType ${componentType} is incompatible with matrix type ${type}`;
}
if (type === MetadataType_default.MAT2 && !(value instanceof Matrix2_default)) {
return `matrix value ${value} must be a Matrix2`;
}
if (type === MetadataType_default.MAT3 && !(value instanceof Matrix3_default)) {
return `matrix value ${value} must be a Matrix3`;
}
if (type === MetadataType_default.MAT4 && !(value instanceof Matrix4_default)) {
return `matrix value ${value} must be a Matrix4`;
}
}
function validateString(value) {
if (typeof value !== "string") {
return getTypeErrorMessage(value, MetadataType_default.STRING);
}
}
function validateBoolean(value) {
if (typeof value !== "boolean") {
return getTypeErrorMessage(value, MetadataType_default.BOOLEAN);
}
}
function validateEnum(value, enumType) {
const javascriptType = typeof value;
if (defined_default(enumType)) {
if (javascriptType !== "string" || !defined_default(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_default.INT8:
case MetadataComponentType_default.UINT8:
case MetadataComponentType_default.INT16:
case MetadataComponentType_default.UINT16:
case MetadataComponentType_default.INT32:
case MetadataComponentType_default.UINT32:
case MetadataComponentType_default.FLOAT32:
case MetadataComponentType_default.FLOAT64:
if (javascriptType !== "number") {
return getTypeErrorMessage(value, componentType);
}
if (!isFinite(value)) {
return getNonFiniteErrorMessage(value, componentType);
}
return checkInRange(value, componentType, normalized);
case MetadataComponentType_default.INT64:
case MetadataComponentType_default.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 min3 = MetadataComponentType_default.isUnsignedIntegerType(componentType) ? 0 : -1;
const max3 = 1;
if (value < min3 || value > max3) {
return getOutOfRangeErrorMessage(value, componentType, normalized);
}
return;
}
if (value < MetadataComponentType_default.getMinimum(componentType) || value > MetadataComponentType_default.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)) {
return transformationFunction(values, offsets, scales);
}
for (let i = 0; i < values.length; i++) {
values[i] = MetadataClassProperty.valueTransformInPlace(
values[i],
offsets[i],
scales[i],
transformationFunction
);
}
return values;
};
var MetadataClassProperty_default = MetadataClassProperty;
// node_modules/@cesium/engine/Source/Scene/MetadataTableProperty.js
function MetadataTableProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const count = options.count;
const property = options.property;
const classProperty = options.classProperty;
const bufferViews = options.bufferViews;
Check_default.typeOf.number.greaterThan("options.count", count, 0);
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.object("options.classProperty", classProperty);
Check_default.typeOf.object("options.bufferViews", bufferViews);
const type = classProperty.type;
const isArray = classProperty.isArray;
const isVariableLengthArray = classProperty.isVariableLengthArray;
let valueType = classProperty.valueType;
const enumType = classProperty.enumType;
const hasStrings = type === MetadataType_default.STRING;
const hasBooleans = type === MetadataType_default.BOOLEAN;
let byteLength = 0;
let arrayOffsets;
if (isVariableLengthArray) {
let arrayOffsetType = defaultValue_default(
property.arrayOffsetType,
property.offsetType
);
arrayOffsetType = defaultValue_default(
MetadataComponentType_default[arrayOffsetType],
MetadataComponentType_default.UINT32
);
const arrayOffsetBufferView = defaultValue_default(
property.arrayOffsets,
property.arrayOffsetBufferView
);
arrayOffsets = new BufferView(
bufferViews[arrayOffsetBufferView],
arrayOffsetType,
count + 1
);
byteLength += arrayOffsets.typedArray.byteLength;
}
const vectorComponentCount = MetadataType_default.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) {
let stringOffsetType = defaultValue_default(
property.stringOffsetType,
property.offsetType
);
stringOffsetType = defaultValue_default(
MetadataComponentType_default[stringOffsetType],
MetadataComponentType_default.UINT32
);
const stringOffsetBufferView = defaultValue_default(
property.stringOffsets,
property.stringOffsetBufferView
);
stringOffsets = new BufferView(
bufferViews[stringOffsetBufferView],
stringOffsetType,
componentCount + 1
);
byteLength += stringOffsets.typedArray.byteLength;
}
if (hasStrings || hasBooleans) {
valueType = MetadataComponentType_default.UINT8;
}
let valueCount;
if (hasStrings) {
valueCount = stringOffsets.get(componentCount) - stringOffsets.get(0);
} else if (hasBooleans) {
valueCount = Math.ceil(componentCount / 8);
} else {
valueCount = componentCount;
}
const valuesBufferView = defaultValue_default(property.values, property.bufferView);
const values = new BufferView(
bufferViews[valuesBufferView],
valueType,
valueCount
);
byteLength += values.typedArray.byteLength;
let offset2 = property.offset;
let scale = property.scale;
const hasValueTransform = classProperty.hasValueTransform || defined_default(offset2) || defined_default(scale);
offset2 = defaultValue_default(offset2, classProperty.offset);
scale = defaultValue_default(scale, classProperty.scale);
offset2 = flatten(offset2);
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_default(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 = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._getValue = getValueFunction;
this._setValue = setValueFunction;
this._unpackedValues = void 0;
this._extras = property.extras;
this._extensions = property.extensions;
this._byteLength = byteLength;
}
Object.defineProperties(MetadataTableProperty.prototype, {
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
offset: {
get: function() {
return this._offset;
}
},
scale: {
get: function() {
return this._scale;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
},
byteLength: {
get: function() {
return this._byteLength;
}
}
});
MetadataTableProperty.prototype.get = function(index) {
checkIndex(this, index);
let value = get(this, index);
value = this._classProperty.handleNoData(value);
if (!defined_default(value)) {
value = this._classProperty.default;
return this._classProperty.unpackVectorAndMatrixTypes(value);
}
value = this._classProperty.normalize(value);
value = applyValueTransform(this, value);
return this._classProperty.unpackVectorAndMatrixTypes(value);
};
MetadataTableProperty.prototype.set = function(index, value) {
const classProperty = this._classProperty;
Check_default.defined("value", value);
checkIndex(this, index);
const errorMessage = classProperty.validate(value);
if (defined_default(errorMessage)) {
throw new DeveloperError_default(errorMessage);
}
value = classProperty.packVectorAndMatrixTypes(value);
value = unapplyValueTransform(this, value);
value = classProperty.unnormalize(value);
set(this, index, value);
};
MetadataTableProperty.prototype.getTypedArray = function() {
if (defined_default(this._values)) {
return this._values.typedArray;
}
return void 0;
};
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(table2, index) {
const count = table2._count;
if (!defined_default(index) || index < 0 || index >= count) {
const maximumIndex = count - 1;
throw new DeveloperError_default(
`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_default.getComponentCount(type);
if (defined_default(property._unpackedValues)) {
const value = property._unpackedValues[index];
if (isArray) {
return clone_default(value, true);
}
return value;
}
if (!isArray && componentCount === 1) {
return property._getValue(index);
}
return getArrayValues(property, classProperty, index);
}
function getArrayValues(property, classProperty, index) {
let offset2;
let length3;
if (classProperty.isVariableLengthArray) {
offset2 = property._arrayOffsets.get(index);
length3 = property._arrayOffsets.get(index + 1) - offset2;
const componentCount = MetadataType_default.getComponentCount(classProperty.type);
offset2 *= componentCount;
length3 *= componentCount;
} else {
const arrayLength = defaultValue_default(classProperty.arrayLength, 1);
const componentCount = arrayLength * property._vectorComponentCount;
offset2 = index * componentCount;
length3 = componentCount;
}
const values = new Array(length3);
for (let i = 0; i < length3; i++) {
values[i] = property._getValue(offset2 + 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_default.getComponentCount(type);
if (defined_default(property._unpackedValues)) {
if (classProperty.isArray) {
value = clone_default(value, true);
}
property._unpackedValues[index] = value;
return;
}
if (!isArray && componentCount === 1) {
property._setValue(index, value);
return;
}
let offset2;
let length3;
if (classProperty.isVariableLengthArray) {
offset2 = property._arrayOffsets.get(index);
length3 = property._arrayOffsets.get(index + 1) - offset2;
} else {
const arrayLength = defaultValue_default(classProperty.arrayLength, 1);
const componentCount2 = arrayLength * property._vectorComponentCount;
offset2 = index * componentCount2;
length3 = componentCount2;
}
for (let i = 0; i < length3; ++i) {
property._setValue(offset2 + i, value[i]);
}
}
function getString(index, values, stringOffsets) {
const stringByteOffset = stringOffsets.get(index);
const stringByteLength = stringOffsets.get(index + 1) - stringByteOffset;
return getStringFromTypedArray_default(
values.typedArray,
stringByteOffset,
stringByteLength
);
}
function getBoolean(index, values) {
const byteIndex = index >> 3;
const bitIndex = index % 8;
return (values.typedArray[byteIndex] >> bitIndex & 1) === 1;
}
function setBoolean(index, values, value) {
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) & 128) > 0;
let carrying = true;
for (let i = 0; i < 8; ++i) {
let byte = dataView.getUint8(byteOffset + i);
if (isNegative) {
if (carrying) {
if (byte !== 0) {
byte = ~(byte - 1) & 255;
carrying = false;
}
} else {
byte = ~byte & 255;
}
}
value += byte * Math.pow(256, i);
}
if (isNegative) {
value = -value;
}
return value;
}
function getInt64BigIntFallback(index, values) {
const dataView = values.dataView;
const byteOffset = index * 8;
let value = BigInt(0);
const isNegative = (dataView.getUint8(byteOffset + 7) & 128) > 0;
let carrying = true;
for (let i = 0; i < 8; ++i) {
let byte = dataView.getUint8(byteOffset + i);
if (isNegative) {
if (carrying) {
if (byte !== 0) {
byte = ~(byte - 1) & 255;
carrying = false;
}
} else {
byte = ~byte & 255;
}
}
value += BigInt(byte) * (BigInt(1) << BigInt(i * 8));
}
if (isNegative) {
value = -value;
}
return value;
}
function getUint64NumberFallback(index, values) {
const dataView = values.dataView;
const byteOffset = index * 8;
const left = dataView.getUint32(byteOffset, true);
const right = dataView.getUint32(byteOffset + 4, true);
const value = left + 4294967296 * right;
return value;
}
function getUint64BigIntFallback(index, values) {
const dataView = values.dataView;
const byteOffset = index * 8;
const left = BigInt(dataView.getUint32(byteOffset, true));
const right = BigInt(dataView.getUint32(byteOffset + 4, true));
const value = left + BigInt(4294967296) * right;
return value;
}
function getComponentDatatype(componentType) {
switch (componentType) {
case MetadataComponentType_default.INT8:
return ComponentDatatype_default.BYTE;
case MetadataComponentType_default.UINT8:
return ComponentDatatype_default.UNSIGNED_BYTE;
case MetadataComponentType_default.INT16:
return ComponentDatatype_default.SHORT;
case MetadataComponentType_default.UINT16:
return ComponentDatatype_default.UNSIGNED_SHORT;
case MetadataComponentType_default.INT32:
return ComponentDatatype_default.INT;
case MetadataComponentType_default.UINT32:
return ComponentDatatype_default.UNSIGNED_INT;
case MetadataComponentType_default.FLOAT32:
return ComponentDatatype_default.FLOAT;
case MetadataComponentType_default.FLOAT64:
return ComponentDatatype_default.DOUBLE;
}
}
function requiresUnpackForGet(property) {
if (defined_default(property._unpackedValues)) {
return false;
}
const classProperty = property._classProperty;
const type = classProperty.type;
const valueType = classProperty.valueType;
if (type === MetadataType_default.STRING) {
return true;
}
if (valueType === MetadataComponentType_default.INT64 && !FeatureDetection_default.supportsBigInt64Array()) {
return true;
}
if (valueType === MetadataComponentType_default.UINT64 && !FeatureDetection_default.supportsBigUint64Array()) {
return true;
}
return false;
}
function requiresUnpackForSet(property, index, value) {
if (requiresUnpackForGet(property)) {
return true;
}
const arrayOffsets = property._arrayOffsets;
if (defined_default(arrayOffsets)) {
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);
property._arrayOffsets = void 0;
property._stringOffsets = void 0;
property._values = void 0;
}
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_default.getComponentCount(type);
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_default.valueTransformInPlace(
value,
property._offset,
property._scale,
MetadataComponentType_default.applyValueTransform
);
}
function unapplyValueTransform(property, value) {
const classProperty = property._classProperty;
const isVariableLengthArray = classProperty.isVariableLengthArray;
if (!property._hasValueTransform || isVariableLengthArray) {
return value;
}
return MetadataClassProperty_default.valueTransformInPlace(
value,
property._offset,
property._scale,
MetadataComponentType_default.unapplyValueTransform
);
}
function BufferView(bufferView, componentType, length3) {
const that = this;
let typedArray;
let getFunction;
let setFunction;
if (componentType === MetadataComponentType_default.INT64) {
if (!FeatureDetection_default.supportsBigInt()) {
oneTimeWarning_default(
"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,
length3 * 8
);
getFunction = function(index) {
return getInt64NumberFallback(index, that);
};
} else if (!FeatureDetection_default.supportsBigInt64Array()) {
typedArray = new Uint8Array(
bufferView.buffer,
bufferView.byteOffset,
length3 * 8
);
getFunction = function(index) {
return getInt64BigIntFallback(index, that);
};
} else {
typedArray = new BigInt64Array(
bufferView.buffer,
bufferView.byteOffset,
length3
);
setFunction = function(index, value) {
that.typedArray[index] = BigInt(value);
};
}
} else if (componentType === MetadataComponentType_default.UINT64) {
if (!FeatureDetection_default.supportsBigInt()) {
oneTimeWarning_default(
"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,
length3 * 8
);
getFunction = function(index) {
return getUint64NumberFallback(index, that);
};
} else if (!FeatureDetection_default.supportsBigUint64Array()) {
typedArray = new Uint8Array(
bufferView.buffer,
bufferView.byteOffset,
length3 * 8
);
getFunction = function(index) {
return getUint64BigIntFallback(index, that);
};
} else {
typedArray = new BigUint64Array(
bufferView.buffer,
bufferView.byteOffset,
length3
);
setFunction = function(index, value) {
that.typedArray[index] = BigInt(value);
};
}
} else {
const componentDatatype = getComponentDatatype(componentType);
typedArray = ComponentDatatype_default.createArrayBufferView(
componentDatatype,
bufferView.buffer,
bufferView.byteOffset,
length3
);
setFunction = function(index, value) {
that.typedArray[index] = value;
};
}
if (!defined_default(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;
this._componentType = componentType;
}
var MetadataTableProperty_default = MetadataTableProperty;
// node_modules/@cesium/engine/Source/Scene/MetadataTable.js
function MetadataTable(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const count = options.count;
const metadataClass = options.class;
Check_default.typeOf.number.greaterThan("options.count", count, 0);
Check_default.typeOf.object("options.class", metadataClass);
let byteLength = 0;
const properties = {};
if (defined_default(options.properties)) {
for (const propertyId in options.properties) {
if (options.properties.hasOwnProperty(propertyId)) {
const property = new MetadataTableProperty_default({
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, {
count: {
get: function() {
return this._count;
}
},
class: {
get: function() {
return this._class;
}
},
byteLength: {
get: function() {
return this._byteLength;
}
}
});
MetadataTable.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
MetadataTable.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
MetadataTable.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
MetadataTable.prototype.getProperty = function(index, propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
const property = this._properties[propertyId];
let value;
if (defined_default(property)) {
value = property.get(index);
} else {
value = getDefault(this._class, propertyId);
}
return value;
};
MetadataTable.prototype.setProperty = function(index, propertyId, value) {
Check_default.typeOf.string("propertyId", propertyId);
const property = this._properties[propertyId];
if (defined_default(property)) {
property.set(index, value);
return true;
}
return false;
};
MetadataTable.prototype.getPropertyBySemantic = function(index, semantic) {
Check_default.typeOf.string("semantic", semantic);
let property;
const propertiesBySemantic = this._class.propertiesBySemantic;
if (defined_default(propertiesBySemantic)) {
property = propertiesBySemantic[semantic];
}
if (defined_default(property)) {
return this.getProperty(index, property.id);
}
return void 0;
};
MetadataTable.prototype.setPropertyBySemantic = function(index, semantic, value) {
Check_default.typeOf.string("semantic", semantic);
let property;
const propertiesBySemantic = this._class.propertiesBySemantic;
if (defined_default(propertiesBySemantic)) {
property = propertiesBySemantic[semantic];
}
if (defined_default(property)) {
return this.setProperty(index, property.id, value);
}
return false;
};
MetadataTable.prototype.getPropertyTypedArray = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
const property = this._properties[propertyId];
if (defined_default(property)) {
return property.getTypedArray();
}
return void 0;
};
MetadataTable.prototype.getPropertyTypedArrayBySemantic = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
let property;
const propertiesBySemantic = this._class.propertiesBySemantic;
if (defined_default(propertiesBySemantic)) {
property = propertiesBySemantic[semantic];
}
if (defined_default(property)) {
return this.getPropertyTypedArray(property.id);
}
return void 0;
};
function getDefault(classDefinition, propertyId) {
const classProperties = classDefinition.properties;
if (!defined_default(classProperties)) {
return void 0;
}
const classProperty = classProperties[propertyId];
if (defined_default(classProperty) && defined_default(classProperty.default)) {
let value = classProperty.default;
if (classProperty.isArray) {
value = clone_default(value, true);
}
value = classProperty.normalize(value);
return classProperty.unpackVectorAndMatrixTypes(value);
}
}
var MetadataTable_default = MetadataTable;
// node_modules/@cesium/engine/Source/Scene/ResourceLoader.js
function ResourceLoader() {
}
Object.defineProperties(ResourceLoader.prototype, {
cacheKey: {
get: function() {
DeveloperError_default.throwInstantiationError();
}
}
});
ResourceLoader.prototype.load = function() {
DeveloperError_default.throwInstantiationError();
};
ResourceLoader.prototype.unload = function() {
};
ResourceLoader.prototype.process = function(frameState) {
return false;
};
ResourceLoader.prototype.getError = function(errorMessage, error) {
Check_default.typeOf.string("errorMessage", errorMessage);
if (defined_default(error) && defined_default(error.message)) {
errorMessage += `
${error.message}`;
}
const runtimeError = new RuntimeError_default(errorMessage);
if (defined_default(error)) {
runtimeError.stack = `Original stack:
${error.stack}
Handler stack:
${runtimeError.stack}`;
}
return runtimeError;
};
ResourceLoader.prototype.isDestroyed = function() {
return false;
};
ResourceLoader.prototype.destroy = function() {
this.unload();
return destroyObject_default(this);
};
var ResourceLoader_default = ResourceLoader;
// node_modules/@cesium/engine/Source/Scene/ResourceLoaderState.js
var ResourceLoaderState = {
UNLOADED: 0,
LOADING: 1,
LOADED: 2,
PROCESSING: 3,
READY: 4,
FAILED: 5
};
var ResourceLoaderState_default = Object.freeze(ResourceLoaderState);
// node_modules/@cesium/engine/Source/Scene/BufferLoader.js
function BufferLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const typedArray = options.typedArray;
const resource = options.resource;
const cacheKey = options.cacheKey;
if (defined_default(typedArray) === defined_default(resource)) {
throw new DeveloperError_default(
"One of options.typedArray and options.resource must be defined."
);
}
this._typedArray = typedArray;
this._resource = resource;
this._cacheKey = cacheKey;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
BufferLoader.prototype = Object.create(ResourceLoader_default.prototype);
BufferLoader.prototype.constructor = BufferLoader;
}
Object.defineProperties(BufferLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
typedArray: {
get: function() {
return this._typedArray;
}
}
});
BufferLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (defined_default(this._typedArray)) {
this._promise = Promise.resolve(this);
return this._promise;
}
this._promise = loadExternalBuffer(this);
return this._promise;
};
async function loadExternalBuffer(bufferLoader) {
const resource = bufferLoader._resource;
bufferLoader._state = ResourceLoaderState_default.LOADING;
try {
const arrayBuffer = await BufferLoader._fetchArrayBuffer(resource);
if (bufferLoader.isDestroyed()) {
return;
}
bufferLoader._typedArray = new Uint8Array(arrayBuffer);
bufferLoader._state = ResourceLoaderState_default.READY;
return bufferLoader;
} catch (error) {
if (bufferLoader.isDestroyed()) {
return;
}
bufferLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = `Failed to load external buffer: ${resource.url}`;
throw bufferLoader.getError(errorMessage, error);
}
}
BufferLoader._fetchArrayBuffer = function(resource) {
return resource.fetchArrayBuffer();
};
BufferLoader.prototype.unload = function() {
this._typedArray = void 0;
};
var BufferLoader_default = BufferLoader;
// node_modules/meshoptimizer/meshopt_encoder.module.js
var MeshoptEncoder = function() {
"use strict";
var wasm = "B9h79tEBBBENQ9gEUEU9gEUB9gBB9gVUUUUUEU9gDUUEU9gLUUUUEU9gVUUUUUB9gLUUUUB9gIUUUEU9gD99UE99I8ayDILEVLEVLOOOOORRVBWWBEdddLVE9wEIIVIEBEOWEUEC+g/KEKR/QIhO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BB8a9tw79o9v9wT9fw9u9j9v9kw9WwvTw949C919m9mwvBE8f9tw79o9v9wT9fw9u9j9v9kw9WwvTw949C919m9mwv9C9v919u9kBDe9tw79o9v9wT9fw9u9j9v9kw9WwvTw949Wwv79p9v9uBIy9tw79o9v9wT9fw9u9j9v9kw69u9kw949C919m9mwvBL8e9tw79o9v9wT9fw9u9j9v9kw69u9kw949C919m9mwv9C9v919u9kBV8a9tw79o9v9wT9fw9u9j9v9kw69u9kw949Wwv79p9v9uBOe9tw79o9v9wT9fw9u9j9v9kw69u9kw949Twg91w9u9jwBRA9tw79o9v9wT9fw9u9j9v9kw69u9kw949Twg91w9u9jw9C9v919u9kBWl9tw79o9v9wT9fw9u9j9v9kws9p2Twv9P9jTBdk9tw79o9v9wT9fw9u9j9v9kws9p2Twv9R919hTBQl9tw79o9v9wT9fw9u9j9v9kws9p2Twvt949wBKe9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94j9h9j9owBpA9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94j9h9j9ow9TTv9p9wBSA9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94swT9j9o9Sw9t9h9wBZL79iv9rBhdWEBCEKDxcQ+1tyDBK/hKEyU8jJJJJBCJO9rGV8kJJJJBCBHODNALCEFAE0MBABCBrB+Q+KJJBC+gEv86BBAVCJDFCBCJDZ+TJJJB8aDNAItMBAVCJDFADALZmJJJB8aKABAEFHRABCEFHWAVALFCBCBCJDAL9rALCfE0eZ+TJJJB8aAVAVCJDFALZmJJJBHdCJ/ABAL9uHEDNDNALtMBAEC/wfBgGECJDAECJD6eHQCBHKINAKAI9PMEAdCJLFCBCJDZ+TJJJB8aAQAIAK9rAKAQFAI6eGXCSFGECL4CIFCD4HMADAKAL2FHpDNDNDNDNDNAEC9wgGStMBCBHZCEHhApHoAWHaXEKDNAXtMBCBHaCEHhApHcINAdAaFrBBHxAcHECBHOINAdCJLFAOFAErBBGqAx9rGxCETAxCkTCk91CR4786BBAEALFHEAqHxAOCEFGOAX9HMBKARAW9rAM6MIAWCBAMZ+TJJJBGEtMIAEAMFHWAcCEFHcAaCEFGaAL6HhAaAL9HMBXVKKARAW9rAM6MOAWCBAMZ+TJJJB8aCEHEINAWGxAMFHWALAEGOsMLDNARAW9rAM6MBAOCEFHEAWCBAMZ+TJJJB8aAxMEKKCBHWAOAL6MOXIKINDNAXtMBAdAZFrBBHxCBHEAoHOINAdCJLFAEFAOrBBGqAx9rGxCETAxCkTCk91CR4786BBAOALFHOAqHxAECEFGEAX9HMBKKARAa9rAM6MEARAaCBAMZ+TJJJBGlAMFGW9rCk6MDCBHkAdCJLFHcINAdCJLFAkFHyCWH8aCZHaCEHqINDNDNAqCE9HMBCUHOAyrBBMECBHODNINAOGECSsMEAECEFHOAcAEFCEFrBBtMBKKCUCBAECS6eHOXEKAqCETC/+fffEgHOCUAqTCU7CfEgHxCBHEINAOAxAcAEFrBB9NFHOAECEFGECZ9HMBKKAOAaAOAa6GEeHaAqA8aAEeH8aAqCETGqCW6MBKDNDNDNDNA8aCUFpDIEBKAlAkCO4FGEAErBBCDCIA8aCLseAkCI4COgTv86BBA8aCW9HMEAWAy8pBB83BBAWCWFAyCWF8pBB83BBAWCZFHWXDKAlAkCO4FGEAErBBCEAkCI4COgTv86BBKDNCWA8a9tGeMBINAWCB86BBAWCEFHWXBKKCUA8aTCU7HqCBH3AcH5INA5HEAeHxCBHOINAErBBGaAqAaAqCfEgGy6eAOCfEgA8aTvHOAECEFHEAxCUFGxMBKAWAO86BBA5AeFH5AWCEFHWA3AeFG3CZ6MBKCBHEINDNAcAEFrBBGOAy6MBAWAO86BBAWCEFHWKAECEFGECZ9HMBKKDNAkCZFGkAS9PMBAcCZFHcARAW9rCl0MEKKAkAS6MEAWtMEAoCEFHoAZCEFGZAL6HhAWHaAZALsMIXBKKCBHWAhCEgtMEXLKCBHWAhCEgMIKAdApAXCUFAL2FALZmJJJB8aAXAKFHKAWMBKCBHOXDKCBHOARAW9rCAALALCA6e6MEDNALC8f0MBAWCBCAAL9rGEZ+TJJJBAEFHWKAWAdCJDFALZmJJJBALFAB9rHOXEKCBHOKAVCJOF8kJJJJBAOK9HEEUAECAAECA0eABCJ/ABAE9uC/wfBgGDCJDADCJD6eGDFCUFAD9uAE2ADCL4CIFCD4ADv2FCEFKMBCBABbD+Q+KJJBK/YSE3U8jJJJJBC/AE9rGL8kJJJJBCBHVDNAICI9uGOChFAE0MBABCBYDn+KJJBGVC/gEv86BBALC/ABFCfECJEZ+TJJJB8aALCuFGR9CU83IBALC8wFGW9CU83IBALCYFGd9CU83IBALCAFGQ9CU83IBALCkFGK9CU83IBALCZFGX9CU83IBAL9CU83IWAL9CU83IBABAEFC9wFHMABCEFGpAOFHEDNAItMBCMCSAVCB9KGSeHZAVCE9IHhCBHoCBHaCBHcCBHxCBHqINDNAEAM9NMBCBHVXIKAqCUFHVADAcCDTFGOYDBHlAOCWFYDBHkAOCLFYDBHyCBH8aDNDNINALC/ABFAVCSgCITFGOYDLHeDNDNDNAOYDBGOAl9HMBAeAysMEKDNAOAy9HMBAeAk9HMBA8aCEFH8aXEKAOAk9HMEAeAl9HMEA8aCDFH8aKA8aC870MDAxCUFHVADA8aCIgCX2GOC+Y1JJBFYDBAcFCDTFYDBHeADAOCn1JJBFYDBAcFCDTFYDBHkADAOC+Q1JJBFYDBAcFCDTFYDBHlCBHODNINDNALAVCSgCDTFYDBAe9HMBAOHyXDKCUHyAVCUFHVAOCEFGOCZ9HMBKKAyCB9KAyAZ9IgGVCU7AeAosGOgH3DNDNDNDNDNAyCBCSAOeAVeGVCS9HMBAhMBAeAeAaAeCEFAasGVeGaCEFsMECMCSAVeHVKApAVA8aCDTC/wEgv86BBAVCS9HMEAeAa9rGVCETAVC8f917HVINAEAVCfB0CRTAVCfBgv86BBAECEFHEAVCJE6HOAVCR4HVAOtMBKAeHaXDKCpHVApA8aCDTCpv86BBAeHaKAVtMBAVAZ9IMEKALAxCDTFAebDBAxCEFCSgHxKAoA3FHoALC/ABFAqCITFGVAkbDLAVAebDBALC/ABFAqCEFCSgGVCITFGOAebDLAOAlbDBAVCEFHOXIKAVCUFHVA8aCLFG8aC/AB9HMBKKDNADCEAkAosCETAyAoseCX2GVC+Q1JJBFYDBAcFCDTFYDBGltADAVCn1JJBFYDBAcFCDTFYDBG8aCEsgADAVC+Y1JJBFYDBAcFCDTFYDBGyCDsgAoCB9HgASgG5CE9HMBAR9CU83IBAW9CU83IBAd9CU83IBAQ9CU83IBAK9CU83IBAX9CU83IBAL9CU83IWAL9CU83IBCBHoKCBHeAxCUFGVHODNINDNALAOCSgCDTFYDBA8a9HMBAeHkXDKCUHkAOCUFHOAeCEFGeCZ9HMBKKCBHODNINDNALAVCSgCDTFYDBAy9HMBAOHeXDKCUHeAVCUFHVAOCEFGOCZ9HMBKKAoAlAosG8eFH3DNDNAkCM0MBAkCEFHkXEKCBCSA8aA3sGVeHkA3AVFH3KDNDNAeCM0MBAeCEFHeXEKCBCSAyA3sGVeHeA3AVFH3KC9+CUA8eeH8fAeAkCLTvHOCBHVDNDNDNINAVCJ1JJBFrBBAOCfEgsMEAVCEFGVCZ9HMBXDKKAlAo9HAVCM0vA5vMBApAVC/wEv86BBXEKApA8f86BBAEAO86BBAECEFHEKDNA8eMBAlAa9rGVCETAVC8f917HVINAEAVCfB0GOCRTAVCfBgv86BBAVCR4HVAECEFHEAOMBKAlHaKDNAkCS9HMBA8aAa9rGVCETAVC8f917HVINAEAVCfB0GOCRTAVCfBgv86BBAVCR4HVAECEFHEAOMBKA8aHaKDNAeCS9HMBAyAa9rGVCETAVC8f917HVINAEAVCfB0GOCRTAVCfBgv86BBAVCR4HVAECEFHEAOMBKAyHaKALAxCDTFAlbDBAxCEFCSgHVDNDNAkpZBEEEEEEEEEEEEEEBEKALAVCDTFA8abDBAxCDFCSgHVKDNDNAepZBEEEEEEEEEEEEEEBEKALAVCDTFAybDBAVCEFCSgHVKALC/ABFAqCITFGOAlbDLAOA8abDBALC/ABFAqCEFCSgCITFGOA8abDLAOAybDBALC/ABFAqCDFCSgCITFGOAybDLAOAlbDBAqCIFHOAVHxA3HoKApCEFHpAOCSgHqAcCIFGcAI6MBKKCBHVAEAM0MBCBHVINAEAVFAVCJ1JJBFrBB86BBAVCEFGVCZ9HMBKAEAB9rAVFHVKALC/AEF8kJJJJBAVKzEEUCBHDDNINADCEFGDC8f0MECEADTAE6MBKKADCRFCfEgCR9uCI2CDFABCI9u2ChFKMBCBABbDn+KJJBK+cDEWU8jJJJJBCZ9rHLCBHVDNAICVFAE0MBCBHOABCBrBn+KJJBC/QEv86BBAL9CB83IWABCEFHRABAEFC98FHWDNAItMBCBHdINDNARAW6MBCBSKADAdCDTFYDBGQALCWFAOAQALCWFAOCDTFYDB9rGEAEC8f91GEFAE7C507GOCDTFGKYDB9rGEC8e91C9+gAECDT7AOvHEINARAECfB0GVCRTAECfBgv86BBAECR4HEARCEFHRAVMBKAKAQbDBAdCEFGdAI9HMBKKCBHVARAW0MBARCBbBBARAB9rCLFHVKAVKbEEUCBHDDNINADCEFGDC8f0MECEADTAE6MBKKADCWFCfEgCR9uAB2CVFK+DVLI99DUI99LUDNAEtMBCUADCETCUFTCU7+yHVDNDNCUAICUFTCU7+yGOjBBBzmGR+LjBBB9P9dtMBAR+oHWXEKCJJJJ94HWKCBHICBHdINALCLFiDBGRjBBBBjBBJzALiDBGQ+LAR+LmALCWFiDBGK+LmGR+VARjBBBB9beGRnHXAQARnHRALCXFiDBHQDNDNAKjBBBB9gtMBAXHKXEKjBBJzAR+L+TGKAK+MAXjBBBB9geHKjBBJzAX+L+TGXAX+MARjBBBB9geHRKDNDNAQjBBJ+/AQjBBJ+/9geGXjBBJzAXjBBJz9feAVnjBBBzjBBB+/AQjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHMXEKCJJJJ94HMKDNDNAKjBBJ+/AKjBBJ+/9geGQjBBJzAQjBBJz9feAOnjBBBzjBBB+/AKjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHpXEKCJJJJ94HpKDNDNARjBBJ+/ARjBBJ+/9geGQjBBJzAQjBBJz9feAOnjBBBzjBBB+/ARjBBBB9gemGR+LjBBB9P9dtMBAR+oHSXEKCJJJJ94HSKDNDNADCL9HMBABAdFGZAS86BBAZCIFAM86BBAZCDFAW86BBAZCEFAp86BBXEKABAIFGZAS87EBAZCOFAM87EBAZCLFAW87EBAZCDFAp87EBKALCZFHLAICWFHIAdCLFHdAECUFGEMBKKK/KLLD99EUD99EUDNAEtMBDNDNCUAICUFTCU7+yGVjBBBzmGO+LjBBB9P9dtMBAO+oHIXEKCJJJJ94HIKAIC/8fIgHRINABCOFCICDALCLFiDB+LALiDB+L9eGIALCWFiDB+LALAICDTFiDB+L9eeGIALCXFiDB+LALAICDTFiDB+L9eeGIARv87EBDNDNALAICEFCIgCDTFiDBj/zL+1znjBBJ+/jBBJzALAICDTFiDBjBBBB9deGOnGWjBBJ+/AWjBBJ+/9geGdjBBJzAdjBBJz9feAVnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHQXEKCJJJJ94HQKABAQ87EBDNDNAOALAICDFCIgCDTFiDBj/zL+1znnGWjBBJ+/AWjBBJ+/9geGdjBBJzAdjBBJz9feAVnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHQXEKCJJJJ94HQKABCDFAQ87EBDNDNAOALAICUFCIgCDTFiDBj/zL+1znnGOjBBJ+/AOjBBJ+/9geGWjBBJzAWjBBJz9feAVnjBBBzjBBB+/AOjBBBB9gemGO+LjBBB9P9dtMBAO+oHIXEKCJJJJ94HIKABCLFAI87EBABCWFHBALCZFHLAECUFGEMBKKK+7DDWUE998jJJJJBCZ9rGV8kJJJJBDNAEtMBADCL6MBCEAI9rHOADCD4GDCEADCE0eHRADCDTHWCBHdINC+cUHDALHIARHQINAIiDBAVCXFZ+XJJJB8aAVYDXGKADADAK9IeHDAICLFHIAQCUFGQMBKAOADFGICkTHKCBHDCBAI9rHXARHIINDNDNALADFiDBGMAXZ+WJJJBjBBBzjBBB+/AMjBBBB9gemGM+LjBBB9P9dtMBAM+oHQXEKCJJJJ94HQKABADFAQCfffRgAKvbDBADCLFHDAICUFGIMBKABAWFHBALAWFHLAdCEFGdAE9HMBKKAVCZF8kJJJJBK/tKDcUI998jJJJJBC+QD9rGV8kJJJJBAVC+oEFCBC/kBZ+TJJJB8aCBHODNADtMBCBHOAItMBDNABAE9HMBAVCUADCDTGOADCffffI0eCBYD1+KJJBhJJJJBBGEbD+oEAVCEbD1DAEABAOZmJJJB8aKAVC+YEFCWFCBbDBAV9CB83I+YEAVC+YEFAEADAIAVC+oEFZ+NJJJBCUAICDTGRAICffffI0eGWCBYD1+KJJBhJJJJBBHOAVC+oEFAVYD1DGdCDTFAObDBAVAdCEFGQbD1DAOAVYD+YEGKARZmJJJBHXAVC+oEFAQCDTFADCI9uGMCBYD1+KJJBhJJJJBBGObDBAVAdCDFGRbD1DAOCBAMZ+TJJJBHpAVC+oEFARCDTFAWCBYD1+KJJBhJJJJBBGSbDBAVAdCIFGQbD1DAXHOASHRINARALiDBALAOYDBGWCWAWCW6eCDTFC/EBFiDBmuDBAOCLFHOARCLFHRAICUFGIMBKAVC+oEFAQCDTFCUAMCDTADCffff970eCBYD1+KJJBhJJJJBBGQbDBAVAdCLFbD1DDNADCI6MBAMCEAMCE0eHIAEHOAQHRINARASAOYDBCDTFiDBASAOCLFYDBCDTFiDBmASAOCWFYDBCDTFiDBmuDBAOCXFHOARCLFHRAICUFGIMBKKAVC/MBFHZAVYD+cEHhAVYD+gEHoAVHOCBHWCBHRCBHaCEHcINAOHxCIHqAEARCI2GlCDTFGOCWFYDBHkAOYDBHDABAaCX2FGICLFAOCLFYDBGdbDBAIADbDBAICWFAkbDBApARFCE86BBAZAkbDWAZAdbDLAZADbDBAQARCDTFCBbDBDNAWtMBCIHqAxHIINDNAIYDBGOADsMBAOAdsMBAOAksMBAZAqCDTFAObDBAqCEFHqKAICLFHIAWCUFGWMBKKAaCEFHaAXADCDTFGOAOYDBCUFbDBAXAdCDTFGOAOYDBCUFbDBAXAkCDTFGOAOYDBCUFbDBCBHWINAoAhAEAWAlFCDTFYDBCDTGIFYDBCDTFGkHOAKAIFGdYDBGDHIDNADtMBDNINAOYDBARsMEAOCLFHOAICUFGItMDXBKKAOADCDTAkFC98FYDBbDBAdAdYDBCUFbDBKAWCEFGWCI9HMBKDNDNDNAqtMBCUHRjBBBBHyCBHOINASAZAOCDTFYDBCDTGIFGWiDBH8aAWALCBAOCEFGdAOCS0eCDTFiDBALAXAIFYDBGOCWAOCW6eCDTFC/EBFiDBmGeuDBDNAKAIFYDBGWtMBAeA8a+THeAoAhAIFYDBCDTFHOAWCDTHIINAQAOYDBGWCDTFGDAeADiDBmG8auDBA8aAyAyA8a9dGDeHyAWARADeHRAOCLFHOAIC98FGIMBKKAdHOAdAq9HMBKARCU9HMEKAcAM9PMEINDNApAcFrBBMBAcHRXDKAMAcCEFGc9HMBXDKKAqCZAqCZ6eHWAZHOAxHZARCU9HMEKKAVYD1DHOKAOCDTAVC+oEFFC98FHRDNINAOtMEARYDBCBYD+E+KJJBh+BJJJBBARC98FHRAOCUFHOXBKKAVC+QDF8kJJJJBK/uLEVUCUAICDTGVAICffffI0eGOCBYD1+KJJBhJJJJBBHRALALYD9gGWCDTFARbDBALAWCEFbD9gABARbDBAOCBYD1+KJJBhJJJJBBHRALALYD9gGOCDTFARbDBALAOCEFbD9gABARbDLCUADCDTADCffffI0eCBYD1+KJJBhJJJJBBHRALALYD9gGOCDTFARbDBALAOCEFbD9gABARbDWABYDBCBAVZ+TJJJB8aADCI9uHWDNADtMBABYDBHOAEHLADHRINAOALYDBCDTFGVAVYDBCEFbDBALCLFHLARCUFGRMBKKDNAItMBABYDBHLABYDLHRCBHVAIHOINARAVbDBARCLFHRALYDBAVFHVALCLFHLAOCUFGOMBKKDNADCI6MBAWCEAWCE0eHdABYDLHRABYDWHVCBHLINAECWFYDBHOAECLFYDBHDARAEYDBCDTFGWAWYDBGWCEFbDBAVAWCDTFALbDBARADCDTFGDADYDBGDCEFbDBAVADCDTFALbDBARAOCDTFGOAOYDBGOCEFbDBAVAOCDTFALbDBAECXFHEAdALCEFGL9HMBKKDNAItMBABYDLHEABYDBHLINAEAEYDBALYDB9rbDBALCLFHLAECLFHEAICUFGIMBKKKqBABAEADAIC+01JJBZ+MJJJBKqBABAEADAIC+c+JJJBZ+MJJJBK9dEEUABCfEAICDTZ+TJJJBHLCBHIDNADtMBINDNALAEYDBCDTFGBYDBCU9HMBABAIbDBAICEFHIKAECLFHEADCUFGDMBKKAIK9TEIUCBCBYD+M+KJJBGEABCIFC98gFGBbD+M+KJJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK/lEEEUDNDNAEABvCIgtMBABHIXEKDNDNADCZ9PMBABHIXEKABHIINAIAEYDBbDBAICLFAECLFYDBbDBAICWFAECWFYDBbDBAICXFAECXFYDBbDBAICZFHIAECZFHEADC9wFGDCS0MBKKADCL6MBINAIAEYDBbDBAECLFHEAICLFHIADC98FGDCI0MBKKDNADtMBINAIAErBB86BBAICEFHIAECEFHEADCUFGDMBKKABK/AEEDUDNDNABCIgtMBABHIXEKAECfEgC+B+C+EW2HLDNDNADCZ9PMBABHIXEKABHIINAIALbDBAICXFALbDBAICWFALbDBAICLFALbDBAICZFHIADC9wFGDCS0MBKKADCL6MBINAIALbDBAICLFHIADC98FGDCI0MBKKDNADtMBINAIAE86BBAICEFHIADCUFGDMBKKABK9TEIUCBCBYD+M+KJJBGEABCIFC98gFGBbD+M+KJJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK9+EIUzBHEDNDNCBYD+M+KJJBGDAECZTGI9NMBCUHEADAI9rCffIFCZ4NBCUsMEKADHEKCBABAE9rCIFC98gCBYD+M+KJJBFGDbD+M+KJJBDNADzBCZTGE9NMBADAE9rCffIFCZ4NB8aKKXBABAEZ+YJJJBK+BEEIUDNAB+8GDCl4GICfEgGLCfEsMBDNALMBDNABjBBBB9cMBAECBbDBABSKABjBBJ9fnAEZ+XJJJBHBAEAEYDBCNFbDBABSKAEAICfEgC+CUFbDBADCfff+D94gCJJJ/4Iv++HBKABK+gEBDNDNAECJE9IMBABjBBBUnHBDNAECfE9PMBAEC+BUFHEXDKABjBBBUnHBAECPDAECPD6eC+C9+FHEXEKAEC+BU9KMBABjBBJXnHBDNAEC+b9+9NMBAEC/mBFHEXEKABjBBJXnHBAEC+299AEC+2990eC/MEFHEKABAEClTCJJJ/8IF++nKK+eDDBCJWK+EDB4+H9W9n94+p+Gw+J9o+YE9pBBBBBBEBBBDBBBEBBBDBBBBBBBDBBBBBBBEBBBBBBB+L29Hz/69+9Kz/n/76z/RG97z/Z/O9Xz8j/b85z/+/U9Yz/B/K9hz+2/z9dz9E+L9Mz59a8kz+R/t3z+a+Zyz79ohz/J4++8++y+d9v8+BBBB9S+49+z8r+Hbz9m9m/m8+l/Z/O8+/8+pg89Q/X+j878r+Hq8++m+b/E87BBBBBBJzBBJzBBJz+e/v/n8++y+dSz9I/h/68+XD/r8+/H0838+/w+nOzBBBB+wv9o8+UF888+9I/h/68+9C9g/l89/N/M9M89/d8kO8+BBBBF+8Tz9M836zs+2azl/Zpzz818ez9E+LXz/u98f8+819e/68+BC+EQKXEBBBDBBBAwBB";
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") {
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 bytes(view) {
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
}
function reorder(indices2, vertices, optf) {
var sbrk = instance.exports.sbrk;
var ip = sbrk(indices2.length * 4);
var rp = sbrk(vertices * 4);
var heap = new Uint8Array(instance.exports.memory.buffer);
var indices8 = bytes(indices2);
heap.set(indices8, ip);
if (optf) {
optf(ip, ip, indices2.length, vertices);
}
var unique = instance.exports.meshopt_optimizeVertexFetchRemap(rp, ip, indices2.length, vertices);
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 + indices2.length * 4));
sbrk(ip - sbrk(0));
for (var i = 0; i < indices2.length; ++i)
indices2[i] = remap[indices2[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(bytes(source), 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);
}
}
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(bytes(source), 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(indices2, triangles, optsize) {
var optf = triangles ? optsize ? instance.exports.meshopt_optimizeVertexCacheStrip : instance.exports.meshopt_optimizeVertexCache : void 0;
return reorder(indices2, maxindex(indices2) + 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 indices2 = index32(source, size);
var bound = instance.exports.meshopt_encodeIndexBufferBound(count, maxindex(indices2) + 1);
return encode(instance.exports.meshopt_encodeIndexBuffer, bound, indices2, count, 4);
},
encodeIndexSequence: function(source, count, size) {
assert(size == 2 || size == 4);
var indices2 = index32(source, size);
var bound = instance.exports.meshopt_encodeIndexSequenceBound(count, maxindex(indices2) + 1);
return encode(instance.exports.meshopt_encodeIndexSequence, bound, indices2, count, 4);
},
encodeGltfBuffer: function(source, count, size, mode2) {
var table2 = {
ATTRIBUTES: this.encodeVertexBuffer,
TRIANGLES: this.encodeIndexBuffer,
INDICES: this.encodeIndexSequence
};
assert(table2[mode2]);
return table2[mode2](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, 16);
},
encodeFilterQuat: function(source, count, stride, bits) {
assert(stride == 8);
assert(bits >= 4 && bits <= 16);
return filter(instance.exports.meshopt_encodeFilterQuat, source, count, stride, bits, 16);
},
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);
}
};
}();
// node_modules/meshoptimizer/meshopt_decoder.module.js
var MeshoptDecoder = function() {
"use strict";
var wasm_base = "B9h79tEBBBE8fV9gBB9gVUUUUUEU9gIUUUB9gEUEU9gIUUUEUIKQBEEEDDDILLVIEBEOWEUEC+Q/IEKR/LEdO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BB8a9tw79o9v9wT9f9kw9j9v9kw9WwvTw949C919m9mwvBEy9tw79o9v9wT9f9kw9j9v9kw69u9kw949C919m9mwvBDe9tw79o9v9wT9f9kw9j9v9kw69u9kw949Twg91w9u9jwBIl9tw79o9v9wT9f9kw9j9v9kws9p2Twv9P9jTBLk9tw79o9v9wT9f9kw9j9v9kws9p2Twv9R919hTBVl9tw79o9v9wT9f9kw9j9v9kws9p2Twvt949wBOL79iv9rBRQ+p8yQDBK/3SEZU8jJJJJBCJ/EB9rGV8kJJJJBC9+HODNADCEFAL0MBCUHOAIrBBC+gE9HMBAVAIALFGRAD9rADZ1JJJBHWCJ/ABAD9uHOAICEFHLDNADtMBAOC/wfBgGOCJDAOCJD6eHdCBHQINAQAE9PMEAdAEAQ9rAQAdFAE6eGKCSFGOCL4CIFCD4HXDNDNDNDNAOC9wgGMtMBCBHpCEHSAWCJDFHZALHhINARAh9rAX6MIDNARAhAXFGL9rCk6MBCZHOINAWCJ/CBFAOGIFGOC9wFHoDNDNDNDNDNAhAIC9wFGaCO4FrBBAaCI4COg4CIgpLBEDIBKAo9CB83IBAoCWF9CB83IBXIKAoALrBLALrBBGaCO4GcAcCIsGce86BBAOCgFALCLFAcFGorBBAaCL4CIgGcAcCIsGce86BBAOCvFAoAcFGorBBAaCD4CIgGcAcCIsGce86BBAOC7FAoAcFGorBBAaCIgGaAaCIsGae86BBAOCTFAoAaFGarBBALrBEGoCO4GcAcCIsGce86BBAOC91FAaAcFGarBBAoCL4CIgGcAcCIsGce86BBAOC4FAaAcFGarBBAoCD4CIgGcAcCIsGce86BBAOC93FAaAcFGarBBAoCIgGoAoCIsGoe86BBAOC94FAaAoFGarBBALrBDGoCO4GcAcCIsGce86BBAOC95FAaAcFGarBBAoCL4CIgGcAcCIsGce86BBAOC96FAaAcFGarBBAoCD4CIgGcAcCIsGce86BBAOC97FAaAcFGarBBAoCIgGoAoCIsGoe86BBAOC98FAaAoFGorBBALrBIGLCO4GaAaCIsGae86BBAOC99FAoAaFGorBBALCL4CIgGaAaCIsGae86BBAOC9+FAoAaFGorBBALCD4CIgGaAaCIsGae86BBAOCUFAoAaFGOrBBALCIgGLALCIsGLe86BBAOALFHLXDKAoALrBWALrBBGaCL4GcAcCSsGce86BBAOCgFALCWFAcFGorBBAaCSgGaAaCSsGae86BBAOCvFAoAaFGorBBALrBEGaCL4GcAcCSsGce86BBAOC7FAoAcFGorBBAaCSgGaAaCSsGae86BBAOCTFAoAaFGorBBALrBDGaCL4GcAcCSsGce86BBAOC91FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC4FAoAaFGorBBALrBIGaCL4GcAcCSsGce86BBAOC93FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC94FAoAaFGorBBALrBLGaCL4GcAcCSsGce86BBAOC95FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC96FAoAaFGorBBALrBVGaCL4GcAcCSsGce86BBAOC97FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC98FAoAaFGorBBALrBOGaCL4GcAcCSsGce86BBAOC99FAoAcFGorBBAaCSgGaAaCSsGae86BBAOC9+FAoAaFGorBBALrBRGLCL4GaAaCSsGae86BBAOCUFAoAaFGOrBBALCSgGLALCSsGLe86BBAOALFHLXEKAoAL8pBB83BBAoCWFALCWF8pBB83BBALCZFHLKDNAIAM9PMBAICZFHOARAL9rCl0MEKKAIAM6MIALtMIDNAKtMBAWApFrBBHoCBHOAZHIINAIAWCJ/CBFAOFrBBGaCE4CBAaCEg9r7AoFGo86BBAIADFHIAOCEFGOAK9HMBKKAZCEFHZApCEFGpAD6HSALHhApAD9HMEXVKKCBHLASCEgMDXIKALAXAD2FHcDNAKtMBCBHhCEHSAWCJDFHMINARAL9rAX6MIALtMDALAXFHLAWAhFrBBHoCBHOAMHIINAIAWCJ/CBFAOFrBBGaCE4CBAaCEg9r7AoFGo86BBAIADFHIAOCEFGOAK9HMBKAMCEFHMAhCEFGhAD6HSAhAD9HMBKAcHLXIKCBHOCEHSINARAL9rAX6MDALtMEALAXFHLAOCEFGOAD6HSADAO9HMBKAcHLXDKCBHLASCEgtMEKC9+HOXIKABAQAD2FAWCJDFAKAD2Z1JJJB8aAWAWCJDFAKCUFAD2FADZ1JJJB8aAKAQFHQALMBKC9+HOXEKCBC99ARAL9rADCAADCA0eseHOKAVCJ/EBF8kJJJJBAOK/YZEhU8jJJJJBC/AE9rGV8kJJJJBC9+HODNAECI9uGRChFAL0MBCUHOAIrBBGWC/wEgC/gE9HMBAWCSgGdCE0MBAVC/ABFCfECJEZ+JJJJB8aAVCuF9CU83IBAVC8wF9CU83IBAVCYF9CU83IBAVCAF9CU83IBAVCkF9CU83IBAVCZF9CU83IBAV9CU83IWAV9CU83IBAIALFC9wFHQAICEFGWARFHODNAEtMBCMCSAdCEseHKCBHXCBHMCBHdCBHICBHLINDNAOAQ9NMBC9+HOXIKDNDNAWrBBGRC/vE0MBAVC/ABFALARCL4CU7FCSgCITFGpYDLHSApYDBHZDNARCSgGpAK9PMBAVAIARCU7FCSgCDTFYDBAXApeHRAptHpDNDNADCD9HMBABAdCETFGhAZ87EBAhCDFAS87EBAhCLFAR87EBXEKABAdCDTFGhAZbDBAhCLFASbDBAhCWFARbDBKAXApFHXAVC/ABFALCITFGhARbDBAhASbDLAVAICDTFARbDBAVC/ABFALCEFCSgGLCITFGhAZbDBAhARbDLAIApFHIALCEFHLXDKDNDNApCSsMBAMApFApC987FCEFHMXEKAOCEFHRAO8sBBGpCfEgHhDNDNApCU9MMBARHOXEKAOCVFHOAhCfBgHhCRHpDNINAR8sBBGoCfBgApTAhvHhAoCU9KMEARCEFHRApCRFGpC8j9HMBXDKKARCEFHOKAhCE4CBAhCEg9r7AMFHMKDNDNADCD9HMBABAdCETFGRAZ87EBARCDFAS87EBARCLFAM87EBXEKABAdCDTFGRAZbDBARCLFASbDBARCWFAMbDBKAVC/ABFALCITFGRAMbDBARASbDLAVAICDTFAMbDBAVC/ABFALCEFCSgGLCITFGRAZbDBARAMbDLAICEFHIALCEFHLXEKDNARCPE0MBAXCEFGoAVAIAQARCSgFrBBGpCL49rCSgCDTFYDBApCZ6GheHRAVAIAp9rCSgCDTFYDBAoAhFGSApCSgGoeHpAotHoDNDNADCD9HMBABAdCETFGZAX87EBAZCDFAR87EBAZCLFAp87EBXEKABAdCDTFGZAXbDBAZCLFARbDBAZCWFApbDBKAVAICDTFAXbDBAVC/ABFALCITFGZARbDBAZAXbDLAVAICEFGICSgCDTFARbDBAVC/ABFALCEFCSgCITFGZApbDBAZARbDLAVAIAhFCSgGICDTFApbDBAVC/ABFALCDFCSgGLCITFGRAXbDBARApbDLALCEFHLAIAoFHIASAoFHXXEKAXCBAOrBBGZeGaARC/+EsGRFHSAZCSgHcAZCL4HxDNDNAZCS0MBASCEFHoXEKASHoAVAIAx9rCSgCDTFYDBHSKDNDNAcMBAoCEFHXXEKAoHXAVAIAZ9rCSgCDTFYDBHoKDNDNARtMBAOCEFHRXEKAOCDFHRAO8sBEGhCfEgHpDNAhCU9KMBAOCOFHaApCfBgHpCRHODNINAR8sBBGhCfBgAOTApvHpAhCU9KMEARCEFHRAOCRFGOC8j9HMBKAaHRXEKARCEFHRKApCE4CBApCEg9r7AMFGMHaKDNDNAxCSsMBARHpXEKARCEFHpAR8sBBGOCfEgHhDNAOCU9KMBARCVFHSAhCfBgHhCRHODNINAp8sBBGRCfBgAOTAhvHhARCU9KMEApCEFHpAOCRFGOC8j9HMBKASHpXEKApCEFHpKAhCE4CBAhCEg9r7AMFGMHSKDNDNAcCSsMBApHOXEKApCEFHOAp8sBBGRCfEgHhDNARCU9KMBApCVFHoAhCfBgHhCRHRDNINAO8sBBGpCfBgARTAhvHhApCU9KMEAOCEFHOARCRFGRC8j9HMBKAoHOXEKAOCEFHOKAhCE4CBAhCEg9r7AMFGMHoKDNDNADCD9HMBABAdCETFGRAa87EBARCDFAS87EBARCLFAo87EBXEKABAdCDTFGRAabDBARCLFASbDBARCWFAobDBKAVC/ABFALCITFGRASbDBARAabDLAVAICDTFAabDBAVC/ABFALCEFCSgCITFGRAobDBARASbDLAVAICEFGICSgCDTFASbDBAVC/ABFALCDFCSgCITFGRAabDBARAobDLAVAIAZCZ6AxCSsvFGICSgCDTFAobDBAIActAcCSsvFHIALCIFHLKAWCEFHWALCSgHLAICSgHIAdCIFGdAE6MBKKCBC99AOAQseHOKAVC/AEF8kJJJJBAOK+LLEVU8jJJJJBCZ9rHVC9+HODNAECVFAL0MBCUHOAIrBBC/+EgC/QE9HMBAV9CB83IWAICEFHRAIALFC98FHWDNAEtMBDNADCDsMBCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCDTFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGLbDBAOALbDBAdCEFGdAE9HMBXDKKCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCETFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGL87EBAOALbDBAdCEFGdAE9HMBKKCBC99ARAWseHOKAOK+lVOEUE99DUD99EUD99DNDNADCL9HMBAEtMEINDNDNABCDFGD8sBB+yAB8sBBGI+yGL+L+TABCEFGV8sBBGO+yGR+L+TGWjBB/+9CAWAWnjBBBBAWAWjBBBB9gGdeGQ+MGKAQAICB9IeALmGWAWnAKAQAOCB9IeARmGQAQnmm+R+VGLnjBBBzjBBB+/AdemGR+LjBBB9P9dtMBAR+oHIXEKCJJJJ94HIKADAI86BBDNDNAQALnjBBBzjBBB+/AQjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHDXEKCJJJJ94HDKAVAD86BBDNDNAWALnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHDXEKCJJJJ94HDKABAD86BBABCLFHBAECUFGEMBXDKKAEtMBINDNDNABCLFGD8uEB+yAB8uEBGI+yGL+L+TABCDFGV8uEBGO+yGR+L+TGWjB/+fsAWAWnjBBBBAWAWjBBBB9gGdeGQ+MGKAQAICB9IeALmGWAWnAKAQAOCB9IeARmGQAQnmm+R+VGLnjBBBzjBBB+/AdemGR+LjBBB9P9dtMBAR+oHIXEKCJJJJ94HIKADAI87EBDNDNAQALnjBBBzjBBB+/AQjBBBB9gemGQ+LjBBB9P9dtMBAQ+oHDXEKCJJJJ94HDKAVAD87EBDNDNAWALnjBBBzjBBB+/AWjBBBB9gemGW+LjBBB9P9dtMBAW+oHDXEKCJJJJ94HDKABAD87EBABCWFHBAECUFGEMBKKK/SILIUI99IUE99DNAEtMBCBHIABHLINDNDNj/zL81zALCOF8uEBGVCIv+y+VGOAL8uEB+ynGRjB/+fsnjBBBzjBBB+/ARjBBBB9gemGW+LjBBB9P9dtMBAW+oHdXEKCJJJJ94HdKALCLF8uEBHQALCDF8uEBHKABAVCEFCIgAIvCETFAd87EBDNDNAOAK+ynGWjB/+fsnjBBBzjBBB+/AWjBBBB9gemGX+LjBBB9P9dtMBAX+oHKXEKCJJJJ94HKKABAVCDFCIgAIvCETFAK87EBDNDNAOAQ+ynGOjB/+fsnjBBBzjBBB+/AOjBBBB9gemGX+LjBBB9P9dtMBAX+oHQXEKCJJJJ94HQKABAVCUFCIgAIvCETFAQ87EBDNDNjBBJzARARn+TAWAWn+TAOAOn+TGRjBBBBARjBBBB9ge+RjB/+fsnjBBBzmGR+LjBBB9P9dtMBAR+oHQXEKCJJJJ94HQKABAVCIgAIvCETFAQ87EBALCWFHLAICLFHIAECUFGEMBKKK9MBDNADCD4AE2GEtMBINABABYDBGDCWTCW91+yADCE91CJJJ/8IFCJJJ98g++nuDBABCLFHBAECUFGEMBKKK9TEIUCBCBYDJ1JJBGEABCIFC98gFGBbDJ1JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK/lEEEUDNDNAEABvCIgtMBABHIXEKDNDNADCZ9PMBABHIXEKABHIINAIAEYDBbDBAICLFAECLFYDBbDBAICWFAECWFYDBbDBAICXFAECXFYDBbDBAICZFHIAECZFHEADC9wFGDCS0MBKKADCL6MBINAIAEYDBbDBAECLFHEAICLFHIADC98FGDCI0MBKKDNADtMBINAIAErBB86BBAICEFHIAECEFHEADCUFGDMBKKABK/AEEDUDNDNABCIgtMBABHIXEKAECfEgC+B+C+EW2HLDNDNADCZ9PMBABHIXEKABHIINAIALbDBAICXFALbDBAICWFALbDBAICLFALbDBAICZFHIADC9wFGDCS0MBKKADCL6MBINAIALbDBAICLFHIADC98FGDCI0MBKKDNADtMBINAIAE86BBAICEFHIADCUFGDMBKKABKKKEBCJWKLZ9kBB";
var wasm_simd = "B9h79tEBBBEkL9gBB9gVUUUUUEU9gIUUUB9gEUEUIKQBBEBEEDDDILVE9wEEEVIEBEOWEUEC+Q/aEKR/LEdO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BB8a9tw79o9v9wT9f9kw9j9v9kw9WwvTw949C919m9mwvBDy9tw79o9v9wT9f9kw9j9v9kw69u9kw949C919m9mwvBLe9tw79o9v9wT9f9kw9j9v9kw69u9kw949Twg91w9u9jwBVl9tw79o9v9wT9f9kw9j9v9kws9p2Twv9P9jTBOk9tw79o9v9wT9f9kw9j9v9kws9p2Twv9R919hTBRl9tw79o9v9wT9f9kw9j9v9kws9p2Twvt949wBWL79iv9rBdQ/T9TQLBZIK9+EVU8jJJJJBCZ9rHBCBHEINCBHDCBHIINABCWFADFAICJUAEAD4CEgGLe86BBAIALFHIADCEFGDCW9HMBKAEC+Q+YJJBFAI86BBAECITC+Q1JJBFAB8pIW83IBAECEFGECJD9HMBKK/H8jLhUD97EUO978jJJJJBCJ/KB9rGV8kJJJJBC9+HODNADCEFAL0MBCUHOAIrBBC+gE9HMBAVAIALFGRAD9rAD/8QBBCJ/ABAD9uHOAICEFHLDNADtMBAOC/wfBgGOCJDAOCJD6eHWCBHdINAdAE9PMEAWAEAd9rAdAWFAE6eGQCSFGOC9wgGKCI2HXAKCETHMAOCL4CIFCD4HpABAdAD2FHSCBHZDNINCEHhALHoCBHaDNINARAo9rAp6MIAVCJ/CBFAaAK2FHcAoApFHLCBHIDNAKC/AB6MBARAL9rC/gB6MBCBHOINAcAOFHIDNDNDNDNDNAoAOCO4FrBBGxCIgpLBEDIBKAIPXBBBBBBBBBBBBBBBBPKLBXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAIALPBBBPKLBALCZFHLKDNDNDNDNDNAxCD4CIgpLBEDIBKAIPXBBBBBBBBBBBBBBBBPKLZXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLZALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLZALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAIALPBBBPKLZALCZFHLKDNDNDNDNDNAxCL4CIgpLBEDIBKAIPXBBBBBBBBBBBBBBBBPKLAXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLAALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLAALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAIALPBBBPKLAALCZFHLKDNDNDNDNDNAxCO4pLBEDIBKAIPXBBBBBBBBBBBBBBBBPKL8wXIKAIALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBAxC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKL8wALCLFAyPqBFAxC+Q+YJJBFrBBFHLXDKAIALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBAxC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGxCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKL8wALCWFAyPqBFAxC+Q+YJJBFrBBFHLXEKAIALPBBBPKL8wALCZFHLKAOC/ABFHIAOCJEFAK0MEAIHOARAL9rC/fB0MBKKDNDNAIAK9PMBAICI4HOINARAL9rCk6MDAcAIFHxDNDNDNDNDNAoAICO4FrBBAOCOg4CIgpLBEDIBKAxPXBBBBBBBBBBBBBBBBPKLBXIKAxALPBBLALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlGqCDP+MEAqPMBZEhDoIaLcVxOqRlPXIIIIIIIIIIIIIIIIP9OGlPXIIIIIIIIIIIIIIIIP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCLFAyPqBFAkC+Q+YJJBFrBBFHLXDKAxALPBBWALPBBBGqCLP+MEAqPMBZEhDoIaLcVxOqRlPXSSSSSSSSSSSSSSSSP9OGlPXSSSSSSSSSSSSSSSSP8jGqP5B9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBAkC+Q+YJJBFPBBBGyAyPMBBBBBBBBBBBBBBBBAqP5E9CJf/8/4/w/g/AB9+9Cu1+nGkCITC+Q1JJBFPBIBP9uPMBEDILVORZhoacxqlPpAlAqP9SPKLBALCWFAyPqBFAkC+Q+YJJBFrBBFHLXEKAxALPBBBPKLBALCZFHLKAOCDFHOAICZFGIAK6MBKKALtMBAaCI6HhALHoAaCEFGOHaAOCLsMDXEKKCBHLAhCEgMDKDNAKtMBAVCJDFAZFHIAVAZFPBDBHyCBHxINAIAVCJ/CBFAxFGOPBLBGlCEP9tAlPXEEEEEEEEEEEEEEEEGqP9OP9hP9RGlAOAKFPBLBG8aCEP9tA8aAqP9OP9hP9RG8aPMBZEhDoIaLcVxOqRlGeAOAMFPBLBG3CEP9tA3AqP9OP9hP9RG3AOAXFPBLBG5CEP9tA5AqP9OP9hP9RG5PMBZEhDoIaLcVxOqRlG8ePMBEZhDIoaLVcxORqlGqAqPMBEDIBEDIBEDIBEDIAyP9uGyP9aDBBAIADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFGOAyAeA8ePMWdkyQK8aeXM35pS8e8fGqAqPMBEDIBEDIBEDIBEDIP9uGyP9aDBBAOADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFGOAyAlA8aPMWkdyQ8aKeX3M5p8eS8fGlA3A5PMWkdyQ8aKeX3M5p8eS8fG8aPMBEZhDIoaLVcxORqlGqAqPMBEDIBEDIBEDIBEDIP9uGyP9aDBBAOADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFGOAyAlA8aPMWdkyQK8aeXM35pS8e8fGqAqPMBEDIBEDIBEDIBEDIP9uGyP9aDBBAOADFGOAyAqAqPMLVORLVORLVORLVORP9uGyP9aDBBAOADFGOAyAqAqPMWdQKWdQKWdQKWdQKP9uGyP9aDBBAOADFGOAyAqAqPMXMpSXMpSXMpSXMpSP9uGyP9aDBBAOADFHIAxCZFGxAK6MBKKAZCLFGZAD6MBKASAVCJDFAQAD2/8QBBAVAVCJDFAQCUFAD2FAD/8QBBAQAdFHdC9+HOALMEXIKKC9+HOXEKCBC99ARAL9rADCAADCA0eseHOKAVCJ/KBF8kJJJJBAOKWBZ+BJJJBK/UZEhU8jJJJJBC/AE9rGV8kJJJJBC9+HODNAECI9uGRChFAL0MBCUHOAIrBBGWC/wEgC/gE9HMBAWCSgGdCE0MBAVC/ABFCfECJE/8KBAVCuF9CU83IBAVC8wF9CU83IBAVCYF9CU83IBAVCAF9CU83IBAVCkF9CU83IBAVCZF9CU83IBAV9CU83IWAV9CU83IBAIALFC9wFHQAICEFGWARFHODNAEtMBCMCSAdCEseHKCBHXCBHMCBHdCBHICBHLINDNAOAQ9NMBC9+HOXIKDNDNAWrBBGRC/vE0MBAVC/ABFALARCL4CU7FCSgCITFGpYDLHSApYDBHZDNARCSgGpAK9PMBAVAIARCU7FCSgCDTFYDBAXApeHRAptHpDNDNADCD9HMBABAdCETFGhAZ87EBAhCDFAS87EBAhCLFAR87EBXEKABAdCDTFGhAZbDBAhCLFASbDBAhCWFARbDBKAXApFHXAVC/ABFALCITFGhARbDBAhASbDLAVAICDTFARbDBAVC/ABFALCEFCSgGLCITFGhAZbDBAhARbDLAIApFHIALCEFHLXDKDNDNApCSsMBAMApFApC987FCEFHMXEKAOCEFHRAO8sBBGpCfEgHhDNDNApCU9MMBARHOXEKAOCVFHOAhCfBgHhCRHpDNINAR8sBBGoCfBgApTAhvHhAoCU9KMEARCEFHRApCRFGpC8j9HMBXDKKARCEFHOKAhCE4CBAhCEg9r7AMFHMKDNDNADCD9HMBABAdCETFGRAZ87EBARCDFAS87EBARCLFAM87EBXEKABAdCDTFGRAZbDBARCLFASbDBARCWFAMbDBKAVC/ABFALCITFGRAMbDBARASbDLAVAICDTFAMbDBAVC/ABFALCEFCSgGLCITFGRAZbDBARAMbDLAICEFHIALCEFHLXEKDNARCPE0MBAXCEFGoAVAIAQARCSgFrBBGpCL49rCSgCDTFYDBApCZ6GheHRAVAIAp9rCSgCDTFYDBAoAhFGSApCSgGoeHpAotHoDNDNADCD9HMBABAdCETFGZAX87EBAZCDFAR87EBAZCLFAp87EBXEKABAdCDTFGZAXbDBAZCLFARbDBAZCWFApbDBKAVAICDTFAXbDBAVC/ABFALCITFGZARbDBAZAXbDLAVAICEFGICSgCDTFARbDBAVC/ABFALCEFCSgCITFGZApbDBAZARbDLAVAIAhFCSgGICDTFApbDBAVC/ABFALCDFCSgGLCITFGRAXbDBARApbDLALCEFHLAIAoFHIASAoFHXXEKAXCBAOrBBGZeGaARC/+EsGRFHSAZCSgHcAZCL4HxDNDNAZCS0MBASCEFHoXEKASHoAVAIAx9rCSgCDTFYDBHSKDNDNAcMBAoCEFHXXEKAoHXAVAIAZ9rCSgCDTFYDBHoKDNDNARtMBAOCEFHRXEKAOCDFHRAO8sBEGhCfEgHpDNAhCU9KMBAOCOFHaApCfBgHpCRHODNINAR8sBBGhCfBgAOTApvHpAhCU9KMEARCEFHRAOCRFGOC8j9HMBKAaHRXEKARCEFHRKApCE4CBApCEg9r7AMFGMHaKDNDNAxCSsMBARHpXEKARCEFHpAR8sBBGOCfEgHhDNAOCU9KMBARCVFHSAhCfBgHhCRHODNINAp8sBBGRCfBgAOTAhvHhARCU9KMEApCEFHpAOCRFGOC8j9HMBKASHpXEKApCEFHpKAhCE4CBAhCEg9r7AMFGMHSKDNDNAcCSsMBApHOXEKApCEFHOAp8sBBGRCfEgHhDNARCU9KMBApCVFHoAhCfBgHhCRHRDNINAO8sBBGpCfBgARTAhvHhApCU9KMEAOCEFHOARCRFGRC8j9HMBKAoHOXEKAOCEFHOKAhCE4CBAhCEg9r7AMFGMHoKDNDNADCD9HMBABAdCETFGRAa87EBARCDFAS87EBARCLFAo87EBXEKABAdCDTFGRAabDBARCLFASbDBARCWFAobDBKAVC/ABFALCITFGRASbDBARAabDLAVAICDTFAabDBAVC/ABFALCEFCSgCITFGRAobDBARASbDLAVAICEFGICSgCDTFASbDBAVC/ABFALCDFCSgCITFGRAabDBARAobDLAVAIAZCZ6AxCSsvFGICSgCDTFAobDBAIActAcCSsvFHIALCIFHLKAWCEFHWALCSgHLAICSgHIAdCIFGdAE6MBKKCBC99AOAQseHOKAVC/AEF8kJJJJBAOK+LLEVU8jJJJJBCZ9rHVC9+HODNAECVFAL0MBCUHOAIrBBC/+EgC/QE9HMBAV9CB83IWAICEFHRAIALFC98FHWDNAEtMBDNADCDsMBCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCDTFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGLbDBAOALbDBAdCEFGdAE9HMBXDKKCBHdINDNARAW6MBC9+SKARCEFHOAR8sBBGLCfEgHIDNDNALCU9MMBAOHRXEKARCVFHRAICfBgHICRHLDNINAO8sBBGDCfBgALTAIvHIADCU9KMEAOCEFHOALCRFGLC8j9HMBXDKKAOCEFHRKABAdCETFAICD4CBAICE4CEg9r7AVCWFAICEgCDTvGOYDBFGL87EBAOALbDBAdCEFGdAE9HMBKKCBC99ARAWseHOKAOK+epLIUO97EUE978jJJJJBCA9rHIDNDNADCL9HMBDNAEC98gGLtMBCBHVABHDINADADPBBBGOCkP+rECkP+sEP/6EGRAOCWP+rECkP+sEP/6EARP/gEAOCZP+rECkP+sEP/6EGWP/gEP/kEP/lEGdPXBBBBBBBBBBBBBBBBP+2EGQARPXBBBJBBBJBBBJBBBJGKP9OP9RP/kEGRPXBB/+9CBB/+9CBB/+9CBB/+9CARARP/mEAdAdP/mEAWAQAWAKP9OP9RP/kEGRARP/mEP/kEP/kEP/jEP/nEGWP/mEPXBBN0BBN0BBN0BBN0GQP/kEPXfBBBfBBBfBBBfBBBP9OAOPXBBBfBBBfBBBfBBBfP9OP9QARAWP/mEAQP/kECWP+rEPXBfBBBfBBBfBBBfBBP9OP9QAdAWP/mEAQP/kECZP+rEPXBBfBBBfBBBfBBBfBP9OP9QPKBBADCZFHDAVCLFGVAL6MBKKALAE9PMEAIAECIgGVCDTGDvCBCZAD9r/8KBAIABALCDTFGLAD/8QBBDNAVtMBAIAIPBLBGOCkP+rECkP+sEP/6EGRAOCWP+rECkP+sEP/6EARP/gEAOCZP+rECkP+sEP/6EGWP/gEP/kEP/lEGdPXBBBBBBBBBBBBBBBBP+2EGQARPXBBBJBBBJBBBJBBBJGKP9OP9RP/kEGRPXBB/+9CBB/+9CBB/+9CBB/+9CARARP/mEAdAdP/mEAWAQAWAKP9OP9RP/kEGRARP/mEP/kEP/kEP/jEP/nEGWP/mEPXBBN0BBN0BBN0BBN0GQP/kEPXfBBBfBBBfBBBfBBBP9OAOPXBBBfBBBfBBBfBBBfP9OP9QARAWP/mEAQP/kECWP+rEPXBfBBBfBBBfBBBfBBP9OP9QAdAWP/mEAQP/kECZP+rEPXBBfBBBfBBBfBBBfBP9OP9QPKLBKALAIAD/8QBBSKDNAEC98gGXtMBCBHVABHDINADCZFGLALPBBBGOPXBBBBBBffBBBBBBffGKP9OADPBBBGdAOPMLVORXMpScxql358e8fPXfUBBfUBBfUBBfUBBP9OP/6EAdAOPMBEDIWdQKZhoaky8aeGOCZP+sEP/6EGRP/gEAOCZP+rECZP+sEP/6EGWP/gEP/kEP/lEGOPXB/+fsB/+fsB/+fsB/+fsAWAOPXBBBBBBBBBBBBBBBBP+2EGQAWPXBBBJBBBJBBBJBBBJGMP9OP9RP/kEGWAWP/mEAOAOP/mEARAQARAMP9OP9RP/kEGOAOP/mEP/kEP/kEP/jEP/nEGRP/mEPXBBN0BBN0BBN0BBN0GQP/kECZP+rEAWARP/mEAQP/kEPXffBBffBBffBBffBBP9OP9QGWAOARP/mEAQP/kEPXffBBffBBffBBffBBP9OGOPMWdkyQK8aeXM35pS8e8fP9QPKBBADAdAKP9OAWAOPMBEZhDIoaLVcxORqlP9QPKBBADCAFHDAVCLFGVAX6MBKKAXAE9PMBAIAECIgGVCITGDFCBCAAD9r/8KBAIABAXCITFGLAD/8QBBDNAVtMBAIAIPBLZGOPXBBBBBBffBBBBBBffGKP9OAIPBLBGdAOPMLVORXMpScxql358e8fPXfUBBfUBBfUBBfUBBP9OP/6EAdAOPMBEDIWdQKZhoaky8aeGOCZP+sEP/6EGRP/gEAOCZP+rECZP+sEP/6EGWP/gEP/kEP/lEGOPXB/+fsB/+fsB/+fsB/+fsAWAOPXBBBBBBBBBBBBBBBBP+2EGQAWPXBBBJBBBJBBBJBBBJGMP9OP9RP/kEGWAWP/mEAOAOP/mEARAQARAMP9OP9RP/kEGOAOP/mEP/kEP/kEP/jEP/nEGRP/mEPXBBN0BBN0BBN0BBN0GQP/kECZP+rEAWARP/mEAQP/kEPXffBBffBBffBBffBBP9OP9QGWAOARP/mEAQP/kEPXffBBffBBffBBffBBP9OGOPMWdkyQK8aeXM35pS8e8fP9QPKLZAIAdAKP9OAWAOPMBEZhDIoaLVcxORqlP9QPKLBKALAIAD/8QBBKK/4WLLUE97EUV978jJJJJBC8w9rHIDNAEC98gGLtMBCBHVABHOINAIAOPBBBGRAOCZFGWPBBBGdPMLVORXMpScxql358e8fGQCZP+sEGKCLP+rEPKLBAOPXBBJzBBJzBBJzBBJzPX/zL81z/zL81z/zL81z/zL81zAKPXIBBBIBBBIBBBIBBBP9QP/6EP/nEGKARAdPMBEDIWdQKZhoaky8aeGRCZP+rECZP+sEP/6EP/mEGdAdP/mEAKARCZP+sEP/6EP/mEGXAXP/mEAKAQCZP+rECZP+sEP/6EP/mEGQAQP/mEP/kEP/kEP/lEPXBBBBBBBBBBBBBBBBP+4EP/jEPXB/+fsB/+fsB/+fsB/+fsGKP/mEPXBBN0BBN0BBN0BBN0GRP/kEPXffBBffBBffBBffBBGMP9OAXAKP/mEARP/kECZP+rEP9QGXAQAKP/mEARP/kECZP+rEAdAKP/mEARP/kEAMP9OP9QGKPMBEZhDIoaLVcxORqlGRP5BAIPBLBPeB+t+J83IBAOCWFARP5EAIPBLBPeE+t+J83IBAWAXAKPMWdkyQK8aeXM35pS8e8fGKP5BAIPBLBPeD+t+J83IBAOCkFAKP5EAIPBLBPeI+t+J83IBAOCAFHOAVCLFGVAL6MBKKDNALAE9PMBAIAECIgGVCITGOFCBCAAO9r/8KBAIABALCITFGWAO/8QBBDNAVtMBAIAIPBLBGRAIPBLZGdPMLVORXMpScxql358e8fGQCZP+sEGKCLP+rEPKLAAIPXBBJzBBJzBBJzBBJzPX/zL81z/zL81z/zL81z/zL81zAKPXIBBBIBBBIBBBIBBBP9QP/6EP/nEGKARAdPMBEDIWdQKZhoaky8aeGRCZP+rECZP+sEP/6EP/mEGdAdP/mEAKARCZP+sEP/6EP/mEGXAXP/mEAKAQCZP+rECZP+sEP/6EP/mEGQAQP/mEP/kEP/kEP/lEPXBBBBBBBBBBBBBBBBP+4EP/jEPXB/+fsB/+fsB/+fsB/+fsGKP/mEPXBBN0BBN0BBN0BBN0GRP/kEPXffBBffBBffBBffBBGMP9OAXAKP/mEARP/kECZP+rEP9QGXAQAKP/mEARP/kECZP+rEAdAKP/mEARP/kEAMP9OP9QGKPMBEZhDIoaLVcxORqlGRP5BAIPBLAPeB+t+J83IBAIARP5EAIPBLAPeE+t+J83IWAIAXAKPMWdkyQK8aeXM35pS8e8fGKP5BAIPBLAPeD+t+J83IZAIAKP5EAIPBLAPeI+t+J83IkKAWAIAO/8QBBKK+pDDIUE978jJJJJBC/AB9rHIDNADCD4AE2GLC98gGVtMBCBHDABHEINAEAEPBBBGOCWP+rECWP+sEP/6EAOCEP+sEPXBBJzBBJzBBJzBBJzP+uEPXBBJfBBJfBBJfBBJfP9OP/mEPKBBAECZFHEADCLFGDAV6MBKKDNAVAL9PMBAIALCIgGDCDTGEvCBC/ABAE9r/8KBAIABAVCDTFGVAE/8QBBDNADtMBAIAIPBLBGOCWP+rECWP+sEP/6EAOCEP+sEPXBBJzBBJzBBJzBBJzP+uEPXBBJfBBJfBBJfBBJfP9OP/mEPKLBKAVAIAE/8QBBKK9TEIUCBCBYDJ1JJBGEABCIFC98gFGBbDJ1JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIKKKEBCJWKLZ9tBB";
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]);
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") {
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;
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 = {
0: "",
1: "meshopt_decodeFilterOct",
2: "meshopt_decodeFilterQuat",
3: "meshopt_decodeFilterExp",
NONE: "",
OCTAHEDRAL: "meshopt_decodeFilterOct",
QUATERNION: "meshopt_decodeFilterQuat",
EXPONENTIAL: "meshopt_decodeFilterExp"
};
var decoders = {
0: "meshopt_decodeVertexBuffer",
1: "meshopt_decodeIndexBuffer",
2: "meshopt_decodeIndexSequence",
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, mode2, filter) {
decode(instance.exports[decoders[mode2]], target, count, size, source, instance.exports[filters[filter]]);
}
};
}();
// node_modules/meshoptimizer/meshopt_simplifier.module.js
var MeshoptSimplifier = function() {
"use strict";
var wasm = "B9h79tEBBBECd9gEUEU9gEUB9gBB9gQUUUUUUU99UUEU9gVUUUUUB9gLUUUUE999gIUUUE999gLUUUUEU9gIUUUEUIMXDILVORBWWBEWLVE9wEIIVIEBEOWEUECJ/JEKR7OO9tw9t9vv95DBh9f9f939h79t9f9j9h229f9jT9vv7BBZ9tw79o9v9wT9f79p9t9w29p9m95BEx9tw79o9v9wT9f79p9t9w29p9m959T9j9h2wBLA9tw79o9v9wT9f9v9wT9p9t9p96w9WwvTw94swT9j9o9Sw9t9h9wBVL79iv9rBOdWEBCEKDdQQ+stXDBK/48yIkUp99hU8jJJJJBCJ/BB9rGQ8kJJJJBAQCkFCBC/kBZ1JJJB8aCUALCDTGKALCffffI0eGXCBYD/s1JJBhJJJJBBHMAQCkFAQYD94GpCDTFAMbDBAQAMbDWAQApCEFbD94AXCBYD/s1JJBhJJJJBBHSAQCkFAQYD94GpCDTFASbDBAQASbDXAQApCEFbD94CUADCITADCffffE0eCBYD/s1JJBhJJJJBBHZAQCkFAQYD94GpCDTFAZbDBAQAZbDZAQApCEFbD94AQCWFAEADALCBZ+CJJJBAXCBYD/s1JJBhJJJJBBHhAQCkFAQYD94GpCDTFAhbDBAQApCEFbD94AXCBYD/s1JJBhJJJJBBHoAQCkFAQYD94GpCDTFAobDBAQApCEFbD94ALCD4ALFHaCEHcINAcGpCETHcApAa6MBKCBHxCUApCDTGaApCffffI0eCBYD/s1JJBhJJJJBBHcAQCkFAQYD94GqCDTFAcbDBAQAqCEFbD94AcCfEAaZ1JJJBHlDNALtMBAVCD4HkApCUFHqINAIAxAk2CDTFGyYDLGpCh4Ap7C+f+B+dd2AyYDBGpCh4Ap7C/d/o+b8j27AyYDWGpCh4Ap7C+3f/n8n27HaCBHpDNDNINAlAaAqgGaCDTFG8aYDBGcCUsMEAIAcAk2CDTFAyCXZ+LJJJBtMDApCEFGpAaFHaApAq9NMBXDKKA8aAxbDBAxHcKAhAxCDTFAcbDBAxCEFGxAL9HMBKCBHpAoHcINAcApbDBAcCLFHcALApCEFGp9HMBKCBHpAhHcAoHaINDNApAcYDBGqsMBAaAoAqCDTFGqYDBbDBAqApbDBKAcCLFHcAaCLFHaALApCEFGp9HMBKKCBHaALCBYD/s1JJBhJJJJBBHyAQCkFAQYD94GpCDTFAybDBAQApCEFbD94AXCBYD/s1JJBhJJJJBBHpAQCkFAQYD94GcCDTFApbDBAQAcCEFbD94AXCBYD/s1JJBhJJJJBBHcAQCkFAQYD94GqCDTFAcbDBAQAqCEFbD94ApCfEAKZ1JJJBHeAcCfEAKZ1JJJBH3DNALtMBAZCWFH5INDNAMAaCDTGpFYDBG8etMBAZASApFYDBCITFH8fA3ApFHAAeApFHxCBHkINDNDNA8fAkCITFYDBGlAa9HMBAxAabDBAAAabDBXEKDNAMAlCDTGKFYDBGHtMBAZASAKFYDBCITGpFYDBAasMEAHCUFH8aA5ApFHcCBHpINA8aApsMEApCEFHpAcYDBHqAcCWFHcAqAa9HMBKApAH6MEKA3AKFGpAaAlApYDBCUsebDBAxAlAaAxYDBCUsebDBKAkCEFGkA8e9HMBKKAaCEFGaAL9HMBKAhHcAoHaA3HqAeHkCBHpINDNDNApAcYDBG8a9HMBDNApAaYDBG8a9HMBAkYDBH8aDNAqYDBGlCU9HMBA8aCU9HMBAyApFCB86BBXIKAyApFHxDNApAlsMBApA8asMBAxCE86BBXIKAxCL86BBXDKDNApAoA8aCDTGlFYDB9HMBDNAqYDBGxCUsMBApAxsMBAkYDBGKCUsMBApAKsMBA3AlFYDBG8eCUsMBA8eA8asMBAeAlFYDBGlCUsMBAlA8asMBDNAhAxCDTFYDBAhAlCDTFYDB9HMBAhAKCDTFYDBAhA8eCDTFYDB9HMBAyApFCD86BBXLKAyApFCL86BBXIKAyApFCL86BBXDKAyApFCL86BBXEKAyApFAyA8aFrBB86BBKAcCLFHcAaCLFHaAqCLFHqAkCLFHkALApCEFGp9HMBKAWCEgtMBAyHpALHcINDNAprBBCE9HMBApCL86BBKApCEFHpAcCUFGcMBKKCBHkCUALCX2ALC/V+q/V+qE0eCBYD/s1JJBhJJJJBBHMAQCkFAQYD94GpCDTFAMbDBAQApCEFbD94AMAIALAVZ+DJJJB8aCUALC8s2GcALC/d/o/F8u0eCBYD/s1JJBhJJJJBBHpAQCkFAQYD94GaCDTFApbDBAQAaCEFbD94ApCBAcZ1JJJBHZDNADtMBAEHcINDNAMAcCLFYDBG8aCX2FGpiDBAMAcYDBGlCX2FGaiDBGG+TG8jAMAcCWFYDBGxCX2FGqCLFiDBAaCLFiDBG8k+TG8lnAqiDBAG+TG8mApCLFiDBA8k+TG8nn+TGYAYnA8nAqCWFiDBAaCWFiDBG8p+TGinA8lApCWFiDBA8p+TG8nn+TG8lA8lnA8nA8mnAiA8jn+TG8jA8jnmm+RG8mjBBBB9etMBAYA8m+VHYA8jA8m+VH8jA8lA8m+VH8lKAZAhAlCDTFYDBC8s2FGpA8lA8m+RG8mA8lnnG8nApiDBmuDBApA8jA8mA8jnG8rnGiApiDLmuDLApAYA8mAYnG8snGrApiDWmuDWApA8rA8lnG8rApiDXmuDXApA8sA8lnG8uApiDZmuDZApA8sA8jnG8sApiDcmuDcApA8lA8mAYA8pnA8lAGnA8kA8jnmm+MG8knGGnG8lApiDkmuDkApA8jAGnG8jApiD3muD3ApAYAGnGYApiDAmuDAApAGA8knGGApiD8kmuD8kApA8mApiDYmuDYAZAhA8aCDTFYDBC8s2FGpA8nApiDBmuDBApAiApiDLmuDLApArApiDWmuDWApA8rApiDXmuDXApA8uApiDZmuDZApA8sApiDcmuDcApA8lApiDkmuDkApA8jApiD3muD3ApAYApiDAmuDAApAGApiD8kmuD8kApA8mApiDYmuDYAZAhAxCDTFYDBC8s2FGpA8nApiDBmuDBApAiApiDLmuDLApArApiDWmuDWApA8rApiDXmuDXApA8uApiDZmuDZApA8sApiDcmuDcApA8lApiDkmuDkApA8jApiD3muD3ApAYApiDAmuDAApAGApiD8kmuD8kApA8mApiDYmuDYAcCXFHcAkCIFGkAD6MBKCBH8aAEHxINCBHcINAyAEAcC+81JJBFYDBGlA8aFCDTFYDBGaFrBBHpDNDNAyAxAcFYDBGqFrBBGkC99FCfEgCPE0MBApCEsMBApCD9HMEKDNAkCUFCfEgCE0MBAeAqCDTFYDBAa9HMEKDNApCUFCfEgCE0MBA3AaCDTFYDBAq9HMEKDNAkCV2ApFC+g1JJBFrBBtMBAhAaCDTFYDBAhAqCDTFYDB0MEKjBBACjBBJzApCEseH8mAkCEsHKAEAlCDTC+81JJBFYDBA8aFCDTFYDBHlDNAMAaCX2FGpCWFiDBAMAqCX2FGkCWFiDBG8k+TG8lA8lnApiDBAkiDBG8p+TG8jA8jnApCLFiDBAkCLFiDBG8n+TGYAYnmm+RGGjBBBB9etMBA8lAG+VH8lAYAG+VHYA8jAG+VH8jKjBBACA8mAKeH8sDNAMAlCX2FGpiDWA8k+TG8mA8lA8mA8lnApiDBA8p+TGrA8jnAYApiDLA8n+TG8rnmmGin+TG8mA8mnArA8jAin+TG8lA8lnA8rAYAin+TG8jA8jnmm+RGYjBBBB9etMBA8mAY+VH8mA8jAY+VH8jA8lAY+VH8lKAZAhAqCDTFYDBC8s2FGpA8lA8sAGnGYA8lnnGiApiDBmuDBApA8jAYA8jnG8snGrApiDLmuDLApA8mAYA8mnGGnG8rApiDWmuDWApA8sA8lnG8sApiDXmuDXApAGA8lnG8uApiDZmuDZApAGA8jnG8vApiDcmuDcApA8lAYA8mA8knA8lA8pnA8nA8jnmm+MG8knGGnG8lApiDkmuDkApA8jAGnG8jApiD3muD3ApA8mAGnG8mApiDAmuDAApAGA8knGGApiD8kmuD8kApAYApiDYmuDYAZAhAaCDTFYDBC8s2FGpAiApiDBmuDBApArApiDLmuDLApA8rApiDWmuDWApA8sApiDXmuDXApA8uApiDZmuDZApA8vApiDcmuDcApA8lApiDkmuDkApA8jApiD3muD3ApA8mApiDAmuDAApAGApiD8kmuD8kApAYApiDYmuDYKAcCLFGcCX9HMBKAxCXFHxA8aCIFG8aAD6MBKKDNABAEsMBABAEADCDTZ+HJJJB8aKCUADCX2ADC/V+q/V+qE0eCBYD/s1JJBhJJJJBBHAAQCkFAQYD94GpCDTFAAbDBAQApCEFbD94CUADCDTADCffffI0eCBYD/s1JJBhJJJJBBH5AQCkFAQYD94GpCDTFA5bDBAQApCEFbD94AXCBYD/s1JJBhJJJJBBHIAQCkFAQYD94GpCDTFAIbDBAQApCEFbD94ALCBYD/s1JJBhJJJJBBH8wAQCkFAQYD94GpCDTFA8wbDBAQApCEFbD94jBBBBHrDNADAO9NMBARARnH8sAACWFH8xAQYDZH8yAQYDXH8zAQYDWH80jBBBBHrINAQCWFABADGSALAhZ+CJJJBCBHHABHxCBHKINCBHpINDNAhAxApFYDBGaCDTGEFYDBGkAhABApC+81JJBFYDBAKFCDTFYDBGcCDTFYDBG8asMBAyAcFrBBGlCV2AyAaFrBBGqFC/Q1JJBFrBBGDAqCV2AlFG8eC/Q1JJBFrBBG8fvCfEgtMBDNA8eC+g1JJBFrBBtMBA8aAk0MEKDNAqAl9HMBAqCUFCfEgCE0MBAeAEFYDBAc9HMEKAAAHCX2FGqAcAaA8fCfEgGkebDLAqAaAcAkebDBAqADA8fgCfEgCB9HbDWAHCEFHHKApCLFGpCX9HMBKAxCXFHxAKCIFGKAS6MBKDNDNAHtMBAAHcAHH8aINAcCWFGljBBBBjBBJzAZAhAcYDBGaCDTFYDBC8s2FGpiDYG8l+VA8ljBBBB9beApiDWAMAcCLFGEYDBGqCX2FGkCWFiDBG8lnApiDZAkiDBG8jnApiDAmG8mA8mmmA8lnApiDLAkCLFiDBG8mnApiDcA8lnApiD3mG8lA8lmmA8mnApiDBA8jnApiDXA8mnApiDkmG8lA8lmmA8jnApiD8kmmm+LnGYjBBBBjBBJzAZAhAqAaAlYDBGkeGlCDTFYDBC8s2FGpiDYG8l+VA8ljBBBB9beApiDWAMAaAqAkeGxCX2FGkCWFiDBG8lnApiDZAkiDBG8jnApiDAmG8mA8mmmA8lnApiDLAkCLFiDBG8mnApiDcA8lnApiD3mG8lA8lmmA8mnApiDBA8jnApiDXA8mnApiDkmG8lA8lmmA8jnApiD8kmmm+LnG8lAYA8l9fGpeuDBAEAqAxApebDBAcAaAlApebDBAcCXFHcA8aCUFG8aMBKAQCJEFCBCJ/ABZ1JJJB8aA8xHpAHHcINAQCJEFApYDBCo4C/8zgFGaAaYDBCEFbDBApCXFHpAcCUFGcMBKCBHpCBHcINAQCJEFApFGaYDBHqAaAcbDBAqAcFHcApCLFGpCJ/AB9HMBKCBHpA8xHcINAQCJEFAcYDBCo4C/8zgFGaAaYDBGaCEFbDBA5AaCDTFApbDBAcCXFHcAHApCEFGp9HMBKASAO9rGaCI9uH81DNALtMBCBHpAIHcINAcApbDBAcCLFHcALApCEFGp9HMBKKCBHbA8wCBALZ1JJJBH83AaCo9uHuA81CE4H85CBH86CBHKDNINAAA5AKCDTFYDBCX2FGxiDWG8jA8s9eMEA86A819PMEjffUUH8lDNA85AH9PMBAAA5A85CDTFYDBCX2FiDWjBB/AznH8lKDNA8jA8l9etMBA86Au0MDKDNA83AhAxYDLG87CDTG88FYDBGaFG89rBBA83AhAxYDBGECDTG8+FYDBGzFGNrBBvMBDNA80AzCDTGpFYDBGqtMBA8yA8zApFYDBCITFHpAMAaCX2FG8eCWFHDA8eCLFHXAMAzCX2FG8fCWFHVA8fCLFHWCBHcCEHlDNINDNAIApYDBCDTFYDBGkAasMBAIApCLFYDBCDTFYDBG8aAasMBAMA8aCX2FG8aiDBAMAkCX2FGkiDBG8m+TG8lAWiDBAkCLFiDBGY+TGGnA8fiDBA8m+TG8kA8aCLFiDBAY+TG8jn+TA8lAXiDBAY+TG8pnA8eiDBA8m+TG8nA8jn+TnA8jAViDBAkCWFiDBGY+TGinAGA8aCWFiDBAY+TG8mn+TA8jADiDBAY+TGYnA8pA8mn+TnA8mA8knAiA8ln+TA8mA8nnAYA8ln+TnmmjBBBB9dMDKApCWFHpAcCEFGcAq6HlAqAc9HMBKKAlCEgtMBA85CEFH85XEKAxCWFHqAZAaC8s2FGpAZAzC8s2FGciDBApiDBmuDBApAciDLApiDLmuDLApAciDWApiDWmuDWApAciDXApiDXmuDXApAciDZApiDZmuDZApAciDcApiDcmuDcApAciDkApiDkmuDkApAciD3ApiD3muD3ApAciDAApiDAmuDAApAciD8kApiD8kmuD8kApAciDYApiDYmuDYDNDNDNDNAyAEFGcrBBC9+FpDEBDKAEHpINAIApCDTGpFAabDBAoApFYDBGpAE9HMBXIKKAoA88FYDBHpAoA8+FYDBHEAIA8+FA87bDBApH87KAIAECDTFA87bDBKANCE86BBA89CE86BBAqiDBG8lArArA8l9deHrAbCEFHbCECDAcrBBCEseA86FH86KAKCEFGKAH9HMBKKAbtMBDNALtMBCBHcAeHpINDNApYDBGaCUsMBDNAcAIAaCDTGqFYDBGa9HMBAeAqFYDBHaKApAabDBKApCLFHpALAcCEFGc9HMBKCBHcA3HpINDNApYDBGaCUsMBDNAcAIAaCDTGqFYDBGa9HMBA3AqFYDBHaKApAabDBKApCLFHpALAcCEFGc9HMBKKCBHDABHpCBHkINDNAIApYDBCDTFYDBGcAIApCLFYDBCDTFYDBGasMBAcAIApCWFYDBCDTFYDBGqsMBAaAqsMBABADCDTFG8aAcbDBA8aCLFAabDBA8aCWFAqbDBADCIFHDKApCXFHpAkCIFGkAS9PMDXBKKASHDXDKADAO0MBKKDNAdtMBAdAr+RuDBKAQYD94GpCDTAQCkFFC98FHhDNINAptMEAhYDBCBYD/w1JJBh+BJJJBBAhC98FHhApCUFHpXBKKAQCJ/BBF8kJJJJBADK/PLEOUABYDBCBAICDTZ1JJJB8aADCI9uHVDNADtMBABYDBHODNALtMBAEHRADHWINAOALARYDBCDTFYDBCDTFGdAdYDBCEFbDBARCLFHRAWCUFGWMBXDKKAEHRADHWINAOARYDBCDTFGdAdYDBCEFbDBARCLFHRAWCUFGWMBKKDNAItMBABYDBHRABYDLHWCBHdAIHOINAWAdbDBAWCLFHWARYDBAdFHdARCLFHRAOCUFGOMBKKDNADCI6MBAVCEAVCE0eHQABYDLHVABYDWHRINAECWFYDBHWAECLFYDBHdAEYDBHODNALtMBALAWCDTFYDBHWALAdCDTFYDBHdALAOCDTFYDBHOKARAVAOCDTFGDYDBCITFAdbDBARADYDBCITFAWbDLADADYDBCEFbDBARAVAdCDTFGDYDBCITFAWbDBARADYDBCITFAObDLADADYDBCEFbDBARAVAWCDTFGWYDBCITFAObDBARAWYDBCITFAdbDLAWAWYDBCEFbDBAECXFHEAQCUFGQMBKKDNAItMBABYDLHRABYDBHWINARARYDBAWYDB9rbDBAWCLFHWARCLFHRAICUFGIMBKKK+3LDOUV998jJJJJBCA9rGLCZFCWFCBYD11JJBbDBALCB8pDJ1JJB83IZALCWFCBYDn1JJBbDBALCB8pD+M1JJB83IBDNADtMBAICD4HVDNABtMBAVCDTHOCBHRAEHWINABARCX2FGIAEARAV2CDTFGdiDBuDBAIAdiDLuDLAIAdiDWuDWCBHIINALCZFAIFGdAWAIFiDBGQAdiDBGKAKAQ9eeuDBALAIFGdAQAdiDBGKAKAQ9deuDBAICLFGICX9HMBKAWAOFHWARCEFGRAD9HMBXDKKAVCDTHRCBHWINCBHIINALCZFAIFGdAEAIFiDBGQAdiDBGKAKAQ9eeuDBALAIFGdAQAdiDBGKAKAQ9deuDBAICLFGICX9HMBKAEARFHEAWCEFGWAD9HMBKKALiDBALiDZGK+TjBBBB+XGQALiDLALiDcGX+TGMAMAQ9deGQALiDWALiDkGM+TGpApAQ9deHpDNABtMBADtMBjBBBBjBBJzAp+VApjBBBB9beHQINABAQABiDBAK+TnuDBABCLFGIAQAIiDBAX+TnuDBABCWFGIAQAIiDBAM+TnuDBABCXFHBADCUFGDMBKKApK+qDIDUI99DUCBHI8jJJJJBCA9rGLCZFCWFCBYD11JJBbDBALCB8pDJ1JJB83IZALCWFCBYDn1JJBbDBALCB8pD+M1JJB83IBDNDNAEMBjBBJfHVjBBJfHOjBBJfHRXEKADCD4CDTHWINCBHDINALCZFADFGdABADFiDBGOAdiDBGRARAO9eeuDBALADFGdAOAdiDBGRARAO9deuDBADCLFGDCX9HMBKABAWFHBAICEFGIAE9HMBKALiDWALiDk+THRALiDLALiDc+THOALiDBALiDZ+THVKAVjBBBB+XGVAOAOAV9deGOARARAO9deK9dEEUABCfEAICDTZ1JJJBHLCBHIDNADtMBINDNALAEYDBCDTFGBYDBCU9HMBABAIbDBAICEFHIKAECLFHEADCUFGDMBKKAIK9TEIUCBCBYD/01JJBGEABCIFC98gFGBbD/01JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK/lEEEUDNDNAEABvCIgtMBABHIXEKDNDNADCZ9PMBABHIXEKABHIINAIAEYDBbDBAICLFAECLFYDBbDBAICWFAECWFYDBbDBAICXFAECXFYDBbDBAICZFHIAECZFHEADC9wFGDCS0MBKKADCL6MBINAIAEYDBbDBAECLFHEAICLFHIADC98FGDCI0MBKKDNADtMBINAIAErBB86BBAICEFHIAECEFHEADCUFGDMBKKABK/AEEDUDNDNABCIgtMBABHIXEKAECfEgC+B+C+EW2HLDNDNADCZ9PMBABHIXEKABHIINAIALbDBAICXFALbDBAICWFALbDBAICLFALbDBAICZFHIADC9wFGDCS0MBKKADCL6MBINAIALbDBAICLFHIADC98FGDCI0MBKKDNADtMBINAIAE86BBAICEFHIADCUFGDMBKKABK9TEIUCBCBYD/01JJBGEABCIFC98gFGBbD/01JJBDNDNABzBCZTGD9NMBCUHIABAD9rCffIFCZ4NBCUsMEKAEHIKAIK9+EIUzBHEDNDNCBYD/01JJBGDAECZTGI9NMBCUHEADAI9rCffIFCZ4NBCUsMEKADHEKCBABAE9rCIFC98gCBYD/01JJBFGDbD/01JJBDNADzBCZTGE9NMBADAE9rCffIFCZ4NB8aKK6EIUCBHIDNADtMBDNINABrBBGLAErBBGV9HMEAECEFHEABCEFHBADCUFGDMBXDKKALAV9rHIKAIKK+CEDBCJWK9pffUUffUUffUUffUfffUfffUfBBBBBBBBEEEBEEBEBBEEEBEBBBBBEBEBBBBBEBBBDBBBBBBBBBBBBBBBEEEEEBEBBBBBEBBBBBEEBBBBBBC/sWKXEBBBDBBBJ9kBB";
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") {
return {
supported: false
};
}
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 assert(cond) {
if (!cond) {
throw new Error("Assertion failed");
}
}
function bytes(view) {
return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
}
function reorder(indices2, vertices) {
var sbrk = instance.exports.sbrk;
var ip = sbrk(indices2.length * 4);
var rp = sbrk(vertices * 4);
var heap = new Uint8Array(instance.exports.memory.buffer);
var indices8 = bytes(indices2);
heap.set(indices8, ip);
var unique = instance.exports.meshopt_optimizeVertexFetchRemap(rp, ip, indices2.length, vertices);
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 + indices2.length * 4));
sbrk(ip - sbrk(0));
for (var i = 0; i < indices2.length; ++i)
indices2[i] = remap[indices2[i]];
return [remap, unique];
}
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 simplify(fun, indices2, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options) {
var sbrk = instance.exports.sbrk;
var te = sbrk(4);
var ti = sbrk(index_count * 4);
var sp = sbrk(vertex_count * vertex_positions_stride);
var si = sbrk(index_count * 4);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(vertex_positions), sp);
heap.set(bytes(indices2), si);
var result = fun(ti, si, index_count, sp, vertex_count, vertex_positions_stride, target_index_count, target_error, options, te);
heap = new Uint8Array(instance.exports.memory.buffer);
var target = new Uint32Array(result);
bytes(target).set(heap.subarray(ti, ti + result * 4));
var error = new Float32Array(1);
bytes(error).set(heap.subarray(te, te + 4));
sbrk(te - sbrk(0));
return [target, error[0]];
}
function simplifyScale(fun, vertex_positions, vertex_count, vertex_positions_stride) {
var sbrk = instance.exports.sbrk;
var sp = sbrk(vertex_count * vertex_positions_stride);
var heap = new Uint8Array(instance.exports.memory.buffer);
heap.set(bytes(vertex_positions), sp);
var result = fun(sp, vertex_count, vertex_positions_stride);
sbrk(sp - sbrk(0));
return result;
}
var simplifyOptions = {
LockBorder: 1
};
return {
ready: promise,
supported: true,
compactMesh: function(indices2) {
assert(indices2 instanceof Uint32Array || indices2 instanceof Int32Array || indices2 instanceof Uint16Array || indices2 instanceof Int16Array);
assert(indices2.length % 3 == 0);
var indices32 = indices2.BYTES_PER_ELEMENT == 4 ? indices2 : new Uint32Array(indices2);
return reorder(indices32, maxindex(indices2) + 1);
},
simplify: function(indices2, vertex_positions, vertex_positions_stride, target_index_count, target_error, flags) {
assert(indices2 instanceof Uint32Array || indices2 instanceof Int32Array || indices2 instanceof Uint16Array || indices2 instanceof Int16Array);
assert(indices2.length % 3 == 0);
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
assert(vertex_positions_stride >= 3);
assert(target_index_count % 3 == 0);
var options = 0;
for (var i = 0; i < (flags ? flags.length : 0); ++i) {
options |= simplifyOptions[flags[i]];
}
var indices32 = indices2.BYTES_PER_ELEMENT == 4 ? indices2 : new Uint32Array(indices2);
var result = simplify(instance.exports.meshopt_simplify, indices32, indices2.length, vertex_positions, vertex_positions.length, vertex_positions_stride * 4, target_index_count, target_error, options);
result[0] = indices2 instanceof Uint32Array ? result[0] : new indices2.constructor(result[0]);
return result;
},
getScale: function(vertex_positions, vertex_positions_stride) {
assert(vertex_positions instanceof Float32Array);
assert(vertex_positions.length % vertex_positions_stride == 0);
return simplifyScale(instance.exports.meshopt_simplifyScale, vertex_positions, vertex_positions.length, vertex_positions_stride * 4);
}
};
}();
// node_modules/@cesium/engine/Source/Scene/GltfBufferViewLoader.js
function GltfBufferViewLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const bufferViewId = options.bufferViewId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.bufferViewId", bufferViewId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
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_default(bufferView, "EXT_meshopt_compression")) {
const meshopt = bufferView.extensions.EXT_meshopt_compression;
bufferId = meshopt.buffer;
byteOffset = defaultValue_default(meshopt.byteOffset, 0);
byteLength = meshopt.byteLength;
hasMeshopt = true;
meshoptByteStride = meshopt.byteStride;
meshoptCount = meshopt.count;
meshoptMode = meshopt.mode;
meshoptFilter = defaultValue_default(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 = baseResource2;
this._buffer = buffer;
this._bufferId = bufferId;
this._byteOffset = byteOffset;
this._byteLength = byteLength;
this._cacheKey = cacheKey;
this._bufferLoader = void 0;
this._typedArray = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfBufferViewLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfBufferViewLoader.prototype.constructor = GltfBufferViewLoader;
}
Object.defineProperties(GltfBufferViewLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
typedArray: {
get: function() {
return this._typedArray;
}
}
});
async function loadResources(loader) {
try {
const bufferLoader = getBufferLoader(loader);
loader._bufferLoader = bufferLoader;
await bufferLoader.load();
if (loader.isDestroyed()) {
return;
}
const bufferTypedArray = bufferLoader.typedArray;
const bufferViewTypedArray = new Uint8Array(
bufferTypedArray.buffer,
bufferTypedArray.byteOffset + loader._byteOffset,
loader._byteLength
);
loader.unload();
loader._typedArray = bufferViewTypedArray;
if (loader._hasMeshopt) {
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_default.READY;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader.unload();
loader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load buffer view";
throw loader.getError(errorMessage, error);
}
}
GltfBufferViewLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
this._promise = loadResources(this);
return this._promise;
};
function getBufferLoader(bufferViewLoader) {
const resourceCache = bufferViewLoader._resourceCache;
const buffer = bufferViewLoader._buffer;
if (defined_default(buffer.uri)) {
const baseResource2 = bufferViewLoader._baseResource;
const resource = baseResource2.getDerivedResource({
url: buffer.uri
});
return resourceCache.getExternalBufferLoader({
resource
});
}
return resourceCache.getEmbeddedBufferLoader({
parentResource: bufferViewLoader._gltfResource,
bufferId: bufferViewLoader._bufferId
});
}
GltfBufferViewLoader.prototype.unload = function() {
if (defined_default(this._bufferLoader) && !this._bufferLoader.isDestroyed()) {
this._resourceCache.unload(this._bufferLoader);
}
this._bufferLoader = void 0;
this._typedArray = void 0;
};
var GltfBufferViewLoader_default = GltfBufferViewLoader;
// node_modules/@cesium/engine/Source/Scene/DracoLoader.js
function DracoLoader() {
}
DracoLoader._maxDecodingConcurrency = Math.max(
FeatureDetection_default.hardwareConcurrency - 1,
1
);
DracoLoader._decoderTaskProcessor = void 0;
DracoLoader._taskProcessorReady = false;
DracoLoader._getDecoderTaskProcessor = function() {
if (!defined_default(DracoLoader._decoderTaskProcessor)) {
const processor = new TaskProcessor_default(
"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;
};
DracoLoader.decodePointCloud = function(parameters) {
const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
if (!DracoLoader._taskProcessorReady) {
return;
}
return decoderTaskProcessor.scheduleTask(parameters, [
parameters.buffer.buffer
]);
};
DracoLoader.decodeBufferView = function(options) {
const decoderTaskProcessor = DracoLoader._getDecoderTaskProcessor();
if (!DracoLoader._taskProcessorReady) {
return;
}
return decoderTaskProcessor.scheduleTask(options, [options.array.buffer]);
};
var DracoLoader_default = DracoLoader;
// node_modules/@cesium/engine/Source/Scene/GltfDracoLoader.js
function GltfDracoLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const draco = options.draco;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._draco = draco;
this._cacheKey = cacheKey;
this._bufferViewLoader = void 0;
this._bufferViewTypedArray = void 0;
this._decodePromise = void 0;
this._decodedData = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
this._dracoError = void 0;
}
if (defined_default(Object.create)) {
GltfDracoLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfDracoLoader.prototype.constructor = GltfDracoLoader;
}
Object.defineProperties(GltfDracoLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
decodedData: {
get: function() {
return this._decodedData;
}
}
});
async function loadResources2(loader) {
const resourceCache = loader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf: loader._gltf,
bufferViewId: loader._draco.bufferView,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource
});
loader._bufferViewLoader = bufferViewLoader;
await bufferViewLoader.load();
if (loader.isDestroyed()) {
return;
}
loader._bufferViewTypedArray = bufferViewLoader.typedArray;
loader._state = ResourceLoaderState_default.PROCESSING;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
handleError(loader, error);
}
}
GltfDracoLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
this._promise = loadResources2(this);
return this._promise;
};
function handleError(dracoLoader, error) {
dracoLoader.unload();
dracoLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load Draco";
throw dracoLoader.getError(errorMessage, error);
}
async function processDecode(loader, decodePromise) {
try {
const results = await decodePromise;
if (loader.isDestroyed()) {
return;
}
loader.unload();
loader._decodedData = {
indices: results.indexArray,
vertexAttributes: results.attributeData
};
loader._state = ResourceLoaderState_default.READY;
return loader._baseResource;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader._dracoError = error;
}
}
GltfDracoLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
if (defined_default(this._dracoError)) {
handleError(this, this._dracoError);
}
if (!defined_default(this._bufferViewTypedArray)) {
return false;
}
if (defined_default(this._decodePromise)) {
return false;
}
const draco = this._draco;
const gltf = this._gltf;
const bufferViews = gltf.bufferViews;
const bufferViewId = draco.bufferView;
const bufferView = bufferViews[bufferViewId];
const compressedAttributes = draco.attributes;
const decodeOptions = {
array: new Uint8Array(this._bufferViewTypedArray),
bufferView,
compressedAttributes,
dequantizeInShader: true
};
const decodePromise = DracoLoader_default.decodeBufferView(decodeOptions);
if (!defined_default(decodePromise)) {
return false;
}
this._decodePromise = processDecode(this, decodePromise);
};
GltfDracoLoader.prototype.unload = function() {
if (defined_default(this._bufferViewLoader)) {
this._resourceCache.unload(this._bufferViewLoader);
}
this._bufferViewLoader = void 0;
this._bufferViewTypedArray = void 0;
this._decodedData = void 0;
this._gltf = void 0;
};
var GltfDracoLoader_default = GltfDracoLoader;
// node_modules/@cesium/engine/Source/Core/loadImageFromTypedArray.js
function loadImageFromTypedArray(options) {
const uint8Array = options.uint8Array;
const format = options.format;
const request = options.request;
const flipY = defaultValue_default(options.flipY, false);
const skipColorSpaceConversion = defaultValue_default(
options.skipColorSpaceConversion,
false
);
Check_default.typeOf.object("uint8Array", uint8Array);
Check_default.typeOf.string("format", format);
const blob = new Blob([uint8Array], {
type: format
});
let blobUrl;
return Resource_default.supportsImageBitmapOptions().then(function(result) {
if (result) {
return Promise.resolve(
Resource_default.createImageBitmapFromBlob(blob, {
flipY,
premultiplyAlpha: false,
skipColorSpaceConversion
})
);
}
blobUrl = window.URL.createObjectURL(blob);
const resource = new Resource_default({
url: blobUrl,
request
});
return resource.fetchImage({
flipY,
skipColorSpaceConversion
});
}).then(function(result) {
if (defined_default(blobUrl)) {
window.URL.revokeObjectURL(blobUrl);
}
return result;
}).catch(function(error) {
if (defined_default(blobUrl)) {
window.URL.revokeObjectURL(blobUrl);
}
return Promise.reject(error);
});
}
var loadImageFromTypedArray_default = loadImageFromTypedArray;
// node_modules/@cesium/engine/Source/Scene/GltfImageLoader.js
function GltfImageLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const imageId = options.imageId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.imageId", imageId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const image = gltf.images[imageId];
const bufferViewId = image.bufferView;
const uri = image.uri;
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._bufferViewId = bufferViewId;
this._uri = uri;
this._cacheKey = cacheKey;
this._bufferViewLoader = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfImageLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfImageLoader.prototype.constructor = GltfImageLoader;
}
Object.defineProperties(GltfImageLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
image: {
get: function() {
return this._image;
}
},
mipLevels: {
get: function() {
return this._mipLevels;
}
}
});
GltfImageLoader.prototype.load = function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (defined_default(this._bufferViewId)) {
this._promise = loadFromBufferView(this);
return this._promise;
}
this._promise = loadFromUri(this);
return this._promise;
};
function getImageAndMipLevels(image) {
let mipLevels;
if (Array.isArray(image)) {
mipLevels = image.slice(1, image.length).map(function(mipLevel) {
return mipLevel.bufferView;
});
image = image[0];
}
return {
image,
mipLevels
};
}
async function loadFromBufferView(imageLoader) {
imageLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = imageLoader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf: imageLoader._gltf,
bufferViewId: imageLoader._bufferViewId,
gltfResource: imageLoader._gltfResource,
baseResource: imageLoader._baseResource
});
imageLoader._bufferViewLoader = bufferViewLoader;
await bufferViewLoader.load();
if (imageLoader.isDestroyed()) {
return;
}
const typedArray = bufferViewLoader.typedArray;
const image = await loadImageFromBufferTypedArray(typedArray);
if (imageLoader.isDestroyed()) {
return;
}
const imageAndMipLevels = getImageAndMipLevels(image);
imageLoader.unload();
imageLoader._image = imageAndMipLevels.image;
imageLoader._mipLevels = imageAndMipLevels.mipLevels;
imageLoader._state = ResourceLoaderState_default.READY;
return imageLoader;
} catch (error) {
if (imageLoader.isDestroyed()) {
return;
}
return handleError2(imageLoader, error, "Failed to load embedded image");
}
}
async function loadFromUri(imageLoader) {
imageLoader._state = ResourceLoaderState_default.LOADING;
const baseResource2 = imageLoader._baseResource;
const uri = imageLoader._uri;
const resource = baseResource2.getDerivedResource({
url: uri
});
try {
const image = await loadImageFromUri(resource);
if (imageLoader.isDestroyed()) {
return;
}
const imageAndMipLevels = getImageAndMipLevels(image);
imageLoader.unload();
imageLoader._image = imageAndMipLevels.image;
imageLoader._mipLevels = imageAndMipLevels.mipLevels;
imageLoader._state = ResourceLoaderState_default.READY;
return imageLoader;
} catch (error) {
if (imageLoader.isDestroyed()) {
return;
}
return handleError2(imageLoader, error, `Failed to load image: ${uri}`);
}
}
function handleError2(imageLoader, error, errorMessage) {
imageLoader.unload();
imageLoader._state = ResourceLoaderState_default.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] === 255 && header[1] === 216) {
return "image/jpeg";
} else if (header[0] === 137 && header[1] === 80) {
return "image/png";
} else if (header[0] === 171 && header[1] === 75) {
return "image/ktx2";
} else if (webpHeaderRIFFChars[0] === 82 && webpHeaderRIFFChars[1] === 73 && webpHeaderRIFFChars[2] === 70 && webpHeaderRIFFChars[3] === 70 && webpHeaderWEBPChars[0] === 87 && webpHeaderWEBPChars[1] === 69 && webpHeaderWEBPChars[2] === 66 && webpHeaderWEBPChars[3] === 80) {
return "image/webp";
}
throw new RuntimeError_default("Image format is not recognized");
}
async function loadImageFromBufferTypedArray(typedArray) {
const mimeType = getMimeTypeFromTypedArray(typedArray);
if (mimeType === "image/ktx2") {
const ktxBuffer = new Uint8Array(typedArray);
return loadKTX2_default(ktxBuffer);
}
return GltfImageLoader._loadImageFromTypedArray({
uint8Array: typedArray,
format: mimeType,
flipY: false,
skipColorSpaceConversion: true
});
}
var ktx2Regex2 = /(^data:image\/ktx2)|(\.ktx2$)/i;
function loadImageFromUri(resource) {
const uri = resource.getUrlComponent(false, true);
if (ktx2Regex2.test(uri)) {
return loadKTX2_default(resource);
}
return resource.fetchImage({
skipColorSpaceConversion: true,
preferImageBitmap: true
});
}
GltfImageLoader.prototype.unload = function() {
if (defined_default(this._bufferViewLoader) && !this._bufferViewLoader.isDestroyed()) {
this._resourceCache.unload(this._bufferViewLoader);
}
this._bufferViewLoader = void 0;
this._uri = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._gltf = void 0;
};
GltfImageLoader._loadImageFromTypedArray = loadImageFromTypedArray_default;
var GltfImageLoader_default = GltfImageLoader;
// node_modules/@cesium/engine/Source/Scene/JobType.js
var JobType = {
TEXTURE: 0,
PROGRAM: 1,
BUFFER: 2,
NUMBER_OF_JOB_TYPES: 3
};
var JobType_default = Object.freeze(JobType);
// node_modules/@cesium/engine/Source/Scene/GltfIndexBufferLoader.js
function GltfIndexBufferLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const accessorId = options.accessorId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const draco = options.draco;
const cacheKey = options.cacheKey;
const asynchronous = defaultValue_default(options.asynchronous, true);
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.accessorId", accessorId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
const indexDatatype = gltf.accessors[accessorId].componentType;
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
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 = void 0;
this._dracoLoader = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfIndexBufferLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfIndexBufferLoader.prototype.constructor = GltfIndexBufferLoader;
}
Object.defineProperties(GltfIndexBufferLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
buffer: {
get: function() {
return this._buffer;
}
},
typedArray: {
get: function() {
return this._typedArray;
}
},
indexDatatype: {
get: function() {
return this._indexDatatype;
}
}
});
var scratchIndexBufferJob = new CreateIndexBufferJob();
GltfIndexBufferLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (defined_default(this._draco)) {
this._promise = loadFromDraco(this);
return this._promise;
}
this._promise = loadFromBufferView2(this);
return this._promise;
};
async function loadFromDraco(indexBufferLoader) {
indexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = indexBufferLoader._resourceCache;
try {
const dracoLoader = resourceCache.getDracoLoader({
gltf: indexBufferLoader._gltf,
draco: indexBufferLoader._draco,
gltfResource: indexBufferLoader._gltfResource,
baseResource: indexBufferLoader._baseResource
});
indexBufferLoader._dracoLoader = dracoLoader;
await dracoLoader.load();
if (indexBufferLoader.isDestroyed()) {
return;
}
indexBufferLoader._state = ResourceLoaderState_default.LOADED;
return indexBufferLoader;
} catch (error) {
if (indexBufferLoader.isDestroyed()) {
return;
}
handleError3(indexBufferLoader, error);
}
}
async function loadFromBufferView2(indexBufferLoader) {
const gltf = indexBufferLoader._gltf;
const accessorId = indexBufferLoader._accessorId;
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
indexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = indexBufferLoader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf,
bufferViewId,
gltfResource: indexBufferLoader._gltfResource,
baseResource: indexBufferLoader._baseResource
});
indexBufferLoader._bufferViewLoader = bufferViewLoader;
await bufferViewLoader.load();
if (indexBufferLoader.isDestroyed()) {
return;
}
const bufferViewTypedArray = bufferViewLoader.typedArray;
indexBufferLoader._typedArray = createIndicesTypedArray(
indexBufferLoader,
bufferViewTypedArray
);
indexBufferLoader._state = ResourceLoaderState_default.PROCESSING;
return indexBufferLoader;
} catch (error) {
if (indexBufferLoader.isDestroyed()) {
return;
}
handleError3(indexBufferLoader, error);
}
}
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 indexSize = IndexDatatype_default.getSizeInBytes(indexDatatype);
let arrayBuffer = bufferViewTypedArray.buffer;
let byteOffset = bufferViewTypedArray.byteOffset + accessor.byteOffset;
if (byteOffset % indexSize !== 0) {
const byteLength = count * indexSize;
const view = new Uint8Array(arrayBuffer, byteOffset, byteLength);
const copy = new Uint8Array(view);
arrayBuffer = copy.buffer;
byteOffset = 0;
deprecationWarning_default(
"index-buffer-unaligned",
`The index array is not aligned to a ${indexSize}-byte boundary.`
);
}
let typedArray;
if (indexDatatype === IndexDatatype_default.UNSIGNED_BYTE) {
typedArray = new Uint8Array(arrayBuffer, byteOffset, count);
} else if (indexDatatype === IndexDatatype_default.UNSIGNED_SHORT) {
typedArray = new Uint16Array(arrayBuffer, byteOffset, count);
} else if (indexDatatype === IndexDatatype_default.UNSIGNED_INT) {
typedArray = new Uint32Array(arrayBuffer, byteOffset, count);
}
return typedArray;
}
function handleError3(indexBufferLoader, error) {
indexBufferLoader.unload();
indexBufferLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load index buffer";
throw indexBufferLoader.getError(errorMessage, error);
}
function CreateIndexBufferJob() {
this.typedArray = void 0;
this.indexDatatype = void 0;
this.context = void 0;
this.buffer = void 0;
}
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_default.createIndexBuffer({
typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype
});
buffer.vertexArrayDestroyable = false;
return buffer;
}
GltfIndexBufferLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.LOADED && this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
let typedArray = this._typedArray;
let indexDatatype = this._indexDatatype;
if (defined_default(this._dracoLoader)) {
try {
const ready = this._dracoLoader.process(frameState);
if (ready) {
const dracoLoader = this._dracoLoader;
typedArray = dracoLoader.decodedData.indices.typedArray;
this._typedArray = typedArray;
indexDatatype = ComponentDatatype_default.fromTypedArray(typedArray);
this._indexDatatype = indexDatatype;
}
} catch (error) {
handleError3(this, error);
}
}
if (!defined_default(typedArray)) {
return false;
}
let buffer;
if (this._loadBuffer && this._asynchronous) {
const indexBufferJob = scratchIndexBufferJob;
indexBufferJob.set(typedArray, indexDatatype, frameState.context);
const jobScheduler = frameState.jobScheduler;
if (!jobScheduler.execute(indexBufferJob, JobType_default.BUFFER)) {
return false;
}
buffer = indexBufferJob.buffer;
} else if (this._loadBuffer) {
buffer = createIndexBuffer(typedArray, indexDatatype, frameState.context);
}
this.unload();
this._buffer = buffer;
this._typedArray = this._loadTypedArray ? typedArray : void 0;
this._state = ResourceLoaderState_default.READY;
this._resourceCache.statistics.addGeometryLoader(this);
return true;
};
GltfIndexBufferLoader.prototype.unload = function() {
if (defined_default(this._buffer)) {
this._buffer.destroy();
}
const resourceCache = this._resourceCache;
if (defined_default(this._bufferViewLoader) && !this._bufferViewLoader.isDestroyed()) {
resourceCache.unload(this._bufferViewLoader);
}
if (defined_default(this._dracoLoader)) {
resourceCache.unload(this._dracoLoader);
}
this._bufferViewLoader = void 0;
this._dracoLoader = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._gltf = void 0;
};
var GltfIndexBufferLoader_default = GltfIndexBufferLoader;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/addToArray.js
function addToArray(array, element, checkDuplicates) {
checkDuplicates = defaultValue_default(checkDuplicates, false);
if (checkDuplicates) {
const index = array.indexOf(element);
if (index > -1) {
return index;
}
}
array.push(element);
return array.length - 1;
}
var addToArray_default = addToArray;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/usesExtension.js
function usesExtension(gltf, extension) {
return defined_default(gltf.extensionsUsed) && gltf.extensionsUsed.indexOf(extension) >= 0;
}
var usesExtension_default = usesExtension;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/ForEach.js
function ForEach() {
}
ForEach.objectLegacy = function(objects, handler) {
if (defined_default(objects)) {
for (const objectId in objects) {
if (Object.prototype.hasOwnProperty.call(objects, objectId)) {
const object = objects[objectId];
const value = handler(object, objectId);
if (defined_default(value)) {
return value;
}
}
}
}
};
ForEach.object = function(arrayOfObjects, handler) {
if (defined_default(arrayOfObjects)) {
const length3 = arrayOfObjects.length;
for (let i = 0; i < length3; i++) {
const object = arrayOfObjects[i];
const value = handler(object, i);
if (defined_default(value)) {
return value;
}
}
}
};
ForEach.topLevel = function(gltf, name, handler) {
const gltfProperty = gltf[name];
if (defined_default(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_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(value)) {
return value;
}
}
}
);
if (defined_default(valueForEach)) {
return valueForEach;
}
return ForEach.meshPrimitiveTarget(primitive, function(target) {
return ForEach.meshPrimitiveTargetAttribute(
target,
function(accessorId, attributeSemantic) {
if (attributeSemantic.indexOf(semantic) === 0 && !defined_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(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_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(value)) {
return value;
}
}
}
);
if (defined_default(valueForEach)) {
return valueForEach;
}
return ForEach.meshPrimitiveTarget(primitive, function(target) {
return ForEach.meshPrimitiveTargetAttribute(
target,
function(accessorId) {
if (!defined_default(visited[accessorId])) {
visited[accessorId] = true;
const value = handler(accessorId);
if (defined_default(value)) {
return value;
}
}
}
);
});
});
});
};
ForEach.accessorContainingIndexData = function(gltf, handler) {
const visited = {};
return ForEach.mesh(gltf, function(mesh) {
return ForEach.meshPrimitive(mesh, function(primitive) {
const indices2 = primitive.indices;
if (defined_default(indices2) && !defined_default(visited[indices2])) {
visited[indices2] = true;
const value = handler(indices2);
if (defined_default(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_default(material.extensions) && defined_default(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_default(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_default(primitives)) {
const primitivesLength = primitives.length;
for (let i = 0; i < primitivesLength; i++) {
const primitive = primitives[i];
const value = handler(primitive, i);
if (defined_default(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_default(value)) {
return value;
}
}
}
};
ForEach.meshPrimitiveTarget = function(primitive, handler) {
const targets = primitive.targets;
if (defined_default(targets)) {
const length3 = targets.length;
for (let i = 0; i < length3; ++i) {
const value = handler(targets[i], i);
if (defined_default(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_default(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_default(nodes)) {
const length3 = nodeIds.length;
for (let i = 0; i < length3; i++) {
const nodeId = nodeIds[i];
const node = nodes[nodeId];
if (defined_default(node)) {
let value = handler(node, nodeId);
if (defined_default(value)) {
return value;
}
const children = node.children;
if (defined_default(children)) {
value = ForEach.nodeInTree(gltf, children, handler);
if (defined_default(value)) {
return value;
}
}
}
}
}
};
ForEach.nodeInScene = function(gltf, scene, handler) {
const sceneNodeIds = scene.nodes;
if (defined_default(sceneNodeIds)) {
return ForEach.nodeInTree(gltf, sceneNodeIds, handler);
}
};
ForEach.program = function(gltf, handler) {
if (usesExtension_default(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_default(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_default(joints)) {
const jointsLength = joints.length;
for (let i = 0; i < jointsLength; i++) {
const joint = joints[i];
const value = handler(joint);
if (defined_default(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_default(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_default(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_default(value)) {
return value;
}
}
}
};
ForEach.technique = function(gltf, handler) {
if (usesExtension_default(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);
};
var ForEach_default = ForEach;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/numberOfComponentsForType.js
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;
}
}
var numberOfComponentsForType_default = numberOfComponentsForType;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/getAccessorByteStride.js
function getAccessorByteStride(gltf, accessor) {
const bufferViewId = accessor.bufferView;
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
if (defined_default(bufferView.byteStride) && bufferView.byteStride > 0) {
return bufferView.byteStride;
}
}
return ComponentDatatype_default.getSizeInBytes(accessor.componentType) * numberOfComponentsForType_default(accessor.type);
}
var getAccessorByteStride_default = getAccessorByteStride;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/addDefaults.js
function addDefaults(gltf) {
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
accessor.byteOffset = defaultValue_default(accessor.byteOffset, 0);
}
});
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer)) {
bufferView.byteOffset = defaultValue_default(bufferView.byteOffset, 0);
}
});
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
primitive.mode = defaultValue_default(primitive.mode, WebGLConstants_default.TRIANGLES);
if (!defined_default(primitive.material)) {
if (!defined_default(gltf.materials)) {
gltf.materials = [];
}
const defaultMaterial4 = {
name: "default"
};
primitive.material = addToArray_default(gltf.materials, defaultMaterial4);
}
});
});
ForEach_default.accessorContainingVertexAttributeData(gltf, function(accessorId) {
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
accessor.normalized = defaultValue_default(accessor.normalized, false);
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
bufferView.byteStride = getAccessorByteStride_default(gltf, accessor);
bufferView.target = WebGLConstants_default.ARRAY_BUFFER;
}
});
ForEach_default.accessorContainingIndexData(gltf, function(accessorId) {
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
bufferView.target = WebGLConstants_default.ELEMENT_ARRAY_BUFFER;
}
});
ForEach_default.material(gltf, function(material) {
const extensions = defaultValue_default(
material.extensions,
defaultValue_default.EMPTY_OBJECT
);
const materialsCommon = extensions.KHR_materials_common;
if (defined_default(materialsCommon)) {
const technique = materialsCommon.technique;
const values = defined_default(materialsCommon.values) ? materialsCommon.values : {};
materialsCommon.values = values;
values.ambient = defined_default(values.ambient) ? values.ambient : [0, 0, 0, 1];
values.emission = defined_default(values.emission) ? values.emission : [0, 0, 0, 1];
values.transparency = defaultValue_default(values.transparency, 1);
if (technique !== "CONSTANT") {
values.diffuse = defined_default(values.diffuse) ? values.diffuse : [0, 0, 0, 1];
if (technique !== "LAMBERT") {
values.specular = defined_default(values.specular) ? values.specular : [0, 0, 0, 1];
values.shininess = defaultValue_default(values.shininess, 0);
}
}
materialsCommon.transparent = defaultValue_default(
materialsCommon.transparent,
false
);
materialsCommon.doubleSided = defaultValue_default(
materialsCommon.doubleSided,
false
);
return;
}
material.emissiveFactor = defaultValue_default(
material.emissiveFactor,
[0, 0, 0]
);
material.alphaMode = defaultValue_default(material.alphaMode, "OPAQUE");
material.doubleSided = defaultValue_default(material.doubleSided, false);
if (material.alphaMode === "MASK") {
material.alphaCutoff = defaultValue_default(material.alphaCutoff, 0.5);
}
const techniquesExtension = extensions.KHR_techniques_webgl;
if (defined_default(techniquesExtension)) {
ForEach_default.materialValue(material, function(materialValue) {
if (defined_default(materialValue.index)) {
addTextureDefaults(materialValue);
}
});
}
addTextureDefaults(material.emissiveTexture);
addTextureDefaults(material.normalTexture);
addTextureDefaults(material.occlusionTexture);
const pbrMetallicRoughness = material.pbrMetallicRoughness;
if (defined_default(pbrMetallicRoughness)) {
pbrMetallicRoughness.baseColorFactor = defaultValue_default(
pbrMetallicRoughness.baseColorFactor,
[1, 1, 1, 1]
);
pbrMetallicRoughness.metallicFactor = defaultValue_default(
pbrMetallicRoughness.metallicFactor,
1
);
pbrMetallicRoughness.roughnessFactor = defaultValue_default(
pbrMetallicRoughness.roughnessFactor,
1
);
addTextureDefaults(pbrMetallicRoughness.baseColorTexture);
addTextureDefaults(pbrMetallicRoughness.metallicRoughnessTexture);
}
const pbrSpecularGlossiness = extensions.KHR_materials_pbrSpecularGlossiness;
if (defined_default(pbrSpecularGlossiness)) {
pbrSpecularGlossiness.diffuseFactor = defaultValue_default(
pbrSpecularGlossiness.diffuseFactor,
[1, 1, 1, 1]
);
pbrSpecularGlossiness.specularFactor = defaultValue_default(
pbrSpecularGlossiness.specularFactor,
[1, 1, 1]
);
pbrSpecularGlossiness.glossinessFactor = defaultValue_default(
pbrSpecularGlossiness.glossinessFactor,
1
);
addTextureDefaults(pbrSpecularGlossiness.specularGlossinessTexture);
}
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
sampler.interpolation = defaultValue_default(sampler.interpolation, "LINEAR");
});
});
const animatedNodes = getAnimatedNodes(gltf);
ForEach_default.node(gltf, function(node, id) {
const animated = defined_default(animatedNodes[id]);
if (animated || defined_default(node.translation) || defined_default(node.rotation) || defined_default(node.scale)) {
node.translation = defaultValue_default(node.translation, [0, 0, 0]);
node.rotation = defaultValue_default(node.rotation, [0, 0, 0, 1]);
node.scale = defaultValue_default(node.scale, [1, 1, 1]);
} else {
node.matrix = defaultValue_default(
node.matrix,
[
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
]
);
}
});
ForEach_default.sampler(gltf, function(sampler) {
sampler.wrapS = defaultValue_default(sampler.wrapS, WebGLConstants_default.REPEAT);
sampler.wrapT = defaultValue_default(sampler.wrapT, WebGLConstants_default.REPEAT);
});
if (defined_default(gltf.scenes) && !defined_default(gltf.scene)) {
gltf.scene = 0;
}
return gltf;
}
function getAnimatedNodes(gltf) {
const nodes = {};
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationChannel(animation, function(channel) {
const target = channel.target;
const nodeId = target.node;
const path = target.path;
if (path === "translation" || path === "rotation" || path === "scale") {
nodes[nodeId] = true;
}
});
});
return nodes;
}
function addTextureDefaults(texture) {
if (defined_default(texture)) {
texture.texCoord = defaultValue_default(texture.texCoord, 0);
}
}
var addDefaults_default = addDefaults;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/addPipelineExtras.js
function addPipelineExtras(gltf) {
ForEach_default.shader(gltf, function(shader) {
addExtras(shader);
});
ForEach_default.buffer(gltf, function(buffer) {
addExtras(buffer);
});
ForEach_default.image(gltf, function(image) {
addExtras(image);
});
addExtras(gltf);
return gltf;
}
function addExtras(object) {
object.extras = defined_default(object.extras) ? object.extras : {};
object.extras._pipeline = defined_default(object.extras._pipeline) ? object.extras._pipeline : {};
}
var addPipelineExtras_default = addPipelineExtras;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/removeExtensionsRequired.js
function removeExtensionsRequired(gltf, extension) {
const extensionsRequired = gltf.extensionsRequired;
if (defined_default(extensionsRequired)) {
const index = extensionsRequired.indexOf(extension);
if (index >= 0) {
extensionsRequired.splice(index, 1);
}
if (extensionsRequired.length === 0) {
delete gltf.extensionsRequired;
}
}
}
var removeExtensionsRequired_default = removeExtensionsRequired;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/removeExtensionsUsed.js
function removeExtensionsUsed(gltf, extension) {
const extensionsUsed = gltf.extensionsUsed;
if (defined_default(extensionsUsed)) {
const index = extensionsUsed.indexOf(extension);
if (index >= 0) {
extensionsUsed.splice(index, 1);
}
removeExtensionsRequired_default(gltf, extension);
if (extensionsUsed.length === 0) {
delete gltf.extensionsUsed;
}
}
}
var removeExtensionsUsed_default = removeExtensionsUsed;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/parseGlb.js
var sizeOfUint323 = 4;
function parseGlb(glb) {
const magic = getMagic_default(glb);
if (magic !== "glTF") {
throw new RuntimeError_default("File is not valid binary glTF");
}
const header = readHeader(glb, 0, 5);
const version2 = header[1];
if (version2 !== 1 && version2 !== 2) {
throw new RuntimeError_default("Binary glTF version is not 1 or 2");
}
if (version2 === 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 * sizeOfUint323,
true
);
}
return header;
}
function parseGlbVersion1(glb, header) {
const length3 = header[2];
const contentLength = header[3];
const contentFormat = header[4];
if (contentFormat !== 0) {
throw new RuntimeError_default("Binary glTF scene format is not JSON");
}
const jsonStart = 20;
const binaryStart = jsonStart + contentLength;
const contentString = getStringFromTypedArray_default(glb, jsonStart, contentLength);
const gltf = JSON.parse(contentString);
addPipelineExtras_default(gltf);
const binaryBuffer = glb.subarray(binaryStart, length3);
const buffers = gltf.buffers;
if (defined_default(buffers) && Object.keys(buffers).length > 0) {
const binaryGltfBuffer = defaultValue_default(
buffers.binary_glTF,
buffers.KHR_binary_glTF
);
if (defined_default(binaryGltfBuffer)) {
binaryGltfBuffer.extras._pipeline.source = binaryBuffer;
delete binaryGltfBuffer.uri;
}
}
removeExtensionsUsed_default(gltf, "KHR_binary_glTF");
return gltf;
}
function parseGlbVersion2(glb, header) {
const length3 = header[2];
let byteOffset = 12;
let gltf;
let binaryBuffer;
while (byteOffset < length3) {
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;
if (chunkType === 1313821514) {
const jsonString = getStringFromTypedArray_default(chunkBuffer);
gltf = JSON.parse(jsonString);
addPipelineExtras_default(gltf);
} else if (chunkType === 5130562) {
binaryBuffer = chunkBuffer;
}
}
if (defined_default(gltf) && defined_default(binaryBuffer)) {
const buffers = gltf.buffers;
if (defined_default(buffers) && buffers.length > 0) {
const buffer = buffers[0];
buffer.extras._pipeline.source = binaryBuffer;
}
}
return gltf;
}
var parseGlb_default = parseGlb;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/removePipelineExtras.js
function removePipelineExtras(gltf) {
ForEach_default.shader(gltf, function(shader) {
removeExtras(shader);
});
ForEach_default.buffer(gltf, function(buffer) {
removeExtras(buffer);
});
ForEach_default.image(gltf, function(image) {
removeExtras(image);
});
removeExtras(gltf);
return gltf;
}
function removeExtras(object) {
if (!defined_default(object.extras)) {
return;
}
if (defined_default(object.extras._pipeline)) {
delete object.extras._pipeline;
}
if (Object.keys(object.extras).length === 0) {
delete object.extras;
}
}
var removePipelineExtras_default = removePipelineExtras;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/addExtensionsUsed.js
function addExtensionsUsed(gltf, extension) {
let extensionsUsed = gltf.extensionsUsed;
if (!defined_default(extensionsUsed)) {
extensionsUsed = [];
gltf.extensionsUsed = extensionsUsed;
}
addToArray_default(extensionsUsed, extension, true);
}
var addExtensionsUsed_default = addExtensionsUsed;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/getComponentReader.js
function getComponentReader(componentType) {
switch (componentType) {
case ComponentDatatype_default.BYTE:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getInt8(
byteOffset + i * componentTypeByteLength
);
}
};
case ComponentDatatype_default.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_default.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_default.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_default.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_default.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_default.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_default.DOUBLE:
return function(dataView, byteOffset, numberOfComponents, componentTypeByteLength, result) {
for (let i = 0; i < numberOfComponents; ++i) {
result[i] = dataView.getFloat64(
byteOffset + i * componentTypeByteLength,
true
);
}
};
}
}
var getComponentReader_default = getComponentReader;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/findAccessorMinMax.js
function findAccessorMinMax(gltf, accessor) {
const bufferViews = gltf.bufferViews;
const buffers = gltf.buffers;
const bufferViewId = accessor.bufferView;
const numberOfComponents = numberOfComponentsForType_default(accessor.type);
if (!defined_default(accessor.bufferView)) {
return {
min: new Array(numberOfComponents).fill(0),
max: new Array(numberOfComponents).fill(0)
};
}
const min3 = new Array(numberOfComponents).fill(Number.POSITIVE_INFINITY);
const max3 = 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_default(gltf, accessor);
let byteOffset = accessor.byteOffset + bufferView.byteOffset + source.byteOffset;
const componentType = accessor.componentType;
const componentTypeByteLength = ComponentDatatype_default.getSizeInBytes(componentType);
const dataView = new DataView(source.buffer);
const components = new Array(numberOfComponents);
const componentReader = getComponentReader_default(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];
min3[j] = Math.min(min3[j], value);
max3[j] = Math.max(max3[j], value);
}
byteOffset += byteStride;
}
return {
min: min3,
max: max3
};
}
var findAccessorMinMax_default = findAccessorMinMax;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/moveTechniqueRenderStates.js
var defaultBlendEquation = [WebGLConstants_default.FUNC_ADD, WebGLConstants_default.FUNC_ADD];
var defaultBlendFactors = [
WebGLConstants_default.ONE,
WebGLConstants_default.ZERO,
WebGLConstants_default.ONE,
WebGLConstants_default.ZERO
];
function isStateEnabled(renderStates, state) {
const enabled = renderStates.enable;
if (!defined_default(enabled)) {
return false;
}
return enabled.indexOf(state) > -1;
}
var supportedBlendFactors = [
WebGLConstants_default.ZERO,
WebGLConstants_default.ONE,
WebGLConstants_default.SRC_COLOR,
WebGLConstants_default.ONE_MINUS_SRC_COLOR,
WebGLConstants_default.SRC_ALPHA,
WebGLConstants_default.ONE_MINUS_SRC_ALPHA,
WebGLConstants_default.DST_ALPHA,
WebGLConstants_default.ONE_MINUS_DST_ALPHA,
WebGLConstants_default.DST_COLOR,
WebGLConstants_default.ONE_MINUS_DST_COLOR
];
function getSupportedBlendFactors(value, defaultValue2) {
if (!defined_default(value)) {
return defaultValue2;
}
for (let i = 0; i < 4; i++) {
if (supportedBlendFactors.indexOf(value[i]) === -1) {
return defaultValue2;
}
}
return value;
}
function moveTechniqueRenderStates(gltf) {
const blendingForTechnique = {};
const materialPropertiesForTechnique = {};
const techniquesLegacy = gltf.techniques;
if (!defined_default(techniquesLegacy)) {
return gltf;
}
ForEach_default.technique(gltf, function(techniqueLegacy, techniqueIndex) {
const renderStates = techniqueLegacy.states;
if (defined_default(renderStates)) {
const materialProperties = materialPropertiesForTechnique[techniqueIndex] = {};
if (isStateEnabled(renderStates, WebGLConstants_default.BLEND)) {
materialProperties.alphaMode = "BLEND";
const blendFunctions = renderStates.functions;
if (defined_default(blendFunctions) && (defined_default(blendFunctions.blendEquationSeparate) || defined_default(blendFunctions.blendFuncSeparate))) {
blendingForTechnique[techniqueIndex] = {
blendEquation: defaultValue_default(
blendFunctions.blendEquationSeparate,
defaultBlendEquation
),
blendFactors: getSupportedBlendFactors(
blendFunctions.blendFuncSeparate,
defaultBlendFactors
)
};
}
}
if (!isStateEnabled(renderStates, WebGLConstants_default.CULL_FACE)) {
materialProperties.doubleSided = true;
}
delete techniqueLegacy.states;
}
});
if (Object.keys(blendingForTechnique).length > 0) {
if (!defined_default(gltf.extensions)) {
gltf.extensions = {};
}
addExtensionsUsed_default(gltf, "KHR_blend");
}
ForEach_default.material(gltf, function(material) {
if (defined_default(material.technique)) {
const materialProperties = materialPropertiesForTechnique[material.technique];
ForEach_default.objectLegacy(materialProperties, function(value, property) {
material[property] = value;
});
const blending = blendingForTechnique[material.technique];
if (defined_default(blending)) {
if (!defined_default(material.extensions)) {
material.extensions = {};
}
material.extensions.KHR_blend = blending;
}
}
});
return gltf;
}
var moveTechniqueRenderStates_default = moveTechniqueRenderStates;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/addExtensionsRequired.js
function addExtensionsRequired(gltf, extension) {
let extensionsRequired = gltf.extensionsRequired;
if (!defined_default(extensionsRequired)) {
extensionsRequired = [];
gltf.extensionsRequired = extensionsRequired;
}
addToArray_default(extensionsRequired, extension, true);
addExtensionsUsed_default(gltf, extension);
}
var addExtensionsRequired_default = addExtensionsRequired;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/moveTechniquesToExtension.js
function moveTechniquesToExtension(gltf) {
const techniquesLegacy = gltf.techniques;
const mappedUniforms = {};
const updatedTechniqueIndices = {};
const seenPrograms = {};
if (defined_default(techniquesLegacy)) {
const extension = {
programs: [],
shaders: [],
techniques: []
};
const glExtensions = gltf.glExtensionsUsed;
delete gltf.glExtensionsUsed;
ForEach_default.technique(gltf, function(techniqueLegacy, techniqueId) {
const technique = {
name: techniqueLegacy.name,
program: void 0,
attributes: {},
uniforms: {}
};
let parameterLegacy;
ForEach_default.techniqueAttribute(
techniqueLegacy,
function(parameterName, attributeName) {
parameterLegacy = techniqueLegacy.parameters[parameterName];
technique.attributes[attributeName] = {
semantic: parameterLegacy.semantic
};
}
);
ForEach_default.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
};
if (!defined_default(mappedUniforms[techniqueId])) {
mappedUniforms[techniqueId] = {};
}
mappedUniforms[techniqueId][parameterName] = uniformName;
}
);
if (!defined_default(seenPrograms[techniqueLegacy.program])) {
const programLegacy = gltf.programs[techniqueLegacy.program];
const program = {
name: programLegacy.name,
fragmentShader: void 0,
vertexShader: void 0,
glExtensions
};
const fs = gltf.shaders[programLegacy.fragmentShader];
program.fragmentShader = addToArray_default(extension.shaders, fs, true);
const vs = gltf.shaders[programLegacy.vertexShader];
program.vertexShader = addToArray_default(extension.shaders, vs, true);
technique.program = addToArray_default(extension.programs, program);
seenPrograms[techniqueLegacy.program] = technique.program;
} else {
technique.program = seenPrograms[techniqueLegacy.program];
}
updatedTechniqueIndices[techniqueId] = addToArray_default(
extension.techniques,
technique
);
});
if (extension.techniques.length > 0) {
if (!defined_default(gltf.extensions)) {
gltf.extensions = {};
}
gltf.extensions.KHR_techniques_webgl = extension;
addExtensionsUsed_default(gltf, "KHR_techniques_webgl");
addExtensionsRequired_default(gltf, "KHR_techniques_webgl");
}
}
ForEach_default.material(gltf, function(material) {
if (defined_default(material.technique)) {
const materialExtension = {
technique: updatedTechniqueIndices[material.technique]
};
ForEach_default.objectLegacy(material.values, function(value, parameterName) {
if (!defined_default(materialExtension.values)) {
materialExtension.values = {};
}
const uniformName = mappedUniforms[material.technique][parameterName];
if (defined_default(uniformName)) {
materialExtension.values[uniformName] = value;
}
});
if (!defined_default(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;
}
var moveTechniquesToExtension_default = moveTechniquesToExtension;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/forEachTextureInMaterial.js
function forEachTextureInMaterial(material, handler) {
Check_default.typeOf.object("material", material);
Check_default.defined("handler", handler);
const pbrMetallicRoughness = material.pbrMetallicRoughness;
if (defined_default(pbrMetallicRoughness)) {
if (defined_default(pbrMetallicRoughness.baseColorTexture)) {
const textureInfo = pbrMetallicRoughness.baseColorTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(pbrMetallicRoughness.metallicRoughnessTexture)) {
const textureInfo = pbrMetallicRoughness.metallicRoughnessTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
}
if (defined_default(material.extensions)) {
const pbrSpecularGlossiness = material.extensions.KHR_materials_pbrSpecularGlossiness;
if (defined_default(pbrSpecularGlossiness)) {
if (defined_default(pbrSpecularGlossiness.diffuseTexture)) {
const textureInfo = pbrSpecularGlossiness.diffuseTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(pbrSpecularGlossiness.specularGlossinessTexture)) {
const textureInfo = pbrSpecularGlossiness.specularGlossinessTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
}
const materialsCommon = material.extensions.KHR_materials_common;
if (defined_default(materialsCommon) && defined_default(materialsCommon.values)) {
const diffuse = materialsCommon.values.diffuse;
const ambient = materialsCommon.values.ambient;
const emission = materialsCommon.values.emission;
const specular = materialsCommon.values.specular;
if (defined_default(diffuse) && defined_default(diffuse.index)) {
const value2 = handler(diffuse.index, diffuse);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(ambient) && defined_default(ambient.index)) {
const value2 = handler(ambient.index, ambient);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(emission) && defined_default(emission.index)) {
const value2 = handler(emission.index, emission);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(specular) && defined_default(specular.index)) {
const value2 = handler(specular.index, specular);
if (defined_default(value2)) {
return value2;
}
}
}
}
const value = ForEach_default.materialValue(material, function(materialValue) {
if (defined_default(materialValue.index)) {
const value2 = handler(materialValue.index, materialValue);
if (defined_default(value2)) {
return value2;
}
}
});
if (defined_default(value)) {
return value;
}
if (defined_default(material.emissiveTexture)) {
const textureInfo = material.emissiveTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(material.normalTexture)) {
const textureInfo = material.normalTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
if (defined_default(material.occlusionTexture)) {
const textureInfo = material.occlusionTexture;
const value2 = handler(textureInfo.index, textureInfo);
if (defined_default(value2)) {
return value2;
}
}
}
var forEachTextureInMaterial_default = forEachTextureInMaterial;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/removeUnusedElements.js
var allElementTypes = [
"mesh",
"node",
"material",
"accessor",
"bufferView",
"buffer",
"texture",
"sampler",
"image"
];
function removeUnusedElements(gltf, elementTypes) {
elementTypes = defaultValue_default(elementTypes, allElementTypes);
allElementTypes.forEach(function(type) {
if (elementTypes.indexOf(type) > -1) {
removeUnusedElementsByType(gltf, type);
}
});
return gltf;
}
var 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_default(arrayOfObjects)) {
let removed = 0;
const usedIds = getListOfElementsIdsInUse[type](gltf);
const length3 = arrayOfObjects.length;
for (let i = 0; i < length3; ++i) {
if (!usedIds[i]) {
Remove[type](gltf, i - removed);
removed++;
}
}
}
}
function Remove() {
}
Remove.accessor = function(gltf, accessorId) {
const accessors = gltf.accessors;
accessors.splice(accessorId, 1);
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.meshPrimitiveAttribute(
primitive,
function(attributeAccessorId, semantic) {
if (attributeAccessorId > accessorId) {
primitive.attributes[semantic]--;
}
}
);
ForEach_default.meshPrimitiveTarget(primitive, function(target) {
ForEach_default.meshPrimitiveTargetAttribute(
target,
function(attributeAccessorId, semantic) {
if (attributeAccessorId > accessorId) {
target[semantic]--;
}
}
);
});
const indices2 = primitive.indices;
if (defined_default(indices2) && indices2 > accessorId) {
primitive.indices--;
}
});
});
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.inverseBindMatrices) && skin.inverseBindMatrices > accessorId) {
skin.inverseBindMatrices--;
}
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
if (defined_default(sampler.input) && sampler.input > accessorId) {
sampler.input--;
}
if (defined_default(sampler.output) && sampler.output > accessorId) {
sampler.output--;
}
});
});
};
Remove.buffer = function(gltf, bufferId) {
const buffers = gltf.buffers;
buffers.splice(bufferId, 1);
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer) && bufferView.buffer > bufferId) {
bufferView.buffer--;
}
if (defined_default(bufferView.extensions) && defined_default(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_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView) && accessor.bufferView > bufferViewId) {
accessor.bufferView--;
}
});
ForEach_default.shader(gltf, function(shader) {
if (defined_default(shader.bufferView) && shader.bufferView > bufferViewId) {
shader.bufferView--;
}
});
ForEach_default.image(gltf, function(image) {
if (defined_default(image.bufferView) && image.bufferView > bufferViewId) {
image.bufferView--;
}
});
if (usesExtension_default(gltf, "KHR_draco_mesh_compression")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.extensions) && defined_default(primitive.extensions.KHR_draco_mesh_compression)) {
if (primitive.extensions.KHR_draco_mesh_compression.bufferView > bufferViewId) {
primitive.extensions.KHR_draco_mesh_compression.bufferView--;
}
}
});
});
}
if (usesExtension_default(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_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.bufferView) && property.bufferView > bufferViewId) {
property.bufferView--;
}
if (defined_default(property.arrayOffsetBufferView) && property.arrayOffsetBufferView > bufferViewId) {
property.arrayOffsetBufferView--;
}
if (defined_default(property.stringOffsetBufferView) && property.stringOffsetBufferView > bufferViewId) {
property.stringOffsetBufferView--;
}
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTables = extension.propertyTables;
if (defined_default(propertyTables)) {
const propertyTablesLength = propertyTables.length;
for (let i = 0; i < propertyTablesLength; ++i) {
const propertyTable = propertyTables[i];
const properties = propertyTable.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.values) && property.values > bufferViewId) {
property.values--;
}
if (defined_default(property.arrayOffsets) && property.arrayOffsets > bufferViewId) {
property.arrayOffsets--;
}
if (defined_default(property.stringOffsets) && property.stringOffsets > bufferViewId) {
property.stringOffsets--;
}
}
}
}
}
}
};
Remove.image = function(gltf, imageId) {
const images = gltf.images;
images.splice(imageId, 1);
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.source)) {
if (texture.source > imageId) {
--texture.source;
}
}
const ext = texture.extensions;
if (defined_default(ext) && defined_default(ext.EXT_texture_webp) && ext.EXT_texture_webp.source > imageId) {
--texture.extensions.EXT_texture_webp.source;
} else if (defined_default(ext) && defined_default(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_default.node(gltf, function(node) {
if (defined_default(node.mesh)) {
if (node.mesh > meshId) {
node.mesh--;
} else if (node.mesh === meshId) {
delete node.mesh;
}
}
});
};
Remove.node = function(gltf, nodeId) {
const nodes = gltf.nodes;
nodes.splice(nodeId, 1);
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.skeleton) && skin.skeleton > nodeId) {
skin.skeleton--;
}
skin.joints = skin.joints.map(function(x) {
return x > nodeId ? x - 1 : x;
});
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationChannel(animation, function(channel) {
if (defined_default(channel.target) && defined_default(channel.target.node) && channel.target.node > nodeId) {
channel.target.node--;
}
});
});
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueUniform(technique, function(uniform) {
if (defined_default(uniform.node) && uniform.node > nodeId) {
uniform.node--;
}
});
});
ForEach_default.node(gltf, function(node) {
if (!defined_default(node.children)) {
return;
}
node.children = node.children.filter(function(x) {
return x !== nodeId;
}).map(function(x) {
return x > nodeId ? x - 1 : x;
});
});
ForEach_default.scene(gltf, function(scene) {
scene.nodes = scene.nodes.filter(function(x) {
return x !== nodeId;
}).map(function(x) {
return x > nodeId ? x - 1 : x;
});
});
};
Remove.material = function(gltf, materialId) {
const materials = gltf.materials;
materials.splice(materialId, 1);
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.material) && primitive.material > materialId) {
primitive.material--;
}
});
});
};
Remove.sampler = function(gltf, samplerId) {
const samplers = gltf.samplers;
samplers.splice(samplerId, 1);
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.sampler)) {
if (texture.sampler > samplerId) {
--texture.sampler;
}
}
});
};
Remove.texture = function(gltf, textureId) {
const textures = gltf.textures;
textures.splice(textureId, 1);
ForEach_default.material(gltf, function(material) {
forEachTextureInMaterial_default(material, function(textureIndex, textureInfo) {
if (textureInfo.index > textureId) {
--textureInfo.index;
}
});
});
if (usesExtension_default(gltf, "EXT_feature_metadata")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_feature_metadata)) {
const extension2 = extensions.EXT_feature_metadata;
const featureIdTextures = extension2.featureIdTextures;
if (defined_default(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_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
const textureInfo = property.texture;
if (textureInfo.index > textureId) {
--textureInfo.index;
}
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_mesh_features")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_mesh_features)) {
const extension = extensions.EXT_mesh_features;
const featureIds = extension.featureIds;
if (defined_default(featureIds)) {
const featureIdsLength = featureIds.length;
for (let i = 0; i < featureIdsLength; ++i) {
const featureId = featureIds[i];
if (defined_default(featureId.texture)) {
if (featureId.texture.index > textureId) {
--featureId.texture.index;
}
}
}
}
}
});
});
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTextures = extension.propertyTextures;
if (defined_default(propertyTextures)) {
const propertyTexturesLength = propertyTextures.length;
for (let i = 0; i < propertyTexturesLength; ++i) {
const propertyTexture = propertyTextures[i];
const properties = propertyTexture.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (property.index > textureId) {
--property.index;
}
}
}
}
}
}
};
function getListOfElementsIdsInUse() {
}
getListOfElementsIdsInUse.accessor = function(gltf) {
const usedAccessorIds = {};
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.meshPrimitiveAttribute(primitive, function(accessorId) {
usedAccessorIds[accessorId] = true;
});
ForEach_default.meshPrimitiveTarget(primitive, function(target) {
ForEach_default.meshPrimitiveTargetAttribute(target, function(accessorId) {
usedAccessorIds[accessorId] = true;
});
});
const indices2 = primitive.indices;
if (defined_default(indices2)) {
usedAccessorIds[indices2] = true;
}
});
});
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.inverseBindMatrices)) {
usedAccessorIds[skin.inverseBindMatrices] = true;
}
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
if (defined_default(sampler.input)) {
usedAccessorIds[sampler.input] = true;
}
if (defined_default(sampler.output)) {
usedAccessorIds[sampler.output] = true;
}
});
});
if (usesExtension_default(gltf, "EXT_mesh_gpu_instancing")) {
ForEach_default.node(gltf, function(node) {
if (defined_default(node.extensions) && defined_default(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) {
const usedBufferIds = {};
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer)) {
usedBufferIds[bufferView.buffer] = true;
}
if (defined_default(bufferView.extensions) && defined_default(bufferView.extensions.EXT_meshopt_compression)) {
usedBufferIds[bufferView.extensions.EXT_meshopt_compression.buffer] = true;
}
});
return usedBufferIds;
};
getListOfElementsIdsInUse.bufferView = function(gltf) {
const usedBufferViewIds = {};
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
usedBufferViewIds[accessor.bufferView] = true;
}
});
ForEach_default.shader(gltf, function(shader) {
if (defined_default(shader.bufferView)) {
usedBufferViewIds[shader.bufferView] = true;
}
});
ForEach_default.image(gltf, function(image) {
if (defined_default(image.bufferView)) {
usedBufferViewIds[image.bufferView] = true;
}
});
if (usesExtension_default(gltf, "KHR_draco_mesh_compression")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.extensions) && defined_default(primitive.extensions.KHR_draco_mesh_compression)) {
usedBufferViewIds[primitive.extensions.KHR_draco_mesh_compression.bufferView] = true;
}
});
});
}
if (usesExtension_default(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_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.bufferView)) {
usedBufferViewIds[property.bufferView] = true;
}
if (defined_default(property.arrayOffsetBufferView)) {
usedBufferViewIds[property.arrayOffsetBufferView] = true;
}
if (defined_default(property.stringOffsetBufferView)) {
usedBufferViewIds[property.stringOffsetBufferView] = true;
}
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTables = extension.propertyTables;
if (defined_default(propertyTables)) {
const propertyTablesLength = propertyTables.length;
for (let i = 0; i < propertyTablesLength; ++i) {
const propertyTable = propertyTables[i];
const properties = propertyTable.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.values)) {
usedBufferViewIds[property.values] = true;
}
if (defined_default(property.arrayOffsets)) {
usedBufferViewIds[property.arrayOffsets] = true;
}
if (defined_default(property.stringOffsets)) {
usedBufferViewIds[property.stringOffsets] = true;
}
}
}
}
}
}
return usedBufferViewIds;
};
getListOfElementsIdsInUse.image = function(gltf) {
const usedImageIds = {};
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.source)) {
usedImageIds[texture.source] = true;
}
if (defined_default(texture.extensions) && defined_default(texture.extensions.EXT_texture_webp)) {
usedImageIds[texture.extensions.EXT_texture_webp.source] = true;
} else if (defined_default(texture.extensions) && defined_default(texture.extensions.KHR_texture_basisu)) {
usedImageIds[texture.extensions.KHR_texture_basisu.source] = true;
}
});
return usedImageIds;
};
getListOfElementsIdsInUse.mesh = function(gltf) {
const usedMeshIds = {};
ForEach_default.node(gltf, function(node) {
if (defined_default(node.mesh && defined_default(gltf.meshes))) {
const mesh = gltf.meshes[node.mesh];
if (defined_default(mesh) && defined_default(mesh.primitives) && mesh.primitives.length > 0) {
usedMeshIds[node.mesh] = true;
}
}
});
return usedMeshIds;
};
function nodeIsEmpty(gltf, nodeId, usedNodeIds) {
const node = gltf.nodes[nodeId];
if (defined_default(node.mesh) || defined_default(node.camera) || defined_default(node.skin) || defined_default(node.weights) || defined_default(node.extras) || defined_default(node.extensions) && Object.keys(node.extensions).length !== 0 || defined_default(usedNodeIds[nodeId])) {
return false;
}
return !defined_default(node.children) || node.children.filter(function(n) {
return !nodeIsEmpty(gltf, n, usedNodeIds);
}).length === 0;
}
getListOfElementsIdsInUse.node = function(gltf) {
const usedNodeIds = {};
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.skeleton)) {
usedNodeIds[skin.skeleton] = true;
}
ForEach_default.skinJoint(skin, function(joint) {
usedNodeIds[joint] = true;
});
});
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationChannel(animation, function(channel) {
if (defined_default(channel.target) && defined_default(channel.target.node)) {
usedNodeIds[channel.target.node] = true;
}
});
});
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueUniform(technique, function(uniform) {
if (defined_default(uniform.node)) {
usedNodeIds[uniform.node] = true;
}
});
});
ForEach_default.node(gltf, function(node, nodeId) {
if (!nodeIsEmpty(gltf, nodeId, usedNodeIds)) {
usedNodeIds[nodeId] = true;
}
});
return usedNodeIds;
};
getListOfElementsIdsInUse.material = function(gltf) {
const usedMaterialIds = {};
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.material)) {
usedMaterialIds[primitive.material] = true;
}
});
});
return usedMaterialIds;
};
getListOfElementsIdsInUse.texture = function(gltf) {
const usedTextureIds = {};
ForEach_default.material(gltf, function(material) {
forEachTextureInMaterial_default(material, function(textureId) {
usedTextureIds[textureId] = true;
});
});
if (usesExtension_default(gltf, "EXT_feature_metadata")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_feature_metadata)) {
const extension2 = extensions.EXT_feature_metadata;
const featureIdTextures = extension2.featureIdTextures;
if (defined_default(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_default(properties)) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
const textureInfo = property.texture;
usedTextureIds[textureInfo.index] = true;
}
}
}
}
}
}
if (usesExtension_default(gltf, "EXT_mesh_features")) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
const extensions = primitive.extensions;
if (defined_default(extensions) && defined_default(extensions.EXT_mesh_features)) {
const extension = extensions.EXT_mesh_features;
const featureIds = extension.featureIds;
if (defined_default(featureIds)) {
const featureIdsLength = featureIds.length;
for (let i = 0; i < featureIdsLength; ++i) {
const featureId = featureIds[i];
if (defined_default(featureId.texture)) {
usedTextureIds[featureId.texture.index] = true;
}
}
}
}
});
});
}
if (usesExtension_default(gltf, "EXT_structural_metadata")) {
const extension = gltf.extensions.EXT_structural_metadata;
const propertyTextures = extension.propertyTextures;
if (defined_default(propertyTextures)) {
const propertyTexturesLength = propertyTextures.length;
for (let i = 0; i < propertyTexturesLength; ++i) {
const propertyTexture = propertyTextures[i];
const properties = propertyTexture.properties;
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
usedTextureIds[property.index] = true;
}
}
}
}
}
return usedTextureIds;
};
getListOfElementsIdsInUse.sampler = function(gltf) {
const usedSamplerIds = {};
ForEach_default.texture(gltf, function(texture) {
if (defined_default(texture.sampler)) {
usedSamplerIds[texture.sampler] = true;
}
});
return usedSamplerIds;
};
var removeUnusedElements_default = removeUnusedElements;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/addBuffer.js
function addBuffer(gltf, buffer) {
const newBuffer = {
byteLength: buffer.length,
extras: {
_pipeline: {
source: buffer
}
}
};
const bufferId = addToArray_default(gltf.buffers, newBuffer);
const bufferView = {
buffer: bufferId,
byteOffset: 0,
byteLength: buffer.length
};
return addToArray_default(gltf.bufferViews, bufferView);
}
var addBuffer_default = addBuffer;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/readAccessorPacked.js
function readAccessorPacked(gltf, accessor) {
const byteStride = getAccessorByteStride_default(gltf, accessor);
const componentTypeByteLength = ComponentDatatype_default.getSizeInBytes(
accessor.componentType
);
const numberOfComponents = numberOfComponentsForType_default(accessor.type);
const count = accessor.count;
const values = new Array(numberOfComponents * count);
if (!defined_default(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_default(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;
}
var readAccessorPacked_default = readAccessorPacked;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/updateAccessorComponentTypes.js
function updateAccessorComponentTypes(gltf) {
let componentType;
ForEach_default.accessorWithSemantic(gltf, "JOINTS_0", function(accessorId) {
const accessor = gltf.accessors[accessorId];
componentType = accessor.componentType;
if (componentType === WebGLConstants_default.BYTE) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_BYTE);
} else if (componentType !== WebGLConstants_default.UNSIGNED_BYTE && componentType !== WebGLConstants_default.UNSIGNED_SHORT) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_SHORT);
}
});
ForEach_default.accessorWithSemantic(gltf, "WEIGHTS_0", function(accessorId) {
const accessor = gltf.accessors[accessorId];
componentType = accessor.componentType;
if (componentType === WebGLConstants_default.BYTE) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_BYTE);
} else if (componentType === WebGLConstants_default.SHORT) {
convertType(gltf, accessor, ComponentDatatype_default.UNSIGNED_SHORT);
}
});
return gltf;
}
function convertType(gltf, accessor, updatedComponentType) {
const typedArray = ComponentDatatype_default.createTypedArray(
updatedComponentType,
readAccessorPacked_default(gltf, accessor)
);
const newBuffer = new Uint8Array(typedArray.buffer);
accessor.bufferView = addBuffer_default(gltf, newBuffer);
accessor.componentType = updatedComponentType;
accessor.byteOffset = 0;
}
var updateAccessorComponentTypes_default = updateAccessorComponentTypes;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/removeExtension.js
function removeExtension(gltf, extension) {
removeExtensionsUsed_default(gltf, extension);
if (extension === "CESIUM_RTC") {
removeCesiumRTC(gltf);
}
return removeExtensionAndTraverse(gltf, extension);
}
function removeCesiumRTC(gltf) {
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueUniform(technique, function(uniform) {
if (uniform.semantic === "CESIUM_RTC_MODELVIEW") {
uniform.semantic = "MODELVIEW";
}
});
});
}
function removeExtensionAndTraverse(object, extension) {
if (Array.isArray(object)) {
const length3 = object.length;
for (let i = 0; i < length3; ++i) {
removeExtensionAndTraverse(object[i], extension);
}
} else if (object !== null && typeof object === "object" && object.constructor === Object) {
const extensions = object.extensions;
let extensionData;
if (defined_default(extensions)) {
extensionData = extensions[extension];
if (defined_default(extensionData)) {
delete extensions[extension];
if (Object.keys(extensions).length === 0) {
delete object.extensions;
}
}
}
for (const key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
removeExtensionAndTraverse(object[key], extension);
}
}
return extensionData;
}
}
var removeExtension_default = removeExtension;
// node_modules/@cesium/engine/Source/Scene/GltfPipeline/updateVersion.js
var updateFunctions = {
0.8: glTF08to10,
"1.0": glTF10to20,
"2.0": void 0
};
function updateVersion(gltf, options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const targetVersion = options.targetVersion;
let version2 = gltf.version;
gltf.asset = defaultValue_default(gltf.asset, {
version: "1.0"
});
gltf.asset.version = defaultValue_default(gltf.asset.version, "1.0");
version2 = defaultValue_default(version2, gltf.asset.version).toString();
if (!Object.prototype.hasOwnProperty.call(updateFunctions, version2)) {
if (defined_default(version2)) {
version2 = version2.substring(0, 3);
}
if (!Object.prototype.hasOwnProperty.call(updateFunctions, version2)) {
version2 = "1.0";
}
}
let updateFunction = updateFunctions[version2];
while (defined_default(updateFunction)) {
if (version2 === targetVersion) {
break;
}
updateFunction(gltf, options);
version2 = gltf.asset.version;
updateFunction = updateFunctions[version2];
}
if (!options.keepLegacyExtensions) {
convertTechniquesToPbr(gltf);
convertMaterialsCommonToPbr(gltf);
}
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_default(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_default(primitives)) {
const primitivesLength = primitives.length;
for (let i = 0; i < primitivesLength; ++i) {
const primitive = primitives[i];
const defaultMode = defaultValue_default(
primitive.primitive,
WebGLConstants_default.TRIANGLES
);
primitive.mode = defaultValue_default(primitive.mode, defaultMode);
delete primitive.primitive;
}
}
}
}
}
function updateNodes(gltf) {
const nodes = gltf.nodes;
const axis = new Cartesian3_default();
const quat = new Quaternion_default();
for (const nodeId in nodes) {
if (Object.prototype.hasOwnProperty.call(nodes, nodeId)) {
const node = nodes[nodeId];
if (defined_default(node.rotation)) {
const rotation = node.rotation;
Cartesian3_default.fromArray(rotation, 0, axis);
Quaternion_default.fromAxisAngle(axis, rotation[3], quat);
node.rotation = [quat.x, quat.y, quat.z, quat.w];
}
const instanceSkin = node.instanceSkin;
if (defined_default(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_default();
const quat = new Quaternion_default();
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_default(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_default(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_default(accessor.type);
const length3 = accessor.count * componentsLength;
const typedArray = ComponentDatatype_default.createArrayBufferView(
componentType,
source.buffer,
byteOffset,
length3
);
for (let j = 0; j < count; j++) {
const offset2 = j * componentsLength;
Cartesian3_default.unpack(typedArray, offset2, axis);
const angle = typedArray[offset2 + 3];
Quaternion_default.fromAxisAngle(axis, angle, quat);
Quaternion_default.pack(quat, typedArray, offset2);
}
}
}
}
}
}
}
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_default(passes)) {
const passName = defaultValue_default(technique.pass, "defaultPass");
if (Object.prototype.hasOwnProperty.call(passes, passName)) {
const pass = passes[passName];
const instanceProgram = pass.instanceProgram;
technique.attributes = defaultValue_default(
technique.attributes,
instanceProgram.attributes
);
technique.program = defaultValue_default(
technique.program,
instanceProgram.program
);
technique.uniforms = defaultValue_default(
technique.uniforms,
instanceProgram.uniforms
);
technique.states = defaultValue_default(technique.states, pass.states);
}
delete technique.passes;
delete technique.pass;
}
}
}
}
function glTF08to10(gltf) {
if (!defined_default(gltf.asset)) {
gltf.asset = {};
}
const asset = gltf.asset;
asset.version = "1.0";
if (typeof asset.profile === "string") {
const split = asset.profile.split(" ");
asset.profile = {
api: split[0],
version: split[1]
};
} else {
asset.profile = {};
}
if (defined_default(gltf.version)) {
delete gltf.version;
}
updateInstanceTechniques(gltf);
setPrimitiveModes(gltf);
updateNodes(gltf);
updateAnimations(gltf);
removeTechniquePasses(gltf);
if (defined_default(gltf.allExtensions)) {
gltf.extensionsUsed = gltf.allExtensions;
delete gltf.allExtensions;
}
if (defined_default(gltf.lights)) {
const extensions = defaultValue_default(gltf.extensions, {});
gltf.extensions = extensions;
const materialsCommon = defaultValue_default(extensions.KHR_materials_common, {});
extensions.KHR_materials_common = materialsCommon;
materialsCommon.lights = gltf.lights;
delete gltf.lights;
addExtensionsUsed_default(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_default(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_default(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: {}
};
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_default(jointName)) {
jointNameToId[jointName] = id;
}
}
}
for (const topLevelId in gltf) {
if (Object.prototype.hasOwnProperty.call(gltf, topLevelId) && defined_default(globalMapping[topLevelId])) {
const objectMapping = {};
const object = gltf[topLevelId];
gltf[topLevelId] = objectToArray(object, objectMapping);
globalMapping[topLevelId] = objectMapping;
}
}
for (jointName in jointNameToId) {
if (Object.prototype.hasOwnProperty.call(jointNameToId, jointName)) {
jointNameToId[jointName] = globalMapping.nodes[jointNameToId[jointName]];
}
}
if (defined_default(gltf.scene)) {
gltf.scene = globalMapping.scenes[gltf.scene];
}
ForEach_default.bufferView(gltf, function(bufferView) {
if (defined_default(bufferView.buffer)) {
bufferView.buffer = globalMapping.buffers[bufferView.buffer];
}
});
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
accessor.bufferView = globalMapping.bufferViews[accessor.bufferView];
}
});
ForEach_default.shader(gltf, function(shader) {
const extensions = shader.extensions;
if (defined_default(extensions)) {
const binaryGltf = extensions.KHR_binary_glTF;
if (defined_default(binaryGltf)) {
shader.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];
delete extensions.KHR_binary_glTF;
}
if (Object.keys(extensions).length === 0) {
delete shader.extensions;
}
}
});
ForEach_default.program(gltf, function(program) {
if (defined_default(program.vertexShader)) {
program.vertexShader = globalMapping.shaders[program.vertexShader];
}
if (defined_default(program.fragmentShader)) {
program.fragmentShader = globalMapping.shaders[program.fragmentShader];
}
});
ForEach_default.technique(gltf, function(technique) {
if (defined_default(technique.program)) {
technique.program = globalMapping.programs[technique.program];
}
ForEach_default.techniqueParameter(technique, function(parameter) {
if (defined_default(parameter.node)) {
parameter.node = globalMapping.nodes[parameter.node];
}
const value = parameter.value;
if (typeof value === "string") {
parameter.value = {
index: globalMapping.textures[value]
};
}
});
});
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
if (defined_default(primitive.indices)) {
primitive.indices = globalMapping.accessors[primitive.indices];
}
ForEach_default.meshPrimitiveAttribute(
primitive,
function(accessorId, semantic) {
primitive.attributes[semantic] = globalMapping.accessors[accessorId];
}
);
if (defined_default(primitive.material)) {
primitive.material = globalMapping.materials[primitive.material];
}
});
});
ForEach_default.node(gltf, function(node) {
let children = node.children;
if (defined_default(children)) {
const childrenLength = children.length;
for (i = 0; i < childrenLength; ++i) {
children[i] = globalMapping.nodes[children[i]];
}
}
if (defined_default(node.meshes)) {
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_default(gltf.nodes, meshNode);
if (!defined_default(children)) {
children = [];
node.children = children;
}
children.push(meshNodeId);
}
}
delete node.meshes;
}
if (defined_default(node.camera)) {
node.camera = globalMapping.cameras[node.camera];
}
if (defined_default(node.skin)) {
node.skin = globalMapping.skins[node.skin];
}
if (defined_default(node.skeletons)) {
const skeletons = node.skeletons;
const skeletonsLength = skeletons.length;
if (skeletonsLength > 0 && defined_default(node.skin)) {
const skin = gltf.skins[node.skin];
skin.skeleton = globalMapping.nodes[skeletons[0]];
}
delete node.skeletons;
}
if (defined_default(node.jointName)) {
delete node.jointName;
}
});
ForEach_default.skin(gltf, function(skin) {
if (defined_default(skin.inverseBindMatrices)) {
skin.inverseBindMatrices = globalMapping.accessors[skin.inverseBindMatrices];
}
const jointNames = skin.jointNames;
if (defined_default(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_default.scene(gltf, function(scene) {
const sceneNodes = scene.nodes;
if (defined_default(sceneNodes)) {
const sceneNodesLength = sceneNodes.length;
for (i = 0; i < sceneNodesLength; ++i) {
sceneNodes[i] = globalMapping.nodes[sceneNodes[i]];
}
}
});
ForEach_default.animation(gltf, function(animation) {
const samplerMapping = {};
animation.samplers = objectToArray(animation.samplers, samplerMapping);
ForEach_default.animationSampler(animation, function(sampler) {
sampler.input = globalMapping.accessors[sampler.input];
sampler.output = globalMapping.accessors[sampler.output];
});
ForEach_default.animationChannel(animation, function(channel) {
channel.sampler = samplerMapping[channel.sampler];
const target = channel.target;
if (defined_default(target)) {
target.node = globalMapping.nodes[target.id];
delete target.id;
}
});
});
ForEach_default.material(gltf, function(material) {
if (defined_default(material.technique)) {
material.technique = globalMapping.techniques[material.technique];
}
ForEach_default.materialValue(material, function(value, name) {
if (typeof value === "string") {
material.values[name] = {
index: globalMapping.textures[value]
};
}
});
const extensions = material.extensions;
if (defined_default(extensions)) {
const materialsCommon = extensions.KHR_materials_common;
if (defined_default(materialsCommon) && defined_default(materialsCommon.values)) {
ForEach_default.materialValue(materialsCommon, function(value, name) {
if (typeof value === "string") {
materialsCommon.values[name] = {
index: globalMapping.textures[value]
};
}
});
}
}
});
ForEach_default.image(gltf, function(image) {
const extensions = image.extensions;
if (defined_default(extensions)) {
const binaryGltf = extensions.KHR_binary_glTF;
if (defined_default(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_default.texture(gltf, function(texture) {
if (defined_default(texture.sampler)) {
texture.sampler = globalMapping.samplers[texture.sampler];
}
if (defined_default(texture.source)) {
texture.source = globalMapping.images[texture.source];
}
});
}
function removeAnimationSamplerNames(gltf) {
ForEach_default.animation(gltf, function(animation) {
ForEach_default.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_default.node(gltf, function(node) {
if (defined_default(node.children) && node.children.length === 0) {
delete node.children;
}
});
}
function stripAsset(gltf) {
const asset = gltf.asset;
delete asset.profile;
delete asset.premultipliedAlpha;
}
var knownExtensions = {
CESIUM_RTC: true,
KHR_materials_common: true,
WEB3D_quantized_attributes: true
};
function requireKnownExtensions(gltf) {
const extensionsUsed = gltf.extensionsUsed;
gltf.extensionsRequired = defaultValue_default(gltf.extensionsRequired, []);
if (defined_default(extensionsUsed)) {
const extensionsUsedLength = extensionsUsed.length;
for (let i = 0; i < extensionsUsedLength; ++i) {
const extension = extensionsUsed[i];
if (defined_default(knownExtensions[extension])) {
gltf.extensionsRequired.push(extension);
}
}
}
}
function removeBufferType(gltf) {
ForEach_default.buffer(gltf, function(buffer) {
delete buffer.type;
});
}
function removeTextureProperties(gltf) {
ForEach_default.texture(gltf, function(texture) {
delete texture.format;
delete texture.internalFormat;
delete texture.target;
delete texture.type;
});
}
function requireAttributeSetIndex(gltf) {
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.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_default.technique(gltf, function(technique) {
ForEach_default.techniqueParameter(technique, function(parameter) {
const semantic = parameter.semantic;
if (defined_default(semantic)) {
if (semantic === "TEXCOORD") {
parameter.semantic = "TEXCOORD_0";
} else if (semantic === "COLOR") {
parameter.semantic = "COLOR_0";
}
}
});
});
}
var knownSemantics = {
POSITION: true,
NORMAL: true,
TANGENT: true
};
var indexedSemantics = {
COLOR: "COLOR",
JOINT: "JOINTS",
JOINTS: "JOINTS",
TEXCOORD: "TEXCOORD",
WEIGHT: "WEIGHTS",
WEIGHTS: "WEIGHTS"
};
function underscoreApplicationSpecificSemantics(gltf) {
const mappedSemantics = {};
ForEach_default.mesh(gltf, function(mesh) {
ForEach_default.meshPrimitive(mesh, function(primitive) {
ForEach_default.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_default(indexedSemantic)) {
newSemantic = indexedSemantic + suffix;
mappedSemantics[semantic] = newSemantic;
} else if (!defined_default(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_default(accessorId)) {
delete primitive.attributes[semantic];
primitive.attributes[mappedSemantic] = accessorId;
}
}
}
});
});
ForEach_default.technique(gltf, function(technique) {
ForEach_default.techniqueParameter(technique, function(parameter) {
const mappedSemantic = mappedSemantics[parameter.semantic];
if (defined_default(mappedSemantic)) {
parameter.semantic = mappedSemantic;
}
});
});
}
function clampCameraParameters(gltf) {
ForEach_default.camera(gltf, function(camera) {
const perspective = camera.perspective;
if (defined_default(perspective)) {
const aspectRatio = perspective.aspectRatio;
if (defined_default(aspectRatio) && aspectRatio === 0) {
delete perspective.aspectRatio;
}
const yfov = perspective.yfov;
if (defined_default(yfov) && yfov === 0) {
perspective.yfov = 1;
}
}
});
}
function computeAccessorByteStride(gltf, accessor) {
return defined_default(accessor.byteStride) && accessor.byteStride !== 0 ? accessor.byteStride : getAccessorByteStride_default(gltf, accessor);
}
function requireByteLength(gltf) {
ForEach_default.buffer(gltf, function(buffer) {
if (!defined_default(buffer.byteLength)) {
buffer.byteLength = buffer.extras._pipeline.source.length;
}
});
ForEach_default.accessor(gltf, function(accessor) {
const bufferViewId = accessor.bufferView;
if (defined_default(bufferViewId)) {
const bufferView = gltf.bufferViews[bufferViewId];
const accessorByteStride = computeAccessorByteStride(gltf, accessor);
const accessorByteEnd = accessor.byteOffset + accessor.count * accessorByteStride;
bufferView.byteLength = Math.max(
defaultValue_default(bufferView.byteLength, 0),
accessorByteEnd
);
}
});
}
function moveByteStrideToBufferView(gltf) {
let i;
let j;
let bufferView;
const bufferViews = gltf.bufferViews;
const bufferViewHasVertexAttributes = {};
ForEach_default.accessorContainingVertexAttributeData(gltf, function(accessorId) {
const accessor = gltf.accessors[accessorId];
if (defined_default(accessor.bufferView)) {
bufferViewHasVertexAttributes[accessor.bufferView] = true;
}
});
const bufferViewMap = {};
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.bufferView)) {
bufferViewMap[accessor.bufferView] = defaultValue_default(
bufferViewMap[accessor.bufferView],
[]
);
bufferViewMap[accessor.bufferView].push(accessor);
}
});
for (const bufferViewId in bufferViewMap) {
if (Object.prototype.hasOwnProperty.call(bufferViewMap, bufferViewId)) {
bufferView = bufferViews[bufferViewId];
const accessors = bufferViewMap[bufferViewId];
accessors.sort(function(a3, b) {
return a3.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]) : void 0;
if (accessorByteStride !== nextAccessorByteStride) {
const newBufferView = clone_default(bufferView, true);
if (bufferViewHasVertexAttributes[bufferViewId]) {
newBufferView.byteStride = accessorByteStride;
}
newBufferView.byteOffset += currentByteOffset;
newBufferView.byteLength = accessorByteOffset + accessorByteLength - currentByteOffset;
const newBufferViewId = addToArray_default(bufferViews, newBufferView);
for (j = currentIndex; j <= i; ++j) {
accessor = accessors[j];
accessor.bufferView = newBufferViewId;
accessor.byteOffset = accessor.byteOffset - currentByteOffset;
}
currentByteOffset = hasNextAccessor ? accessors[i + 1].byteOffset : void 0;
currentIndex = i + 1;
}
}
}
}
removeUnusedElements_default(gltf, ["accessor", "bufferView", "buffer"]);
}
function requirePositionAccessorMinMax(gltf) {
ForEach_default.accessorWithSemantic(gltf, "POSITION", function(accessorId) {
const accessor = gltf.accessors[accessorId];
if (!defined_default(accessor.min) || !defined_default(accessor.max)) {
const minMax = findAccessorMinMax_default(gltf, accessor);
accessor.min = minMax.min;
accessor.max = minMax.max;
}
});
}
function isNodeEmpty(node) {
return (!defined_default(node.children) || node.children.length === 0) && (!defined_default(node.meshes) || node.meshes.length === 0) && !defined_default(node.camera) && !defined_default(node.skin) && !defined_default(node.skeletons) && !defined_default(node.jointName) && (!defined_default(node.translation) || Cartesian3_default.fromArray(node.translation).equals(Cartesian3_default.ZERO)) && (!defined_default(node.scale) || Cartesian3_default.fromArray(node.scale).equals(new Cartesian3_default(1, 1, 1))) && (!defined_default(node.rotation) || Cartesian4_default.fromArray(node.rotation).equals(
new Cartesian4_default(0, 0, 0, 1)
)) && (!defined_default(node.matrix) || Matrix4_default.fromColumnMajorArray(node.matrix).equals(Matrix4_default.IDENTITY)) && !defined_default(node.extensions) && !defined_default(node.extras);
}
function deleteNode(gltf, nodeId) {
ForEach_default.scene(gltf, function(scene) {
const sceneNodes = scene.nodes;
if (defined_default(sceneNodes)) {
const sceneNodesLength = sceneNodes.length;
for (let i = sceneNodesLength; i >= 0; --i) {
if (sceneNodes[i] === nodeId) {
sceneNodes.splice(i, 1);
return;
}
}
}
});
ForEach_default.node(gltf, function(parentNode, parentNodeId) {
if (defined_default(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_default.node(gltf, function(node, nodeId) {
if (isNodeEmpty(node)) {
deleteNode(gltf, nodeId);
}
});
return gltf;
}
function requireAnimationAccessorMinMax(gltf) {
ForEach_default.animation(gltf, function(animation) {
ForEach_default.animationSampler(animation, function(sampler) {
const accessor = gltf.accessors[sampler.input];
if (!defined_default(accessor.min) || !defined_default(accessor.max)) {
const minMax = findAccessorMinMax_default(gltf, accessor);
accessor.min = minMax.min;
accessor.max = minMax.max;
}
});
});
}
function validatePresentAccessorMinMax(gltf) {
ForEach_default.accessor(gltf, function(accessor) {
if (defined_default(accessor.min) || defined_default(accessor.max)) {
const minMax = findAccessorMinMax_default(gltf, accessor);
if (defined_default(accessor.min)) {
accessor.min = minMax.min;
}
if (defined_default(accessor.max)) {
accessor.max = minMax.max;
}
}
});
}
function glTF10to20(gltf) {
gltf.asset = defaultValue_default(gltf.asset, {});
gltf.asset.version = "2.0";
updateInstanceTechniques(gltf);
removeAnimationSamplersIndirection(gltf);
removeEmptyNodes(gltf);
objectsToArrays(gltf);
removeAnimationSamplerNames(gltf);
stripAsset(gltf);
requireKnownExtensions(gltf);
requireByteLength(gltf);
moveByteStrideToBufferView(gltf);
requirePositionAccessorMinMax(gltf);
requireAnimationAccessorMinMax(gltf);
validatePresentAccessorMinMax(gltf);
removeBufferType(gltf);
removeTextureProperties(gltf);
requireAttributeSetIndex(gltf);
underscoreApplicationSpecificSemantics(gltf);
updateAccessorComponentTypes_default(gltf);
clampCameraParameters(gltf);
moveTechniqueRenderStates_default(gltf);
moveTechniquesToExtension_default(gltf);
removeEmptyArrays(gltf);
}
var baseColorTextureNames = ["u_tex", "u_diffuse", "u_emission"];
var baseColorFactorNames = ["u_diffuse"];
function initializePbrMaterial(material) {
material.pbrMetallicRoughness = defined_default(material.pbrMetallicRoughness) ? material.pbrMetallicRoughness : {};
material.pbrMetallicRoughness.roughnessFactor = 1;
material.pbrMetallicRoughness.metallicFactor = 0;
}
function isTexture(value) {
return defined_default(value.index);
}
function isVec4(value) {
return Array.isArray(value) && value.length === 4;
}
function srgbToLinear(srgb) {
const linear = new Array(4);
linear[3] = srgb[3];
for (let i = 0; i < 3; i++) {
const c = srgb[i];
if (c <= 0.04045) {
linear[i] = srgb[i] * 0.07739938080495357;
} else {
linear[i] = Math.pow(
(c + 0.055) * 0.9478672985781991,
2.4
);
}
}
return linear;
}
function convertTechniquesToPbr(gltf) {
ForEach_default.material(gltf, function(material) {
ForEach_default.materialValue(material, function(value, name) {
if (baseColorTextureNames.indexOf(name) !== -1 && isTexture(value)) {
initializePbrMaterial(material);
material.pbrMetallicRoughness.baseColorTexture = value;
} else if (baseColorFactorNames.indexOf(name) !== -1 && isVec4(value)) {
initializePbrMaterial(material);
material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(value);
}
});
});
removeExtension_default(gltf, "KHR_techniques_webgl");
removeExtension_default(gltf, "KHR_blend");
}
function convertMaterialsCommonToPbr(gltf) {
ForEach_default.material(gltf, function(material) {
const materialsCommon = defaultValue_default(
material.extensions,
defaultValue_default.EMPTY_OBJECT
).KHR_materials_common;
if (defined_default(materialsCommon)) {
const technique = materialsCommon.technique;
if (technique === "CONSTANT") {
addExtensionsUsed_default(gltf, "KHR_materials_unlit");
material.extensions = defined_default(material.extensions) ? material.extensions : {};
material.extensions["KHR_materials_unlit"] = {};
}
const values = defined_default(materialsCommon.values) ? materialsCommon.values : {};
const ambient = values.ambient;
const diffuse = values.diffuse;
const emission = values.emission;
const transparency = values.transparency;
const doubleSided = materialsCommon.doubleSided;
const transparent = materialsCommon.transparent;
initializePbrMaterial(material);
if (defined_default(ambient)) {
if (isVec4(ambient)) {
material.emissiveFactor = ambient.slice(0, 3);
} else if (isTexture(ambient)) {
material.emissiveTexture = ambient;
}
}
if (defined_default(diffuse)) {
if (isVec4(diffuse)) {
material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(diffuse);
} else if (isTexture(diffuse)) {
material.pbrMetallicRoughness.baseColorTexture = diffuse;
}
}
if (defined_default(doubleSided)) {
material.doubleSided = doubleSided;
}
if (defined_default(emission)) {
if (isVec4(emission)) {
material.emissiveFactor = emission.slice(0, 3);
} else if (isTexture(emission)) {
material.emissiveTexture = emission;
}
}
if (defined_default(transparency)) {
if (defined_default(material.pbrMetallicRoughness.baseColorFactor)) {
material.pbrMetallicRoughness.baseColorFactor[3] *= transparency;
} else {
material.pbrMetallicRoughness.baseColorFactor = [
1,
1,
1,
transparency
];
}
}
if (defined_default(transparent)) {
material.alphaMode = transparent ? "BLEND" : "OPAQUE";
}
}
});
removeExtension_default(gltf, "KHR_materials_common");
}
var updateVersion_default = updateVersion;
// node_modules/@cesium/engine/Source/Scene/VertexAttributeSemantic.js
var VertexAttributeSemantic = {
POSITION: "POSITION",
NORMAL: "NORMAL",
TANGENT: "TANGENT",
TEXCOORD: "TEXCOORD",
COLOR: "COLOR",
JOINTS: "JOINTS",
WEIGHTS: "WEIGHTS",
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";
default:
throw new DeveloperError_default("semantic is not a valid value.");
}
}
VertexAttributeSemantic.hasSetIndex = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
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;
default:
throw new DeveloperError_default("semantic is not a valid value.");
}
};
VertexAttributeSemantic.fromGltfSemantic = function(gltfSemantic) {
Check_default.typeOf.string("gltfSemantic", gltfSemantic);
let semantic = gltfSemantic;
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 void 0;
};
VertexAttributeSemantic.fromPntsSemantic = function(pntsSemantic) {
Check_default.typeOf.string("pntsSemantic", pntsSemantic);
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;
default:
throw new DeveloperError_default("pntsSemantic is not a valid value.");
}
};
VertexAttributeSemantic.getGlslType = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
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";
default:
throw new DeveloperError_default("semantic is not a valid value.");
}
};
VertexAttributeSemantic.getVariableName = function(semantic, setIndex) {
Check_default.typeOf.string("semantic", semantic);
let variableName = semanticToVariableName(semantic);
if (defined_default(setIndex)) {
variableName += `_${setIndex}`;
}
return variableName;
};
var VertexAttributeSemantic_default = Object.freeze(VertexAttributeSemantic);
// node_modules/@cesium/engine/Source/Scene/Model/ModelUtility.js
function ModelUtility() {
}
ModelUtility.getError = function(type, path, error) {
let message = `Failed to load ${type}: ${path}`;
if (defined_default(error) && defined_default(error.message)) {
message += `
${error.message}`;
}
const runtimeError = new RuntimeError_default(message);
if (defined_default(error)) {
runtimeError.stack = `Original stack:
${error.stack}
Handler stack:
${runtimeError.stack}`;
}
return runtimeError;
};
ModelUtility.getNodeTransform = function(node) {
if (defined_default(node.matrix)) {
return node.matrix;
}
return Matrix4_default.fromTranslationQuaternionRotationScale(
defined_default(node.translation) ? node.translation : Cartesian3_default.ZERO,
defined_default(node.rotation) ? node.rotation : Quaternion_default.IDENTITY,
defined_default(node.scale) ? node.scale : Cartesian3_default.ONE
);
};
ModelUtility.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_default(setIndex) ? attribute.setIndex === setIndex : true;
if (attribute.semantic === semantic && matchesSetIndex) {
return attribute;
}
}
return void 0;
};
ModelUtility.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;
}
}
return void 0;
};
ModelUtility.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 void 0;
};
ModelUtility.hasQuantizedAttributes = function(attributes) {
if (!defined_default(attributes)) {
return false;
}
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
if (defined_default(attribute.quantization)) {
return true;
}
}
return false;
};
ModelUtility.getAttributeInfo = function(attribute) {
const semantic = attribute.semantic;
const setIndex = attribute.setIndex;
let variableName;
let hasSemantic = false;
if (defined_default(semantic)) {
variableName = VertexAttributeSemantic_default.getVariableName(semantic, setIndex);
hasSemantic = true;
} else {
variableName = attribute.name;
variableName = variableName.replace(/^_/, "");
variableName = variableName.toLowerCase();
}
const isVertexColor = /^color_\d+$/.test(variableName);
const attributeType = attribute.type;
let glslType = AttributeType_default.getGlslType(attributeType);
if (isVertexColor) {
glslType = "vec4";
}
const isQuantized = defined_default(attribute.quantization);
let quantizedGlslType;
if (isQuantized) {
quantizedGlslType = isVertexColor ? "vec4" : AttributeType_default.getGlslType(attribute.quantization.type);
}
return {
attribute,
isQuantized,
variableName,
hasSemantic,
glslType,
quantizedGlslType
};
};
var cartesianMaxScratch = new Cartesian3_default();
var cartesianMinScratch = new Cartesian3_default();
ModelUtility.getPositionMinMax = function(primitive, instancingTranslationMin, instancingTranslationMax) {
const positionGltfAttribute = ModelUtility.getAttributeBySemantic(
primitive,
"POSITION"
);
let positionMax = positionGltfAttribute.max;
let positionMin = positionGltfAttribute.min;
if (defined_default(instancingTranslationMax) && defined_default(instancingTranslationMin)) {
positionMin = Cartesian3_default.add(
positionMin,
instancingTranslationMin,
cartesianMinScratch
);
positionMax = Cartesian3_default.add(
positionMax,
instancingTranslationMax,
cartesianMaxScratch
);
}
return {
min: positionMin,
max: positionMax
};
};
ModelUtility.getAxisCorrectionMatrix = function(upAxis, forwardAxis, result) {
result = Matrix4_default.clone(Matrix4_default.IDENTITY, result);
if (upAxis === Axis_default.Y) {
result = Matrix4_default.clone(Axis_default.Y_UP_TO_Z_UP, result);
} else if (upAxis === Axis_default.X) {
result = Matrix4_default.clone(Axis_default.X_UP_TO_Z_UP, result);
}
if (forwardAxis === Axis_default.Z) {
result = Matrix4_default.multiplyTransformation(result, Axis_default.Z_UP_TO_X_UP, result);
}
return result;
};
var scratchMatrix32 = new Matrix3_default();
ModelUtility.getCullFace = function(modelMatrix, primitiveType) {
if (!PrimitiveType_default.isTriangles(primitiveType)) {
return CullFace_default.BACK;
}
const matrix3 = Matrix4_default.getMatrix3(modelMatrix, scratchMatrix32);
return Matrix3_default.determinant(matrix3) < 0 ? CullFace_default.FRONT : CullFace_default.BACK;
};
ModelUtility.sanitizeGlslIdentifier = function(identifier) {
let sanitizedIdentifier = identifier.replaceAll(/[^A-Za-z0-9]+/g, "_");
sanitizedIdentifier = sanitizedIdentifier.replace(/^gl_/, "");
if (/^\d/.test(sanitizedIdentifier)) {
sanitizedIdentifier = `_${sanitizedIdentifier}`;
}
return sanitizedIdentifier;
};
ModelUtility.supportedExtensions = {
AGI_articulations: true,
CESIUM_primitive_outline: true,
CESIUM_RTC: true,
EXT_feature_metadata: true,
EXT_instance_features: true,
EXT_mesh_features: true,
EXT_mesh_gpu_instancing: true,
EXT_meshopt_compression: true,
EXT_structural_metadata: true,
EXT_texture_webp: true,
KHR_blend: true,
KHR_draco_mesh_compression: true,
KHR_techniques_webgl: true,
KHR_materials_common: true,
KHR_materials_pbrSpecularGlossiness: true,
KHR_materials_unlit: true,
KHR_mesh_quantization: true,
KHR_texture_basisu: true,
KHR_texture_transform: true,
WEB3D_quantized_attributes: true
};
ModelUtility.checkSupportedExtensions = function(extensionsRequired) {
const length3 = extensionsRequired.length;
for (let i = 0; i < length3; i++) {
const extension = extensionsRequired[i];
if (!ModelUtility.supportedExtensions[extension]) {
throw new RuntimeError_default(`Unsupported glTF Extension: ${extension}`);
}
}
};
var ModelUtility_default = ModelUtility;
// node_modules/@cesium/engine/Source/Scene/GltfJsonLoader.js
function GltfJsonLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const typedArray = options.typedArray;
const gltfJson = options.gltfJson;
const cacheKey = options.cacheKey;
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._typedArray = typedArray;
this._gltfJson = gltfJson;
this._cacheKey = cacheKey;
this._gltf = void 0;
this._bufferLoaders = [];
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfJsonLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfJsonLoader.prototype.constructor = GltfJsonLoader;
}
Object.defineProperties(GltfJsonLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
gltf: {
get: function() {
return this._gltf;
}
}
});
GltfJsonLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
if (defined_default(this._gltfJson)) {
this._promise = processGltfJson(this, this._gltfJson);
return this._promise;
}
if (defined_default(this._typedArray)) {
this._promise = processGltfTypedArray(this, this._typedArray);
return this._promise;
}
this._promise = loadFromUri2(this);
return this._promise;
};
async function loadFromUri2(gltfJsonLoader) {
let typedArray;
try {
const arrayBuffer = await gltfJsonLoader._fetchGltf();
if (gltfJsonLoader.isDestroyed()) {
return;
}
typedArray = new Uint8Array(arrayBuffer);
} catch (error) {
if (gltfJsonLoader.isDestroyed()) {
return;
}
handleError4(gltfJsonLoader, error);
}
return processGltfTypedArray(gltfJsonLoader, typedArray);
}
function handleError4(gltfJsonLoader, error) {
gltfJsonLoader.unload();
gltfJsonLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = `Failed to load glTF: ${gltfJsonLoader._gltfResource.url}`;
throw gltfJsonLoader.getError(errorMessage, error);
}
async function upgradeVersion(gltfJsonLoader, gltf) {
if (defined_default(gltf.asset) && gltf.asset.version === "2.0" && !usesExtension_default(gltf, "KHR_techniques_webgl") && !usesExtension_default(gltf, "KHR_materials_common")) {
return Promise.resolve();
}
const promises = [];
ForEach_default.buffer(gltf, function(buffer) {
if (!defined_default(buffer.extras._pipeline.source) && defined_default(buffer.uri)) {
const resource = gltfJsonLoader._baseResource.getDerivedResource({
url: buffer.uri
});
const resourceCache = gltfJsonLoader._resourceCache;
const bufferLoader = resourceCache.getExternalBufferLoader({
resource
});
gltfJsonLoader._bufferLoaders.push(bufferLoader);
promises.push(
bufferLoader.load().then(function() {
if (bufferLoader.isDestroyed()) {
return;
}
buffer.extras._pipeline.source = bufferLoader.typedArray;
})
);
}
});
await Promise.all(promises);
updateVersion_default(gltf);
}
function decodeDataUris(gltf) {
const promises = [];
ForEach_default.buffer(gltf, function(buffer) {
const bufferUri = buffer.uri;
if (!defined_default(buffer.extras._pipeline.source) && defined_default(bufferUri) && isDataUri_default(bufferUri)) {
delete buffer.uri;
promises.push(
Resource_default.fetchArrayBuffer(bufferUri).then(function(arrayBuffer) {
buffer.extras._pipeline.source = new Uint8Array(arrayBuffer);
})
);
}
});
return Promise.all(promises);
}
function loadEmbeddedBuffers(gltfJsonLoader, gltf) {
const promises = [];
ForEach_default.buffer(gltf, function(buffer, bufferId) {
const source = buffer.extras._pipeline.source;
if (defined_default(source) && !defined_default(buffer.uri)) {
const resourceCache = gltfJsonLoader._resourceCache;
const bufferLoader = resourceCache.getEmbeddedBufferLoader({
parentResource: gltfJsonLoader._gltfResource,
bufferId,
typedArray: source
});
gltfJsonLoader._bufferLoaders.push(bufferLoader);
promises.push(bufferLoader.load());
}
});
return Promise.all(promises);
}
async function processGltfJson(gltfJsonLoader, gltf) {
try {
addPipelineExtras_default(gltf);
await decodeDataUris(gltf);
await upgradeVersion(gltfJsonLoader, gltf);
addDefaults_default(gltf);
await loadEmbeddedBuffers(gltfJsonLoader, gltf);
removePipelineExtras_default(gltf);
const version2 = gltf.asset.version;
if (version2 !== "1.0" && version2 !== "2.0") {
throw new RuntimeError_default(`Unsupported glTF version: ${version2}`);
}
const extensionsRequired = gltf.extensionsRequired;
if (defined_default(extensionsRequired)) {
ModelUtility_default.checkSupportedExtensions(extensionsRequired);
}
gltfJsonLoader._gltf = gltf;
gltfJsonLoader._state = ResourceLoaderState_default.READY;
return gltfJsonLoader;
} catch (error) {
if (gltfJsonLoader.isDestroyed()) {
return;
}
handleError4(gltfJsonLoader, error);
}
}
async function processGltfTypedArray(gltfJsonLoader, typedArray) {
let gltf;
try {
if (getMagic_default(typedArray) === "glTF") {
gltf = parseGlb_default(typedArray);
} else {
gltf = getJsonFromTypedArray_default(typedArray);
}
} catch (error) {
if (gltfJsonLoader.isDestroyed()) {
return;
}
handleError4(gltfJsonLoader, error);
}
return processGltfJson(gltfJsonLoader, gltf);
}
GltfJsonLoader.prototype.unload = function() {
const bufferLoaders = this._bufferLoaders;
const bufferLoadersLength = bufferLoaders.length;
for (let i = 0; i < bufferLoadersLength; ++i) {
bufferLoaders[i] = !bufferLoaders[i].isDestroyed() && this._resourceCache.unload(bufferLoaders[i]);
}
this._bufferLoaders.length = 0;
this._gltf = void 0;
};
GltfJsonLoader.prototype._fetchGltf = function() {
return this._gltfResource.fetchArrayBuffer();
};
var GltfJsonLoader_default = GltfJsonLoader;
// node_modules/@cesium/engine/Source/Scene/AlphaMode.js
var AlphaMode = {
OPAQUE: "OPAQUE",
MASK: "MASK",
BLEND: "BLEND"
};
var AlphaMode_default = Object.freeze(AlphaMode);
// node_modules/@cesium/engine/Source/Scene/ModelComponents.js
var ModelComponents = {};
function Quantization() {
this.octEncoded = false;
this.octEncodedZXY = false;
this.normalizationRange = void 0;
this.quantizedVolumeOffset = void 0;
this.quantizedVolumeDimensions = void 0;
this.quantizedVolumeStepSize = void 0;
this.componentDatatype = void 0;
this.type = void 0;
}
function Attribute() {
this.name = void 0;
this.semantic = void 0;
this.setIndex = void 0;
this.componentDatatype = void 0;
this.type = void 0;
this.normalized = false;
this.count = void 0;
this.min = void 0;
this.max = void 0;
this.constant = void 0;
this.quantization = void 0;
this.typedArray = void 0;
this.buffer = void 0;
this.byteOffset = 0;
this.byteStride = void 0;
}
function Indices() {
this.indexDatatype = void 0;
this.count = void 0;
this.buffer = void 0;
this.typedArray = void 0;
}
function FeatureIdAttribute() {
this.featureCount = void 0;
this.nullFeatureId = void 0;
this.propertyTableId = void 0;
this.setIndex = void 0;
this.label = void 0;
this.positionalLabel = void 0;
}
function FeatureIdImplicitRange() {
this.featureCount = void 0;
this.nullFeatureId = void 0;
this.propertyTableId = void 0;
this.offset = 0;
this.repeat = void 0;
this.label = void 0;
this.positionalLabel = void 0;
}
function FeatureIdTexture() {
this.featureCount = void 0;
this.nullFeatureId = void 0;
this.propertyTableId = void 0;
this.textureReader = void 0;
this.label = void 0;
this.positionalLabel = void 0;
}
function MorphTarget() {
this.attributes = [];
}
function Primitive2() {
this.attributes = [];
this.morphTargets = [];
this.indices = void 0;
this.material = void 0;
this.primitiveType = void 0;
this.featureIds = [];
this.propertyTextureIds = [];
this.propertyAttributeIds = [];
this.outlineCoordinates = void 0;
}
function Instances() {
this.attributes = [];
this.featureIds = [];
this.transformInWorldSpace = false;
}
function Skin() {
this.index = void 0;
this.joints = [];
this.inverseBindMatrices = [];
}
function Node3() {
this.name = void 0;
this.index = void 0;
this.children = [];
this.primitives = [];
this.instances = void 0;
this.skin = void 0;
this.matrix = void 0;
this.translation = void 0;
this.rotation = void 0;
this.scale = void 0;
this.morphWeights = [];
this.articulationName = void 0;
}
function Scene() {
this.nodes = [];
}
var AnimatedPropertyType = {
TRANSLATION: "translation",
ROTATION: "rotation",
SCALE: "scale",
WEIGHTS: "weights"
};
function AnimationSampler() {
this.input = [];
this.interpolation = void 0;
this.output = [];
}
function AnimationTarget() {
this.node = void 0;
this.path = void 0;
}
function AnimationChannel() {
this.sampler = void 0;
this.target = void 0;
}
function Animation() {
this.name = void 0;
this.samplers = [];
this.channels = [];
}
function ArticulationStage() {
this.name = void 0;
this.type = void 0;
this.minimumValue = void 0;
this.maximumValue = void 0;
this.initialValue = void 0;
}
function Articulation() {
this.name = void 0;
this.stages = [];
}
function Asset() {
this.credits = [];
}
function Components() {
this.asset = new Asset();
this.scene = void 0;
this.nodes = [];
this.skins = [];
this.animations = [];
this.articulations = [];
this.structuralMetadata = void 0;
this.upAxis = void 0;
this.forwardAxis = void 0;
this.transform = Matrix4_default.clone(Matrix4_default.IDENTITY);
}
function TextureReader() {
this.texture = void 0;
this.index = void 0;
this.texCoord = 0;
this.transform = Matrix3_default.clone(Matrix3_default.IDENTITY);
this.channels = void 0;
}
function MetallicRoughness() {
this.baseColorTexture = void 0;
this.metallicRoughnessTexture = void 0;
this.baseColorFactor = Cartesian4_default.clone(
MetallicRoughness.DEFAULT_BASE_COLOR_FACTOR
);
this.metallicFactor = MetallicRoughness.DEFAULT_METALLIC_FACTOR;
this.roughnessFactor = MetallicRoughness.DEFAULT_ROUGHNESS_FACTOR;
}
MetallicRoughness.DEFAULT_BASE_COLOR_FACTOR = Cartesian4_default.ONE;
MetallicRoughness.DEFAULT_METALLIC_FACTOR = 1;
MetallicRoughness.DEFAULT_ROUGHNESS_FACTOR = 1;
function SpecularGlossiness() {
this.diffuseTexture = void 0;
this.specularGlossinessTexture = void 0;
this.diffuseFactor = Cartesian4_default.clone(
SpecularGlossiness.DEFAULT_DIFFUSE_FACTOR
);
this.specularFactor = Cartesian3_default.clone(
SpecularGlossiness.DEFAULT_SPECULAR_FACTOR
);
this.glossinessFactor = SpecularGlossiness.DEFAULT_GLOSSINESS_FACTOR;
}
SpecularGlossiness.DEFAULT_DIFFUSE_FACTOR = Cartesian4_default.ONE;
SpecularGlossiness.DEFAULT_SPECULAR_FACTOR = Cartesian3_default.ONE;
SpecularGlossiness.DEFAULT_GLOSSINESS_FACTOR = 1;
function Material2() {
this.metallicRoughness = new MetallicRoughness();
this.specularGlossiness = void 0;
this.emissiveTexture = void 0;
this.normalTexture = void 0;
this.occlusionTexture = void 0;
this.emissiveFactor = Cartesian3_default.clone(Material2.DEFAULT_EMISSIVE_FACTOR);
this.alphaMode = AlphaMode_default.OPAQUE;
this.alphaCutoff = 0.5;
this.doubleSided = false;
this.unlit = false;
}
Material2.DEFAULT_EMISSIVE_FACTOR = Cartesian3_default.ZERO;
ModelComponents.Quantization = Quantization;
ModelComponents.Attribute = Attribute;
ModelComponents.Indices = Indices;
ModelComponents.FeatureIdAttribute = FeatureIdAttribute;
ModelComponents.FeatureIdTexture = FeatureIdTexture;
ModelComponents.FeatureIdImplicitRange = FeatureIdImplicitRange;
ModelComponents.MorphTarget = MorphTarget;
ModelComponents.Primitive = Primitive2;
ModelComponents.Instances = Instances;
ModelComponents.Skin = Skin;
ModelComponents.Node = Node3;
ModelComponents.Scene = Scene;
ModelComponents.AnimatedPropertyType = Object.freeze(AnimatedPropertyType);
ModelComponents.AnimationSampler = AnimationSampler;
ModelComponents.AnimationTarget = AnimationTarget;
ModelComponents.AnimationChannel = AnimationChannel;
ModelComponents.Animation = Animation;
ModelComponents.ArticulationStage = ArticulationStage;
ModelComponents.Articulation = Articulation;
ModelComponents.Asset = Asset;
ModelComponents.Components = Components;
ModelComponents.TextureReader = TextureReader;
ModelComponents.MetallicRoughness = MetallicRoughness;
ModelComponents.SpecularGlossiness = SpecularGlossiness;
ModelComponents.Material = Material2;
var ModelComponents_default = ModelComponents;
// node_modules/@cesium/engine/Source/Scene/GltfLoaderUtil.js
var GltfLoaderUtil = {};
GltfLoaderUtil.getImageIdFromTexture = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const textureId = options.textureId;
const supportedImageFormats = options.supportedImageFormats;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.textureId", textureId);
Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats);
const texture = gltf.textures[textureId];
const extensions = texture.extensions;
if (defined_default(extensions)) {
if (supportedImageFormats.webp && defined_default(extensions.EXT_texture_webp)) {
return extensions.EXT_texture_webp.source;
} else if (supportedImageFormats.basis && defined_default(extensions.KHR_texture_basisu)) {
return extensions.KHR_texture_basisu.source;
}
}
return texture.source;
};
GltfLoaderUtil.createSampler = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const textureInfo = options.textureInfo;
const compressedTextureNoMipmap = defaultValue_default(
options.compressedTextureNoMipmap,
false
);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.textureInfo", textureInfo);
let wrapS = TextureWrap_default.REPEAT;
let wrapT = TextureWrap_default.REPEAT;
let minFilter = TextureMinificationFilter_default.LINEAR;
let magFilter = TextureMagnificationFilter_default.LINEAR;
const textureId = textureInfo.index;
const texture = gltf.textures[textureId];
const samplerId = texture.sampler;
if (defined_default(samplerId)) {
const sampler = gltf.samplers[samplerId];
wrapS = defaultValue_default(sampler.wrapS, wrapS);
wrapT = defaultValue_default(sampler.wrapT, wrapT);
minFilter = defaultValue_default(sampler.minFilter, minFilter);
magFilter = defaultValue_default(sampler.magFilter, magFilter);
}
let usesTextureTransform = false;
const extensions = textureInfo.extensions;
if (defined_default(extensions) && defined_default(extensions.KHR_texture_transform)) {
usesTextureTransform = true;
}
if ((compressedTextureNoMipmap || usesTextureTransform) && minFilter !== TextureMinificationFilter_default.LINEAR && minFilter !== TextureMinificationFilter_default.NEAREST) {
if (minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_NEAREST || minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_LINEAR) {
minFilter = TextureMinificationFilter_default.NEAREST;
} else {
minFilter = TextureMinificationFilter_default.LINEAR;
}
}
return new Sampler_default({
wrapS,
wrapT,
minificationFilter: minFilter,
magnificationFilter: magFilter
});
};
var defaultScale3 = new Cartesian2_default(1, 1);
GltfLoaderUtil.createModelTextureReader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const textureInfo = options.textureInfo;
const channels = options.channels;
const texture = options.texture;
Check_default.typeOf.object("options.textureInfo", textureInfo);
let texCoord = defaultValue_default(textureInfo.texCoord, 0);
let transform3;
const textureTransform = defaultValue_default(
textureInfo.extensions,
defaultValue_default.EMPTY_OBJECT
).KHR_texture_transform;
if (defined_default(textureTransform)) {
texCoord = defaultValue_default(textureTransform.texCoord, texCoord);
const offset2 = defined_default(textureTransform.offset) ? Cartesian2_default.unpack(textureTransform.offset) : Cartesian2_default.ZERO;
let rotation = defaultValue_default(textureTransform.rotation, 0);
const scale = defined_default(textureTransform.scale) ? Cartesian2_default.unpack(textureTransform.scale) : defaultScale3;
rotation = -rotation;
transform3 = new Matrix3_default(
Math.cos(rotation) * scale.x,
-Math.sin(rotation) * scale.y,
offset2.x,
Math.sin(rotation) * scale.x,
Math.cos(rotation) * scale.y,
offset2.y,
0,
0,
1
);
}
const modelTextureReader = new ModelComponents_default.TextureReader();
modelTextureReader.index = textureInfo.index;
modelTextureReader.texture = texture;
modelTextureReader.texCoord = texCoord;
modelTextureReader.transform = transform3;
modelTextureReader.channels = channels;
return modelTextureReader;
};
var GltfLoaderUtil_default = GltfLoaderUtil;
// node_modules/@cesium/engine/Source/Core/resizeImageToNextPowerOfTwo.js
function resizeImageToNextPowerOfTwo(image) {
const canvas = document.createElement("canvas");
canvas.width = Math_default.nextPowerOfTwo(image.width);
canvas.height = Math_default.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;
}
var resizeImageToNextPowerOfTwo_default = resizeImageToNextPowerOfTwo;
// node_modules/@cesium/engine/Source/Scene/GltfTextureLoader.js
function GltfTextureLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const textureInfo = options.textureInfo;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const supportedImageFormats = options.supportedImageFormats;
const cacheKey = options.cacheKey;
const asynchronous = defaultValue_default(options.asynchronous, true);
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.textureInfo", textureInfo);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats);
const textureId = textureInfo.index;
const imageId = GltfLoaderUtil_default.getImageIdFromTexture({
gltf,
textureId,
supportedImageFormats
});
this._resourceCache = resourceCache;
this._gltf = gltf;
this._textureInfo = textureInfo;
this._imageId = imageId;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._cacheKey = cacheKey;
this._asynchronous = asynchronous;
this._imageLoader = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._texture = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfTextureLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfTextureLoader.prototype.constructor = GltfTextureLoader;
}
Object.defineProperties(GltfTextureLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
texture: {
get: function() {
return this._texture;
}
}
});
var scratchTextureJob = new CreateTextureJob();
async function loadResources3(loader) {
const resourceCache = loader._resourceCache;
try {
const imageLoader = resourceCache.getImageLoader({
gltf: loader._gltf,
imageId: loader._imageId,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource
});
loader._imageLoader = imageLoader;
await imageLoader.load();
if (loader.isDestroyed()) {
return;
}
loader._image = imageLoader.image;
loader._mipLevels = imageLoader.mipLevels;
loader._state = ResourceLoaderState_default.LOADED;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader.unload();
loader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load texture";
throw loader.getError(errorMessage, error);
}
}
GltfTextureLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
this._promise = loadResources3(this);
return this._promise;
};
function CreateTextureJob() {
this.gltf = void 0;
this.textureInfo = void 0;
this.image = void 0;
this.context = void 0;
this.texture = void 0;
}
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 = createTexture3(
this.gltf,
this.textureInfo,
this.image,
this.mipLevels,
this.context
);
};
function createTexture3(gltf, textureInfo, image, mipLevels, context) {
const internalFormat = image.internalFormat;
let compressedTextureNoMipmap = false;
if (PixelFormat_default.isCompressedFormat(internalFormat) && !defined_default(mipLevels)) {
compressedTextureNoMipmap = true;
}
const sampler = GltfLoaderUtil_default.createSampler({
gltf,
textureInfo,
compressedTextureNoMipmap
});
const minFilter = sampler.minificationFilter;
const wrapS = sampler.wrapS;
const wrapT = sampler.wrapT;
const samplerRequiresMipmap2 = minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_NEAREST || minFilter === TextureMinificationFilter_default.NEAREST_MIPMAP_LINEAR || minFilter === TextureMinificationFilter_default.LINEAR_MIPMAP_NEAREST || minFilter === TextureMinificationFilter_default.LINEAR_MIPMAP_LINEAR;
const generateMipmap = !defined_default(internalFormat) && samplerRequiresMipmap2;
const requiresPowerOfTwo = generateMipmap || wrapS === TextureWrap_default.REPEAT || wrapS === TextureWrap_default.MIRRORED_REPEAT || wrapT === TextureWrap_default.REPEAT || wrapT === TextureWrap_default.MIRRORED_REPEAT;
const nonPowerOfTwo = !Math_default.isPowerOfTwo(image.width) || !Math_default.isPowerOfTwo(image.height);
const requiresResize = requiresPowerOfTwo && nonPowerOfTwo;
let texture;
if (defined_default(internalFormat)) {
if (!context.webgl2 && PixelFormat_default.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_default.create({
context,
source: {
arrayBufferView: image.bufferView,
mipLevels
},
width: image.width,
height: image.height,
pixelFormat: image.internalFormat,
sampler
});
} else {
if (requiresResize) {
image = resizeImageToNextPowerOfTwo_default(image);
}
texture = Texture_default.create({
context,
source: image,
sampler,
flipY: false,
skipColorSpaceConversion: true
});
}
if (generateMipmap) {
texture.generateMipmap();
}
return texture;
}
GltfTextureLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.LOADED && this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
if (defined_default(this._texture)) {
return false;
}
if (!defined_default(this._image)) {
return false;
}
this._state = ResourceLoaderState_default.PROCESSING;
let texture;
if (this._asynchronous) {
const textureJob = scratchTextureJob;
textureJob.set(
this._gltf,
this._textureInfo,
this._image,
this._mipLevels,
frameState.context
);
const jobScheduler = frameState.jobScheduler;
if (!jobScheduler.execute(textureJob, JobType_default.TEXTURE)) {
return;
}
texture = textureJob.texture;
} else {
texture = createTexture3(
this._gltf,
this._textureInfo,
this._image,
this._mipLevels,
frameState.context
);
}
this.unload();
this._texture = texture;
this._state = ResourceLoaderState_default.READY;
this._resourceCache.statistics.addTextureLoader(this);
return true;
};
GltfTextureLoader.prototype.unload = function() {
if (defined_default(this._texture)) {
this._texture.destroy();
}
if (defined_default(this._imageLoader) && !this._imageLoader.isDestroyed()) {
this._resourceCache.unload(this._imageLoader);
}
this._imageLoader = void 0;
this._image = void 0;
this._mipLevels = void 0;
this._texture = void 0;
this._gltf = void 0;
};
var GltfTextureLoader_default = GltfTextureLoader;
// node_modules/@cesium/engine/Source/Scene/GltfVertexBufferLoader.js
function GltfVertexBufferLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resourceCache = options.resourceCache;
const gltf = options.gltf;
const gltfResource = options.gltfResource;
const baseResource2 = 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_default(options.asynchronous, true);
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.func("options.resourceCache", resourceCache);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
const hasBufferViewId = defined_default(bufferViewId);
const hasDraco = hasDracoCompression(draco, attributeSemantic);
const hasAttributeSemantic = defined_default(attributeSemantic);
const hasAccessorId = defined_default(accessorId);
if (hasBufferViewId === hasDraco) {
throw new DeveloperError_default(
"One of options.bufferViewId and options.draco must be defined."
);
}
if (hasDraco && !hasAttributeSemantic) {
throw new DeveloperError_default(
"When options.draco is defined options.attributeSemantic must also be defined."
);
}
if (hasDraco && !hasAccessorId) {
throw new DeveloperError_default(
"When options.draco is defined options.accessorId must also be defined."
);
}
if (hasDraco) {
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.string("options.attributeSemantic", attributeSemantic);
Check_default.typeOf.number("options.accessorId", accessorId);
}
this._resourceCache = resourceCache;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._bufferViewId = bufferViewId;
this._draco = draco;
this._attributeSemantic = attributeSemantic;
this._accessorId = accessorId;
this._cacheKey = cacheKey;
this._asynchronous = asynchronous;
this._loadBuffer = loadBuffer;
this._loadTypedArray = loadTypedArray;
this._bufferViewLoader = void 0;
this._dracoLoader = void 0;
this._quantization = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfVertexBufferLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfVertexBufferLoader.prototype.constructor = GltfVertexBufferLoader;
}
Object.defineProperties(GltfVertexBufferLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
buffer: {
get: function() {
return this._buffer;
}
},
typedArray: {
get: function() {
return this._typedArray;
}
},
quantization: {
get: function() {
return this._quantization;
}
}
});
function hasDracoCompression(draco, semantic) {
return defined_default(draco) && defined_default(draco.attributes) && defined_default(draco.attributes[semantic]);
}
GltfVertexBufferLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (hasDracoCompression(this._draco, this._attributeSemantic)) {
this._promise = loadFromDraco2(this);
return this._promise;
}
this._promise = loadFromBufferView3(this);
return this._promise;
};
function getQuantizationInformation(dracoQuantization, componentDatatype, componentCount, type) {
const quantizationBits = dracoQuantization.quantizationBits;
const normalizationRange = (1 << quantizationBits) - 1;
const normalizationDivisor = 1 / normalizationRange;
const quantization = new ModelComponents_default.Quantization();
quantization.componentDatatype = componentDatatype;
quantization.octEncoded = dracoQuantization.octEncoded;
quantization.octEncodedZXY = true;
quantization.type = type;
if (quantization.octEncoded) {
quantization.type = AttributeType_default.VEC2;
quantization.normalizationRange = normalizationRange;
} else {
const MathType = AttributeType_default.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
);
const packedSteps = packedDimensions.map(function(dimension) {
return dimension * normalizationDivisor;
});
quantization.quantizedVolumeStepSize = MathType.unpack(packedSteps);
}
}
return quantization;
}
async function loadFromDraco2(vertexBufferLoader) {
vertexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = vertexBufferLoader._resourceCache;
try {
const dracoLoader = resourceCache.getDracoLoader({
gltf: vertexBufferLoader._gltf,
draco: vertexBufferLoader._draco,
gltfResource: vertexBufferLoader._gltfResource,
baseResource: vertexBufferLoader._baseResource
});
vertexBufferLoader._dracoLoader = dracoLoader;
await dracoLoader.load();
if (vertexBufferLoader.isDestroyed()) {
return;
}
vertexBufferLoader._state = ResourceLoaderState_default.LOADED;
return vertexBufferLoader;
} catch {
if (vertexBufferLoader.isDestroyed()) {
return;
}
handleError5(vertexBufferLoader);
}
}
function processDraco(vertexBufferLoader) {
vertexBufferLoader._state = ResourceLoaderState_default.PROCESSING;
const dracoLoader = vertexBufferLoader._dracoLoader;
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_default(dracoQuantization)) {
vertexBufferLoader._quantization = getQuantizationInformation(
dracoQuantization,
dracoAttribute.data.componentDatatype,
dracoAttribute.data.componentsPerAttribute,
type
);
}
vertexBufferLoader._typedArray = new Uint8Array(
typedArray.buffer,
typedArray.byteOffset,
typedArray.byteLength
);
}
async function loadFromBufferView3(vertexBufferLoader) {
vertexBufferLoader._state = ResourceLoaderState_default.LOADING;
const resourceCache = vertexBufferLoader._resourceCache;
try {
const bufferViewLoader = resourceCache.getBufferViewLoader({
gltf: vertexBufferLoader._gltf,
bufferViewId: vertexBufferLoader._bufferViewId,
gltfResource: vertexBufferLoader._gltfResource,
baseResource: vertexBufferLoader._baseResource
});
vertexBufferLoader._bufferViewLoader = bufferViewLoader;
await bufferViewLoader.load();
if (vertexBufferLoader.isDestroyed()) {
return;
}
vertexBufferLoader._typedArray = bufferViewLoader.typedArray;
vertexBufferLoader._state = ResourceLoaderState_default.PROCESSING;
return vertexBufferLoader;
} catch (error) {
if (vertexBufferLoader.isDestroyed()) {
return;
}
handleError5(vertexBufferLoader, error);
}
}
function handleError5(vertexBufferLoader, error) {
vertexBufferLoader.unload();
vertexBufferLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load vertex buffer";
throw vertexBufferLoader.getError(errorMessage, error);
}
function CreateVertexBufferJob() {
this.typedArray = void 0;
this.context = void 0;
this.buffer = void 0;
}
CreateVertexBufferJob.prototype.set = function(typedArray, context) {
this.typedArray = typedArray;
this.context = context;
};
CreateVertexBufferJob.prototype.execute = function() {
this.buffer = createVertexBuffer(this.typedArray, this.context);
};
function createVertexBuffer(typedArray, context) {
const buffer = Buffer_default.createVertexBuffer({
typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
return buffer;
}
var scratchVertexBufferJob = new CreateVertexBufferJob();
GltfVertexBufferLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.LOADED && this._state !== ResourceLoaderState_default.PROCESSING) {
return false;
}
if (defined_default(this._dracoLoader)) {
try {
const ready = this._dracoLoader.process(frameState);
if (!ready) {
return false;
}
} catch (error) {
handleError5(this, error);
}
processDraco(this);
}
let buffer;
const typedArray = this._typedArray;
if (this._loadBuffer && this._asynchronous) {
const vertexBufferJob = scratchVertexBufferJob;
vertexBufferJob.set(typedArray, frameState.context);
const jobScheduler = frameState.jobScheduler;
if (!jobScheduler.execute(vertexBufferJob, JobType_default.BUFFER)) {
return false;
}
buffer = vertexBufferJob.buffer;
} else if (this._loadBuffer) {
buffer = createVertexBuffer(typedArray, frameState.context);
}
this.unload();
this._buffer = buffer;
this._typedArray = this._loadTypedArray ? typedArray : void 0;
this._state = ResourceLoaderState_default.READY;
this._resourceCache.statistics.addGeometryLoader(this);
return true;
};
GltfVertexBufferLoader.prototype.unload = function() {
if (defined_default(this._buffer)) {
this._buffer.destroy();
}
const resourceCache = this._resourceCache;
if (defined_default(this._bufferViewLoader) && !this._bufferViewLoader.isDestroyed()) {
resourceCache.unload(this._bufferViewLoader);
}
if (defined_default(this._dracoLoader)) {
resourceCache.unload(this._dracoLoader);
}
this._bufferViewLoader = void 0;
this._dracoLoader = void 0;
this._typedArray = void 0;
this._buffer = void 0;
this._gltf = void 0;
};
var GltfVertexBufferLoader_default = GltfVertexBufferLoader;
// node_modules/@cesium/engine/Source/Scene/MetadataClass.js
function MetadataClass(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
Check_default.typeOf.string("options.id", id);
const properties = defaultValue_default(options.properties, {});
const propertiesBySemantic = {};
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const property = properties[propertyId];
if (defined_default(property.semantic)) {
propertiesBySemantic[property.semantic] = property;
}
}
}
this._id = id;
this._name = options.name;
this._description = options.description;
this._properties = properties;
this._propertiesBySemantic = propertiesBySemantic;
this._extras = clone_default(options.extras, true);
this._extensions = clone_default(options.extensions, true);
}
MetadataClass.fromJson = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const classDefinition = options.class;
Check_default.typeOf.string("options.id", id);
Check_default.typeOf.object("options.class", classDefinition);
const properties = {};
for (const propertyId in classDefinition.properties) {
if (classDefinition.properties.hasOwnProperty(propertyId)) {
const property = MetadataClassProperty_default.fromJson({
id: propertyId,
property: classDefinition.properties[propertyId],
enums: options.enums
});
properties[propertyId] = property;
}
}
return new MetadataClass({
id,
name: classDefinition.name,
description: classDefinition.description,
properties,
extras: classDefinition.extras,
extensions: classDefinition.extensions
});
};
Object.defineProperties(MetadataClass.prototype, {
properties: {
get: function() {
return this._properties;
}
},
propertiesBySemantic: {
get: function() {
return this._propertiesBySemantic;
}
},
id: {
get: function() {
return this._id;
}
},
name: {
get: function() {
return this._name;
}
},
description: {
get: function() {
return this._description;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
MetadataClass.BATCH_TABLE_CLASS_NAME = "_batchTable";
var MetadataClass_default = MetadataClass;
// node_modules/@cesium/engine/Source/Scene/MetadataEnumValue.js
function MetadataEnumValue(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const value = options.value;
const name = options.name;
Check_default.typeOf.number("options.value", value);
Check_default.typeOf.string("options.name", name);
this._value = value;
this._name = name;
this._description = options.description;
this._extras = clone_default(options.extras, true);
this._extensions = clone_default(options.extensions, true);
}
MetadataEnumValue.fromJson = function(value) {
Check_default.typeOf.object("value", value);
return new MetadataEnumValue({
value: value.value,
name: value.name,
description: value.description,
extras: value.extras,
extensions: value.extensions
});
};
Object.defineProperties(MetadataEnumValue.prototype, {
value: {
get: function() {
return this._value;
}
},
name: {
get: function() {
return this._name;
}
},
description: {
get: function() {
return this._description;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
var MetadataEnumValue_default = MetadataEnumValue;
// node_modules/@cesium/engine/Source/Scene/MetadataEnum.js
function MetadataEnum(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const values = options.values;
Check_default.typeOf.string("options.id", id);
Check_default.defined("options.values", values);
const namesByValue = {};
const valuesByName = {};
const valuesLength = values.length;
for (let i = 0; i < valuesLength; ++i) {
const value = values[i];
namesByValue[value.value] = value.name;
valuesByName[value.name] = value.value;
}
const valueType = defaultValue_default(
options.valueType,
MetadataComponentType_default.UINT16
);
this._values = values;
this._namesByValue = namesByValue;
this._valuesByName = valuesByName;
this._valueType = valueType;
this._id = id;
this._name = options.name;
this._description = options.description;
this._extras = clone_default(options.extras, true);
this._extensions = clone_default(options.extensions, true);
}
MetadataEnum.fromJson = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const enumDefinition = options.enum;
Check_default.typeOf.string("options.id", id);
Check_default.typeOf.object("options.enum", enumDefinition);
const values = enumDefinition.values.map(function(value) {
return MetadataEnumValue_default.fromJson(value);
});
return new MetadataEnum({
id,
values,
valueType: MetadataComponentType_default[enumDefinition.valueType],
name: enumDefinition.name,
description: enumDefinition.description,
extras: enumDefinition.extras,
extensions: enumDefinition.extensions
});
};
Object.defineProperties(MetadataEnum.prototype, {
values: {
get: function() {
return this._values;
}
},
namesByValue: {
get: function() {
return this._namesByValue;
}
},
valuesByName: {
get: function() {
return this._valuesByName;
}
},
valueType: {
get: function() {
return this._valueType;
}
},
id: {
get: function() {
return this._id;
}
},
name: {
get: function() {
return this._name;
}
},
description: {
get: function() {
return this._description;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
var MetadataEnum_default = MetadataEnum;
// node_modules/@cesium/engine/Source/Scene/MetadataSchema.js
function MetadataSchema(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const classes = defaultValue_default(options.classes, {});
const enums = defaultValue_default(options.enums, {});
this._classes = classes;
this._enums = enums;
this._id = options.id;
this._name = options.name;
this._description = options.description;
this._version = options.version;
this._extras = clone_default(options.extras, true);
this._extensions = clone_default(options.extensions, true);
}
MetadataSchema.fromJson = function(schema) {
Check_default.typeOf.object("schema", schema);
const enums = {};
if (defined_default(schema.enums)) {
for (const enumId in schema.enums) {
if (schema.enums.hasOwnProperty(enumId)) {
enums[enumId] = MetadataEnum_default.fromJson({
id: enumId,
enum: schema.enums[enumId]
});
}
}
}
const classes = {};
if (defined_default(schema.classes)) {
for (const classId in schema.classes) {
if (schema.classes.hasOwnProperty(classId)) {
classes[classId] = MetadataClass_default.fromJson({
id: classId,
class: schema.classes[classId],
enums
});
}
}
}
return new MetadataSchema({
id: schema.id,
name: schema.name,
description: schema.description,
version: schema.version,
classes,
enums,
extras: schema.extras,
extensions: schema.extensions
});
};
Object.defineProperties(MetadataSchema.prototype, {
classes: {
get: function() {
return this._classes;
}
},
enums: {
get: function() {
return this._enums;
}
},
id: {
get: function() {
return this._id;
}
},
name: {
get: function() {
return this._name;
}
},
description: {
get: function() {
return this._description;
}
},
version: {
get: function() {
return this._version;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
var MetadataSchema_default = MetadataSchema;
// node_modules/@cesium/engine/Source/Scene/MetadataSchemaLoader.js
function MetadataSchemaLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const schema = options.schema;
const resource = options.resource;
const cacheKey = options.cacheKey;
if (defined_default(schema) === defined_default(resource)) {
throw new DeveloperError_default(
"One of options.schema and options.resource must be defined."
);
}
this._schema = defined_default(schema) ? MetadataSchema_default.fromJson(schema) : void 0;
this._resource = resource;
this._cacheKey = cacheKey;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
MetadataSchemaLoader.prototype = Object.create(ResourceLoader_default.prototype);
MetadataSchemaLoader.prototype.constructor = MetadataSchemaLoader;
}
Object.defineProperties(MetadataSchemaLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
schema: {
get: function() {
return this._schema;
}
}
});
MetadataSchemaLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
if (defined_default(this._schema)) {
this._promise = Promise.resolve(this);
return this._promise;
}
this._promise = loadExternalSchema(this);
return this._promise;
};
async function loadExternalSchema(schemaLoader) {
const resource = schemaLoader._resource;
schemaLoader._state = ResourceLoaderState_default.LOADING;
try {
const json = await resource.fetchJson();
if (schemaLoader.isDestroyed()) {
return;
}
schemaLoader._schema = MetadataSchema_default.fromJson(json);
schemaLoader._state = ResourceLoaderState_default.READY;
return schemaLoader;
} catch (error) {
if (schemaLoader.isDestroyed()) {
return;
}
schemaLoader._state = ResourceLoaderState_default.FAILED;
const errorMessage = `Failed to load schema: ${resource.url}`;
throw schemaLoader.getError(errorMessage, error);
}
}
MetadataSchemaLoader.prototype.unload = function() {
this._schema = void 0;
};
var MetadataSchemaLoader_default = MetadataSchemaLoader;
// node_modules/@cesium/engine/Source/Scene/ResourceCacheKey.js
var ResourceCacheKey = {};
function getExternalResourceCacheKey(resource) {
return getAbsoluteUri_default(resource.url);
}
function getBufferViewCacheKey(bufferView) {
let byteOffset = bufferView.byteOffset;
let byteLength = bufferView.byteLength;
if (hasExtension_default(bufferView, "EXT_meshopt_compression")) {
const meshopt = bufferView.extensions.EXT_meshopt_compression;
byteOffset = defaultValue_default(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, baseResource2) {
if (defined_default(buffer.uri)) {
const resource = baseResource2.getDerivedResource({
url: buffer.uri
});
return getExternalBufferCacheKey(resource);
}
return getEmbeddedBufferCacheKey(gltfResource, bufferId);
}
function getDracoCacheKey(gltf, draco, gltfResource, baseResource2) {
const bufferViewId = draco.bufferView;
const bufferView = gltf.bufferViews[bufferViewId];
const bufferId = bufferView.buffer;
const buffer = gltf.buffers[bufferId];
const bufferCacheKey = getBufferCacheKey(
buffer,
bufferId,
gltfResource,
baseResource2
);
const bufferViewCacheKey = getBufferViewCacheKey(bufferView);
return `${bufferCacheKey}-range-${bufferViewCacheKey}`;
}
function getImageCacheKey(gltf, imageId, gltfResource, baseResource2) {
const image = gltf.images[imageId];
const bufferViewId = image.bufferView;
const uri = image.uri;
if (defined_default(uri)) {
const resource = baseResource2.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,
baseResource2
);
const bufferViewCacheKey = getBufferViewCacheKey(bufferView);
return `${bufferCacheKey}-range-${bufferViewCacheKey}`;
}
function getSamplerCacheKey(gltf, textureInfo) {
const sampler = GltfLoaderUtil_default.createSampler({
gltf,
textureInfo
});
return `${sampler.wrapS}-${sampler.wrapT}-${sampler.minificationFilter}-${sampler.magnificationFilter}`;
}
ResourceCacheKey.getSchemaCacheKey = function(options) {
const schema = options.schema;
const resource = options.resource;
if (defined_default(schema) === defined_default(resource)) {
throw new DeveloperError_default(
"One of options.schema and options.resource must be defined."
);
}
if (defined_default(schema)) {
return `embedded-schema:${JSON.stringify(schema)}`;
}
return `external-schema:${getExternalResourceCacheKey(resource)}`;
};
ResourceCacheKey.getExternalBufferCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resource = options.resource;
Check_default.typeOf.object("options.resource", resource);
return `external-buffer:${getExternalBufferCacheKey(resource)}`;
};
ResourceCacheKey.getEmbeddedBufferCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const parentResource = options.parentResource;
const bufferId = options.bufferId;
Check_default.typeOf.object("options.parentResource", parentResource);
Check_default.typeOf.number("options.bufferId", bufferId);
return `embedded-buffer:${getEmbeddedBufferCacheKey(
parentResource,
bufferId
)}`;
};
ResourceCacheKey.getGltfCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltfResource = options.gltfResource;
Check_default.typeOf.object("options.gltfResource", gltfResource);
return `gltf:${getExternalResourceCacheKey(gltfResource)}`;
};
ResourceCacheKey.getBufferViewCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const bufferViewId = options.bufferViewId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.bufferViewId", bufferViewId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const bufferView = gltf.bufferViews[bufferViewId];
let bufferId = bufferView.buffer;
const buffer = gltf.buffers[bufferId];
if (hasExtension_default(bufferView, "EXT_meshopt_compression")) {
const meshopt = bufferView.extensions.EXT_meshopt_compression;
bufferId = meshopt.buffer;
}
const bufferCacheKey = getBufferCacheKey(
buffer,
bufferId,
gltfResource,
baseResource2
);
const bufferViewCacheKey = getBufferViewCacheKey(bufferView);
return `buffer-view:${bufferCacheKey}-range-${bufferViewCacheKey}`;
};
ResourceCacheKey.getDracoCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const draco = options.draco;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
return `draco:${getDracoCacheKey(gltf, draco, gltfResource, baseResource2)}`;
};
ResourceCacheKey.getVertexBufferCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const frameState = options.frameState;
const bufferViewId = options.bufferViewId;
const draco = options.draco;
const attributeSemantic = options.attributeSemantic;
const dequantize = defaultValue_default(options.dequantize, false);
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.frameState", frameState);
const hasBufferViewId = defined_default(bufferViewId);
const hasDraco = hasDracoCompression2(draco, attributeSemantic);
const hasAttributeSemantic = defined_default(attributeSemantic);
if (hasBufferViewId === hasDraco) {
throw new DeveloperError_default(
"One of options.bufferViewId and options.draco must be defined."
);
}
if (hasDraco && !hasAttributeSemantic) {
throw new DeveloperError_default(
"When options.draco is defined options.attributeSemantic must also be defined."
);
}
if (hasDraco) {
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.string("options.attributeSemantic", attributeSemantic);
}
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
let cacheKeySuffix = "";
if (dequantize) {
cacheKeySuffix += "-dequantize";
}
if (loadBuffer) {
cacheKeySuffix += "-buffer";
cacheKeySuffix += `-context-${frameState.context.id}`;
}
if (loadTypedArray) {
cacheKeySuffix += "-typed-array";
}
if (defined_default(draco)) {
const dracoCacheKey = getDracoCacheKey(
gltf,
draco,
gltfResource,
baseResource2
);
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,
baseResource2
);
const bufferViewCacheKey = getBufferViewCacheKey(bufferView);
return `vertex-buffer:${bufferCacheKey}-range-${bufferViewCacheKey}${cacheKeySuffix}`;
};
function hasDracoCompression2(draco, semantic) {
return defined_default(draco) && defined_default(draco.attributes) && defined_default(draco.attributes[semantic]);
}
ResourceCacheKey.getIndexBufferCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const accessorId = options.accessorId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const frameState = options.frameState;
const draco = options.draco;
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.accessorId", accessorId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.frameState", frameState);
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
let cacheKeySuffix = "";
if (loadBuffer) {
cacheKeySuffix += "-buffer";
cacheKeySuffix += `-context-${frameState.context.id}`;
}
if (loadTypedArray) {
cacheKeySuffix += "-typed-array";
}
if (defined_default(draco)) {
const dracoCacheKey = getDracoCacheKey(
gltf,
draco,
gltfResource,
baseResource2
);
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,
baseResource2
);
const accessorCacheKey = getAccessorCacheKey(accessor, bufferView);
return `index-buffer:${bufferCacheKey}-accessor-${accessorCacheKey}${cacheKeySuffix}`;
};
ResourceCacheKey.getImageCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const imageId = options.imageId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.imageId", imageId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const imageCacheKey = getImageCacheKey(
gltf,
imageId,
gltfResource,
baseResource2
);
return `image:${imageCacheKey}`;
};
ResourceCacheKey.getTextureCacheKey = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const textureInfo = options.textureInfo;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const supportedImageFormats = options.supportedImageFormats;
const frameState = options.frameState;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.textureInfo", textureInfo);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats);
Check_default.typeOf.object("options.frameState", frameState);
const textureId = textureInfo.index;
const imageId = GltfLoaderUtil_default.getImageIdFromTexture({
gltf,
textureId,
supportedImageFormats
});
const imageCacheKey = getImageCacheKey(
gltf,
imageId,
gltfResource,
baseResource2
);
const samplerCacheKey = getSamplerCacheKey(gltf, textureInfo);
return `texture:${imageCacheKey}-sampler-${samplerCacheKey}-context-${frameState.context.id}`;
};
var ResourceCacheKey_default = ResourceCacheKey;
// node_modules/@cesium/engine/Source/Scene/ResourceCacheStatistics.js
function ResourceCacheStatistics() {
this.geometryByteLength = 0;
this.texturesByteLength = 0;
this._geometrySizes = {};
this._textureSizes = {};
}
ResourceCacheStatistics.prototype.clear = function() {
this.geometryByteLength = 0;
this.texturesByteLength = 0;
this._geometrySizes = {};
this._textureSizes = {};
};
ResourceCacheStatistics.prototype.addGeometryLoader = function(loader) {
Check_default.typeOf.object("loader", loader);
const cacheKey = loader.cacheKey;
if (this._geometrySizes.hasOwnProperty(cacheKey)) {
return;
}
this._geometrySizes[cacheKey] = 0;
const buffer = loader.buffer;
const typedArray = loader.typedArray;
let totalSize = 0;
if (defined_default(buffer)) {
totalSize += buffer.sizeInBytes;
}
if (defined_default(typedArray)) {
totalSize += typedArray.byteLength;
}
this.geometryByteLength += totalSize;
this._geometrySizes[cacheKey] = totalSize;
};
ResourceCacheStatistics.prototype.addTextureLoader = function(loader) {
Check_default.typeOf.object("loader", loader);
const cacheKey = loader.cacheKey;
if (this._textureSizes.hasOwnProperty(cacheKey)) {
return;
}
this._textureSizes[cacheKey] = 0;
const totalSize = loader.texture.sizeInBytes;
this.texturesByteLength += loader.texture.sizeInBytes;
this._textureSizes[cacheKey] = totalSize;
};
ResourceCacheStatistics.prototype.removeLoader = function(loader) {
Check_default.typeOf.object("loader", loader);
const cacheKey = loader.cacheKey;
const geometrySize = this._geometrySizes[cacheKey];
delete this._geometrySizes[cacheKey];
if (defined_default(geometrySize)) {
this.geometryByteLength -= geometrySize;
}
const textureSize = this._textureSizes[cacheKey];
delete this._textureSizes[cacheKey];
if (defined_default(textureSize)) {
this.texturesByteLength -= textureSize;
}
};
var ResourceCacheStatistics_default = ResourceCacheStatistics;
// node_modules/@cesium/engine/Source/Scene/ResourceCache.js
function ResourceCache() {
}
ResourceCache.cacheEntries = {};
ResourceCache.statistics = new ResourceCacheStatistics_default();
function CacheEntry(resourceLoader) {
this.referenceCount = 1;
this.resourceLoader = resourceLoader;
this._statisticsPromise = void 0;
}
ResourceCache.get = function(cacheKey) {
Check_default.typeOf.string("cacheKey", cacheKey);
const cacheEntry = ResourceCache.cacheEntries[cacheKey];
if (defined_default(cacheEntry)) {
++cacheEntry.referenceCount;
return cacheEntry.resourceLoader;
}
return void 0;
};
ResourceCache.add = function(resourceLoader) {
Check_default.typeOf.object("resourceLoader", resourceLoader);
const cacheKey = resourceLoader.cacheKey;
Check_default.typeOf.string("options.resourceLoader.cacheKey", cacheKey);
if (defined_default(ResourceCache.cacheEntries[cacheKey])) {
throw new DeveloperError_default(
`Resource with this cacheKey is already in the cache: ${cacheKey}`
);
}
ResourceCache.cacheEntries[cacheKey] = new CacheEntry(resourceLoader);
return resourceLoader;
};
ResourceCache.unload = function(resourceLoader) {
Check_default.typeOf.object("resourceLoader", resourceLoader);
const cacheKey = resourceLoader.cacheKey;
const cacheEntry = ResourceCache.cacheEntries[cacheKey];
if (!defined_default(cacheEntry)) {
throw new DeveloperError_default(`Resource is not in the cache: ${cacheKey}`);
}
--cacheEntry.referenceCount;
if (cacheEntry.referenceCount === 0) {
ResourceCache.statistics.removeLoader(resourceLoader);
resourceLoader.destroy();
delete ResourceCache.cacheEntries[cacheKey];
}
};
ResourceCache.getSchemaLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const schema = options.schema;
const resource = options.resource;
if (defined_default(schema) === defined_default(resource)) {
throw new DeveloperError_default(
"One of options.schema and options.resource must be defined."
);
}
const cacheKey = ResourceCacheKey_default.getSchemaCacheKey({
schema,
resource
});
let schemaLoader = ResourceCache.get(cacheKey);
if (defined_default(schemaLoader)) {
return schemaLoader;
}
schemaLoader = new MetadataSchemaLoader_default({
schema,
resource,
cacheKey
});
return ResourceCache.add(schemaLoader);
};
ResourceCache.getEmbeddedBufferLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const parentResource = options.parentResource;
const bufferId = options.bufferId;
const typedArray = options.typedArray;
Check_default.typeOf.object("options.parentResource", parentResource);
Check_default.typeOf.number("options.bufferId", bufferId);
const cacheKey = ResourceCacheKey_default.getEmbeddedBufferCacheKey({
parentResource,
bufferId
});
let bufferLoader = ResourceCache.get(cacheKey);
if (defined_default(bufferLoader)) {
return bufferLoader;
}
Check_default.typeOf.object("options.typedArray", typedArray);
bufferLoader = new BufferLoader_default({
typedArray,
cacheKey
});
return ResourceCache.add(bufferLoader);
};
ResourceCache.getExternalBufferLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resource = options.resource;
Check_default.typeOf.object("options.resource", resource);
const cacheKey = ResourceCacheKey_default.getExternalBufferCacheKey({
resource
});
let bufferLoader = ResourceCache.get(cacheKey);
if (defined_default(bufferLoader)) {
return bufferLoader;
}
bufferLoader = new BufferLoader_default({
resource,
cacheKey
});
return ResourceCache.add(bufferLoader);
};
ResourceCache.getGltfJsonLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const typedArray = options.typedArray;
const gltfJson = options.gltfJson;
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const cacheKey = ResourceCacheKey_default.getGltfCacheKey({
gltfResource
});
let gltfJsonLoader = ResourceCache.get(cacheKey);
if (defined_default(gltfJsonLoader)) {
return gltfJsonLoader;
}
gltfJsonLoader = new GltfJsonLoader_default({
resourceCache: ResourceCache,
gltfResource,
baseResource: baseResource2,
typedArray,
gltfJson,
cacheKey
});
return ResourceCache.add(gltfJsonLoader);
};
ResourceCache.getBufferViewLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const bufferViewId = options.bufferViewId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.bufferViewId", bufferViewId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const cacheKey = ResourceCacheKey_default.getBufferViewCacheKey({
gltf,
bufferViewId,
gltfResource,
baseResource: baseResource2
});
let bufferViewLoader = ResourceCache.get(cacheKey);
if (defined_default(bufferViewLoader)) {
return bufferViewLoader;
}
bufferViewLoader = new GltfBufferViewLoader_default({
resourceCache: ResourceCache,
gltf,
bufferViewId,
gltfResource,
baseResource: baseResource2,
cacheKey
});
return ResourceCache.add(bufferViewLoader);
};
ResourceCache.getDracoLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const draco = options.draco;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const cacheKey = ResourceCacheKey_default.getDracoCacheKey({
gltf,
draco,
gltfResource,
baseResource: baseResource2
});
let dracoLoader = ResourceCache.get(cacheKey);
if (defined_default(dracoLoader)) {
return dracoLoader;
}
dracoLoader = new GltfDracoLoader_default({
resourceCache: ResourceCache,
gltf,
draco,
gltfResource,
baseResource: baseResource2,
cacheKey
});
return ResourceCache.add(dracoLoader);
};
ResourceCache.getVertexBufferLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const frameState = options.frameState;
const bufferViewId = options.bufferViewId;
const draco = options.draco;
const attributeSemantic = options.attributeSemantic;
const accessorId = options.accessorId;
const asynchronous = defaultValue_default(options.asynchronous, true);
const dequantize = defaultValue_default(options.dequantize, false);
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.frameState", frameState);
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
const hasBufferViewId = defined_default(bufferViewId);
const hasDraco = hasDracoCompression3(draco, attributeSemantic);
const hasAttributeSemantic = defined_default(attributeSemantic);
const hasAccessorId = defined_default(accessorId);
if (hasBufferViewId === hasDraco) {
throw new DeveloperError_default(
"One of options.bufferViewId and options.draco must be defined."
);
}
if (hasDraco && !hasAttributeSemantic) {
throw new DeveloperError_default(
"When options.draco is defined options.attributeSemantic must also be defined."
);
}
if (hasDraco && !hasAccessorId) {
throw new DeveloperError_default(
"When options.draco is defined options.haAccessorId must also be defined."
);
}
if (hasDraco) {
Check_default.typeOf.object("options.draco", draco);
Check_default.typeOf.string("options.attributeSemantic", attributeSemantic);
Check_default.typeOf.number("options.accessorId", accessorId);
}
const cacheKey = ResourceCacheKey_default.getVertexBufferCacheKey({
gltf,
gltfResource,
baseResource: baseResource2,
frameState,
bufferViewId,
draco,
attributeSemantic,
dequantize,
loadBuffer,
loadTypedArray
});
let vertexBufferLoader = ResourceCache.get(cacheKey);
if (defined_default(vertexBufferLoader)) {
return vertexBufferLoader;
}
vertexBufferLoader = new GltfVertexBufferLoader_default({
resourceCache: ResourceCache,
gltf,
gltfResource,
baseResource: baseResource2,
bufferViewId,
draco,
attributeSemantic,
accessorId,
cacheKey,
asynchronous,
dequantize,
loadBuffer,
loadTypedArray
});
return ResourceCache.add(vertexBufferLoader);
};
function hasDracoCompression3(draco, semantic) {
return defined_default(draco) && defined_default(draco.attributes) && defined_default(draco.attributes[semantic]);
}
ResourceCache.getIndexBufferLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const accessorId = options.accessorId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const frameState = options.frameState;
const draco = options.draco;
const asynchronous = defaultValue_default(options.asynchronous, true);
const loadBuffer = defaultValue_default(options.loadBuffer, false);
const loadTypedArray = defaultValue_default(options.loadTypedArray, false);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.accessorId", accessorId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.frameState", frameState);
if (!loadBuffer && !loadTypedArray) {
throw new DeveloperError_default(
"At least one of loadBuffer and loadTypedArray must be true."
);
}
const cacheKey = ResourceCacheKey_default.getIndexBufferCacheKey({
gltf,
accessorId,
gltfResource,
baseResource: baseResource2,
frameState,
draco,
loadBuffer,
loadTypedArray
});
let indexBufferLoader = ResourceCache.get(cacheKey);
if (defined_default(indexBufferLoader)) {
return indexBufferLoader;
}
indexBufferLoader = new GltfIndexBufferLoader_default({
resourceCache: ResourceCache,
gltf,
accessorId,
gltfResource,
baseResource: baseResource2,
draco,
cacheKey,
asynchronous,
loadBuffer,
loadTypedArray
});
return ResourceCache.add(indexBufferLoader);
};
ResourceCache.getImageLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const imageId = options.imageId;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.number("options.imageId", imageId);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
const cacheKey = ResourceCacheKey_default.getImageCacheKey({
gltf,
imageId,
gltfResource,
baseResource: baseResource2
});
let imageLoader = ResourceCache.get(cacheKey);
if (defined_default(imageLoader)) {
return imageLoader;
}
imageLoader = new GltfImageLoader_default({
resourceCache: ResourceCache,
gltf,
imageId,
gltfResource,
baseResource: baseResource2,
cacheKey
});
return ResourceCache.add(imageLoader);
};
ResourceCache.getTextureLoader = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const textureInfo = options.textureInfo;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const supportedImageFormats = options.supportedImageFormats;
const frameState = options.frameState;
const asynchronous = defaultValue_default(options.asynchronous, true);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.textureInfo", textureInfo);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats);
Check_default.typeOf.object("options.frameState", frameState);
const cacheKey = ResourceCacheKey_default.getTextureCacheKey({
gltf,
textureInfo,
gltfResource,
baseResource: baseResource2,
supportedImageFormats,
frameState
});
let textureLoader = ResourceCache.get(cacheKey);
if (defined_default(textureLoader)) {
return textureLoader;
}
textureLoader = new GltfTextureLoader_default({
resourceCache: ResourceCache,
gltf,
textureInfo,
gltfResource,
baseResource: baseResource2,
supportedImageFormats,
cacheKey,
asynchronous
});
return ResourceCache.add(textureLoader);
};
ResourceCache.clearForSpecs = function() {
const precedence = [
GltfVertexBufferLoader_default,
GltfIndexBufferLoader_default,
GltfDracoLoader_default,
GltfTextureLoader_default,
GltfImageLoader_default,
GltfBufferViewLoader_default,
BufferLoader_default,
MetadataSchemaLoader_default,
GltfJsonLoader_default
];
let cacheKey;
const cacheEntries = ResourceCache.cacheEntries;
const cacheEntriesSorted = [];
for (cacheKey in cacheEntries) {
if (cacheEntries.hasOwnProperty(cacheKey)) {
cacheEntriesSorted.push(cacheEntries[cacheKey]);
}
}
cacheEntriesSorted.sort(function(a3, b) {
const indexA = precedence.indexOf(a3.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_default(cacheEntries[cacheKey])) {
cacheEntry.resourceLoader.destroy();
delete cacheEntries[cacheKey];
}
}
ResourceCache.statistics.clear();
};
var ResourceCache_default = ResourceCache;
// node_modules/@cesium/engine/Source/Scene/ImplicitSubtree.js
function ImplicitSubtree(resource, implicitTileset, implicitCoordinates) {
Check_default.typeOf.object("resource", resource);
Check_default.typeOf.object("implicitTileset", implicitTileset);
Check_default.typeOf.object("implicitCoordinates", implicitCoordinates);
this._resource = resource;
this._subtreeJson = void 0;
this._bufferLoader = void 0;
this._tileAvailability = void 0;
this._contentAvailabilityBitstreams = [];
this._childSubtreeAvailability = void 0;
this._implicitCoordinates = implicitCoordinates;
this._subtreeLevels = implicitTileset.subtreeLevels;
this._subdivisionScheme = implicitTileset.subdivisionScheme;
this._branchingFactor = implicitTileset.branchingFactor;
this._metadata = void 0;
this._tileMetadataTable = void 0;
this._tilePropertyTableJson = void 0;
this._contentMetadataTables = [];
this._contentPropertyTableJsons = [];
this._tileJumpBuffer = void 0;
this._contentJumpBuffers = [];
this._ready = false;
}
Object.defineProperties(ImplicitSubtree.prototype, {
ready: {
get: function() {
return this._ready;
}
},
metadata: {
get: function() {
return this._metadata;
}
},
tileMetadataTable: {
get: function() {
return this._tileMetadataTable;
}
},
tilePropertyTableJson: {
get: function() {
return this._tilePropertyTableJson;
}
},
contentMetadataTables: {
get: function() {
return this._contentMetadataTables;
}
},
contentPropertyTableJsons: {
get: function() {
return this._contentPropertyTableJsons;
}
},
implicitCoordinates: {
get: function() {
return this._implicitCoordinates;
}
}
});
ImplicitSubtree.prototype.tileIsAvailableAtIndex = function(index) {
return this._tileAvailability.getBit(index);
};
ImplicitSubtree.prototype.tileIsAvailableAtCoordinates = function(implicitCoordinates) {
const index = this.getTileIndex(implicitCoordinates);
return this.tileIsAvailableAtIndex(index);
};
ImplicitSubtree.prototype.contentIsAvailableAtIndex = function(index, contentIndex) {
contentIndex = defaultValue_default(contentIndex, 0);
if (contentIndex < 0 || contentIndex >= this._contentAvailabilityBitstreams.length) {
throw new DeveloperError_default("contentIndex out of bounds.");
}
return this._contentAvailabilityBitstreams[contentIndex].getBit(index);
};
ImplicitSubtree.prototype.contentIsAvailableAtCoordinates = function(implicitCoordinates, contentIndex) {
const index = this.getTileIndex(implicitCoordinates);
return this.contentIsAvailableAtIndex(index, contentIndex);
};
ImplicitSubtree.prototype.childSubtreeIsAvailableAtIndex = function(index) {
return this._childSubtreeAvailability.getBit(index);
};
ImplicitSubtree.prototype.childSubtreeIsAvailableAtCoordinates = function(implicitCoordinates) {
const index = this.getChildSubtreeIndex(implicitCoordinates);
return this.childSubtreeIsAvailableAtIndex(index);
};
ImplicitSubtree.prototype.getLevelOffset = function(level) {
const branchingFactor = this._branchingFactor;
return (Math.pow(branchingFactor, level) - 1) / (branchingFactor - 1);
};
ImplicitSubtree.prototype.getParentMortonIndex = function(mortonIndex) {
let bitsPerLevel = 2;
if (this._subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
bitsPerLevel = 3;
}
return mortonIndex >> bitsPerLevel;
};
ImplicitSubtree.fromSubtreeJson = async function(resource, json, subtreeView, implicitTileset, implicitCoordinates) {
Check_default.typeOf.object("resource", resource);
if (defined_default(json) === defined_default(subtreeView)) {
throw new DeveloperError_default("One of json and subtreeView must be defined.");
}
Check_default.typeOf.object("implicitTileset", implicitTileset);
Check_default.typeOf.object("implicitCoordinates", implicitCoordinates);
const subtree = new ImplicitSubtree(
resource,
implicitTileset,
implicitCoordinates
);
let chunks;
if (defined_default(json)) {
chunks = {
json,
binary: void 0
};
} else {
chunks = parseSubtreeChunks(subtreeView);
}
const subtreeJson = chunks.json;
subtree._subtreeJson = subtreeJson;
let tilePropertyTableJson;
if (hasExtension_default(subtreeJson, "3DTILES_metadata")) {
tilePropertyTableJson = subtreeJson.extensions["3DTILES_metadata"];
} else if (defined_default(subtreeJson.tileMetadata)) {
const propertyTableIndex = subtreeJson.tileMetadata;
tilePropertyTableJson = subtreeJson.propertyTables[propertyTableIndex];
}
const contentPropertyTableJsons = [];
if (defined_default(subtreeJson.contentMetadata)) {
const length3 = subtreeJson.contentMetadata.length;
for (let i = 0; i < length3; i++) {
const propertyTableIndex = subtreeJson.contentMetadata[i];
contentPropertyTableJsons.push(
subtreeJson.propertyTables[propertyTableIndex]
);
}
}
let metadata;
const schema = implicitTileset.metadataSchema;
const subtreeMetadata = subtreeJson.subtreeMetadata;
if (defined_default(subtreeMetadata)) {
const metadataClass = subtreeMetadata.class;
const subtreeMetadataClass = schema.classes[metadataClass];
metadata = new ImplicitSubtreeMetadata_default({
subtreeMetadata,
class: subtreeMetadataClass
});
}
subtree._metadata = metadata;
subtree._tilePropertyTableJson = tilePropertyTableJson;
subtree._contentPropertyTableJsons = contentPropertyTableJsons;
const defaultContentAvailability = {
constant: 0
};
subtreeJson.contentAvailabilityHeaders = [];
if (hasExtension_default(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_default(subtreeJson.contentAvailability, defaultContentAvailability)
);
}
const bufferHeaders = preprocessBuffers(subtreeJson.buffers);
const bufferViewHeaders = preprocessBufferViews(
subtreeJson.bufferViews,
bufferHeaders
);
markActiveBufferViews(subtreeJson, bufferViewHeaders);
if (defined_default(tilePropertyTableJson)) {
markActiveMetadataBufferViews(tilePropertyTableJson, bufferViewHeaders);
}
for (let i = 0; i < contentPropertyTableJsons.length; i++) {
const contentPropertyTableJson = contentPropertyTableJsons[i];
markActiveMetadataBufferViews(contentPropertyTableJson, bufferViewHeaders);
}
const buffersU8 = await requestActiveBuffers(
subtree,
bufferHeaders,
chunks.binary
);
const bufferViewsU8 = parseActiveBufferViews(bufferViewHeaders, buffersU8);
parseAvailability(subtree, subtreeJson, implicitTileset, bufferViewsU8);
if (defined_default(tilePropertyTableJson)) {
parseTileMetadataTable(subtree, implicitTileset, bufferViewsU8);
makeTileJumpBuffer(subtree);
}
parseContentMetadataTables(subtree, implicitTileset, bufferViewsU8);
makeContentJumpBuffers(subtree);
subtree._ready = true;
return subtree;
};
function parseSubtreeChunks(subtreeView) {
const littleEndian2 = true;
const subtreeReader = new DataView(
subtreeView.buffer,
subtreeView.byteOffset
);
let byteOffset = 8;
const jsonByteLength = subtreeReader.getUint32(byteOffset, littleEndian2);
byteOffset += 8;
const binaryByteLength = subtreeReader.getUint32(byteOffset, littleEndian2);
byteOffset += 8;
const subtreeJson = getJsonFromTypedArray_default(
subtreeView,
byteOffset,
jsonByteLength
);
byteOffset += jsonByteLength;
const subtreeBinary = subtreeView.subarray(
byteOffset,
byteOffset + binaryByteLength
);
return {
json: subtreeJson,
binary: subtreeBinary
};
}
function preprocessBuffers(bufferHeaders) {
bufferHeaders = defined_default(bufferHeaders) ? bufferHeaders : [];
for (let i = 0; i < bufferHeaders.length; i++) {
const bufferHeader = bufferHeaders[i];
bufferHeader.isExternal = defined_default(bufferHeader.uri);
bufferHeader.isActive = false;
}
return bufferHeaders;
}
function preprocessBufferViews(bufferViewHeaders, bufferHeaders) {
bufferViewHeaders = defined_default(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;
}
function markActiveBufferViews(subtreeJson, bufferViewHeaders) {
let header;
const tileAvailabilityHeader = subtreeJson.tileAvailability;
if (defined_default(tileAvailabilityHeader.bitstream)) {
header = bufferViewHeaders[tileAvailabilityHeader.bitstream];
} else if (defined_default(tileAvailabilityHeader.bufferView)) {
header = bufferViewHeaders[tileAvailabilityHeader.bufferView];
}
if (defined_default(header)) {
header.isActive = true;
header.bufferHeader.isActive = true;
}
const contentAvailabilityHeaders = subtreeJson.contentAvailabilityHeaders;
for (let i = 0; i < contentAvailabilityHeaders.length; i++) {
header = void 0;
if (defined_default(contentAvailabilityHeaders[i].bitstream)) {
header = bufferViewHeaders[contentAvailabilityHeaders[i].bitstream];
} else if (defined_default(contentAvailabilityHeaders[i].bufferView)) {
header = bufferViewHeaders[contentAvailabilityHeaders[i].bufferView];
}
if (defined_default(header)) {
header.isActive = true;
header.bufferHeader.isActive = true;
}
}
header = void 0;
const childSubtreeAvailabilityHeader = subtreeJson.childSubtreeAvailability;
if (defined_default(childSubtreeAvailabilityHeader.bitstream)) {
header = bufferViewHeaders[childSubtreeAvailabilityHeader.bitstream];
} else if (defined_default(childSubtreeAvailabilityHeader.bufferView)) {
header = bufferViewHeaders[childSubtreeAvailabilityHeader.bufferView];
}
if (defined_default(header)) {
header.isActive = true;
header.bufferHeader.isActive = true;
}
}
function markActiveMetadataBufferViews(propertyTableJson, bufferViewHeaders) {
const properties = propertyTableJson.properties;
let header;
for (const key in properties) {
if (properties.hasOwnProperty(key)) {
const metadataHeader = properties[key];
const valuesBufferView = defaultValue_default(
metadataHeader.values,
metadataHeader.bufferView
);
header = bufferViewHeaders[valuesBufferView];
header.isActive = true;
header.bufferHeader.isActive = true;
const stringOffsetBufferView = defaultValue_default(
metadataHeader.stringOffsets,
metadataHeader.stringOffsetBufferView
);
if (defined_default(stringOffsetBufferView)) {
header = bufferViewHeaders[stringOffsetBufferView];
header.isActive = true;
header.bufferHeader.isActive = true;
}
const arrayOffsetBufferView = defaultValue_default(
metadataHeader.arrayOffsets,
metadataHeader.arrayOffsetBufferView
);
if (defined_default(arrayOffsetBufferView)) {
header = bufferViewHeaders[arrayOffsetBufferView];
header.isActive = true;
header.bufferHeader.isActive = true;
}
}
}
}
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(void 0));
} 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_default(result)) {
buffersU8[i] = result;
}
}
return buffersU8;
});
}
async function requestExternalBuffer(subtree, bufferHeader) {
const baseResource2 = subtree._resource;
const bufferResource = baseResource2.getDerivedResource({
url: bufferHeader.uri
});
const bufferLoader = ResourceCache_default.getExternalBufferLoader({
resource: bufferResource
});
subtree._bufferLoader = bufferLoader;
try {
await bufferLoader.load();
} catch (error) {
if (bufferLoader.isDestroyed()) {
return;
}
throw error;
}
return bufferLoader.typedArray;
}
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;
}
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);
const hasMetadataExtension = hasExtension_default(subtreeJson, "3DTILES_metadata");
const hasTileMetadata = defined_default(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,
tileAvailabilityBits,
computeAvailableCountEnabled
);
subtree._contentAvailabilityBitstreams.push(bitstream);
}
subtree._childSubtreeAvailability = parseAvailabilityBitstream(
subtreeJson.childSubtreeAvailability,
bufferViewsU8,
childSubtreeBits
);
}
function parseAvailabilityBitstream(availabilityJson, bufferViewsU8, lengthBits, computeAvailableCountEnabled) {
if (defined_default(availabilityJson.constant)) {
return new ImplicitAvailabilityBitstream_default({
constant: Boolean(availabilityJson.constant),
lengthBits,
availableCount: availabilityJson.availableCount
});
}
let bufferView;
if (defined_default(availabilityJson.bitstream)) {
bufferView = bufferViewsU8[availabilityJson.bitstream];
} else if (defined_default(availabilityJson.bufferView)) {
bufferView = bufferViewsU8[availabilityJson.bufferView];
}
return new ImplicitAvailabilityBitstream_default({
bitstream: bufferView,
lengthBits,
availableCount: availabilityJson.availableCount,
computeAvailableCountEnabled
});
}
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_default({
class: tileMetadataClass,
count: tileCount,
properties: tilePropertyTableJson.properties,
bufferViews: bufferViewsU8
});
}
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_default({
class: contentMetadataClass,
count: contentCount,
properties: contentPropertyTableJson.properties,
bufferViews: bufferViewsU8
});
contentMetadataTables.push(metadataTable);
}
}
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;
}
function makeTileJumpBuffer(subtree) {
const tileJumpBuffer = makeJumpBuffer(subtree._tileAvailability);
subtree._tileJumpBuffer = tileJumpBuffer;
}
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);
}
}
ImplicitSubtree.prototype.getTileIndex = function(implicitCoordinates) {
const localLevel = implicitCoordinates.level - this._implicitCoordinates.level;
if (localLevel < 0 || this._subtreeLevels <= localLevel) {
throw new RuntimeError_default("level is out of bounds for this subtree");
}
const subtreeCoordinates = implicitCoordinates.getSubtreeCoordinates();
const offsetCoordinates = subtreeCoordinates.getOffsetCoordinates(
implicitCoordinates
);
const index = offsetCoordinates.tileIndex;
return index;
};
ImplicitSubtree.prototype.getChildSubtreeIndex = function(implicitCoordinates) {
const localLevel = implicitCoordinates.level - this._implicitCoordinates.level;
if (localLevel !== this._implicitCoordinates.subtreeLevels) {
throw new RuntimeError_default("level is out of bounds for this subtree");
}
const parentSubtreeCoordinates = implicitCoordinates.getParentSubtreeCoordinates();
const offsetCoordinates = parentSubtreeCoordinates.getOffsetCoordinates(
implicitCoordinates
);
const index = offsetCoordinates.mortonIndex;
return index;
};
function getTileEntityId(subtree, implicitCoordinates) {
if (!defined_default(subtree._tileMetadataTable)) {
return void 0;
}
const tileIndex = subtree.getTileIndex(implicitCoordinates);
if (subtree._tileAvailability.getBit(tileIndex)) {
return subtree._tileJumpBuffer[tileIndex];
}
return void 0;
}
function getContentEntityId(subtree, implicitCoordinates, contentIndex) {
const metadataTables = subtree._contentMetadataTables;
if (!defined_default(metadataTables)) {
return void 0;
}
const metadataTable = metadataTables[contentIndex];
if (!defined_default(metadataTable)) {
return void 0;
}
const availability = subtree._contentAvailabilityBitstreams[contentIndex];
const tileIndex = subtree.getTileIndex(implicitCoordinates);
if (availability.getBit(tileIndex)) {
const contentJumpBuffer = subtree._contentJumpBuffers[contentIndex];
return contentJumpBuffer[tileIndex];
}
return void 0;
}
ImplicitSubtree.prototype.getTileMetadataView = function(implicitCoordinates) {
const entityId = getTileEntityId(this, implicitCoordinates);
if (!defined_default(entityId)) {
return void 0;
}
const metadataTable = this._tileMetadataTable;
return new ImplicitMetadataView_default({
class: metadataTable.class,
metadataTable,
entityId,
propertyTableJson: this._tilePropertyTableJson
});
};
ImplicitSubtree.prototype.getContentMetadataView = function(implicitCoordinates, contentIndex) {
const entityId = getContentEntityId(this, implicitCoordinates, contentIndex);
if (!defined_default(entityId)) {
return void 0;
}
const metadataTable = this._contentMetadataTables[contentIndex];
const propertyTableJson = this._contentPropertyTableJsons[contentIndex];
return new ImplicitMetadataView_default({
class: metadataTable.class,
metadataTable,
entityId,
contentIndex,
propertyTableJson
});
};
ImplicitSubtree.prototype.isDestroyed = function() {
return false;
};
ImplicitSubtree.prototype.destroy = function() {
if (defined_default(this._bufferLoader)) {
ResourceCache_default.unload(this._bufferLoader);
}
return destroyObject_default(this);
};
var ImplicitSubtree_default = ImplicitSubtree;
// node_modules/@cesium/engine/Source/Scene/MetadataSemantic.js
var MetadataSemantic = {
ID: "ID",
NAME: "NAME",
DESCRIPTION: "DESCRIPTION",
TILESET_TILE_COUNT: "TILESET_TILE_COUNT",
TILE_BOUNDING_BOX: "TILE_BOUNDING_BOX",
TILE_BOUNDING_REGION: "TILE_BOUNDING_REGION",
TILE_BOUNDING_SPHERE: "TILE_BOUNDING_SPHERE",
TILE_MINIMUM_HEIGHT: "TILE_MINIMUM_HEIGHT",
TILE_MAXIMUM_HEIGHT: "TILE_MAXIMUM_HEIGHT",
TILE_HORIZON_OCCLUSION_POINT: "TILE_HORIZON_OCCLUSION_POINT",
TILE_GEOMETRIC_ERROR: "TILE_GEOMETRIC_ERROR",
CONTENT_BOUNDING_BOX: "CONTENT_BOUNDING_BOX",
CONTENT_BOUNDING_REGION: "CONTENT_BOUNDING_REGION",
CONTENT_BOUNDING_SPHERE: "CONTENT_BOUNDING_SPHERE",
CONTENT_MINIMUM_HEIGHT: "CONTENT_MINIMUM_HEIGHT",
CONTENT_MAXIMUM_HEIGHT: "CONTENT_MAXIMUM_HEIGHT",
CONTENT_HORIZON_OCCLUSION_POINT: "CONTENT_HORIZON_OCCLUSION_POINT"
};
var MetadataSemantic_default = Object.freeze(MetadataSemantic);
// node_modules/@cesium/engine/Source/Scene/parseBoundingVolumeSemantics.js
function parseBoundingVolumeSemantics(tileMetadata) {
Check_default.typeOf.object("tileMetadata", tileMetadata);
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)
}
};
}
function parseBoundingVolume(prefix, tileMetadata) {
const boundingBoxSemantic = `${prefix}_BOUNDING_BOX`;
const boundingBox = tileMetadata.getPropertyBySemantic(boundingBoxSemantic);
if (defined_default(boundingBox)) {
return {
box: boundingBox
};
}
const boundingRegionSemantic = `${prefix}_BOUNDING_REGION`;
const boundingRegion = tileMetadata.getPropertyBySemantic(
boundingRegionSemantic
);
if (defined_default(boundingRegion)) {
return {
region: boundingRegion
};
}
const boundingSphereSemantic = `${prefix}_BOUNDING_SPHERE`;
const boundingSphere = tileMetadata.getPropertyBySemantic(
boundingSphereSemantic
);
if (defined_default(boundingSphere)) {
return {
sphere: boundingSphere
};
}
return void 0;
}
function parseMinimumHeight(prefix, tileMetadata) {
const minimumHeightSemantic = `${prefix}_MINIMUM_HEIGHT`;
return tileMetadata.getPropertyBySemantic(minimumHeightSemantic);
}
function parseMaximumHeight(prefix, tileMetadata) {
const maximumHeightSemantic = `${prefix}_MAXIMUM_HEIGHT`;
return tileMetadata.getPropertyBySemantic(maximumHeightSemantic);
}
var parseBoundingVolumeSemantics_default = parseBoundingVolumeSemantics;
// node_modules/@cesium/engine/Source/Scene/Implicit3DTileContent.js
function Implicit3DTileContent(tileset, tile, resource) {
Check_default.defined("tile.implicitTileset", tile.implicitTileset);
Check_default.defined("tile.implicitCoordinates", tile.implicitCoordinates);
const implicitTileset = tile.implicitTileset;
const implicitCoordinates = tile.implicitCoordinates;
this._implicitTileset = implicitTileset;
this._implicitCoordinates = implicitCoordinates;
this._implicitSubtree = void 0;
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
this._metadata = void 0;
this.featurePropertiesDirty = false;
this._group = void 0;
const templateValues = implicitCoordinates.getTemplateValues();
const subtreeResource = implicitTileset.subtreeUriTemplate.getDerivedResource(
{
templateValues
}
);
this._url = subtreeResource.getUrlComponent(true);
this._ready = false;
this._readyPromise = void 0;
}
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 void 0;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Implicit3DTileContent.readyPromise",
"Implicit3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Implicit3DTileContent.ready to return true instead."
);
return this._readyPromise;
}
},
tileset: {
get: function() {
return this._tileset;
}
},
tile: {
get: function() {
return this._tile;
}
},
url: {
get: function() {
return this._url;
}
},
metadata: {
get: function() {
return void 0;
},
set: function() {
throw new DeveloperError_default("Implicit3DTileContent cannot have metadata");
}
},
batchTable: {
get: function() {
return void 0;
}
},
group: {
get: function() {
return this._group;
},
set: function(value) {
this._group = value;
}
}
});
Implicit3DTileContent.fromSubtreeJson = async function(tileset, tile, resource, json, arrayBuffer, byteOffset) {
Check_default.defined("tile.implicitTileset", tile.implicitTileset);
Check_default.defined("tile.implicitCoordinates", tile.implicitCoordinates);
if (defined_default(json) === defined_default(arrayBuffer)) {
throw new DeveloperError_default("One of json and arrayBuffer must be defined.");
}
byteOffset = defaultValue_default(byteOffset, 0);
let uint8Array;
if (defined_default(arrayBuffer)) {
uint8Array = new Uint8Array(arrayBuffer, byteOffset);
}
const implicitTileset = tile.implicitTileset;
const implicitCoordinates = tile.implicitCoordinates;
const subtree = await ImplicitSubtree_default.fromSubtreeJson(
resource,
json,
uint8Array,
implicitTileset,
implicitCoordinates
);
const content = new Implicit3DTileContent(tileset, tile, resource);
content._implicitSubtree = subtree;
expandSubtree(content, subtree);
content._ready = true;
content._readyPromise = Promise.resolve(content);
return content;
};
function expandSubtree(content, subtree) {
const placeholderTile = content._tile;
const childIndex = content._implicitCoordinates.childIndex;
const results = transcodeSubtreeTiles(
content,
subtree,
placeholderTile,
childIndex
);
const statistics2 = content._tileset.statistics;
placeholderTile.children.push(results.rootTile);
statistics2.numberOfTilesTotal++;
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);
statistics2.numberOfTilesTotal++;
}
}
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_default(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;
}
function transcodeSubtreeTiles(content, subtree, placeholderTile, childIndex) {
const rootBitIndex = 0;
const rootParentIsPlaceholder = true;
const rootTile = deriveChildTile(
content,
subtree,
placeholderTile,
childIndex,
rootBitIndex,
rootParentIsPlaceholder
);
const statistics2 = content._tileset.statistics;
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(void 0);
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);
statistics2.numberOfTilesTotal++;
currentRow.push(childTile);
}
parentRow = currentRow;
currentRow = [];
}
return {
rootTile,
bottomRow: parentRow
};
}
function getGeometricError(tileMetadata, implicitTileset, implicitCoordinates) {
const semantic = MetadataSemantic_default.TILE_GEOMETRIC_ERROR;
if (defined_default(tileMetadata) && tileMetadata.hasPropertyBySemantic(semantic)) {
return tileMetadata.getPropertyBySemantic(semantic);
}
return implicitTileset.geometricError / Math.pow(2, implicitCoordinates.level);
}
function deriveChildTile(implicitContent, subtree, parentTile, childIndex, childBitIndex, parentIsPlaceholderTile) {
const implicitTileset = implicitContent._implicitTileset;
let implicitCoordinates;
if (defaultValue_default(parentIsPlaceholderTile, false)) {
implicitCoordinates = parentTile.implicitCoordinates;
} else {
implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
childIndex
);
}
let tileMetadata;
let tileBounds;
let contentBounds;
if (defined_default(subtree.tilePropertyTableJson)) {
tileMetadata = subtree.getTileMetadataView(implicitCoordinates);
const boundingVolumeSemantics = parseBoundingVolumeSemantics_default(tileMetadata);
tileBounds = boundingVolumeSemantics.tile;
contentBounds = boundingVolumeSemantics.content;
}
const contentPropertyTableJsons = subtree.contentPropertyTableJsons;
const length3 = contentPropertyTableJsons.length;
let hasImplicitContentMetadata = false;
for (let i = 0; i < length3; 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(
boundingVolume,
contentBounds
);
if (defined_default(contentBoundingVolume)) {
contentJson.boundingVolume = contentBoundingVolume;
}
contentJsons.push(combine_default(contentJson, implicitTileset.contentHeaders[i]));
}
const childGeometricError = getGeometricError(
tileMetadata,
implicitTileset,
implicitCoordinates
);
const tileJson = {
boundingVolume,
geometricError: childGeometricError,
refine: implicitTileset.refine,
contents: contentJsons
};
const deep = true;
const rootHeader = clone_default(implicitTileset.tileHeader, deep);
delete rootHeader.boundingVolume;
delete rootHeader.transform;
const combinedTileJson = combine_default(tileJson, rootHeader, deep);
const childTile = makeTile(
implicitContent,
implicitTileset.baseResource,
combinedTileJson,
parentTile
);
childTile.implicitCoordinates = implicitCoordinates;
childTile.implicitSubtree = subtree;
childTile.metadata = tileMetadata;
childTile.hasImplicitContentMetadata = hasImplicitContentMetadata;
return childTile;
}
function canUpdateHeights(boundingVolume, tileBounds) {
return defined_default(boundingVolume) && defined_default(tileBounds) && (defined_default(tileBounds.minimumHeight) || defined_default(tileBounds.maximumHeight)) && (hasExtension_default(boundingVolume, "3DTILES_bounding_volume_S2") || defined_default(boundingVolume.region));
}
function updateHeights(boundingVolume, tileBounds) {
if (!defined_default(tileBounds)) {
return;
}
if (hasExtension_default(boundingVolume, "3DTILES_bounding_volume_S2")) {
updateS2CellHeights(
boundingVolume.extensions["3DTILES_bounding_volume_S2"],
tileBounds.minimumHeight,
tileBounds.maximumHeight
);
} else if (defined_default(boundingVolume.region)) {
updateRegionHeights(
boundingVolume.region,
tileBounds.minimumHeight,
tileBounds.maximumHeight
);
}
}
function updateRegionHeights(region, minimumHeight, maximumHeight) {
if (defined_default(minimumHeight)) {
region[4] = minimumHeight;
}
if (defined_default(maximumHeight)) {
region[5] = maximumHeight;
}
}
function updateS2CellHeights(s2CellVolume, minimumHeight, maximumHeight) {
if (defined_default(minimumHeight)) {
s2CellVolume.minimumHeight = minimumHeight;
}
if (defined_default(maximumHeight)) {
s2CellVolume.maximumHeight = maximumHeight;
}
}
function getTileBoundingVolume(implicitTileset, implicitCoordinates, childIndex, parentIsPlaceholderTile, parentTile, tileBounds) {
let boundingVolume;
if (!defined_default(tileBounds) || !defined_default(tileBounds.boundingVolume) || !canUpdateHeights(tileBounds.boundingVolume, tileBounds) && canUpdateHeights(implicitTileset.boundingVolume, tileBounds)) {
boundingVolume = deriveBoundingVolume(
implicitTileset,
implicitCoordinates,
childIndex,
defaultValue_default(parentIsPlaceholderTile, false),
parentTile
);
} else {
boundingVolume = tileBounds.boundingVolume;
}
updateHeights(boundingVolume, tileBounds);
return boundingVolume;
}
function getContentBoundingVolume(tileBoundingVolume, contentBounds) {
let contentBoundingVolume;
if (defined_default(contentBounds)) {
contentBoundingVolume = contentBounds.boundingVolume;
}
if (canUpdateHeights(contentBoundingVolume, contentBounds)) {
updateHeights(contentBoundingVolume, contentBounds);
} else if (canUpdateHeights(tileBoundingVolume, contentBounds)) {
contentBoundingVolume = clone_default(tileBoundingVolume, true);
updateHeights(contentBoundingVolume, contentBounds);
}
return contentBoundingVolume;
}
function deriveBoundingVolume(implicitTileset, implicitCoordinates, childIndex, parentIsPlaceholderTile, parentTile) {
const rootBoundingVolume = implicitTileset.boundingVolume;
if (hasExtension_default(rootBoundingVolume, "3DTILES_bounding_volume_S2")) {
return deriveBoundingVolumeS2(
parentIsPlaceholderTile,
parentTile,
childIndex,
implicitCoordinates.level,
implicitCoordinates.x,
implicitCoordinates.y,
implicitCoordinates.z
);
}
if (defined_default(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
};
}
function deriveBoundingVolumeS2(parentIsPlaceholderTile, parentTile, childIndex, level, x, y, z) {
Check_default.typeOf.bool("parentIsPlaceholderTile", parentIsPlaceholderTile);
Check_default.typeOf.object("parentTile", parentTile);
Check_default.typeOf.number("childIndex", childIndex);
Check_default.typeOf.number("level", level);
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (defined_default(z)) {
Check_default.typeOf.number("z", z);
}
const boundingVolumeS2 = parentTile._boundingVolume;
if (parentIsPlaceholderTile) {
return {
extensions: {
"3DTILES_bounding_volume_S2": {
token: S2Cell_default.getTokenFromId(boundingVolumeS2.s2Cell._cellId),
minimumHeight: boundingVolumeS2.minimumHeight,
maximumHeight: boundingVolumeS2.maximumHeight
}
}
};
}
const face = Number(parentTile._boundingVolume.s2Cell._cellId >> BigInt(61));
const position = face % 2 === 0 ? HilbertOrder_default.encode2D(level, x, y) : HilbertOrder_default.encode2D(level, y, x);
const cell = S2Cell_default.fromFacePositionLevel(face, BigInt(position), level);
let minHeight, maxHeight;
if (defined_default(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_default.getTokenFromId(cell._cellId),
minimumHeight: minHeight,
maximumHeight: maxHeight
}
}
};
}
var scratchScaleFactors = new Cartesian3_default();
var scratchRootCenter = new Cartesian3_default();
var scratchCenter2 = new Cartesian3_default();
var scratchHalfAxes = new Matrix3_default();
function deriveBoundingBox(rootBox, level, x, y, z) {
Check_default.typeOf.object("rootBox", rootBox);
Check_default.typeOf.number("level", level);
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (defined_default(z)) {
Check_default.typeOf.number("z", z);
}
if (level === 0) {
return rootBox;
}
const rootCenter = Cartesian3_default.unpack(rootBox, 0, scratchRootCenter);
const rootHalfAxes = Matrix3_default.unpack(rootBox, 3, scratchHalfAxes);
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_default.fromElements(
tileScale,
tileScale,
1,
scratchScaleFactors
);
if (defined_default(z)) {
modelSpaceZ = -1 + (2 * z + 1) * tileScale;
scaleFactors.z = tileScale;
}
let center = Cartesian3_default.fromElements(
modelSpaceX,
modelSpaceY,
modelSpaceZ,
scratchCenter2
);
center = Matrix3_default.multiplyByVector(rootHalfAxes, center, scratchCenter2);
center = Cartesian3_default.add(center, rootCenter, scratchCenter2);
let halfAxes = Matrix3_default.clone(rootHalfAxes);
halfAxes = Matrix3_default.multiplyByScale(halfAxes, scaleFactors, halfAxes);
const childBox = new Array(12);
Cartesian3_default.pack(center, childBox);
Matrix3_default.pack(halfAxes, childBox, 3);
return childBox;
}
var scratchRectangle = new Rectangle_default();
function deriveBoundingRegion(rootRegion, level, x, y, z) {
Check_default.typeOf.object("rootRegion", rootRegion);
Check_default.typeOf.number("level", level);
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (defined_default(z)) {
Check_default.typeOf.number("z", z);
}
if (level === 0) {
return rootRegion.slice();
}
const rectangle = Rectangle_default.unpack(rootRegion, 0, scratchRectangle);
const rootMinimumHeight = rootRegion[4];
const rootMaximumHeight = rootRegion[5];
const tileScale = Math.pow(2, -level);
const childWidth = tileScale * rectangle.width;
const west = Math_default.negativePiToPi(rectangle.west + x * childWidth);
const east = Math_default.negativePiToPi(west + childWidth);
const childHeight = tileScale * rectangle.height;
const south = Math_default.negativePiToPi(rectangle.south + y * childHeight);
const north = Math_default.negativePiToPi(south + childHeight);
let minimumHeight = rootMinimumHeight;
let maximumHeight = rootMaximumHeight;
if (defined_default(z)) {
const childThickness = tileScale * (rootMaximumHeight - rootMinimumHeight);
minimumHeight += z * childThickness;
maximumHeight = minimumHeight + childThickness;
}
return [west, south, east, north, minimumHeight, maximumHeight];
}
function makePlaceholderChildSubtree(content, parentTile, childIndex) {
const implicitTileset = content._implicitTileset;
const implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
childIndex
);
const childBoundingVolume = deriveBoundingVolume(
implicitTileset,
implicitCoordinates,
childIndex,
false,
parentTile
);
const childGeometricError = getGeometricError(
void 0,
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(
content,
implicitTileset.baseResource,
tileJson,
parentTile
);
tile.implicitTileset = implicitTileset;
tile.implicitCoordinates = implicitCoordinates;
return tile;
}
function makeTile(content, baseResource2, tileJson, parentTile) {
const Cesium3DTile2 = content._tile.constructor;
return new Cesium3DTile2(content._tileset, baseResource2, tileJson, parentTile);
}
Implicit3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Implicit3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
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_default(this);
};
Implicit3DTileContent._deriveBoundingBox = deriveBoundingBox;
Implicit3DTileContent._deriveBoundingRegion = deriveBoundingRegion;
Implicit3DTileContent._deriveBoundingVolumeS2 = deriveBoundingVolumeS2;
var Implicit3DTileContent_default = Implicit3DTileContent;
// node_modules/@cesium/engine/Source/Scene/ModelAnimationLoop.js
var ModelAnimationLoop = {
NONE: 0,
REPEAT: 1,
MIRRORED_REPEAT: 2
};
var ModelAnimationLoop_default = Object.freeze(ModelAnimationLoop);
// node_modules/@cesium/engine/Source/Scene/ClippingPlane.js
function ClippingPlane(normal2, distance2) {
Check_default.typeOf.object("normal", normal2);
Check_default.typeOf.number("distance", distance2);
this._distance = distance2;
this._normal = new UpdateChangedCartesian3(normal2, this);
this.onChangeCallback = void 0;
this.index = -1;
}
Object.defineProperties(ClippingPlane.prototype, {
distance: {
get: function() {
return this._distance;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (defined_default(this.onChangeCallback) && value !== this._distance) {
this.onChangeCallback(this.index);
}
this._distance = value;
}
},
normal: {
get: function() {
return this._normal;
},
set: function(value) {
Check_default.typeOf.object("value", value);
if (defined_default(this.onChangeCallback) && !Cartesian3_default.equals(this._normal._cartesian3, value)) {
this.onChangeCallback(this.index);
}
Cartesian3_default.clone(value, this._normal._cartesian3);
}
}
});
ClippingPlane.fromPlane = function(plane, result) {
Check_default.typeOf.object("plane", plane);
if (!defined_default(result)) {
result = new ClippingPlane(plane.normal, plane.distance);
} else {
result.normal = plane.normal;
result.distance = plane.distance;
}
return result;
};
ClippingPlane.clone = function(clippingPlane, result) {
if (!defined_default(result)) {
return new ClippingPlane(clippingPlane.normal, clippingPlane.distance);
}
result.normal = clippingPlane.normal;
result.distance = clippingPlane.distance;
return result;
};
function UpdateChangedCartesian3(normal2, clippingPlane) {
this._clippingPlane = clippingPlane;
this._cartesian3 = Cartesian3_default.clone(normal2);
}
Object.defineProperties(UpdateChangedCartesian3.prototype, {
x: {
get: function() {
return this._cartesian3.x;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (defined_default(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) {
Check_default.typeOf.number("value", value);
if (defined_default(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) {
Check_default.typeOf.number("value", value);
if (defined_default(this._clippingPlane.onChangeCallback) && value !== this._cartesian3.z) {
this._clippingPlane.onChangeCallback(this._clippingPlane.index);
}
this._cartesian3.z = value;
}
}
});
var ClippingPlane_default = ClippingPlane;
// node_modules/@cesium/engine/Source/Scene/ClippingPlaneCollection.js
function ClippingPlaneCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._planes = [];
this._dirtyIndex = -1;
this._multipleDirtyPlanes = false;
this._enabled = defaultValue_default(options.enabled, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this.edgeColor = Color_default.clone(defaultValue_default(options.edgeColor, Color_default.WHITE));
this.edgeWidth = defaultValue_default(options.edgeWidth, 0);
this.planeAdded = new Event_default();
this.planeRemoved = new Event_default();
this._owner = void 0;
const unionClippingRegions = defaultValue_default(
options.unionClippingRegions,
false
);
this._unionClippingRegions = unionClippingRegions;
this._testIntersection = unionClippingRegions ? unionIntersectFunction : defaultIntersectFunction;
this._uint8View = void 0;
this._float32View = void 0;
this._clippingPlanesTexture = void 0;
const planes = options.planes;
if (defined_default(planes)) {
const planesLength = planes.length;
for (let i = 0; i < planesLength; ++i) {
this.add(planes[i]);
}
}
}
function unionIntersectFunction(value) {
return value === Intersect_default.OUTSIDE;
}
function defaultIntersectFunction(value) {
return value === Intersect_default.INSIDE;
}
Object.defineProperties(ClippingPlaneCollection.prototype, {
length: {
get: function() {
return this._planes.length;
}
},
unionClippingRegions: {
get: function() {
return this._unionClippingRegions;
},
set: function(value) {
if (this._unionClippingRegions === value) {
return;
}
this._unionClippingRegions = value;
this._testIntersection = value ? unionIntersectFunction : defaultIntersectFunction;
}
},
enabled: {
get: function() {
return this._enabled;
},
set: function(value) {
if (this._enabled === value) {
return;
}
this._enabled = value;
}
},
texture: {
get: function() {
return this._clippingPlanesTexture;
}
},
owner: {
get: function() {
return this._owner;
}
},
clippingPlanesState: {
get: function() {
return this._unionClippingRegions ? this._planes.length : -this._planes.length;
}
}
});
function setIndexDirty(collection, index) {
collection._multipleDirtyPlanes = collection._multipleDirtyPlanes || collection._dirtyIndex !== -1 && collection._dirtyIndex !== index;
collection._dirtyIndex = index;
}
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);
};
ClippingPlaneCollection.prototype.get = function(index) {
Check_default.typeOf.number("index", index);
return this._planes[index];
};
function indexOf(planes, plane) {
const length3 = planes.length;
for (let i = 0; i < length3; ++i) {
if (Plane_default.equals(planes[i], plane)) {
return i;
}
}
return -1;
}
ClippingPlaneCollection.prototype.contains = function(clippingPlane) {
return indexOf(this._planes, clippingPlane) !== -1;
};
ClippingPlaneCollection.prototype.remove = function(clippingPlane) {
const planes = this._planes;
const index = indexOf(planes, clippingPlane);
if (index === -1) {
return false;
}
if (clippingPlane instanceof ClippingPlane_default) {
clippingPlane.onChangeCallback = void 0;
clippingPlane.index = -1;
}
const length3 = planes.length - 1;
for (let i = index; i < length3; ++i) {
const planeToKeep = planes[i + 1];
planes[i] = planeToKeep;
if (planeToKeep instanceof ClippingPlane_default) {
planeToKeep.index = i;
}
}
this._multipleDirtyPlanes = true;
planes.length = length3;
this.planeRemoved.raiseEvent(clippingPlane, index);
return true;
};
ClippingPlaneCollection.prototype.removeAll = function() {
const planes = this._planes;
const planesCount = planes.length;
for (let i = 0; i < planesCount; ++i) {
const plane = planes[i];
if (plane instanceof ClippingPlane_default) {
plane.onChangeCallback = void 0;
plane.index = -1;
}
this.planeRemoved.raiseEvent(plane, i);
}
this._multipleDirtyPlanes = true;
this._planes = [];
};
var distanceEncodeScratch = new Cartesian4_default();
var oct32EncodeScratch = new Cartesian4_default();
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_default.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_default.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;
}
}
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 normal2 = plane.normal;
float32View[floatIndex] = normal2.x;
float32View[floatIndex + 1] = normal2.y;
float32View[floatIndex + 2] = normal2.z;
float32View[floatIndex + 3] = plane.distance;
floatIndex += 4;
}
}
function computeTextureResolution(pixelsNeeded, result) {
const maxSize = ContextLimits_default.maximumTextureSize;
result.x = Math.min(pixelsNeeded, maxSize);
result.y = Math.ceil(pixelsNeeded / result.x);
return result;
}
var textureResolutionScratch = new Cartesian2_default();
ClippingPlaneCollection.prototype.update = function(frameState) {
let clippingPlanesTexture = this._clippingPlanesTexture;
const context = frameState.context;
const useFloatTexture = ClippingPlaneCollection.useFloatTexture(context);
const pixelsNeeded = useFloatTexture ? this.length : this.length * 2;
if (defined_default(clippingPlanesTexture)) {
const currentPixelCount = clippingPlanesTexture.width * clippingPlanesTexture.height;
if (currentPixelCount < pixelsNeeded || pixelsNeeded < 0.25 * currentPixelCount) {
clippingPlanesTexture.destroy();
clippingPlanesTexture = void 0;
this._clippingPlanesTexture = void 0;
}
}
if (this.length === 0) {
return;
}
if (!defined_default(clippingPlanesTexture)) {
const requiredResolution = computeTextureResolution(
pixelsNeeded,
textureResolutionScratch
);
requiredResolution.y *= 2;
if (useFloatTexture) {
clippingPlanesTexture = new Texture_default({
context,
width: requiredResolution.x,
height: requiredResolution.y,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: PixelDatatype_default.FLOAT,
sampler: Sampler_default.NEAREST,
flipY: false
});
this._float32View = new Float32Array(
requiredResolution.x * requiredResolution.y * 4
);
} else {
clippingPlanesTexture = new Texture_default({
context,
width: requiredResolution.x,
height: requiredResolution.y,
pixelFormat: PixelFormat_default.RGBA,
pixelDatatype: PixelDatatype_default.UNSIGNED_BYTE,
sampler: Sampler_default.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) {
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;
};
var scratchMatrix = new Matrix4_default();
var scratchPlane3 = new Plane_default(Cartesian3_default.UNIT_X, 0);
ClippingPlaneCollection.prototype.computeIntersectionWithBoundingVolume = function(tileBoundingVolume, transform3) {
const planes = this._planes;
const length3 = planes.length;
let modelMatrix = this.modelMatrix;
if (defined_default(transform3)) {
modelMatrix = Matrix4_default.multiply(transform3, modelMatrix, scratchMatrix);
}
let intersection = Intersect_default.INSIDE;
if (!this.unionClippingRegions && length3 > 0) {
intersection = Intersect_default.OUTSIDE;
}
for (let i = 0; i < length3; ++i) {
const plane = planes[i];
Plane_default.transform(plane, modelMatrix, scratchPlane3);
const value = tileBoundingVolume.intersectPlane(scratchPlane3);
if (value === Intersect_default.INTERSECTING) {
intersection = value;
} else if (this._testIntersection(value)) {
return value;
}
}
return intersection;
};
ClippingPlaneCollection.setOwner = function(clippingPlaneCollection, owner, key) {
if (clippingPlaneCollection === owner[key]) {
return;
}
owner[key] = owner[key] && owner[key].destroy();
if (defined_default(clippingPlaneCollection)) {
if (defined_default(clippingPlaneCollection._owner)) {
throw new DeveloperError_default(
"ClippingPlaneCollection should only be assigned to one object"
);
}
clippingPlaneCollection._owner = owner;
owner[key] = clippingPlaneCollection;
}
};
ClippingPlaneCollection.useFloatTexture = function(context) {
return context.floatingPointTexture;
};
ClippingPlaneCollection.getTextureResolution = function(clippingPlaneCollection, context, result) {
const texture = clippingPlaneCollection.texture;
if (defined_default(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);
requiredResolution.y *= 2;
return requiredResolution;
};
ClippingPlaneCollection.prototype.isDestroyed = function() {
return false;
};
ClippingPlaneCollection.prototype.destroy = function() {
this._clippingPlanesTexture = this._clippingPlanesTexture && this._clippingPlanesTexture.destroy();
return destroyObject_default(this);
};
var ClippingPlaneCollection_default = ClippingPlaneCollection;
// node_modules/@cesium/engine/Source/Scene/ColorBlendMode.js
var ColorBlendMode = {
HIGHLIGHT: 0,
REPLACE: 1,
MIX: 2
};
ColorBlendMode.getColorBlend = function(colorBlendMode, colorBlendAmount) {
if (colorBlendMode === ColorBlendMode.HIGHLIGHT) {
return 0;
} else if (colorBlendMode === ColorBlendMode.REPLACE) {
return 1;
} else if (colorBlendMode === ColorBlendMode.MIX) {
return Math_default.clamp(colorBlendAmount, Math_default.EPSILON4, 1);
}
};
var ColorBlendMode_default = Object.freeze(ColorBlendMode);
// node_modules/@cesium/engine/Source/Core/ArticulationStageType.js
var ArticulationStageType = {
XTRANSLATE: "xTranslate",
YTRANSLATE: "yTranslate",
ZTRANSLATE: "zTranslate",
XROTATE: "xRotate",
YROTATE: "yRotate",
ZROTATE: "zRotate",
XSCALE: "xScale",
YSCALE: "yScale",
ZSCALE: "zScale",
UNIFORMSCALE: "uniformScale"
};
var ArticulationStageType_default = Object.freeze(ArticulationStageType);
// node_modules/@cesium/engine/Source/Core/InterpolationType.js
var InterpolationType = {
STEP: 0,
LINEAR: 1,
CUBICSPLINE: 2
};
var InterpolationType_default = Object.freeze(InterpolationType);
// node_modules/@cesium/engine/Source/Scene/JsonMetadataTable.js
var emptyClass = {};
function JsonMetadataTable(options) {
Check_default.typeOf.number.greaterThan("options.count", options.count, 0);
Check_default.typeOf.object("options.properties", options.properties);
this._count = options.count;
this._properties = clone_default(options.properties, true);
}
JsonMetadataTable.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, emptyClass);
};
JsonMetadataTable.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, emptyClass, results);
};
JsonMetadataTable.prototype.getProperty = function(index, propertyId) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("propertyId", propertyId);
if (index < 0 || index >= this._count) {
throw new DeveloperError_default(`index must be in the range [0, ${this._count})`);
}
const property = this._properties[propertyId];
if (defined_default(property)) {
return clone_default(property[index], true);
}
return void 0;
};
JsonMetadataTable.prototype.setProperty = function(index, propertyId, value) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("propertyId", propertyId);
if (index < 0 || index >= this._count) {
throw new DeveloperError_default(`index must be in the range [0, ${this._count})`);
}
let property = this._properties[propertyId];
if (!defined_default(property)) {
property = new Array(this._count);
this._properties[propertyId] = property;
}
property[index] = clone_default(value, true);
};
var JsonMetadataTable_default = JsonMetadataTable;
// node_modules/@cesium/engine/Source/Scene/PropertyTable.js
function PropertyTable(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.number("options.count", options.count);
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, {
name: {
get: function() {
return this._name;
}
},
id: {
get: function() {
return this._id;
}
},
count: {
get: function() {
return this._count;
}
},
class: {
get: function() {
if (defined_default(this._metadataTable)) {
return this._metadataTable.class;
}
return void 0;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
},
byteLength: {
get: function() {
let totalByteLength = 0;
if (defined_default(this._metadataTable)) {
totalByteLength += this._metadataTable.byteLength;
}
if (defined_default(this._batchTableHierarchy)) {
totalByteLength += this._batchTableHierarchy.byteLength;
}
return totalByteLength;
}
}
});
PropertyTable.prototype.hasProperty = function(index, propertyId) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("propertyId", propertyId);
if (defined_default(this._metadataTable) && this._metadataTable.hasProperty(propertyId)) {
return true;
}
if (defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.hasProperty(index, propertyId)) {
return true;
}
if (defined_default(this._jsonMetadataTable) && this._jsonMetadataTable.hasProperty(propertyId)) {
return true;
}
return false;
};
PropertyTable.prototype.hasPropertyBySemantic = function(index, semantic) {
Check_default.typeOf.number("index", index);
Check_default.typeOf.string("semantic", semantic);
if (defined_default(this._metadataTable)) {
return this._metadataTable.hasPropertyBySemantic(semantic);
}
return false;
};
PropertyTable.prototype.propertyExists = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
if (defined_default(this._metadataTable) && this._metadataTable.hasProperty(propertyId)) {
return true;
}
if (defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.propertyExists(propertyId)) {
return true;
}
if (defined_default(this._jsonMetadataTable) && this._jsonMetadataTable.hasProperty(propertyId)) {
return true;
}
return false;
};
PropertyTable.prototype.propertyExistsBySemantic = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
if (defined_default(this._metadataTable)) {
return this._metadataTable.hasPropertyBySemantic(semantic);
}
return false;
};
var scratchResults = [];
PropertyTable.prototype.getPropertyIds = function(index, results) {
results = defined_default(results) ? results : [];
results.length = 0;
if (defined_default(this._metadataTable)) {
results.push.apply(
results,
this._metadataTable.getPropertyIds(scratchResults)
);
}
if (defined_default(this._batchTableHierarchy)) {
results.push.apply(
results,
this._batchTableHierarchy.getPropertyIds(index, scratchResults)
);
}
if (defined_default(this._jsonMetadataTable)) {
results.push.apply(
results,
this._jsonMetadataTable.getPropertyIds(scratchResults)
);
}
return results;
};
PropertyTable.prototype.getProperty = function(index, propertyId) {
let result;
if (defined_default(this._metadataTable)) {
result = this._metadataTable.getProperty(index, propertyId);
if (defined_default(result)) {
return result;
}
}
if (defined_default(this._batchTableHierarchy)) {
result = this._batchTableHierarchy.getProperty(index, propertyId);
if (defined_default(result)) {
return result;
}
}
if (defined_default(this._jsonMetadataTable)) {
result = this._jsonMetadataTable.getProperty(index, propertyId);
if (defined_default(result)) {
return result;
}
}
return void 0;
};
PropertyTable.prototype.setProperty = function(index, propertyId, value) {
if (defined_default(this._metadataTable) && this._metadataTable.setProperty(index, propertyId, value)) {
return;
}
if (defined_default(this._batchTableHierarchy) && this._batchTableHierarchy.setProperty(index, propertyId, value)) {
return;
}
if (!defined_default(this._jsonMetadataTable)) {
this._jsonMetadataTable = new JsonMetadataTable_default({
count: this._count,
properties: {}
});
}
this._jsonMetadataTable.setProperty(index, propertyId, value);
};
PropertyTable.prototype.getPropertyBySemantic = function(index, semantic) {
if (defined_default(this._metadataTable)) {
return this._metadataTable.getPropertyBySemantic(index, semantic);
}
return void 0;
};
PropertyTable.prototype.setPropertyBySemantic = function(index, semantic, value) {
if (defined_default(this._metadataTable)) {
return this._metadataTable.setPropertyBySemantic(index, semantic, value);
}
return false;
};
PropertyTable.prototype.getPropertyTypedArray = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
if (defined_default(this._metadataTable)) {
return this._metadataTable.getPropertyTypedArray(propertyId);
}
return void 0;
};
PropertyTable.prototype.getPropertyTypedArrayBySemantic = function(semantic) {
Check_default.typeOf.string("semantic", semantic);
if (defined_default(this._metadataTable)) {
return this._metadataTable.getPropertyTypedArrayBySemantic(semantic);
}
return void 0;
};
function checkFeatureId(featureId, featuresLength) {
if (!defined_default(featureId) || featureId < 0 || featureId >= featuresLength) {
throw new DeveloperError_default(
`featureId is required and must be between zero and featuresLength - 1 (${featuresLength}` - +")."
);
}
}
PropertyTable.prototype.isClass = function(featureId, className) {
checkFeatureId(featureId, this.count);
Check_default.typeOf.string("className", className);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return false;
}
return hierarchy.isClass(featureId, className);
};
PropertyTable.prototype.isExactClass = function(featureId, className) {
checkFeatureId(featureId, this.count);
Check_default.typeOf.string("className", className);
return this.getExactClassName(featureId) === className;
};
PropertyTable.prototype.getExactClassName = function(featureId) {
checkFeatureId(featureId, this.count);
const hierarchy = this._batchTableHierarchy;
if (!defined_default(hierarchy)) {
return void 0;
}
return hierarchy.getClassName(featureId);
};
var PropertyTable_default = PropertyTable;
// node_modules/@cesium/engine/Source/Scene/PropertyTextureProperty.js
function PropertyTextureProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const property = options.property;
const classProperty = options.classProperty;
const textures = options.textures;
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.object("options.classProperty", classProperty);
Check_default.typeOf.object("options.textures", textures);
const channels = defined_default(property.channels) ? property.channels : [0];
const textureInfo = property;
const textureReader = GltfLoaderUtil_default.createModelTextureReader({
textureInfo,
channels: reformatChannels(channels),
texture: textures[textureInfo.index]
});
this._min = property.min;
this._max = property.max;
let offset2 = property.offset;
let scale = property.scale;
const hasValueTransform = classProperty.hasValueTransform || defined_default(offset2) || defined_default(scale);
offset2 = defaultValue_default(offset2, classProperty.offset);
scale = defaultValue_default(scale, classProperty.scale);
offset2 = classProperty.unpackVectorAndMatrixTypes(offset2);
scale = classProperty.unpackVectorAndMatrixTypes(scale);
this._offset = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._textureReader = textureReader;
this._classProperty = classProperty;
this._extras = property.extras;
this._extensions = property.extensions;
}
Object.defineProperties(PropertyTextureProperty.prototype, {
textureReader: {
get: function() {
return this._textureReader;
}
},
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
offset: {
get: function() {
return this._offset;
}
},
scale: {
get: function() {
return this._scale;
}
},
classProperty: {
get: function() {
return this._classProperty;
}
},
extras: {
get: function() {
return this._extras;
}
},
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) {
return !classProperty.isVariableLengthArray && classProperty.arrayLength <= 4 && type === MetadataType_default.SCALAR && componentType === MetadataComponentType_default.UINT8;
}
if (MetadataType_default.isVectorType(type) || type === MetadataType_default.SCALAR) {
return componentType === MetadataComponentType_default.UINT8;
}
return false;
};
var floatTypesByComponentCount = [void 0, "float", "vec2", "vec3", "vec4"];
var integerTypesByComponentCount = [
void 0,
"int",
"ivec2",
"ivec3",
"ivec4"
];
PropertyTextureProperty.prototype.getGlslType = function() {
const classProperty = this._classProperty;
let componentCount = MetadataType_default.getComponentCount(classProperty.type);
if (classProperty.isArray) {
componentCount = classProperty.arrayLength;
}
if (classProperty.normalized) {
return floatTypesByComponentCount[componentCount];
}
return integerTypesByComponentCount[componentCount];
};
PropertyTextureProperty.prototype.unpackInShader = function(packedValueGlsl) {
const classProperty = this._classProperty;
if (classProperty.normalized) {
return packedValueGlsl;
}
const glslType = this.getGlslType();
return `${glslType}(255.0 * ${packedValueGlsl})`;
};
function reformatChannels(channels) {
return channels.map(function(channelIndex) {
return "rgba".charAt(channelIndex);
}).join("");
}
var PropertyTextureProperty_default = PropertyTextureProperty;
// node_modules/@cesium/engine/Source/Scene/PropertyTexture.js
function PropertyTexture(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const propertyTexture = options.propertyTexture;
const classDefinition = options.class;
const textures = options.textures;
Check_default.typeOf.object("options.propertyTexture", propertyTexture);
Check_default.typeOf.object("options.class", classDefinition);
Check_default.typeOf.object("options.textures", textures);
const extensions = propertyTexture.extensions;
const extras = propertyTexture.extras;
const properties = {};
if (defined_default(propertyTexture.properties)) {
for (const propertyId in propertyTexture.properties) {
if (propertyTexture.properties.hasOwnProperty(propertyId)) {
properties[propertyId] = new PropertyTextureProperty_default({
property: propertyTexture.properties[propertyId],
classProperty: classDefinition.properties[propertyId],
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, {
name: {
get: function() {
return this._name;
}
},
id: {
get: function() {
return this._id;
}
},
class: {
get: function() {
return this._class;
}
},
properties: {
get: function() {
return this._properties;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
PropertyTexture.prototype.getProperty = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
return this._properties[propertyId];
};
var PropertyTexture_default = PropertyTexture;
// node_modules/@cesium/engine/Source/Scene/PropertyAttributeProperty.js
function PropertyAttributeProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const property = options.property;
const classProperty = options.classProperty;
Check_default.typeOf.object("options.property", property);
Check_default.typeOf.object("options.classProperty", classProperty);
this._attribute = property.attribute;
this._classProperty = classProperty;
this._min = property.min;
this._max = property.max;
let offset2 = property.offset;
let scale = property.scale;
const hasValueTransform = classProperty.hasValueTransform || defined_default(offset2) || defined_default(scale);
offset2 = defaultValue_default(offset2, classProperty.offset);
scale = defaultValue_default(scale, classProperty.scale);
offset2 = classProperty.unpackVectorAndMatrixTypes(offset2);
scale = classProperty.unpackVectorAndMatrixTypes(scale);
this._offset = offset2;
this._scale = scale;
this._hasValueTransform = hasValueTransform;
this._extras = property.extras;
this._extensions = property.extensions;
}
Object.defineProperties(PropertyAttributeProperty.prototype, {
attribute: {
get: function() {
return this._attribute;
}
},
hasValueTransform: {
get: function() {
return this._hasValueTransform;
}
},
offset: {
get: function() {
return this._offset;
}
},
scale: {
get: function() {
return this._scale;
}
},
classProperty: {
get: function() {
return this._classProperty;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
var PropertyAttributeProperty_default = PropertyAttributeProperty;
// node_modules/@cesium/engine/Source/Scene/PropertyAttribute.js
function PropertyAttribute(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const propertyAttribute = options.propertyAttribute;
const classDefinition = options.class;
Check_default.typeOf.object("options.propertyAttribute", propertyAttribute);
Check_default.typeOf.object("options.class", classDefinition);
const properties = {};
if (defined_default(propertyAttribute.properties)) {
for (const propertyId in propertyAttribute.properties) {
if (propertyAttribute.properties.hasOwnProperty(propertyId)) {
properties[propertyId] = new PropertyAttributeProperty_default({
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, {
name: {
get: function() {
return this._name;
}
},
id: {
get: function() {
return this._id;
}
},
class: {
get: function() {
return this._class;
}
},
properties: {
get: function() {
return this._properties;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
PropertyAttribute.prototype.getProperty = function(propertyId) {
Check_default.typeOf.string("propertyId", propertyId);
return this._properties[propertyId];
};
var PropertyAttribute_default = PropertyAttribute;
// node_modules/@cesium/engine/Source/Scene/StructuralMetadata.js
function StructuralMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.schema", options.schema);
this._schema = options.schema;
const propertyTables = options.propertyTables;
this._propertyTableCount = defined_default(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: {
get: function() {
return this._schema;
}
},
statistics: {
get: function() {
return this._statistics;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
},
propertyTableCount: {
get: function() {
return this._propertyTableCount;
}
},
propertyTables: {
get: function() {
return this._propertyTables;
}
},
propertyTextures: {
get: function() {
return this._propertyTextures;
}
},
propertyAttributes: {
get: function() {
return this._propertyAttributes;
}
},
propertyTablesByteLength: {
get: function() {
if (!defined_default(this._propertyTables)) {
return 0;
}
let totalByteLength = 0;
const length3 = this._propertyTables.length;
for (let i = 0; i < length3; i++) {
totalByteLength += this._propertyTables[i].byteLength;
}
return totalByteLength;
}
}
});
StructuralMetadata.prototype.getPropertyTable = function(propertyTableId) {
Check_default.typeOf.number("propertyTableId", propertyTableId);
return this._propertyTables[propertyTableId];
};
StructuralMetadata.prototype.getPropertyTexture = function(propertyTextureId) {
Check_default.typeOf.number("propertyTextureId", propertyTextureId);
return this._propertyTextures[propertyTextureId];
};
StructuralMetadata.prototype.getPropertyAttribute = function(propertyAttributeId) {
Check_default.typeOf.number("propertyAttributeId", propertyAttributeId);
return this._propertyAttributes[propertyAttributeId];
};
var StructuralMetadata_default = StructuralMetadata;
// node_modules/@cesium/engine/Source/Scene/parseStructuralMetadata.js
function parseStructuralMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const extension = options.extension;
const schema = options.schema;
Check_default.typeOf.object("options.extension", extension);
Check_default.typeOf.object("options.schema", schema);
const propertyTables = [];
if (defined_default(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_default({
count: propertyTable.count,
properties: propertyTable.properties,
class: classDefinition,
bufferViews: options.bufferViews
});
propertyTables.push(
new PropertyTable_default({
id: i,
name: propertyTable.name,
count: propertyTable.count,
metadataTable,
extras: propertyTable.extras,
extensions: propertyTable.extensions
})
);
}
}
const propertyTextures = [];
if (defined_default(extension.propertyTextures)) {
for (let i = 0; i < extension.propertyTextures.length; i++) {
const propertyTexture = extension.propertyTextures[i];
propertyTextures.push(
new PropertyTexture_default({
id: i,
name: propertyTexture.name,
propertyTexture,
class: schema.classes[propertyTexture.class],
textures: options.textures
})
);
}
}
const propertyAttributes = [];
if (defined_default(extension.propertyAttributes)) {
for (let i = 0; i < extension.propertyAttributes.length; i++) {
const propertyAttribute = extension.propertyAttributes[i];
propertyAttributes.push(
new PropertyAttribute_default({
id: i,
name: propertyAttribute.name,
class: schema.classes[propertyAttribute.class],
propertyAttribute
})
);
}
}
return new StructuralMetadata_default({
schema,
propertyTables,
propertyTextures,
propertyAttributes,
statistics: extension.statistics,
extras: extension.extras,
extensions: extension.extensions
});
}
var parseStructuralMetadata_default = parseStructuralMetadata;
// node_modules/@cesium/engine/Source/Scene/parseFeatureMetadataLegacy.js
function parseFeatureMetadataLegacy(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const extension = options.extension;
const schema = options.schema;
Check_default.typeOf.object("options.extension", extension);
Check_default.typeOf.object("options.schema", schema);
let i;
const propertyTables = [];
let sortedIds;
if (defined_default(extension.featureTables)) {
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_default({
count: featureTable.count,
properties: featureTable.properties,
class: classDefinition,
bufferViews: options.bufferViews
});
propertyTables.push(
new PropertyTable_default({
id: featureTableId,
count: featureTable.count,
metadataTable,
extras: featureTable.extras,
extensions: featureTable.extensions
})
);
}
}
const propertyTextures = [];
if (defined_default(extension.featureTextures)) {
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_default({
id: featureTextureId,
propertyTexture: transcodeToPropertyTexture(featureTexture),
class: schema.classes[featureTexture.class],
textures: options.textures
})
);
}
}
return new StructuralMetadata_default({
schema,
propertyTables,
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 = {
channels: reformatChannels2(oldProperty.channels),
extras: oldProperty.extras,
extensions: oldProperty.extensions
};
propertyTexture.properties[propertyId] = combine_default(
oldProperty.texture,
property,
true
);
}
}
return propertyTexture;
}
function reformatChannels2(channelsString) {
const length3 = channelsString.length;
const result = new Array(length3);
for (let i = 0; i < length3; i++) {
result[i] = "rgba".indexOf(channelsString[i]);
}
return result;
}
var parseFeatureMetadataLegacy_default = parseFeatureMetadataLegacy;
// node_modules/@cesium/engine/Source/Scene/GltfStructuralMetadataLoader.js
function GltfStructuralMetadataLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltf = options.gltf;
const extension = options.extension;
const extensionLegacy = options.extensionLegacy;
const gltfResource = options.gltfResource;
const baseResource2 = options.baseResource;
const supportedImageFormats = options.supportedImageFormats;
const frameState = options.frameState;
const cacheKey = options.cacheKey;
const asynchronous = defaultValue_default(options.asynchronous, true);
Check_default.typeOf.object("options.gltf", gltf);
Check_default.typeOf.object("options.gltfResource", gltfResource);
Check_default.typeOf.object("options.baseResource", baseResource2);
Check_default.typeOf.object("options.supportedImageFormats", supportedImageFormats);
Check_default.typeOf.object("options.frameState", frameState);
if (!defined_default(options.extension) && !defined_default(options.extensionLegacy)) {
throw new DeveloperError_default(
"One of options.extension or options.extensionLegacy must be specified"
);
}
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
this._gltf = gltf;
this._extension = extension;
this._extensionLegacy = extensionLegacy;
this._supportedImageFormats = supportedImageFormats;
this._frameState = frameState;
this._cacheKey = cacheKey;
this._asynchronous = asynchronous;
this._bufferViewLoaders = [];
this._bufferViewIds = [];
this._textureLoaders = [];
this._textureIds = [];
this._schemaLoader = void 0;
this._structuralMetadata = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._promise = void 0;
}
if (defined_default(Object.create)) {
GltfStructuralMetadataLoader.prototype = Object.create(
ResourceLoader_default.prototype
);
GltfStructuralMetadataLoader.prototype.constructor = GltfStructuralMetadataLoader;
}
Object.defineProperties(GltfStructuralMetadataLoader.prototype, {
cacheKey: {
get: function() {
return this._cacheKey;
}
},
structuralMetadata: {
get: function() {
return this._structuralMetadata;
}
}
});
async function loadResources4(loader) {
try {
const bufferViewsPromise = loadBufferViews(loader);
const texturesPromise = loadTextures(loader);
const schemaPromise = loadSchema(loader);
await Promise.all([bufferViewsPromise, texturesPromise, schemaPromise]);
if (loader.isDestroyed()) {
return;
}
loader._gltf = void 0;
loader._state = ResourceLoaderState_default.LOADED;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader.unload();
loader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load structural metadata";
throw loader.getError(errorMessage, error);
}
}
GltfStructuralMetadataLoader.prototype.load = function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._state = ResourceLoaderState_default.LOADING;
this._promise = loadResources4(this);
return this._promise;
};
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;
if (defined_default(values)) {
bufferViewIdSet[values] = true;
}
if (defined_default(arrayOffsets)) {
bufferViewIdSet[arrayOffsets] = true;
}
if (defined_default(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;
if (defined_default(bufferView)) {
bufferViewIdSet[bufferView] = true;
}
if (defined_default(arrayOffsetBufferView)) {
bufferViewIdSet[arrayOffsetBufferView] = true;
}
if (defined_default(stringOffsetBufferView)) {
bufferViewIdSet[stringOffsetBufferView] = true;
}
}
}
}
function gatherUsedBufferViewIds(extension) {
const propertyTables = extension.propertyTables;
const bufferViewIdSet = {};
if (defined_default(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_default(featureTables)) {
for (const featureTableId in featureTables) {
if (featureTables.hasOwnProperty(featureTableId)) {
const featureTable = featureTables[featureTableId];
const properties = featureTable.properties;
if (defined_default(properties)) {
gatherBufferViewIdsFromPropertiesLegacy(properties, bufferViewIdSet);
}
}
}
}
return bufferViewIdSet;
}
async function loadBufferViews(structuralMetadataLoader) {
let bufferViewIds;
if (defined_default(structuralMetadataLoader._extension)) {
bufferViewIds = gatherUsedBufferViewIds(
structuralMetadataLoader._extension
);
} else {
bufferViewIds = gatherUsedBufferViewIdsLegacy(
structuralMetadataLoader._extensionLegacy
);
}
const bufferViewPromises = [];
for (const bufferViewId in bufferViewIds) {
if (bufferViewIds.hasOwnProperty(bufferViewId)) {
const bufferViewLoader = ResourceCache_default.getBufferViewLoader({
gltf: structuralMetadataLoader._gltf,
bufferViewId: parseInt(bufferViewId),
gltfResource: structuralMetadataLoader._gltfResource,
baseResource: structuralMetadataLoader._baseResource
});
structuralMetadataLoader._bufferViewLoaders.push(bufferViewLoader);
structuralMetadataLoader._bufferViewIds.push(bufferViewId);
bufferViewPromises.push(bufferViewLoader.load());
}
}
return Promise.all(bufferViewPromises);
}
function gatherUsedTextureIds(structuralMetadataExtension) {
const textureIds = {};
const propertyTextures = structuralMetadataExtension.propertyTextures;
if (defined_default(propertyTextures)) {
for (let i = 0; i < propertyTextures.length; i++) {
const propertyTexture = propertyTextures[i];
const properties = propertyTexture.properties;
if (defined_default(properties)) {
gatherTextureIdsFromProperties(properties, textureIds);
}
}
}
return textureIds;
}
function gatherTextureIdsFromProperties(properties, textureIds) {
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const textureInfo = properties[propertyId];
textureIds[textureInfo.index] = textureInfo;
}
}
}
function gatherUsedTextureIdsLegacy(extensionLegacy) {
const textureIds = {};
const featureTextures = extensionLegacy.featureTextures;
if (defined_default(featureTextures)) {
for (const featureTextureId in featureTextures) {
if (featureTextures.hasOwnProperty(featureTextureId)) {
const featureTexture = featureTextures[featureTextureId];
const properties = featureTexture.properties;
if (defined_default(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_default(structuralMetadataLoader._extension)) {
textureIds = gatherUsedTextureIds(structuralMetadataLoader._extension);
} else {
textureIds = gatherUsedTextureIdsLegacy(
structuralMetadataLoader._extensionLegacy
);
}
const gltf = structuralMetadataLoader._gltf;
const gltfResource = structuralMetadataLoader._gltfResource;
const baseResource2 = structuralMetadataLoader._baseResource;
const supportedImageFormats = structuralMetadataLoader._supportedImageFormats;
const frameState = structuralMetadataLoader._frameState;
const asynchronous = structuralMetadataLoader._asynchronous;
const texturePromises = [];
for (const textureId in textureIds) {
if (textureIds.hasOwnProperty(textureId)) {
const textureLoader = ResourceCache_default.getTextureLoader({
gltf,
textureInfo: textureIds[textureId],
gltfResource,
baseResource: baseResource2,
supportedImageFormats,
frameState,
asynchronous
});
structuralMetadataLoader._textureLoaders.push(textureLoader);
structuralMetadataLoader._textureIds.push(textureId);
texturePromises.push(textureLoader.load());
}
}
return Promise.all(texturePromises);
}
async function loadSchema(structuralMetadataLoader) {
const extension = defaultValue_default(
structuralMetadataLoader._extension,
structuralMetadataLoader._extensionLegacy
);
let schemaLoader;
if (defined_default(extension.schemaUri)) {
const resource = structuralMetadataLoader._baseResource.getDerivedResource({
url: extension.schemaUri
});
schemaLoader = ResourceCache_default.getSchemaLoader({
resource
});
} else {
schemaLoader = ResourceCache_default.getSchemaLoader({
schema: extension.schema
});
}
structuralMetadataLoader._schemaLoader = schemaLoader;
await schemaLoader.load();
if (!schemaLoader.isDestroyed()) {
return schemaLoader.schema;
}
}
GltfStructuralMetadataLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state !== ResourceLoaderState_default.LOADED) {
return false;
}
const textureLoaders = this._textureLoaders;
const textureLoadersLength = textureLoaders.length;
let ready = true;
for (let i = 0; i < textureLoadersLength; ++i) {
const textureLoader = textureLoaders[i];
const textureReady = textureLoader.process(frameState);
ready = ready && textureReady;
}
if (!ready) {
return false;
}
const schema = this._schemaLoader.schema;
const bufferViews = {};
for (let i = 0; i < this._bufferViewIds.length; ++i) {
const bufferViewId = this._bufferViewIds[i];
const bufferViewLoader = this._bufferViewLoaders[i];
if (!bufferViewLoader.isDestroyed()) {
const bufferViewTypedArray = new Uint8Array(bufferViewLoader.typedArray);
bufferViews[bufferViewId] = bufferViewTypedArray;
}
}
const textures = {};
for (let i = 0; i < this._textureIds.length; ++i) {
const textureId = this._textureIds[i];
const textureLoader = textureLoaders[i];
if (!textureLoader.isDestroyed()) {
textures[textureId] = textureLoader.texture;
}
}
if (defined_default(this._extension)) {
this._structuralMetadata = parseStructuralMetadata_default({
extension: this._extension,
schema,
bufferViews,
textures
});
} else {
this._structuralMetadata = parseFeatureMetadataLegacy_default({
extension: this._extensionLegacy,
schema,
bufferViews,
textures
});
}
unloadBufferViews(this);
this._state = ResourceLoaderState_default.READY;
return true;
};
function unloadBufferViews(structuralMetadataLoader) {
const bufferViewLoaders = structuralMetadataLoader._bufferViewLoaders;
const bufferViewLoadersLength = bufferViewLoaders.length;
for (let i = 0; i < bufferViewLoadersLength; ++i) {
ResourceCache_default.unload(bufferViewLoaders[i]);
}
structuralMetadataLoader._bufferViewLoaders.length = 0;
structuralMetadataLoader._bufferViewIds.length = 0;
}
function unloadTextures(structuralMetadataLoader) {
const textureLoaders = structuralMetadataLoader._textureLoaders;
const textureLoadersLength = textureLoaders.length;
for (let i = 0; i < textureLoadersLength; ++i) {
ResourceCache_default.unload(textureLoaders[i]);
}
structuralMetadataLoader._textureLoaders.length = 0;
structuralMetadataLoader._textureIds.length = 0;
}
GltfStructuralMetadataLoader.prototype.unload = function() {
unloadBufferViews(this);
unloadTextures(this);
if (defined_default(this._schemaLoader)) {
ResourceCache_default.unload(this._schemaLoader);
}
this._schemaLoader = void 0;
this._structuralMetadata = void 0;
};
var GltfStructuralMetadataLoader_default = GltfStructuralMetadataLoader;
// node_modules/@cesium/engine/Source/Scene/InstanceAttributeSemantic.js
var InstanceAttributeSemantic = {
TRANSLATION: "TRANSLATION",
ROTATION: "ROTATION",
SCALE: "SCALE",
FEATURE_ID: "_FEATURE_ID"
};
InstanceAttributeSemantic.fromGltfSemantic = function(gltfSemantic) {
Check_default.typeOf.string("gltfSemantic", gltfSemantic);
let semantic = gltfSemantic;
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 void 0;
};
var InstanceAttributeSemantic_default = Object.freeze(InstanceAttributeSemantic);
// node_modules/@cesium/engine/Source/Scene/Model/PrimitiveOutlineGenerator.js
var MAX_GLTF_UINT16_INDEX = 65534;
var MAX_GLTF_UINT8_INDEX = 255;
function PrimitiveOutlineGenerator(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const triangleIndices = options.triangleIndices;
const outlineIndices = options.outlineIndices;
const originalVertexCount = options.originalVertexCount;
Check_default.typeOf.object("options.triangleIndices", triangleIndices);
Check_default.typeOf.object("options.outlineIndices", outlineIndices);
Check_default.typeOf.number("options.originalVertexCount", originalVertexCount);
this._triangleIndices = triangleIndices;
this._originalVertexCount = originalVertexCount;
this._edges = new EdgeSet(outlineIndices, originalVertexCount);
this._outlineCoordinatesTypedArray = void 0;
this._extraVertices = [];
initialize5(this);
}
Object.defineProperties(PrimitiveOutlineGenerator.prototype, {
updatedTriangleIndices: {
get: function() {
return this._triangleIndices;
}
},
outlineCoordinates: {
get: function() {
return this._outlineCoordinatesTypedArray;
}
}
});
function initialize5(outlineGenerator) {
let triangleIndices = outlineGenerator._triangleIndices;
const edges = outlineGenerator._edges;
const outlineCoordinates = [];
const extraVertices = outlineGenerator._extraVertices;
const vertexCount = outlineGenerator._originalVertexCount;
const vertexCopies = {};
for (let i = 0; i < triangleIndices.length; i += 3) {
let i0 = triangleIndices[i];
let i1 = triangleIndices[i + 1];
let i2 = triangleIndices[i + 2];
const all = false;
const hasEdge01 = all || edges.hasEdge(i0, i1);
const hasEdge12 = all || edges.hasEdge(i1, i2);
const hasEdge20 = all || edges.hasEdge(i2, i0);
let unmatchableVertexIndex = matchAndStoreCoordinates(
outlineCoordinates,
i0,
i1,
i2,
hasEdge01,
hasEdge12,
hasEdge20
);
while (defined_default(unmatchableVertexIndex)) {
let copy = vertexCopies[unmatchableVertexIndex];
if (!defined_default(copy)) {
copy = vertexCount + extraVertices.length;
let original2 = unmatchableVertexIndex;
while (original2 >= vertexCount) {
original2 = extraVertices[original2 - vertexCount];
}
extraVertices.push(original2);
vertexCopies[unmatchableVertexIndex] = copy;
}
if (copy > MAX_GLTF_UINT16_INDEX && (triangleIndices instanceof Uint16Array || triangleIndices instanceof Uint8Array)) {
triangleIndices = new Uint32Array(triangleIndices);
} else if (copy > MAX_GLTF_UINT8_INDEX && triangleIndices instanceof Uint8Array) {
triangleIndices = new Uint16Array(triangleIndices);
}
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;
}
unmatchableVertexIndex = matchAndStoreCoordinates(
outlineCoordinates,
i0,
i1,
i2,
hasEdge01,
hasEdge12,
hasEdge20
);
}
}
outlineGenerator._triangleIndices = triangleIndices;
outlineGenerator._outlineCoordinatesTypedArray = new Float32Array(
outlineCoordinates
);
}
function matchAndStoreCoordinates(outlineCoordinates, i0, i1, i2, hasEdge01, hasEdge12, hasEdge20) {
const a0 = hasEdge20 ? 1 : 0;
const b0 = hasEdge01 ? 1 : 0;
const c0 = 0;
const i0Mask = computeOrderMask(outlineCoordinates, i0, a0, b0, c0);
if (i0Mask === 0) {
return i0;
}
const a1 = 0;
const b1 = hasEdge01 ? 1 : 0;
const c14 = hasEdge12 ? 1 : 0;
const i1Mask = computeOrderMask(outlineCoordinates, i1, a1, b1, c14);
if (i1Mask === 0) {
return i1;
}
const a22 = hasEdge20 ? 1 : 0;
const b2 = 0;
const c22 = hasEdge12 ? 1 : 0;
const i2Mask = computeOrderMask(outlineCoordinates, i2, a22, b2, c22);
if (i2Mask === 0) {
return i2;
}
const workingOrders = i0Mask & i1Mask & i2Mask;
let a3, b, c;
if (workingOrders & 1 << 0) {
a3 = 0;
b = 1;
c = 2;
} else if (workingOrders & 1 << 1) {
a3 = 0;
c = 1;
b = 2;
} else if (workingOrders & 1 << 2) {
b = 0;
a3 = 1;
c = 2;
} else if (workingOrders & 1 << 3) {
b = 0;
c = 1;
a3 = 2;
} else if (workingOrders & 1 << 4) {
c = 0;
a3 = 1;
b = 2;
} else if (workingOrders & 1 << 5) {
c = 0;
b = 1;
a3 = 2;
} else {
const i0ValidOrderCount = popcount6Bit(i0Mask);
const i1ValidOrderCount = popcount6Bit(i1Mask);
const i2ValidOrderCount = popcount6Bit(i2Mask);
if (i0ValidOrderCount < i1ValidOrderCount && i0ValidOrderCount < i2ValidOrderCount) {
return i0;
} else if (i1ValidOrderCount < i2ValidOrderCount) {
return i1;
}
return i2;
}
const i0Start = i0 * 3;
outlineCoordinates[i0Start + a3] = a0;
outlineCoordinates[i0Start + b] = b0;
outlineCoordinates[i0Start + c] = c0;
const i1Start = i1 * 3;
outlineCoordinates[i1Start + a3] = a1;
outlineCoordinates[i1Start + b] = b1;
outlineCoordinates[i1Start + c] = c14;
const i2Start = i2 * 3;
outlineCoordinates[i2Start + a3] = a22;
outlineCoordinates[i2Start + b] = b2;
outlineCoordinates[i2Start + c] = c22;
return void 0;
}
function computeOrderMask(outlineCoordinates, vertexIndex, a3, b, c) {
const startIndex = vertexIndex * 3;
const first = outlineCoordinates[startIndex];
const second = outlineCoordinates[startIndex + 1];
const third = outlineCoordinates[startIndex + 2];
if (!defined_default(first)) {
return 63;
}
return (first === a3 && second === b && third === c) << 0 | (first === a3 && second === c && third === b) << 1 | (first === b && second === a3 && third === c) << 2 | (first === b && second === c && third === a3) << 3 | (first === c && second === a3 && third === b) << 4 | (first === c && second === b && third === a3) << 5;
}
function popcount6Bit(value) {
return (value & 1) + (value >> 1 & 1) + (value >> 2 & 1) + (value >> 3 & 1) + (value >> 4 & 1) + (value >> 5 & 1);
}
PrimitiveOutlineGenerator.prototype.updateAttribute = function(attributeTypedArray) {
const extraVertices = this._extraVertices;
const originalLength = attributeTypedArray.length;
const stride = originalLength / this._originalVertexCount;
const extraVerticesLength = extraVertices.length;
const ArrayType = attributeTypedArray.constructor;
const result = new ArrayType(
attributeTypedArray.length + extraVerticesLength * stride
);
result.set(attributeTypedArray);
for (let i = 0; i < extraVerticesLength; i++) {
const sourceIndex = extraVertices[i] * stride;
const resultIndex = originalLength + i * stride;
for (let j = 0; j < stride; j++) {
result[resultIndex + j] = result[sourceIndex + j];
}
}
return result;
};
PrimitiveOutlineGenerator.createTexture = function(context) {
let cache = context.cache.modelOutliningCache;
if (!defined_default(cache)) {
cache = context.cache.modelOutliningCache = {};
}
if (defined_default(cache.outlineTexture)) {
return cache.outlineTexture;
}
const maxSize = Math.min(4096, ContextLimits_default.maximumTextureSize);
let size = maxSize;
const levelZero = createMipLevel(size);
const mipLevels = [];
while (size > 1) {
size >>= 1;
mipLevels.push(createMipLevel(size));
}
const texture = new Texture_default({
context,
source: {
arrayBufferView: levelZero,
mipLevels
},
width: maxSize,
height: 1,
pixelFormat: PixelFormat_default.LUMINANCE,
sampler: new Sampler_default({
wrapS: TextureWrap_default.CLAMP_TO_EDGE,
wrapT: TextureWrap_default.CLAMP_TO_EDGE,
minificationFilter: TextureMinificationFilter_default.LINEAR_MIPMAP_LINEAR,
magnificationFilter: TextureMagnificationFilter_default.LINEAR
})
});
cache.outlineTexture = texture;
return texture;
};
function createMipLevel(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 EdgeSet(edgeIndices, originalVertexCount) {
this._originalVertexCount = originalVertexCount;
this._edges = /* @__PURE__ */ new Set();
for (let i = 0; i < edgeIndices.length; i += 2) {
const a3 = edgeIndices[i];
const b = edgeIndices[i + 1];
const small = Math.min(a3, b);
const big = Math.max(a3, b);
const hash2 = small * this._originalVertexCount + big;
this._edges.add(hash2);
}
}
EdgeSet.prototype.hasEdge = function(a3, b) {
const small = Math.min(a3, b);
const big = Math.max(a3, b);
const hash2 = small * this._originalVertexCount + big;
return this._edges.has(hash2);
};
var PrimitiveOutlineGenerator_default = PrimitiveOutlineGenerator;
// node_modules/@cesium/engine/Source/Scene/PrimitiveLoadPlan.js
function AttributeLoadPlan(attribute) {
Check_default.typeOf.object("attribute", attribute);
this.attribute = attribute;
this.loadBuffer = false;
this.loadTypedArray = false;
}
function IndicesLoadPlan(indices2) {
Check_default.typeOf.object("indices", indices2);
this.indices = indices2;
this.loadBuffer = false;
this.loadTypedArray = false;
}
function PrimitiveLoadPlan(primitive) {
Check_default.typeOf.object("primitive", primitive);
this.primitive = primitive;
this.attributePlans = [];
this.indicesPlan = void 0;
this.needsOutlines = false;
this.outlineIndices = void 0;
}
PrimitiveLoadPlan.prototype.postProcess = function(context) {
if (this.needsOutlines) {
generateOutlines(this);
generateBuffers(this, context);
}
};
function generateOutlines(loadPlan) {
const primitive = loadPlan.primitive;
const indices2 = primitive.indices;
const vertexCount = primitive.attributes[0].count;
const generator = new PrimitiveOutlineGenerator_default({
triangleIndices: indices2.typedArray,
outlineIndices: loadPlan.outlineIndices,
originalVertexCount: vertexCount
});
indices2.typedArray = generator.updatedTriangleIndices;
indices2.indexDatatype = IndexDatatype_default.fromTypedArray(indices2.typedArray);
const outlineCoordinates = makeOutlineCoordinatesAttribute(
generator.outlineCoordinates
);
const outlineCoordinatesPlan = new AttributeLoadPlan(outlineCoordinates);
outlineCoordinatesPlan.loadBuffer = true;
outlineCoordinatesPlan.loadTypedArray = false;
loadPlan.attributePlans.push(outlineCoordinatesPlan);
primitive.outlineCoordinates = outlineCoordinatesPlan.attribute;
const attributePlans = loadPlan.attributePlans;
const attributesLength = loadPlan.attributePlans.length;
for (let i = 0; i < attributesLength; i++) {
const attribute = attributePlans[i].attribute;
attribute.typedArray = generator.updateAttribute(attribute.typedArray);
}
}
function makeOutlineCoordinatesAttribute(outlineCoordinatesTypedArray) {
const attribute = new ModelComponents_default.Attribute();
attribute.name = "_OUTLINE_COORDINATES";
attribute.typedArray = outlineCoordinatesTypedArray;
attribute.componentDatatype = ComponentDatatype_default.FLOAT;
attribute.type = AttributeType_default.VEC3;
attribute.normalized = false;
attribute.count = outlineCoordinatesTypedArray.length / 3;
return attribute;
}
function generateBuffers(loadPlan, context) {
generateAttributeBuffers(loadPlan.attributePlans, context);
if (defined_default(loadPlan.indicesPlan)) {
generateIndexBuffers(loadPlan.indicesPlan, context);
}
}
function generateAttributeBuffers(attributePlans, context) {
const attributesLength = attributePlans.length;
for (let i = 0; i < attributesLength; i++) {
const attributePlan = attributePlans[i];
const attribute = attributePlan.attribute;
const typedArray = attribute.typedArray;
if (attributePlan.loadBuffer) {
const buffer = Buffer_default.createVertexBuffer({
typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
attribute.buffer = buffer;
}
if (!attributePlan.loadTypedArray) {
attribute.typedArray = void 0;
}
}
}
function generateIndexBuffers(indicesPlan, context) {
const indices2 = indicesPlan.indices;
if (indicesPlan.loadBuffer) {
const buffer = Buffer_default.createIndexBuffer({
typedArray: indices2.typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: indices2.indexDatatype
});
indices2.buffer = buffer;
buffer.vertexArrayDestroyable = false;
}
if (!indicesPlan.loadTypedArray) {
indices2.typedArray = void 0;
}
}
PrimitiveLoadPlan.AttributeLoadPlan = AttributeLoadPlan;
PrimitiveLoadPlan.IndicesLoadPlan = IndicesLoadPlan;
var PrimitiveLoadPlan_default = PrimitiveLoadPlan;
// node_modules/@cesium/engine/Source/Scene/SupportedImageFormats.js
function SupportedImageFormats(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.webp = defaultValue_default(options.webp, false);
this.basis = defaultValue_default(options.basis, false);
}
var SupportedImageFormats_default = SupportedImageFormats;
// node_modules/@cesium/engine/Source/Scene/GltfLoader.js
var Attribute2 = ModelComponents_default.Attribute;
var Indices2 = ModelComponents_default.Indices;
var FeatureIdAttribute2 = ModelComponents_default.FeatureIdAttribute;
var FeatureIdTexture2 = ModelComponents_default.FeatureIdTexture;
var FeatureIdImplicitRange2 = ModelComponents_default.FeatureIdImplicitRange;
var MorphTarget2 = ModelComponents_default.MorphTarget;
var Primitive3 = ModelComponents_default.Primitive;
var Instances2 = ModelComponents_default.Instances;
var Skin2 = ModelComponents_default.Skin;
var Node4 = ModelComponents_default.Node;
var AnimatedPropertyType2 = ModelComponents_default.AnimatedPropertyType;
var AnimationSampler2 = ModelComponents_default.AnimationSampler;
var AnimationTarget2 = ModelComponents_default.AnimationTarget;
var AnimationChannel2 = ModelComponents_default.AnimationChannel;
var Animation2 = ModelComponents_default.Animation;
var ArticulationStage2 = ModelComponents_default.ArticulationStage;
var Articulation2 = ModelComponents_default.Articulation;
var Asset2 = ModelComponents_default.Asset;
var Scene2 = ModelComponents_default.Scene;
var Components2 = ModelComponents_default.Components;
var MetallicRoughness2 = ModelComponents_default.MetallicRoughness;
var SpecularGlossiness2 = ModelComponents_default.SpecularGlossiness;
var Material3 = ModelComponents_default.Material;
var GltfLoaderState = {
NOT_LOADED: 0,
LOADING: 1,
LOADED: 2,
PROCESSING: 3,
POST_PROCESSING: 4,
PROCESSED: 5,
READY: 6,
FAILED: 7,
UNLOADED: 8
};
function GltfLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const gltfResource = options.gltfResource;
let baseResource2 = options.baseResource;
const typedArray = options.typedArray;
const releaseGltfJson = defaultValue_default(options.releaseGltfJson, false);
const asynchronous = defaultValue_default(options.asynchronous, true);
const incrementallyLoadTextures = defaultValue_default(
options.incrementallyLoadTextures,
true
);
const upAxis = defaultValue_default(options.upAxis, Axis_default.Y);
const forwardAxis = defaultValue_default(options.forwardAxis, Axis_default.Z);
const loadAttributesAsTypedArray = defaultValue_default(
options.loadAttributesAsTypedArray,
false
);
const loadAttributesFor2D = defaultValue_default(options.loadAttributesFor2D, false);
const loadIndicesForWireframe = defaultValue_default(
options.loadIndicesForWireframe,
false
);
const loadPrimitiveOutline2 = defaultValue_default(options.loadPrimitiveOutline, true);
const loadForClassification = defaultValue_default(
options.loadForClassification,
false
);
const renameBatchIdSemantic = defaultValue_default(
options.renameBatchIdSemantic,
false
);
Check_default.typeOf.object("options.gltfResource", gltfResource);
baseResource2 = defined_default(baseResource2) ? baseResource2 : gltfResource.clone();
this._gltfJson = options.gltfJson;
this._gltfResource = gltfResource;
this._baseResource = baseResource2;
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._loadPrimitiveOutline = loadPrimitiveOutline2;
this._loadForClassification = loadForClassification;
this._renameBatchIdSemantic = renameBatchIdSemantic;
this._sortedPropertyTableIds = void 0;
this._sortedFeatureTextureIds = void 0;
this._gltfJsonLoader = void 0;
this._state = GltfLoaderState.NOT_LOADED;
this._textureState = GltfLoaderState.NOT_LOADED;
this._promise = void 0;
this._processError = void 0;
this._textureErrors = [];
this._primitiveLoadPlans = [];
this._loaderPromises = [];
this._textureLoaders = [];
this._texturesPromises = [];
this._textureCallbacks = [];
this._bufferViewLoaders = [];
this._geometryLoaders = [];
this._geometryCallbacks = [];
this._structuralMetadataLoader = void 0;
this._loadResourcesPromise = void 0;
this._resourcesLoaded = false;
this._texturesLoaded = false;
this._postProcessBuffers = [];
this._components = void 0;
}
if (defined_default(Object.create)) {
GltfLoader.prototype = Object.create(ResourceLoader_default.prototype);
GltfLoader.prototype.constructor = GltfLoader;
}
Object.defineProperties(GltfLoader.prototype, {
cacheKey: {
get: function() {
return void 0;
}
},
components: {
get: function() {
return this._components;
}
},
gltfJson: {
get: function() {
if (defined_default(this._gltfJsonLoader)) {
return this._gltfJsonLoader.gltf;
}
return this._gltfJson;
}
},
incrementallyLoadTextures: {
get: function() {
return this._incrementallyLoadTextures;
}
},
texturesLoaded: {
get: function() {
return this._texturesLoaded;
}
}
});
async function loadGltfJson(loader) {
loader._state = GltfLoaderState.LOADING;
loader._textureState = GltfLoaderState.LOADING;
try {
const gltfJsonLoader = ResourceCache_default.getGltfJsonLoader({
gltfResource: loader._gltfResource,
baseResource: loader._baseResource,
typedArray: loader._typedArray,
gltfJson: loader._gltfJson
});
loader._gltfJsonLoader = gltfJsonLoader;
await gltfJsonLoader.load();
if (loader.isDestroyed() || loader.isUnloaded() || gltfJsonLoader.isDestroyed()) {
return;
}
loader._state = GltfLoaderState.LOADED;
loader._textureState = GltfLoaderState.LOADED;
return loader;
} catch (error) {
if (loader.isDestroyed()) {
return;
}
loader._state = GltfLoaderState.FAILED;
loader._textureState = GltfLoaderState.FAILED;
handleError6(loader, error);
}
}
async function loadResources5(loader, frameState) {
if (!FeatureDetection_default.supportsWebP.initialized) {
await FeatureDetection_default.supportsWebP.initialize();
}
const supportedImageFormats = new SupportedImageFormats_default({
webp: FeatureDetection_default.supportsWebP(),
basis: frameState.context.supportsBasis
});
const gltf = loader.gltfJson;
const promise = parse(loader, gltf, supportedImageFormats, frameState);
loader._state = GltfLoaderState.PROCESSING;
loader._textureState = GltfLoaderState.PROCESSING;
if (defined_default(loader._gltfJsonLoader) && loader._releaseGltfJson) {
ResourceCache_default.unload(loader._gltfJsonLoader);
loader._gltfJsonLoader = void 0;
}
return promise;
}
GltfLoader.prototype.load = async function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._promise = loadGltfJson(this);
return this._promise;
};
function handleError6(gltfLoader, error) {
gltfLoader.unload();
const errorMessage = "Failed to load glTF";
throw gltfLoader.getError(errorMessage, error);
}
function processLoaders(loader, frameState) {
let i;
let ready = true;
const geometryLoaders = loader._geometryLoaders;
const geometryLoadersLength = geometryLoaders.length;
for (i = 0; i < geometryLoadersLength; ++i) {
const geometryReady = geometryLoaders[i].process(frameState);
if (geometryReady && defined_default(loader._geometryCallbacks[i])) {
loader._geometryCallbacks[i]();
loader._geometryCallbacks[i] = void 0;
}
ready = ready && geometryReady;
}
const structuralMetadataLoader = loader._structuralMetadataLoader;
if (defined_default(structuralMetadataLoader)) {
const metadataReady = structuralMetadataLoader.process(frameState);
if (metadataReady) {
loader._components.structuralMetadata = structuralMetadataLoader.structuralMetadata;
}
ready = ready && metadataReady;
}
if (ready) {
loader._state = GltfLoaderState.POST_PROCESSING;
}
}
function postProcessGeometry(loader, context) {
const loadPlans = loader._primitiveLoadPlans;
const length3 = loadPlans.length;
for (let i = 0; i < length3; i++) {
const loadPlan = loadPlans[i];
loadPlan.postProcess(context);
if (loadPlan.needsOutlines) {
gatherPostProcessBuffers(loader, loadPlan);
}
}
}
function gatherPostProcessBuffers(loader, primitiveLoadPlan) {
const buffers = loader._postProcessBuffers;
const primitive = primitiveLoadPlan.primitive;
const outlineCoordinates = primitive.outlineCoordinates;
if (defined_default(outlineCoordinates)) {
buffers.push(outlineCoordinates.buffer);
}
const attributes = primitive.attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; i++) {
const attribute = attributes[i];
if (defined_default(attribute.buffer)) {
buffers.push(attribute.buffer);
}
}
const indices2 = primitive.indices;
if (defined_default(indices2) && defined_default(indices2.buffer)) {
buffers.push(indices2.buffer);
}
}
GltfLoader.prototype._process = function(frameState) {
if (this._state === GltfLoaderState.READY) {
return true;
}
if (this._state === GltfLoaderState.PROCESSING) {
processLoaders(this, frameState);
}
if (this._resourcesLoaded && this._state === GltfLoaderState.POST_PROCESSING) {
postProcessGeometry(this, frameState.context);
this._state = GltfLoaderState.PROCESSED;
}
if (this._resourcesLoaded && this._state === GltfLoaderState.PROCESSED) {
unloadBufferViewLoaders(this);
this._typedArray = void 0;
this._state = GltfLoaderState.READY;
return true;
}
return false;
};
GltfLoader.prototype._processTextures = function(frameState) {
if (this._textureState === GltfLoaderState.READY) {
return true;
}
if (this._textureState !== GltfLoaderState.PROCESSING) {
return false;
}
let i;
let ready = true;
const textureLoaders = this._textureLoaders;
const textureLoadersLength = textureLoaders.length;
for (i = 0; i < textureLoadersLength; ++i) {
const textureReady = textureLoaders[i].process(frameState);
if (textureReady && defined_default(this._textureCallbacks[i])) {
this._textureCallbacks[i]();
this._textureCallbacks[i] = void 0;
}
ready = ready && textureReady;
}
if (!ready) {
return false;
}
this._textureState = GltfLoaderState.READY;
this._texturesLoaded = true;
return true;
};
GltfLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === GltfLoaderState.LOADED && !defined_default(this._loadResourcesPromise)) {
this._loadResourcesPromise = loadResources5(this, frameState).then(() => {
this._resourcesLoaded = true;
}).catch((error) => {
this._processError = error;
});
}
if (defined_default(this._processError)) {
this._state = GltfLoaderState.FAILED;
const error = this._processError;
this._processError = void 0;
handleError6(this, error);
}
const textureError = this._textureErrors.pop();
if (defined_default(textureError)) {
const error = this.getError("Failed to load glTF texture", textureError);
error.name = "TextureError";
throw error;
}
if (this._state === GltfLoaderState.FAILED) {
return false;
}
let ready = false;
try {
ready = this._process(frameState);
} catch (error) {
this._state = GltfLoaderState.FAILED;
handleError6(this, error);
}
let texturesReady = false;
try {
texturesReady = this._processTextures(frameState);
} catch (error) {
this._textureState = GltfLoaderState.FAILED;
handleError6(this, error);
}
if (this._incrementallyLoadTextures) {
return ready;
}
return ready && texturesReady;
};
function getVertexBufferLoader(loader, gltf, accessorId, semantic, draco, loadBuffer, loadTypedArray, frameState) {
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
const vertexBufferLoader = ResourceCache_default.getVertexBufferLoader({
gltf,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource,
frameState,
bufferViewId,
draco,
attributeSemantic: semantic,
accessorId,
asynchronous: loader._asynchronous,
loadBuffer,
loadTypedArray
});
return vertexBufferLoader;
}
function getIndexBufferLoader(loader, gltf, accessorId, draco, loadBuffer, loadTypedArray, frameState) {
const indexBufferLoader = ResourceCache_default.getIndexBufferLoader({
gltf,
accessorId,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource,
frameState,
draco,
asynchronous: loader._asynchronous,
loadBuffer,
loadTypedArray
});
return indexBufferLoader;
}
function getBufferViewLoader(loader, gltf, bufferViewId) {
const bufferViewLoader = ResourceCache_default.getBufferViewLoader({
gltf,
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_default(gltf, accessor);
const count = accessor.count;
const componentCount = numberOfComponentsForType_default(accessor.type);
const componentType = accessor.componentType;
const componentByteLength = ComponentDatatype_default.getSizeInBytes(componentType);
const defaultByteStride = componentByteLength * componentCount;
const componentsLength = count * componentCount;
if (byteStride === defaultByteStride) {
bufferViewTypedArray = new Uint8Array(bufferViewTypedArray);
return ComponentDatatype_default.createArrayBufferView(
componentType,
bufferViewTypedArray.buffer,
bufferViewTypedArray.byteOffset + byteOffset,
componentsLength
);
}
const accessorTypedArray = ComponentDatatype_default.createTypedArray(
componentType,
componentsLength
);
const dataView = new DataView(bufferViewTypedArray.buffer);
const components = new Array(componentCount);
const componentReader = getComponentReader_default(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_default.SCALAR) {
return values.fill(0);
}
const MathType = AttributeType_default.getMathType(accessorType);
return values.fill(MathType.clone(MathType.ZERO));
}
function loadAccessorValues(accessor, typedArray, values, useQuaternion) {
const accessorType = accessor.type;
const accessorCount = accessor.count;
if (accessorType === AttributeType_default.SCALAR) {
for (let i = 0; i < accessorCount; i++) {
values[i] = typedArray[i];
}
} else if (accessorType === AttributeType_default.VEC4 && useQuaternion) {
for (let i = 0; i < accessorCount; i++) {
values[i] = Quaternion_default.unpack(typedArray, i * 4);
}
} else {
const MathType = AttributeType_default.getMathType(accessorType);
const numberOfComponents = AttributeType_default.getNumberOfComponents(
accessorType
);
for (let i = 0; i < accessorCount; i++) {
values[i] = MathType.unpack(typedArray, i * numberOfComponents);
}
}
return values;
}
async function loadAccessorBufferView(loader, bufferViewLoader, gltf, accessor, useQuaternion, values) {
await bufferViewLoader.load();
if (loader.isDestroyed()) {
return;
}
const bufferViewTypedArray = bufferViewLoader.typedArray;
const typedArray = getPackedTypedArray(gltf, accessor, bufferViewTypedArray);
useQuaternion = defaultValue_default(useQuaternion, false);
loadAccessorValues(accessor, typedArray, values, useQuaternion);
}
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_default(bufferViewId)) {
const bufferViewLoader = getBufferViewLoader(loader, gltf, bufferViewId);
const promise = loadAccessorBufferView(
loader,
bufferViewLoader,
gltf,
accessor,
useQuaternion,
values
);
loader._loaderPromises.push(promise);
return values;
}
return loadDefaultAccessorValues(accessor, values);
}
function fromArray(MathType, values) {
if (!defined_default(values)) {
return void 0;
}
if (MathType === Number) {
return values[0];
}
return MathType.unpack(values);
}
function getDefault2(MathType) {
if (MathType === Number) {
return 0;
}
return new MathType();
}
function getQuantizationDivisor(componentDatatype) {
switch (componentDatatype) {
case ComponentDatatype_default.BYTE:
return 127;
case ComponentDatatype_default.UNSIGNED_BYTE:
return 255;
case ComponentDatatype_default.SHORT:
return 32767;
case ComponentDatatype_default.UNSIGNED_SHORT:
return 65535;
default:
return 1;
}
}
var minimumBoundsByType = {
VEC2: new Cartesian2_default(-1, -1),
VEC3: new Cartesian3_default(-1, -1, -1),
VEC4: new Cartesian4_default(-1, -1, -1, -1)
};
function dequantizeMinMax(attribute, VectorType) {
const divisor = getQuantizationDivisor(attribute.componentDatatype);
const minimumBound = minimumBoundsByType[attribute.type];
let min3 = attribute.min;
if (defined_default(min3)) {
min3 = VectorType.divideByScalar(min3, divisor, min3);
min3 = VectorType.maximumByComponent(min3, minimumBound, min3);
}
let max3 = attribute.max;
if (defined_default(max3)) {
max3 = VectorType.divideByScalar(max3, divisor, max3);
max3 = VectorType.maximumByComponent(max3, minimumBound, max3);
}
attribute.min = min3;
attribute.max = max3;
}
function setQuantizationFromWeb3dQuantizedAttributes(extension, attribute, MathType) {
const decodeMatrix = extension.decodeMatrix;
const decodedMin = fromArray(MathType, extension.decodedMin);
const decodedMax = fromArray(MathType, extension.decodedMax);
if (defined_default(decodedMin) && defined_default(decodedMax)) {
attribute.min = decodedMin;
attribute.max = decodedMax;
}
const quantization = new ModelComponents_default.Quantization();
quantization.componentDatatype = attribute.componentDatatype;
quantization.type = attribute.type;
if (decodeMatrix.length === 4) {
quantization.quantizedVolumeOffset = decodeMatrix[2];
quantization.quantizedVolumeStepSize = decodeMatrix[0];
} else if (decodeMatrix.length === 9) {
quantization.quantizedVolumeOffset = new Cartesian2_default(
decodeMatrix[6],
decodeMatrix[7]
);
quantization.quantizedVolumeStepSize = new Cartesian2_default(
decodeMatrix[0],
decodeMatrix[4]
);
} else if (decodeMatrix.length === 16) {
quantization.quantizedVolumeOffset = new Cartesian3_default(
decodeMatrix[12],
decodeMatrix[13],
decodeMatrix[14]
);
quantization.quantizedVolumeStepSize = new Cartesian3_default(
decodeMatrix[0],
decodeMatrix[5],
decodeMatrix[10]
);
} else if (decodeMatrix.length === 25) {
quantization.quantizedVolumeOffset = new Cartesian4_default(
decodeMatrix[20],
decodeMatrix[21],
decodeMatrix[22],
decodeMatrix[23]
);
quantization.quantizedVolumeStepSize = new Cartesian4_default(
decodeMatrix[0],
decodeMatrix[6],
decodeMatrix[12],
decodeMatrix[18]
);
}
attribute.quantization = quantization;
}
function createAttribute(gltf, accessorId, name, semantic, setIndex) {
var _a;
const accessor = gltf.accessors[accessorId];
const MathType = AttributeType_default.getMathType(accessor.type);
const normalized = defaultValue_default(accessor.normalized, false);
const attribute = new Attribute2();
attribute.name = name;
attribute.semantic = semantic;
attribute.setIndex = setIndex;
attribute.constant = getDefault2(MathType);
attribute.componentDatatype = accessor.componentType;
attribute.normalized = normalized;
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_default(gltf, accessor);
if (hasExtension_default(accessor, "WEB3D_quantized_attributes")) {
setQuantizationFromWeb3dQuantizedAttributes(
accessor.extensions.WEB3D_quantized_attributes,
attribute,
MathType
);
}
const isQuantizable = attribute.semantic === VertexAttributeSemantic_default.POSITION || attribute.semantic === VertexAttributeSemantic_default.NORMAL || attribute.semantic === VertexAttributeSemantic_default.TANGENT || attribute.semantic === VertexAttributeSemantic_default.TEXCOORD;
const hasKhrMeshQuantization = (_a = gltf.extensionsRequired) == null ? void 0 : _a.includes(
"KHR_mesh_quantization"
);
if (hasKhrMeshQuantization && normalized && isQuantizable) {
dequantizeMinMax(attribute, MathType);
}
return attribute;
}
function getSetIndex(gltfSemantic) {
const setIndexRegex = /^\w+_(\d+)$/;
const setIndexMatch = setIndexRegex.exec(gltfSemantic);
if (setIndexMatch !== null) {
return parseInt(setIndexMatch[1]);
}
return void 0;
}
var scratchSemanticInfo = {
gltfSemantic: void 0,
renamedSemantic: void 0,
modelSemantic: void 0
};
function getSemanticInfo(loader, semanticType, gltfSemantic) {
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 isClassificationAttribute(attributeSemantic) {
const isPositionAttribute = attributeSemantic === VertexAttributeSemantic_default.POSITION;
const isFeatureIdAttribute = attributeSemantic === VertexAttributeSemantic_default.FEATURE_ID;
const isTexcoordAttribute = attributeSemantic === VertexAttributeSemantic_default.TEXCOORD;
return isPositionAttribute || isFeatureIdAttribute || isTexcoordAttribute;
}
function finalizeDracoAttribute(attribute, vertexBufferLoader, loadBuffer, loadTypedArray) {
attribute.byteOffset = 0;
attribute.byteStride = void 0;
attribute.quantization = vertexBufferLoader.quantization;
if (loadBuffer) {
attribute.buffer = vertexBufferLoader.buffer;
}
if (loadTypedArray) {
const componentDatatype = defined_default(vertexBufferLoader.quantization) ? vertexBufferLoader.quantization.componentDatatype : attribute.componentDatatype;
attribute.typedArray = ComponentDatatype_default.createArrayBufferView(
componentDatatype,
vertexBufferLoader.typedArray.buffer
);
}
}
function finalizeAttribute(gltf, accessor, attribute, vertexBufferLoader, loadBuffer, loadTypedArray) {
if (loadBuffer) {
attribute.buffer = vertexBufferLoader.buffer;
}
if (loadTypedArray) {
const bufferViewTypedArray = vertexBufferLoader.typedArray;
attribute.typedArray = getPackedTypedArray(
gltf,
accessor,
bufferViewTypedArray
);
if (!loadBuffer) {
attribute.byteOffset = 0;
attribute.byteStride = void 0;
}
}
}
function loadAttribute(loader, gltf, accessorId, semanticInfo, draco, loadBuffer, loadTypedArray, frameState) {
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
const gltfSemantic = semanticInfo.gltfSemantic;
const renamedSemantic = semanticInfo.renamedSemantic;
const modelSemantic = semanticInfo.modelSemantic;
const setIndex = defined_default(modelSemantic) ? getSetIndex(renamedSemantic) : void 0;
const name = gltfSemantic;
const attribute = createAttribute(
gltf,
accessorId,
name,
modelSemantic,
setIndex
);
if (!defined_default(draco) && !defined_default(bufferViewId)) {
return attribute;
}
const vertexBufferLoader = getVertexBufferLoader(
loader,
gltf,
accessorId,
gltfSemantic,
draco,
loadBuffer,
loadTypedArray,
frameState
);
const index = loader._geometryLoaders.length;
loader._geometryLoaders.push(vertexBufferLoader);
const promise = vertexBufferLoader.load();
loader._loaderPromises.push(promise);
loader._geometryCallbacks[index] = () => {
if (defined_default(draco) && defined_default(draco.attributes) && defined_default(draco.attributes[gltfSemantic])) {
finalizeDracoAttribute(
attribute,
vertexBufferLoader,
loadBuffer,
loadTypedArray
);
} else {
finalizeAttribute(
gltf,
accessor,
attribute,
vertexBufferLoader,
loadBuffer,
loadTypedArray
);
}
};
return attribute;
}
function loadVertexAttribute(loader, gltf, accessorId, semanticInfo, draco, hasInstances, needsPostProcessing, frameState) {
const modelSemantic = semanticInfo.modelSemantic;
const isPositionAttribute = modelSemantic === VertexAttributeSemantic_default.POSITION;
const isFeatureIdAttribute = modelSemantic === VertexAttributeSemantic_default.FEATURE_ID;
const loadTypedArrayFor2D = isPositionAttribute && !hasInstances && loader._loadAttributesFor2D && !frameState.scene3DOnly;
const loadTypedArrayForClassification = loader._loadForClassification && isFeatureIdAttribute;
const outputTypedArrayOnly = loader._loadAttributesAsTypedArray;
const outputBuffer = !outputTypedArrayOnly;
const outputTypedArray = outputTypedArrayOnly || loadTypedArrayFor2D || loadTypedArrayForClassification;
const loadBuffer = needsPostProcessing ? false : outputBuffer;
const loadTypedArray = needsPostProcessing ? true : outputTypedArray;
const attribute = loadAttribute(
loader,
gltf,
accessorId,
semanticInfo,
draco,
loadBuffer,
loadTypedArray,
frameState
);
const attributePlan = new PrimitiveLoadPlan_default.AttributeLoadPlan(attribute);
attributePlan.loadBuffer = outputBuffer;
attributePlan.loadTypedArray = outputTypedArray;
return attributePlan;
}
function loadInstancedAttribute(loader, gltf, accessorId, attributes, gltfSemantic, frameState) {
const hasRotation = defined_default(attributes.ROTATION);
const hasTranslationMinMax = defined_default(attributes.TRANSLATION) && defined_default(gltf.accessors[attributes.TRANSLATION].min) && defined_default(gltf.accessors[attributes.TRANSLATION].max);
const semanticInfo = getSemanticInfo(
loader,
InstanceAttributeSemantic_default,
gltfSemantic
);
const modelSemantic = semanticInfo.modelSemantic;
const isTransformAttribute = modelSemantic === InstanceAttributeSemantic_default.TRANSLATION || modelSemantic === InstanceAttributeSemantic_default.ROTATION || modelSemantic === InstanceAttributeSemantic_default.SCALE;
const isTranslationAttribute = modelSemantic === InstanceAttributeSemantic_default.TRANSLATION;
const loadAsTypedArrayOnly = loader._loadAttributesAsTypedArray || hasRotation && isTransformAttribute || !frameState.context.instancedArrays;
const loadBuffer = !loadAsTypedArrayOnly;
const loadFor2D = loader._loadAttributesFor2D && !frameState.scene3DOnly;
const loadTranslationAsTypedArray = isTranslationAttribute && (!hasTranslationMinMax || loadFor2D);
const loadTypedArray = loadAsTypedArrayOnly || loadTranslationAsTypedArray;
return loadAttribute(
loader,
gltf,
accessorId,
semanticInfo,
void 0,
loadBuffer,
loadTypedArray,
frameState
);
}
function loadIndices(loader, gltf, accessorId, draco, hasFeatureIds, needsPostProcessing, frameState) {
const accessor = gltf.accessors[accessorId];
const bufferViewId = accessor.bufferView;
if (!defined_default(draco) && !defined_default(bufferViewId)) {
return void 0;
}
const indices2 = new Indices2();
indices2.count = accessor.count;
const loadAttributesAsTypedArray = loader._loadAttributesAsTypedArray;
const loadForWireframe = loader._loadIndicesForWireframe && !frameState.context.webgl2;
const loadForClassification = loader._loadForClassification && hasFeatureIds;
const outputTypedArrayOnly = loadAttributesAsTypedArray;
const outputBuffer = !outputTypedArrayOnly;
const outputTypedArray = loadAttributesAsTypedArray || loadForWireframe || loadForClassification;
const loadBuffer = needsPostProcessing ? false : outputBuffer;
const loadTypedArray = needsPostProcessing ? true : outputTypedArray;
const indexBufferLoader = getIndexBufferLoader(
loader,
gltf,
accessorId,
draco,
loadBuffer,
loadTypedArray,
frameState
);
const index = loader._geometryLoaders.length;
loader._geometryLoaders.push(indexBufferLoader);
const promise = indexBufferLoader.load();
loader._loaderPromises.push(promise);
loader._geometryCallbacks[index] = () => {
indices2.indexDatatype = indexBufferLoader.indexDatatype;
indices2.buffer = indexBufferLoader.buffer;
indices2.typedArray = indexBufferLoader.typedArray;
};
const indicesPlan = new PrimitiveLoadPlan_default.IndicesLoadPlan(indices2);
indicesPlan.loadBuffer = outputBuffer;
indicesPlan.loadTypedArray = outputTypedArray;
return indicesPlan;
}
function loadTexture(loader, gltf, textureInfo, supportedImageFormats, frameState, samplerOverride) {
const imageId = GltfLoaderUtil_default.getImageIdFromTexture({
gltf,
textureId: textureInfo.index,
supportedImageFormats
});
if (!defined_default(imageId)) {
return void 0;
}
const textureLoader = ResourceCache_default.getTextureLoader({
gltf,
textureInfo,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource,
supportedImageFormats,
frameState,
asynchronous: loader._asynchronous
});
const textureReader = GltfLoaderUtil_default.createModelTextureReader({
textureInfo
});
const index = loader._textureLoaders.length;
loader._textureLoaders.push(textureLoader);
const promise = textureLoader.load().catch((error) => {
if (loader.isDestroyed()) {
return;
}
if (!loader._incrementallyLoadTextures) {
throw error;
}
loader._textureState = GltfLoaderState.FAILED;
loader._textureErrors.push(error);
});
loader._texturesPromises.push(promise);
loader._textureCallbacks[index] = () => {
textureReader.texture = textureLoader.texture;
if (defined_default(samplerOverride)) {
textureReader.texture.sampler = samplerOverride;
}
};
return textureReader;
}
function loadMaterial(loader, gltf, gltfMaterial, supportedImageFormats, frameState) {
const material = new Material3();
const extensions = defaultValue_default(
gltfMaterial.extensions,
defaultValue_default.EMPTY_OBJECT
);
const pbrSpecularGlossiness = extensions.KHR_materials_pbrSpecularGlossiness;
const pbrMetallicRoughness = gltfMaterial.pbrMetallicRoughness;
material.unlit = defined_default(extensions.KHR_materials_unlit);
if (defined_default(pbrSpecularGlossiness)) {
const specularGlossiness = new SpecularGlossiness2();
material.specularGlossiness = specularGlossiness;
if (defined_default(pbrSpecularGlossiness.diffuseTexture)) {
specularGlossiness.diffuseTexture = loadTexture(
loader,
gltf,
pbrSpecularGlossiness.diffuseTexture,
supportedImageFormats,
frameState
);
}
if (defined_default(pbrSpecularGlossiness.specularGlossinessTexture)) {
if (defined_default(pbrSpecularGlossiness.specularGlossinessTexture)) {
specularGlossiness.specularGlossinessTexture = loadTexture(
loader,
gltf,
pbrSpecularGlossiness.specularGlossinessTexture,
supportedImageFormats,
frameState
);
}
}
specularGlossiness.diffuseFactor = fromArray(
Cartesian4_default,
pbrSpecularGlossiness.diffuseFactor
);
specularGlossiness.specularFactor = fromArray(
Cartesian3_default,
pbrSpecularGlossiness.specularFactor
);
specularGlossiness.glossinessFactor = pbrSpecularGlossiness.glossinessFactor;
material.pbrSpecularGlossiness = pbrSpecularGlossiness;
} else if (defined_default(pbrMetallicRoughness)) {
const metallicRoughness = new MetallicRoughness2();
if (defined_default(pbrMetallicRoughness.baseColorTexture)) {
metallicRoughness.baseColorTexture = loadTexture(
loader,
gltf,
pbrMetallicRoughness.baseColorTexture,
supportedImageFormats,
frameState
);
}
if (defined_default(pbrMetallicRoughness.metallicRoughnessTexture)) {
metallicRoughness.metallicRoughnessTexture = loadTexture(
loader,
gltf,
pbrMetallicRoughness.metallicRoughnessTexture,
supportedImageFormats,
frameState
);
}
metallicRoughness.baseColorFactor = fromArray(
Cartesian4_default,
pbrMetallicRoughness.baseColorFactor
);
metallicRoughness.metallicFactor = pbrMetallicRoughness.metallicFactor;
metallicRoughness.roughnessFactor = pbrMetallicRoughness.roughnessFactor;
material.metallicRoughness = metallicRoughness;
}
if (defined_default(gltfMaterial.emissiveTexture)) {
material.emissiveTexture = loadTexture(
loader,
gltf,
gltfMaterial.emissiveTexture,
supportedImageFormats,
frameState
);
}
if (defined_default(gltfMaterial.normalTexture) && !loader._loadForClassification) {
material.normalTexture = loadTexture(
loader,
gltf,
gltfMaterial.normalTexture,
supportedImageFormats,
frameState
);
}
if (defined_default(gltfMaterial.occlusionTexture)) {
material.occlusionTexture = loadTexture(
loader,
gltf,
gltfMaterial.occlusionTexture,
supportedImageFormats,
frameState
);
}
material.emissiveFactor = fromArray(Cartesian3_default, gltfMaterial.emissiveFactor);
material.alphaMode = gltfMaterial.alphaMode;
material.alphaCutoff = gltfMaterial.alphaCutoff;
material.doubleSided = gltfMaterial.doubleSided;
return material;
}
function loadFeatureIdAttribute(featureIds, positionalLabel) {
const featureIdAttribute = new FeatureIdAttribute2();
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;
}
function loadFeatureIdAttributeLegacy(gltfFeatureIdAttribute, featureTableId, featureCount, positionalLabel) {
const featureIdAttribute = new FeatureIdAttribute2();
const featureIds = gltfFeatureIdAttribute.featureIds;
featureIdAttribute.featureCount = featureCount;
featureIdAttribute.propertyTableId = featureTableId;
featureIdAttribute.setIndex = getSetIndex(featureIds.attribute);
featureIdAttribute.positionalLabel = positionalLabel;
return featureIdAttribute;
}
function loadDefaultFeatureIds(featureIds, positionalLabel) {
const featureIdRange = new FeatureIdImplicitRange2();
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;
}
function loadFeatureIdImplicitRangeLegacy(gltfFeatureIdAttribute, featureTableId, featureCount, positionalLabel) {
const featureIdRange = new FeatureIdImplicitRange2();
const featureIds = gltfFeatureIdAttribute.featureIds;
featureIdRange.propertyTableId = featureTableId;
featureIdRange.featureCount = featureCount;
featureIdRange.offset = defaultValue_default(featureIds.constant, 0);
const divisor = defaultValue_default(featureIds.divisor, 0);
featureIdRange.repeat = divisor === 0 ? void 0 : divisor;
featureIdRange.positionalLabel = positionalLabel;
return featureIdRange;
}
function loadFeatureIdTexture(loader, gltf, gltfFeatureIdTexture, supportedImageFormats, frameState, positionalLabel) {
const featureIdTexture = new FeatureIdTexture2();
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,
frameState,
Sampler_default.NEAREST
);
const channels = defined_default(textureInfo.channels) ? textureInfo.channels : [0];
const channelString = channels.map(function(channelIndex) {
return "rgba".charAt(channelIndex);
}).join("");
featureIdTexture.textureReader.channels = channelString;
return featureIdTexture;
}
function loadFeatureIdTextureLegacy(loader, gltf, gltfFeatureIdTexture, featureTableId, supportedImageFormats, frameState, featureCount, positionalLabel) {
const featureIdTexture = new FeatureIdTexture2();
const featureIds = gltfFeatureIdTexture.featureIds;
const textureInfo = featureIds.texture;
featureIdTexture.featureCount = featureCount;
featureIdTexture.propertyTableId = featureTableId;
featureIdTexture.textureReader = loadTexture(
loader,
gltf,
textureInfo,
supportedImageFormats,
frameState,
Sampler_default.NEAREST
);
featureIdTexture.textureReader.channels = featureIds.channels;
featureIdTexture.positionalLabel = positionalLabel;
return featureIdTexture;
}
function loadMorphTarget(loader, gltf, target, needsPostProcessing, primitiveLoadPlan, frameState) {
const morphTarget = new MorphTarget2();
const draco = void 0;
const hasInstances = false;
for (const semantic in target) {
if (target.hasOwnProperty(semantic)) {
const accessorId = target[semantic];
const semanticInfo = getSemanticInfo(
loader,
VertexAttributeSemantic_default,
semantic
);
const attributePlan = loadVertexAttribute(
loader,
gltf,
accessorId,
semanticInfo,
draco,
hasInstances,
needsPostProcessing,
frameState
);
morphTarget.attributes.push(attributePlan.attribute);
primitiveLoadPlan.attributePlans.push(attributePlan);
}
}
return morphTarget;
}
function loadPrimitive(loader, gltf, gltfPrimitive, hasInstances, supportedImageFormats, frameState) {
const primitive = new Primitive3();
const primitivePlan = new PrimitiveLoadPlan_default(primitive);
loader._primitiveLoadPlans.push(primitivePlan);
const materialId = gltfPrimitive.material;
if (defined_default(materialId)) {
primitive.material = loadMaterial(
loader,
gltf,
gltf.materials[materialId],
supportedImageFormats,
frameState
);
}
const extensions = defaultValue_default(
gltfPrimitive.extensions,
defaultValue_default.EMPTY_OBJECT
);
let needsPostProcessing = false;
const outlineExtension = extensions.CESIUM_primitive_outline;
if (loader._loadPrimitiveOutline && defined_default(outlineExtension)) {
needsPostProcessing = true;
primitivePlan.needsOutlines = true;
primitivePlan.outlineIndices = loadPrimitiveOutline(
loader,
gltf,
outlineExtension,
primitivePlan
);
}
const loadForClassification = loader._loadForClassification;
const draco = extensions.KHR_draco_mesh_compression;
let hasFeatureIds = false;
const attributes = gltfPrimitive.attributes;
if (defined_default(attributes)) {
for (const semantic in attributes) {
if (attributes.hasOwnProperty(semantic)) {
const accessorId = attributes[semantic];
const semanticInfo = getSemanticInfo(
loader,
VertexAttributeSemantic_default,
semantic
);
const modelSemantic = semanticInfo.modelSemantic;
if (loadForClassification && !isClassificationAttribute(modelSemantic)) {
continue;
}
if (modelSemantic === VertexAttributeSemantic_default.FEATURE_ID) {
hasFeatureIds = true;
}
const attributePlan = loadVertexAttribute(
loader,
gltf,
accessorId,
semanticInfo,
draco,
hasInstances,
needsPostProcessing,
frameState
);
primitivePlan.attributePlans.push(attributePlan);
primitive.attributes.push(attributePlan.attribute);
}
}
}
const targets = gltfPrimitive.targets;
if (defined_default(targets) && !loadForClassification) {
const targetsLength = targets.length;
for (let i = 0; i < targetsLength; ++i) {
primitive.morphTargets.push(
loadMorphTarget(
loader,
gltf,
targets[i],
needsPostProcessing,
primitivePlan,
frameState
)
);
}
}
const indices2 = gltfPrimitive.indices;
if (defined_default(indices2)) {
const indicesPlan = loadIndices(
loader,
gltf,
indices2,
draco,
hasFeatureIds,
needsPostProcessing,
frameState
);
if (defined_default(indicesPlan)) {
primitivePlan.indicesPlan = indicesPlan;
primitive.indices = indicesPlan.indices;
}
}
const structuralMetadata = extensions.EXT_structural_metadata;
const meshFeatures = extensions.EXT_mesh_features;
const featureMetadataLegacy = extensions.EXT_feature_metadata;
const hasFeatureMetadataLegacy = defined_default(featureMetadataLegacy);
if (defined_default(meshFeatures)) {
loadPrimitiveFeatures(
loader,
gltf,
primitive,
meshFeatures,
supportedImageFormats,
frameState
);
} else if (hasFeatureMetadataLegacy) {
loadPrimitiveFeaturesLegacy(
loader,
gltf,
primitive,
featureMetadataLegacy,
supportedImageFormats,
frameState
);
}
if (defined_default(structuralMetadata)) {
loadPrimitiveMetadata(primitive, structuralMetadata);
} else if (hasFeatureMetadataLegacy) {
loadPrimitiveMetadataLegacy(loader, primitive, featureMetadataLegacy);
}
const primitiveType = gltfPrimitive.mode;
if (loadForClassification && primitiveType !== PrimitiveType_default.TRIANGLES) {
throw new RuntimeError_default(
"Only triangle meshes can be used for classification."
);
}
primitive.primitiveType = primitiveType;
return primitive;
}
function loadPrimitiveOutline(loader, gltf, outlineExtension) {
const accessorId = outlineExtension.indices;
const useQuaternion = false;
return loadAccessor(loader, gltf, accessorId, useQuaternion);
}
function loadPrimitiveFeatures(loader, gltf, primitive, meshFeaturesExtension, supportedImageFormats, frameState) {
let featureIdsArray;
if (defined_default(meshFeaturesExtension) && defined_default(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_default(featureIds.texture)) {
featureIdComponent = loadFeatureIdTexture(
loader,
gltf,
featureIds,
supportedImageFormats,
frameState,
label
);
} else if (defined_default(featureIds.attribute)) {
featureIdComponent = loadFeatureIdAttribute(featureIds, label);
} else {
featureIdComponent = loadDefaultFeatureIds(featureIds, label);
}
primitive.featureIds.push(featureIdComponent);
}
}
function loadPrimitiveFeaturesLegacy(loader, gltf, primitive, metadataExtension, supportedImageFormats, frameState) {
const featureTables = gltf.extensions.EXT_feature_metadata.featureTables;
let nextFeatureIdIndex = 0;
const featureIdAttributes = metadataExtension.featureIdAttributes;
if (defined_default(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_default(featureIdAttribute.featureIds.attribute)) {
featureIdComponent = loadFeatureIdAttributeLegacy(
featureIdAttribute,
propertyTableId,
featureCount,
label
);
} else {
featureIdComponent = loadFeatureIdImplicitRangeLegacy(
featureIdAttribute,
propertyTableId,
featureCount,
label
);
}
primitive.featureIds.push(featureIdComponent);
}
}
const featureIdTextures = metadataExtension.featureIdTextures;
if (defined_default(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,
frameState,
featureCount,
featureIdLabel
);
primitive.featureIds.push(featureIdComponent);
}
}
}
function loadPrimitiveMetadata(primitive, structuralMetadataExtension) {
if (!defined_default(structuralMetadataExtension)) {
return;
}
if (defined_default(structuralMetadataExtension.propertyTextures)) {
primitive.propertyTextureIds = structuralMetadataExtension.propertyTextures;
}
if (defined_default(structuralMetadataExtension.propertyAttributes)) {
primitive.propertyAttributeIds = structuralMetadataExtension.propertyAttributes;
}
}
function loadPrimitiveMetadataLegacy(loader, primitive, metadataExtension) {
if (defined_default(metadataExtension.featureTextures)) {
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 Instances2();
const attributes = instancingExtension.attributes;
if (defined_default(attributes)) {
for (const semantic in attributes) {
if (attributes.hasOwnProperty(semantic)) {
const accessorId = attributes[semantic];
instances.attributes.push(
loadInstancedAttribute(
loader,
gltf,
accessorId,
attributes,
semantic,
frameState
)
);
}
}
}
const instancingExtExtensions = defaultValue_default(
instancingExtension.extensions,
defaultValue_default.EMPTY_OBJECT
);
const instanceFeatures = nodeExtensions.EXT_instance_features;
const featureMetadataLegacy = instancingExtExtensions.EXT_feature_metadata;
if (defined_default(instanceFeatures)) {
loadInstanceFeatures(instances, instanceFeatures);
} else if (defined_default(featureMetadataLegacy)) {
loadInstanceFeaturesLegacy(
gltf,
instances,
featureMetadataLegacy,
loader._sortedPropertyTableIds
);
}
return instances;
}
function loadInstanceFeatures(instances, instanceFeaturesExtension) {
const featureIdsArray = instanceFeaturesExtension.featureIds;
for (let i = 0; i < featureIdsArray.length; i++) {
const featureIds = featureIdsArray[i];
const label = `instanceFeatureId_${i}`;
let featureIdComponent;
if (defined_default(featureIds.attribute)) {
featureIdComponent = loadFeatureIdAttribute(featureIds, label);
} else {
featureIdComponent = loadDefaultFeatureIds(featureIds, label);
}
instances.featureIds.push(featureIdComponent);
}
}
function loadInstanceFeaturesLegacy(gltf, instances, metadataExtension, sortedPropertyTableIds) {
const featureTables = gltf.extensions.EXT_feature_metadata.featureTables;
const featureIdAttributes = metadataExtension.featureIdAttributes;
if (defined_default(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_default(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 Node4();
node.name = gltfNode.name;
node.matrix = fromArray(Matrix4_default, gltfNode.matrix);
node.translation = fromArray(Cartesian3_default, gltfNode.translation);
node.rotation = fromArray(Quaternion_default, gltfNode.rotation);
node.scale = fromArray(Cartesian3_default, gltfNode.scale);
const nodeExtensions = defaultValue_default(
gltfNode.extensions,
defaultValue_default.EMPTY_OBJECT
);
const instancingExtension = nodeExtensions.EXT_mesh_gpu_instancing;
const articulationsExtension = nodeExtensions.AGI_articulations;
if (defined_default(instancingExtension)) {
if (loader._loadForClassification) {
throw new RuntimeError_default(
"Models with the EXT_mesh_gpu_instancing extension cannot be used for classification."
);
}
node.instances = loadInstances(loader, gltf, nodeExtensions, frameState);
}
if (defined_default(articulationsExtension)) {
node.articulationName = articulationsExtension.articulationName;
}
const meshId = gltfNode.mesh;
if (defined_default(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_default(node.instances),
supportedImageFormats,
frameState
)
);
}
const morphWeights = defaultValue_default(gltfNode.weights, mesh.weights);
const targets = node.primitives[0].morphTargets;
const targetsLength = targets.length;
node.morphWeights = defined_default(morphWeights) ? morphWeights.slice() : new Array(targetsLength).fill(0);
}
return node;
}
function loadNodes(loader, gltf, supportedImageFormats, frameState) {
if (!defined_default(gltf.nodes)) {
return [];
}
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_default(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 Skin2();
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_default(inverseBindMatricesAccessorId)) {
skin.inverseBindMatrices = loadAccessor(
loader,
gltf,
inverseBindMatricesAccessorId
);
} else {
skin.inverseBindMatrices = new Array(jointsLength).fill(Matrix4_default.IDENTITY);
}
return skin;
}
function loadSkins(loader, gltf, nodes) {
const gltfSkins = gltf.skins;
if (loader._loadForClassification || !defined_default(gltfSkins)) {
return [];
}
const skinsLength = gltf.skins.length;
const skins = new Array(skinsLength);
for (let 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 (let i = 0; i < nodesLength; ++i) {
const skinId = gltf.nodes[i].skin;
if (defined_default(skinId)) {
nodes[i].skin = skins[skinId];
}
}
return skins;
}
async function loadStructuralMetadata(loader, gltf, extension, extensionLegacy, supportedImageFormats, frameState) {
const structuralMetadataLoader = new GltfStructuralMetadataLoader_default({
gltf,
extension,
extensionLegacy,
gltfResource: loader._gltfResource,
baseResource: loader._baseResource,
supportedImageFormats,
frameState,
asynchronous: loader._asynchronous
});
loader._structuralMetadataLoader = structuralMetadataLoader;
return structuralMetadataLoader.load();
}
function loadAnimationSampler(loader, gltf, gltfSampler) {
const animationSampler = new AnimationSampler2();
const inputAccessorId = gltfSampler.input;
animationSampler.input = loadAccessor(loader, gltf, inputAccessorId);
const gltfInterpolation = gltfSampler.interpolation;
animationSampler.interpolation = defaultValue_default(
InterpolationType_default[gltfInterpolation],
InterpolationType_default.LINEAR
);
const outputAccessorId = gltfSampler.output;
animationSampler.output = loadAccessor(loader, gltf, outputAccessorId, true);
return animationSampler;
}
function loadAnimationTarget(gltfTarget, nodes) {
const animationTarget = new AnimationTarget2();
const nodeIndex = gltfTarget.node;
if (!defined_default(nodeIndex)) {
return void 0;
}
animationTarget.node = nodes[nodeIndex];
const path = gltfTarget.path.toUpperCase();
animationTarget.path = AnimatedPropertyType2[path];
return animationTarget;
}
function loadAnimationChannel(gltfChannel, samplers, nodes) {
const animationChannel = new AnimationChannel2();
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 Animation2();
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) {
const gltfAnimations = gltf.animations;
if (loader._loadForClassification || !defined_default(gltfAnimations)) {
return [];
}
const animationsLength = gltf.animations.length;
const animations = new Array(animationsLength);
for (let 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 ArticulationStage2();
stage.name = gltfStage.name;
const type = gltfStage.type.toUpperCase();
stage.type = ArticulationStageType_default[type];
stage.minimumValue = gltfStage.minimumValue;
stage.maximumValue = gltfStage.maximumValue;
stage.initialValue = gltfStage.initialValue;
return stage;
}
function loadArticulation(gltfArticulation) {
const articulation = new Articulation2();
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_default(gltf.extensions, defaultValue_default.EMPTY_OBJECT);
const articulationsExtension = extensions.AGI_articulations;
if (!defined_default(articulationsExtension)) {
return [];
}
const gltfArticulations = articulationsExtension.articulations;
if (!defined_default(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_default(gltf.scenes) && defined_default(gltf.scene)) {
nodesIds = gltf.scenes[gltf.scene].nodes;
}
nodesIds = defaultValue_default(nodesIds, gltf.nodes);
nodesIds = defined_default(nodesIds) ? nodesIds : [];
return nodesIds;
}
function loadScene(gltf, nodes) {
const scene = new Scene2();
const sceneNodeIds = getSceneNodeIds(gltf);
scene.nodes = sceneNodeIds.map(function(sceneNodeId) {
return nodes[sceneNodeId];
});
return scene;
}
var scratchCenter3 = new Cartesian3_default();
function parse(loader, gltf, supportedImageFormats, frameState) {
const extensions = defaultValue_default(gltf.extensions, defaultValue_default.EMPTY_OBJECT);
const structuralMetadataExtension = extensions.EXT_structural_metadata;
const featureMetadataExtensionLegacy = extensions.EXT_feature_metadata;
const cesiumRtcExtension = extensions.CESIUM_RTC;
if (defined_default(featureMetadataExtensionLegacy)) {
const featureTables = featureMetadataExtensionLegacy.featureTables;
const featureTextures = featureMetadataExtensionLegacy.featureTextures;
const allPropertyTableIds = defined_default(featureTables) ? featureTables : [];
const allFeatureTextureIds = defined_default(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 Components2();
const asset = new Asset2();
const copyright = gltf.asset.copyright;
if (defined_default(copyright)) {
const credits = copyright.split(";").map(function(string) {
return new Credit_default(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;
if (defined_default(cesiumRtcExtension)) {
const center = Cartesian3_default.fromArray(
cesiumRtcExtension.center,
0,
scratchCenter3
);
components.transform = Matrix4_default.fromTranslation(
center,
components.transform
);
}
loader._components = components;
if (defined_default(structuralMetadataExtension) || defined_default(featureMetadataExtensionLegacy)) {
const promise = loadStructuralMetadata(
loader,
gltf,
structuralMetadataExtension,
featureMetadataExtensionLegacy,
supportedImageFormats,
frameState
);
loader._loaderPromises.push(promise);
}
const readyPromises = [];
readyPromises.push.apply(readyPromises, loader._loaderPromises);
if (!loader._incrementallyLoadTextures) {
readyPromises.push.apply(readyPromises, loader._texturesPromises);
}
return Promise.all(readyPromises);
}
function unloadTextures2(loader) {
const textureLoaders = loader._textureLoaders;
const textureLoadersLength = textureLoaders.length;
for (let i = 0; i < textureLoadersLength; ++i) {
textureLoaders[i] = !textureLoaders[i].isDestroyed() && ResourceCache_default.unload(textureLoaders[i]);
}
loader._textureLoaders.length = 0;
}
function unloadBufferViewLoaders(loader) {
const bufferViewLoaders = loader._bufferViewLoaders;
const bufferViewLoadersLength = bufferViewLoaders.length;
for (let i = 0; i < bufferViewLoadersLength; ++i) {
bufferViewLoaders[i] = !bufferViewLoaders[i].isDestroyed() && ResourceCache_default.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) {
geometryLoaders[i] = !geometryLoaders[i].isDestroyed() && ResourceCache_default.unload(geometryLoaders[i]);
}
loader._geometryLoaders.length = 0;
}
function unloadGeneratedAttributes(loader) {
const buffers = loader._postProcessBuffers;
const length3 = buffers.length;
for (let i = 0; i < length3; i++) {
const buffer = buffers[i];
if (!buffer.isDestroyed()) {
buffer.destroy();
}
}
buffers.length = 0;
}
function unloadStructuralMetadata(loader) {
if (defined_default(loader._structuralMetadataLoader) && !loader._structuralMetadataLoader.isDestroyed()) {
loader._structuralMetadataLoader.destroy();
loader._structuralMetadataLoader = void 0;
}
}
GltfLoader.prototype.isUnloaded = function() {
return this._state === GltfLoaderState.UNLOADED;
};
GltfLoader.prototype.unload = function() {
if (defined_default(this._gltfJsonLoader) && !this._gltfJsonLoader.isDestroyed()) {
ResourceCache_default.unload(this._gltfJsonLoader);
}
this._gltfJsonLoader = void 0;
unloadTextures2(this);
unloadBufferViewLoaders(this);
unloadGeometry(this);
unloadGeneratedAttributes(this);
unloadStructuralMetadata(this);
this._components = void 0;
this._typedArray = void 0;
this._state = GltfLoaderState.UNLOADED;
};
var GltfLoader_default = GltfLoader;
// node_modules/@cesium/engine/Source/Shaders/PostProcessStages/PointCloudEyeDomeLighting.js
var PointCloudEyeDomeLighting_default = "uniform sampler2D u_pointCloud_colorGBuffer;\nuniform sampler2D u_pointCloud_depthGBuffer;\nuniform vec2 u_distanceAndEdlStrength;\nin vec2 v_textureCoordinates;\n\nvec2 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\n float depthOrLogDepth0 = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, texCoord0));\n float depthOrLogDepth1 = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, texCoord1));\n\n // ignore depth values that are the clear depth\n if (depthOrLogDepth0 == 0.0 || depthOrLogDepth1 == 0.0) {\n return vec2(0.0);\n }\n\n // interpolate the two adjacent depth values\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\nvoid main()\n{\n float depthOrLogDepth = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, v_textureCoordinates));\n\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, depthOrLogDepth);\n eyeCoordinate /= eyeCoordinate.w;\n\n float log2Depth = log2(-eyeCoordinate.z);\n\n if (depthOrLogDepth == 0.0) // 0.0 is the clear value for the gbuffer\n {\n discard;\n }\n\n vec4 color = texture(u_pointCloud_colorGBuffer, v_textureCoordinates);\n\n // sample from neighbors left, right, down, up\n vec2 texelSize = 1.0 / czm_viewport.zw;\n\n vec2 responseAndCount = vec2(0.0);\n\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\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 out_FragColor = vec4(color);\n\n // Input and output depth are the same.\n gl_FragDepth = depthOrLogDepth;\n}\n";
// node_modules/@cesium/engine/Source/Scene/PointCloudEyeDomeLighting.js
function PointCloudEyeDomeLighting() {
this._framebuffer = new FramebufferManager_default({
colorAttachmentsLength: 2,
depth: true,
supportsDepthTexture: true
});
this._drawCommand = void 0;
this._clearCommand = void 0;
this._strength = 1;
this._radius = 1;
}
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(processor) {
processor._framebuffer.destroy();
processor._drawCommand = void 0;
processor._clearCommand = void 0;
}
var distanceAndEdlStrengthScratch = new Cartesian2_default();
function createCommands4(processor, context) {
const blendFS = new ShaderSource_default({
defines: ["LOG_DEPTH_WRITE"],
sources: [PointCloudEyeDomeLighting_default]
});
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_default.fromCache({
blending: BlendingState_default.ALPHA_BLEND,
depthMask: true,
depthTest: {
enabled: true
},
stencilTest: StencilConstants_default.setCesium3DTileBit(),
stencilMask: StencilConstants_default.CESIUM_3D_TILE_MASK
});
processor._drawCommand = context.createViewportQuadCommand(blendFS, {
uniformMap: blendUniformMap,
renderState: blendRenderState,
pass: Pass_default.CESIUM_3D_TILE,
owner: processor
});
processor._clearCommand = new ClearCommand_default({
framebuffer: processor.framebuffer,
color: new Color_default(0, 0, 0, 0),
depth: 1,
renderState: RenderState_default.fromCache(),
pass: Pass_default.CESIUM_3D_TILE,
owner: processor
});
}
function createResources(processor, context) {
const width = context.drawingBufferWidth;
const height = context.drawingBufferHeight;
processor._framebuffer.update(context, width, height);
createCommands4(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_default(shader)) {
const attributeLocations8 = shaderProgram._attributeLocations;
const fs = shaderProgram.fragmentShaderSource.clone();
fs.sources.splice(
0,
0,
`layout (location = 0) out vec4 out_FragData_0;
layout (location = 1) out vec4 out_FragData_1;`
);
fs.sources = fs.sources.map(function(source) {
source = ShaderSource_default.replaceMain(
source,
"czm_point_cloud_post_process_main"
);
source = source.replaceAll(/out_FragColor/g, "out_FragData_0");
return source;
});
fs.sources.push(
"void main() \n{ \n czm_point_cloud_post_process_main(); \n#ifdef LOG_DEPTH\n czm_writeLogDepth();\n out_FragData_1 = czm_packDepth(gl_FragDepth); \n#else\n out_FragData_1 = czm_packDepth(gl_FragCoord.z);\n#endif\n}"
);
shader = context.shaderCache.createDerivedShaderProgram(
shaderProgram,
"EC",
{
vertexShaderSource: shaderProgram.vertexShaderSource,
fragmentShaderSource: fs,
attributeLocations: attributeLocations8
}
);
}
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(this, frameState.context);
let i;
const commandList = frameState.commandList;
const commandEnd = commandList.length;
for (i = commandStart; i < commandEnd; ++i) {
const command = commandList[i];
if (command.primitiveType !== PrimitiveType_default.POINTS || command.pass === Pass_default.TRANSLUCENT) {
continue;
}
let derivedCommand;
let originalShaderProgram;
let derivedCommandObject = command.derivedCommands.pointCloudProcessor;
if (defined_default(derivedCommandObject)) {
derivedCommand = derivedCommandObject.command;
originalShaderProgram = derivedCommandObject.originalShaderProgram;
}
if (!defined_default(derivedCommand) || command.dirty || originalShaderProgram !== command.shaderProgram || derivedCommand.framebuffer !== this.framebuffer) {
derivedCommand = DrawCommand_default.shallowClone(command, derivedCommand);
derivedCommand.framebuffer = this.framebuffer;
derivedCommand.shaderProgram = getECShaderProgram(
frameState.context,
command.shaderProgram
);
derivedCommand.castShadows = false;
derivedCommand.receiveShadows = false;
if (!defined_default(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;
commandList.push(blendCommand);
commandList.push(clearCommand);
};
PointCloudEyeDomeLighting.prototype.isDestroyed = function() {
return false;
};
PointCloudEyeDomeLighting.prototype.destroy = function() {
destroyFramebuffer(this);
return destroyObject_default(this);
};
var PointCloudEyeDomeLighting_default2 = PointCloudEyeDomeLighting;
// node_modules/@cesium/engine/Source/Scene/PointCloudShading.js
function PointCloudShading(options) {
const pointCloudShading = defaultValue_default(options, {});
this.attenuation = defaultValue_default(pointCloudShading.attenuation, false);
this.geometricErrorScale = defaultValue_default(
pointCloudShading.geometricErrorScale,
1
);
this.maximumAttenuation = pointCloudShading.maximumAttenuation;
this.baseResolution = pointCloudShading.baseResolution;
this.eyeDomeLighting = defaultValue_default(pointCloudShading.eyeDomeLighting, true);
this.eyeDomeLightingStrength = defaultValue_default(
pointCloudShading.eyeDomeLightingStrength,
1
);
this.eyeDomeLightingRadius = defaultValue_default(
pointCloudShading.eyeDomeLightingRadius,
1
);
this.backFaceCulling = defaultValue_default(pointCloudShading.backFaceCulling, false);
this.normalShading = defaultValue_default(pointCloudShading.normalShading, true);
}
PointCloudShading.isSupported = function(scene) {
return PointCloudEyeDomeLighting_default2.isSupported(scene.context);
};
var PointCloudShading_default = PointCloudShading;
// node_modules/@cesium/engine/Source/Scene/SceneTransforms.js
var SceneTransforms = {};
var actualPositionScratch = new Cartesian4_default(0, 0, 0, 1);
var positionCC = new Cartesian4_default();
var scratchViewport2 = new BoundingRectangle_default();
var scratchWindowCoord0 = new Cartesian2_default();
var scratchWindowCoord1 = new Cartesian2_default();
SceneTransforms.wgs84ToWindowCoordinates = function(scene, position, result) {
return SceneTransforms.wgs84WithEyeOffsetToWindowCoordinates(
scene,
position,
Cartesian3_default.ZERO,
result
);
};
var scratchCartesian42 = new Cartesian4_default();
var scratchEyeOffset = new Cartesian3_default();
function worldToClip(position, eyeOffset, camera, result) {
const viewMatrix = camera.viewMatrix;
const positionEC = Matrix4_default.multiplyByVector(
viewMatrix,
Cartesian4_default.fromElements(
position.x,
position.y,
position.z,
1,
scratchCartesian42
),
scratchCartesian42
);
const zEyeOffset = Cartesian3_default.multiplyComponents(
eyeOffset,
Cartesian3_default.normalize(positionEC, scratchEyeOffset),
scratchEyeOffset
);
positionEC.x += eyeOffset.x + zEyeOffset.x;
positionEC.y += eyeOffset.y + zEyeOffset.y;
positionEC.z += zEyeOffset.z;
return Matrix4_default.multiplyByVector(
camera.frustum.projectionMatrix,
positionEC,
result
);
}
var scratchMaxCartographic = new Cartographic_default(
Math.PI,
Math_default.PI_OVER_TWO
);
var scratchProjectedCartesian = new Cartesian3_default();
var scratchCameraPosition = new Cartesian3_default();
SceneTransforms.wgs84WithEyeOffsetToWindowCoordinates = function(scene, position, eyeOffset, result) {
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
if (!defined_default(position)) {
throw new DeveloperError_default("position is required.");
}
const frameState = scene.frameState;
const actualPosition = SceneTransforms.computeActualWgs84Position(
frameState,
position,
actualPositionScratch
);
if (!defined_default(actualPosition)) {
return void 0;
}
const canvas = scene.canvas;
const viewport = scratchViewport2;
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_default.SCENE2D) {
const projection = scene.mapProjection;
const maxCartographic = scratchMaxCartographic;
const maxCoord = projection.project(
maxCartographic,
scratchProjectedCartesian
);
const cameraPosition = Cartesian3_default.clone(
camera.position,
scratchCameraPosition
);
const frustum = camera.frustum.clone();
const viewportTransformation = Matrix4_default.computeViewportTransformation(
viewport,
0,
1,
new Matrix4_default()
);
const projectionMatrix = camera.frustum.projectionMatrix;
const x = camera.positionWC.y;
const eyePoint = Cartesian3_default.fromElements(
Math_default.sign(x) * maxCoord.x - x,
0,
-camera.positionWC.x
);
const windowCoordinates = Transforms_default.pointToGLWindowCoordinates(
projectionMatrix,
viewportTransformation,
eyePoint
);
if (x === 0 || windowCoordinates.x <= 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_default.clone(cameraPosition, camera.position);
camera.frustum = frustum.clone();
result = Cartesian2_default.clone(scratchWindowCoord0, result);
if (result.x < 0 || result.x > canvas.clientWidth) {
result.x = scratchWindowCoord1.x;
}
}
}
if (frameState.mode !== SceneMode_default.SCENE2D || cameraCentered) {
positionCC = worldToClip(actualPosition, eyeOffset, camera, positionCC);
if (positionCC.z < 0 && !(camera.frustum instanceof OrthographicFrustum_default) && !(camera.frustum instanceof OrthographicOffCenterFrustum_default)) {
return void 0;
}
result = SceneTransforms.clipToGLWindowCoordinates(
viewport,
positionCC,
result
);
}
result.y = canvas.clientHeight - result.y;
return result;
};
SceneTransforms.wgs84ToDrawingBufferCoordinates = function(scene, position, result) {
result = SceneTransforms.wgs84ToWindowCoordinates(scene, position, result);
if (!defined_default(result)) {
return void 0;
}
return SceneTransforms.transformWindowToDrawingBuffer(scene, result, result);
};
var projectedPosition = new Cartesian3_default();
var positionInCartographic = new Cartographic_default();
SceneTransforms.computeActualWgs84Position = function(frameState, position, result) {
const mode2 = frameState.mode;
if (mode2 === SceneMode_default.SCENE3D) {
return Cartesian3_default.clone(position, result);
}
const projection = frameState.mapProjection;
const cartographic2 = projection.ellipsoid.cartesianToCartographic(
position,
positionInCartographic
);
if (!defined_default(cartographic2)) {
return void 0;
}
projection.project(cartographic2, projectedPosition);
if (mode2 === SceneMode_default.COLUMBUS_VIEW) {
return Cartesian3_default.fromElements(
projectedPosition.z,
projectedPosition.x,
projectedPosition.y,
result
);
}
if (mode2 === SceneMode_default.SCENE2D) {
return Cartesian3_default.fromElements(
0,
projectedPosition.x,
projectedPosition.y,
result
);
}
const morphTime = frameState.morphTime;
return Cartesian3_default.fromElements(
Math_default.lerp(projectedPosition.z, position.x, morphTime),
Math_default.lerp(projectedPosition.x, position.y, morphTime),
Math_default.lerp(projectedPosition.y, position.z, morphTime),
result
);
};
var positionNDC = new Cartesian3_default();
var positionWC = new Cartesian3_default();
var viewportTransform = new Matrix4_default();
SceneTransforms.clipToGLWindowCoordinates = function(viewport, position, result) {
Cartesian3_default.divideByScalar(position, position.w, positionNDC);
Matrix4_default.computeViewportTransformation(viewport, 0, 1, viewportTransform);
Matrix4_default.multiplyByPoint(viewportTransform, positionNDC, positionWC);
return Cartesian2_default.fromCartesian3(positionWC, result);
};
SceneTransforms.transformWindowToDrawingBuffer = function(scene, windowPosition, result) {
const canvas = scene.canvas;
const xScale = scene.drawingBufferWidth / canvas.clientWidth;
const yScale = scene.drawingBufferHeight / canvas.clientHeight;
return Cartesian2_default.fromElements(
windowPosition.x * xScale,
windowPosition.y * yScale,
result
);
};
var scratchNDC = new Cartesian4_default();
var scratchWorldCoords = new Cartesian4_default();
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) {
const log2Depth = depth * uniformState.log2FarDepthFromNearPlusOne;
const depthFromNear = Math.pow(2, log2Depth) - 1;
depth = far * (1 - near / (depthFromNear + near)) / (far - near);
}
const viewport = scene.view.passState.viewport;
const ndc = Cartesian4_default.clone(Cartesian4_default.UNIT_W, scratchNDC);
ndc.x = (drawingBufferPosition.x - viewport.x) / viewport.width * 2 - 1;
ndc.y = (drawingBufferPosition.y - viewport.y) / viewport.height * 2 - 1;
ndc.z = depth * 2 - 1;
ndc.w = 1;
let worldCoords;
let frustum = scene.camera.frustum;
if (!defined_default(frustum.fovy)) {
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
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;
worldCoords = Matrix4_default.multiplyByVector(
uniformState.inverseView,
worldCoords,
worldCoords
);
} else {
worldCoords = Matrix4_default.multiplyByVector(
uniformState.inverseViewProjection,
ndc,
scratchWorldCoords
);
const w = 1 / worldCoords.w;
Cartesian3_default.multiplyByScalar(worldCoords, w, worldCoords);
}
return Cartesian3_default.fromCartesian4(worldCoords, result);
};
var SceneTransforms_default = SceneTransforms;
// node_modules/@cesium/engine/Source/Scene/SplitDirection.js
var SplitDirection = {
LEFT: -1,
NONE: 0,
RIGHT: 1
};
var SplitDirection_default = Object.freeze(SplitDirection);
// node_modules/@cesium/engine/Source/Scene/B3dmParser.js
var B3dmParser = {};
B3dmParser._deprecationWarning = deprecationWarning_default;
var sizeOfUint324 = Uint32Array.BYTES_PER_ELEMENT;
B3dmParser.parse = function(arrayBuffer, byteOffset) {
const byteStart = defaultValue_default(byteOffset, 0);
Check_default.defined("arrayBuffer", arrayBuffer);
byteOffset = byteStart;
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint324;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Batched 3D Model version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint324;
const byteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint324;
let featureTableJsonByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint324;
let featureTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint324;
let batchTableJsonByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint324;
let batchTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint324;
let batchLength;
if (batchTableJsonByteLength >= 570425344) {
byteOffset -= sizeOfUint324 * 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) {
byteOffset -= sizeOfUint324;
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_default(batchLength, 0)
};
} else {
featureTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
featureTableJsonByteLength
);
byteOffset += featureTableJsonByteLength;
}
const featureTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
featureTableBinaryByteLength
);
byteOffset += featureTableBinaryByteLength;
let batchTableJson;
let batchTableBinary;
if (batchTableJsonByteLength > 0) {
batchTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
batchTableJsonByteLength
);
byteOffset += batchTableJsonByteLength;
if (batchTableBinaryByteLength > 0) {
batchTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
batchTableBinaryByteLength
);
batchTableBinary = new Uint8Array(batchTableBinary);
byteOffset += batchTableBinaryByteLength;
}
}
const gltfByteLength = byteStart + byteLength - byteOffset;
if (gltfByteLength === 0) {
throw new RuntimeError_default("glTF byte length must be greater than 0.");
}
let gltfView;
if (byteOffset % 4 === 0) {
gltfView = new Uint8Array(arrayBuffer, byteOffset, gltfByteLength);
} else {
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,
featureTableJson,
featureTableBinary,
batchTableJson,
batchTableBinary,
gltf: gltfView
};
};
var B3dmParser_default = B3dmParser;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileFeatureTable.js
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_default(typedArray)) {
typedArray = ComponentDatatype_default.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_default(typedArray)) {
typedArray = ComponentDatatype_default.createTypedArray(componentType, array);
cachedTypedArrays[semantic] = typedArray;
}
return typedArray;
}
Cesium3DTileFeatureTable.prototype.getGlobalProperty = function(semantic, componentType, componentLength) {
const jsonValue = this.json[semantic];
if (!defined_default(jsonValue)) {
return void 0;
}
if (defined_default(jsonValue.byteOffset)) {
componentType = defaultValue_default(componentType, ComponentDatatype_default.UNSIGNED_INT);
componentLength = defaultValue_default(componentLength, 1);
return getTypedArrayFromBinary(
this,
semantic,
componentType,
componentLength,
1,
jsonValue.byteOffset
);
}
return jsonValue;
};
Cesium3DTileFeatureTable.prototype.hasProperty = function(semantic) {
return defined_default(this.json[semantic]);
};
Cesium3DTileFeatureTable.prototype.getPropertyArray = function(semantic, componentType, componentLength) {
const jsonValue = this.json[semantic];
if (!defined_default(jsonValue)) {
return void 0;
}
if (defined_default(jsonValue.byteOffset)) {
if (defined_default(jsonValue.componentType)) {
componentType = ComponentDatatype_default.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_default(jsonValue)) {
return void 0;
}
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;
};
var Cesium3DTileFeatureTable_default = Cesium3DTileFeatureTable;
// node_modules/@cesium/engine/Source/Scene/parseBatchTable.js
function parseBatchTable(options) {
Check_default.typeOf.number("options.count", options.count);
Check_default.typeOf.object("options.batchTable", options.batchTable);
const featureCount = options.count;
const batchTable = options.batchTable;
const binaryBody = options.binaryBody;
const parseAsPropertyAttributes = defaultValue_default(
options.parseAsPropertyAttributes,
false
);
const customAttributeOutput = options.customAttributeOutput;
if (parseAsPropertyAttributes && !defined_default(customAttributeOutput)) {
throw new DeveloperError_default(
"customAttributeOutput is required when parsing batch table as property attributes"
);
}
const partitionResults = partitionProperties(batchTable);
let jsonMetadataTable;
if (defined_default(partitionResults.jsonProperties)) {
jsonMetadataTable = new JsonMetadataTable_default({
count: featureCount,
properties: partitionResults.jsonProperties
});
}
let hierarchy;
if (defined_default(partitionResults.hierarchy)) {
hierarchy = new BatchTableHierarchy_default({
extension: partitionResults.hierarchy,
binaryBody
});
}
const className = MetadataClass_default.BATCH_TABLE_CLASS_NAME;
const binaryProperties = partitionResults.binaryProperties;
let metadataTable;
let propertyAttributes;
let transcodedSchema;
if (parseAsPropertyAttributes) {
const attributeResults = transcodeBinaryPropertiesAsPropertyAttributes(
featureCount,
className,
binaryProperties,
binaryBody,
customAttributeOutput
);
transcodedSchema = attributeResults.transcodedSchema;
const propertyAttribute = new PropertyAttribute_default({
propertyAttribute: attributeResults.propertyAttributeJson,
class: attributeResults.transcodedClass
});
propertyAttributes = [propertyAttribute];
} else {
const binaryResults = transcodeBinaryProperties(
featureCount,
className,
binaryProperties,
binaryBody
);
transcodedSchema = binaryResults.transcodedSchema;
const featureTableJson = binaryResults.featureTableJson;
metadataTable = new MetadataTable_default({
count: featureTableJson.count,
properties: featureTableJson.properties,
class: binaryResults.transcodedClass,
bufferViews: binaryResults.bufferViewsTypedArrays
});
propertyAttributes = [];
}
const propertyTables = [];
if (defined_default(metadataTable) || defined_default(jsonMetadataTable) || defined_default(hierarchy)) {
const propertyTable = new PropertyTable_default({
id: 0,
name: "Batch Table",
count: featureCount,
metadataTable,
jsonMetadataTable,
batchTableHierarchy: hierarchy
});
propertyTables.push(propertyTable);
}
const metadataOptions = {
schema: transcodedSchema,
propertyTables,
propertyAttributes,
extensions: partitionResults.extensions,
extras: partitionResults.extras
};
return new StructuralMetadata_default(metadataOptions);
}
function partitionProperties(batchTable) {
const legacyHierarchy = batchTable.HIERARCHY;
const extras = batchTable.extras;
const extensions = batchTable.extensions;
let hierarchyExtension;
if (defined_default(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_default(extensions)) {
hierarchyExtension = extensions["3DTILES_batch_table_hierarchy"];
}
let jsonProperties;
const binaryProperties = {};
for (const propertyId in batchTable) {
if (!batchTable.hasOwnProperty(propertyId) || propertyId === "HIERARCHY" || propertyId === "extensions" || propertyId === "extras") {
continue;
}
const property = batchTable[propertyId];
if (Array.isArray(property)) {
jsonProperties = defined_default(jsonProperties) ? jsonProperties : {};
jsonProperties[propertyId] = property;
} else {
binaryProperties[propertyId] = property;
}
}
return {
binaryProperties,
jsonProperties,
hierarchy: hierarchyExtension,
extras,
extensions
};
}
function transcodeBinaryProperties(featureCount, className, binaryProperties, binaryBody) {
const classProperties = {};
const featureTableProperties = {};
const bufferViewsTypedArrays = {};
let bufferViewCount = 0;
for (const propertyId in binaryProperties) {
if (!binaryProperties.hasOwnProperty(propertyId)) {
continue;
}
if (!defined_default(binaryBody)) {
throw new RuntimeError_default(
`Property ${propertyId} requires a batch table binary.`
);
}
const property = binaryProperties[propertyId];
const binaryAccessor = getBinaryAccessor_default(property);
featureTableProperties[propertyId] = {
bufferView: bufferViewCount
};
classProperties[propertyId] = transcodePropertyType(property);
bufferViewsTypedArrays[bufferViewCount] = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + property.byteOffset,
featureCount
);
bufferViewCount++;
}
const schemaJson = {
classes: {}
};
schemaJson.classes[className] = {
properties: classProperties
};
const transcodedSchema = MetadataSchema_default.fromJson(schemaJson);
const featureTableJson = {
class: className,
count: featureCount,
properties: featureTableProperties
};
return {
featureTableJson,
bufferViewsTypedArrays,
transcodedSchema,
transcodedClass: transcodedSchema.classes[className]
};
}
function transcodeBinaryPropertiesAsPropertyAttributes(featureCount, className, binaryProperties, binaryBody, customAttributeOutput) {
const classProperties = {};
const propertyAttributeProperties = {};
let nextPlaceholderId = 0;
for (const propertyId in binaryProperties) {
if (!binaryProperties.hasOwnProperty(propertyId)) {
continue;
}
const property = binaryProperties[propertyId];
if (!defined_default(binaryBody) && !defined_default(property.typedArray)) {
throw new RuntimeError_default(
`Property ${propertyId} requires a batch table binary.`
);
}
let sanitizedPropertyId = ModelUtility_default.sanitizeGlslIdentifier(propertyId);
if (sanitizedPropertyId === "" || classProperties.hasOwnProperty(sanitizedPropertyId)) {
sanitizedPropertyId = `property_${nextPlaceholderId}`;
nextPlaceholderId++;
}
const classProperty = transcodePropertyType(property);
classProperty.name = propertyId;
classProperties[sanitizedPropertyId] = classProperty;
let customAttributeName = sanitizedPropertyId.toUpperCase();
if (!customAttributeName.startsWith("_")) {
customAttributeName = `_${customAttributeName}`;
}
let attributeTypedArray = property.typedArray;
if (!defined_default(attributeTypedArray)) {
const binaryAccessor = getBinaryAccessor_default(property);
attributeTypedArray = binaryAccessor.createArrayBufferView(
binaryBody.buffer,
binaryBody.byteOffset + property.byteOffset,
featureCount
);
}
const attribute = new ModelComponents_default.Attribute();
attribute.name = customAttributeName;
attribute.count = featureCount;
attribute.type = property.type;
const componentDatatype = ComponentDatatype_default.fromTypedArray(
attributeTypedArray
);
if (componentDatatype === ComponentDatatype_default.INT || componentDatatype === ComponentDatatype_default.UNSIGNED_INT || componentDatatype === ComponentDatatype_default.DOUBLE) {
parseBatchTable._oneTimeWarning(
"Cast pnts property to floats",
`Point cloud property "${customAttributeName}" will be cast to a float array because INT, UNSIGNED_INT, and DOUBLE are not valid WebGL vertex attribute types. Some precision may be lost.`
);
attributeTypedArray = new Float32Array(attributeTypedArray);
}
attribute.componentDatatype = ComponentDatatype_default.fromTypedArray(
attributeTypedArray
);
attribute.typedArray = attributeTypedArray;
customAttributeOutput.push(attribute);
propertyAttributeProperties[sanitizedPropertyId] = {
attribute: customAttributeName
};
}
const schemaJson = {
classes: {}
};
schemaJson.classes[className] = {
properties: classProperties
};
const transcodedSchema = MetadataSchema_default.fromJson(schemaJson);
const propertyAttributeJson = {
properties: propertyAttributeProperties
};
return {
class: className,
propertyAttributeJson,
transcodedSchema,
transcodedClass: transcodedSchema.classes[className]
};
}
function transcodePropertyType(property) {
const componentType = transcodeComponentType(property.componentType);
return {
type: property.type,
componentType
};
}
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";
}
}
parseBatchTable._deprecationWarning = deprecationWarning_default;
parseBatchTable._oneTimeWarning = oneTimeWarning_default;
var parseBatchTable_default = parseBatchTable;
// node_modules/@cesium/engine/Source/Scene/Model/B3dmLoader.js
var B3dmLoaderState = {
UNLOADED: 0,
LOADING: 1,
PROCESSING: 2,
READY: 3,
FAILED: 4
};
var FeatureIdAttribute3 = ModelComponents_default.FeatureIdAttribute;
function B3dmLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const b3dmResource = options.b3dmResource;
let baseResource2 = options.baseResource;
const arrayBuffer = options.arrayBuffer;
const byteOffset = defaultValue_default(options.byteOffset, 0);
const releaseGltfJson = defaultValue_default(options.releaseGltfJson, false);
const asynchronous = defaultValue_default(options.asynchronous, true);
const incrementallyLoadTextures = defaultValue_default(
options.incrementallyLoadTextures,
true
);
const upAxis = defaultValue_default(options.upAxis, Axis_default.Y);
const forwardAxis = defaultValue_default(options.forwardAxis, Axis_default.X);
const loadAttributesAsTypedArray = defaultValue_default(
options.loadAttributesAsTypedArray,
false
);
const loadAttributesFor2D = defaultValue_default(options.loadAttributesFor2D, false);
const loadIndicesForWireframe = defaultValue_default(
options.loadIndicesForWireframe,
false
);
const loadPrimitiveOutline2 = defaultValue_default(options.loadPrimitiveOutline, true);
const loadForClassification = defaultValue_default(
options.loadForClassification,
false
);
Check_default.typeOf.object("options.b3dmResource", b3dmResource);
Check_default.typeOf.object("options.arrayBuffer", arrayBuffer);
baseResource2 = defined_default(baseResource2) ? baseResource2 : b3dmResource.clone();
this._b3dmResource = b3dmResource;
this._baseResource = baseResource2;
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._loadPrimitiveOutline = loadPrimitiveOutline2;
this._loadForClassification = loadForClassification;
this._state = B3dmLoaderState.UNLOADED;
this._promise = void 0;
this._gltfLoader = void 0;
this._batchLength = 0;
this._propertyTable = void 0;
this._batchTable = void 0;
this._components = void 0;
this._transform = Matrix4_default.IDENTITY;
}
if (defined_default(Object.create)) {
B3dmLoader.prototype = Object.create(ResourceLoader_default.prototype);
B3dmLoader.prototype.constructor = B3dmLoader;
}
Object.defineProperties(B3dmLoader.prototype, {
texturesLoaded: {
get: function() {
var _a;
return (_a = this._gltfLoader) == null ? void 0 : _a.texturesLoaded;
}
},
cacheKey: {
get: function() {
return void 0;
}
},
components: {
get: function() {
return this._components;
}
}
});
B3dmLoader.prototype.load = function() {
if (defined_default(this._promise)) {
return this._promise;
}
const b3dm = B3dmParser_default.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_default(
featureTableJson,
featureTableBinary
);
batchLength = featureTable.getGlobalProperty("BATCH_LENGTH");
this._batchLength = batchLength;
const rtcCenter = featureTable.getGlobalProperty(
"RTC_CENTER",
ComponentDatatype_default.FLOAT,
3
);
if (defined_default(rtcCenter)) {
this._transform = Matrix4_default.fromTranslation(Cartesian3_default.fromArray(rtcCenter));
}
this._batchTable = {
json: batchTableJson,
binary: batchTableBinary
};
const gltfLoader = new GltfLoader_default({
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,
loadPrimitiveOutline: this._loadPrimitiveOutline,
loadForClassification: this._loadForClassification,
renameBatchIdSemantic: true
});
this._gltfLoader = gltfLoader;
this._state = B3dmLoaderState.LOADING;
const that = this;
this._promise = gltfLoader.load().then(function() {
if (that.isDestroyed()) {
return;
}
that._state = B3dmLoaderState.PROCESSING;
return that;
}).catch(function(error) {
if (that.isDestroyed()) {
return;
}
return handleError7(that, error);
});
return this._promise;
};
function handleError7(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) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === B3dmLoaderState.READY) {
return true;
}
if (this._state !== B3dmLoaderState.PROCESSING) {
return false;
}
const ready = this._gltfLoader.process(frameState);
if (!ready) {
return false;
}
const components = this._gltfLoader.components;
components.transform = Matrix4_default.multiplyTransformation(
this._transform,
components.transform,
components.transform
);
createStructuralMetadata(this, components);
this._components = components;
this._arrayBuffer = void 0;
this._state = B3dmLoaderState.READY;
return true;
};
function createStructuralMetadata(loader, components) {
const batchTable = loader._batchTable;
const batchLength = loader._batchLength;
if (batchLength === 0) {
return;
}
let structuralMetadata;
if (defined_default(batchTable.json)) {
structuralMetadata = parseBatchTable_default({
count: batchLength,
batchTable: batchTable.json,
binaryBody: batchTable.binary
});
} else {
const emptyPropertyTable = new PropertyTable_default({
name: MetadataClass_default.BATCH_TABLE_CLASS_NAME,
count: batchLength
});
structuralMetadata = new StructuralMetadata_default({
schema: {},
propertyTables: [emptyPropertyTable]
});
}
const nodes = components.scene.nodes;
const length3 = nodes.length;
for (let i = 0; i < length3; i++) {
processNode(nodes[i]);
}
components.structuralMetadata = structuralMetadata;
}
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 = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.FEATURE_ID
);
if (defined_default(featureIdVertexAttribute)) {
featureIdVertexAttribute.setIndex = 0;
const featureIdAttribute = new FeatureIdAttribute3();
featureIdAttribute.propertyTableId = 0;
featureIdAttribute.setIndex = 0;
featureIdAttribute.positionalLabel = "featureId_0";
primitive.featureIds.push(featureIdAttribute);
}
}
}
B3dmLoader.prototype.unload = function() {
if (defined_default(this._gltfLoader) && !this._gltfLoader.isDestroyed()) {
this._gltfLoader.unload();
}
this._components = void 0;
this._arrayBuffer = void 0;
};
var B3dmLoader_default = B3dmLoader;
// node_modules/@cesium/engine/Source/Scene/Model/GeoJsonLoader.js
function GeoJsonLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.geoJson", options.geoJson);
this._geoJson = options.geoJson;
this._components = void 0;
}
if (defined_default(Object.create)) {
GeoJsonLoader.prototype = Object.create(ResourceLoader_default.prototype);
GeoJsonLoader.prototype.constructor = GeoJsonLoader;
}
Object.defineProperties(GeoJsonLoader.prototype, {
cacheKey: {
get: function() {
return void 0;
}
},
components: {
get: function() {
return this._components;
}
}
});
GeoJsonLoader.prototype.load = function() {
return Promise.resolve(this);
};
GeoJsonLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (defined_default(this._components)) {
return true;
}
this._components = parse2(this._geoJson, frameState);
this._geoJson = void 0;
return true;
};
function ParsedFeature() {
this.lines = void 0;
this.points = void 0;
this.properties = void 0;
}
function ParseResult() {
this.features = [];
}
function parsePosition(position) {
const x = position[0];
const y = position[1];
const z = defaultValue_default(position[2], 0);
return new Cartesian3_default(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) {
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;
}
function parsePoint(coordinates) {
return [parsePosition(coordinates)];
}
function parseMultiPoint(coordinates) {
const pointsLength = coordinates.length;
const points = new Array(pointsLength);
for (let i = 0; i < pointsLength; i++) {
points[i] = parsePosition(coordinates[i]);
}
return points;
}
var geometryTypes = {
LineString: parseLineString,
MultiLineString: parseMultiLineString,
MultiPolygon: parseMultiPolygon,
Polygon: parsePolygon,
MultiPoint: parseMultiPoint,
Point: parsePoint
};
var primitiveTypes = {
LineString: PrimitiveType_default.LINES,
MultiLineString: PrimitiveType_default.LINES,
MultiPolygon: PrimitiveType_default.LINES,
Polygon: PrimitiveType_default.LINES,
MultiPoint: PrimitiveType_default.POINTS,
Point: PrimitiveType_default.POINTS
};
function parseFeature(feature, result) {
if (!defined_default(feature.geometry)) {
return;
}
const geometryType = feature.geometry.type;
const geometryFunction = geometryTypes[geometryType];
const primitiveType = primitiveTypes[geometryType];
const coordinates = feature.geometry.coordinates;
if (!defined_default(geometryFunction)) {
return;
}
if (!defined_default(coordinates)) {
return;
}
const parsedFeature = new ParsedFeature();
if (primitiveType === PrimitiveType_default.LINES) {
parsedFeature.lines = geometryFunction(coordinates);
} else if (primitiveType === PrimitiveType_default.POINTS) {
parsedFeature.points = 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);
}
}
var geoJsonObjectTypes = {
FeatureCollection: parseFeatureCollection,
Feature: parseFeature
};
var scratchCartesian7 = new Cartesian3_default();
function createLinesPrimitive(features, toLocal, frameState) {
let vertexCount = 0;
let indexCount = 0;
const featureCount = features.length;
for (let i = 0; i < featureCount; i++) {
const feature = features[i];
if (defined_default(feature.lines)) {
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;
}
}
}
const positionsTypedArray = new Float32Array(vertexCount * 3);
const featureIdsTypedArray = new Float32Array(vertexCount);
const indicesTypedArray = IndexDatatype_default.createTypedArray(
vertexCount,
indexCount
);
const indexDatatype = IndexDatatype_default.fromTypedArray(indicesTypedArray);
const localMin = new Cartesian3_default(
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY
);
const localMax = new Cartesian3_default(
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY
);
let vertexCounter = 0;
let segmentCounter = 0;
for (let i = 0; i < featureCount; i++) {
const feature = features[i];
if (!defined_default(feature.lines)) {
continue;
}
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 cartographic2 = line[k];
const globalCartesian = Cartesian3_default.fromDegrees(
cartographic2.x,
cartographic2.y,
cartographic2.z,
Ellipsoid_default.WGS84,
scratchCartesian7
);
const localCartesian = Matrix4_default.multiplyByPoint(
toLocal,
globalCartesian,
scratchCartesian7
);
Cartesian3_default.minimumByComponent(localMin, localCartesian, localMin);
Cartesian3_default.maximumByComponent(localMax, localCartesian, localMax);
Cartesian3_default.pack(localCartesian, positionsTypedArray, vertexCounter * 3);
featureIdsTypedArray[vertexCounter] = i;
if (k < positionsLength - 1) {
indicesTypedArray[segmentCounter * 2] = vertexCounter;
indicesTypedArray[segmentCounter * 2 + 1] = vertexCounter + 1;
segmentCounter++;
}
vertexCounter++;
}
}
}
const positionBuffer = Buffer_default.createVertexBuffer({
typedArray: positionsTypedArray,
context: frameState.context,
usage: BufferUsage_default.STATIC_DRAW
});
positionBuffer.vertexArrayDestroyable = false;
const featureIdBuffer = Buffer_default.createVertexBuffer({
typedArray: featureIdsTypedArray,
context: frameState.context,
usage: BufferUsage_default.STATIC_DRAW
});
featureIdBuffer.vertexArrayDestroyable = false;
const indexBuffer = Buffer_default.createIndexBuffer({
typedArray: indicesTypedArray,
context: frameState.context,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype
});
indexBuffer.vertexArrayDestroyable = false;
const positionAttribute = new ModelComponents_default.Attribute();
positionAttribute.semantic = VertexAttributeSemantic_default.POSITION;
positionAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
positionAttribute.type = AttributeType_default.VEC3;
positionAttribute.count = vertexCount;
positionAttribute.min = localMin;
positionAttribute.max = localMax;
positionAttribute.buffer = positionBuffer;
const featureIdAttribute = new ModelComponents_default.Attribute();
featureIdAttribute.semantic = VertexAttributeSemantic_default.FEATURE_ID;
featureIdAttribute.setIndex = 0;
featureIdAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
featureIdAttribute.type = AttributeType_default.SCALAR;
featureIdAttribute.count = vertexCount;
featureIdAttribute.buffer = featureIdBuffer;
const attributes = [positionAttribute, featureIdAttribute];
const material = new ModelComponents_default.Material();
material.unlit = true;
const indices2 = new ModelComponents_default.Indices();
indices2.indexDatatype = indexDatatype;
indices2.count = indicesTypedArray.length;
indices2.buffer = indexBuffer;
const featureId = new ModelComponents_default.FeatureIdAttribute();
featureId.featureCount = featureCount;
featureId.propertyTableId = 0;
featureId.setIndex = 0;
featureId.positionalLabel = "featureId_0";
const featureIds = [featureId];
const primitive = new ModelComponents_default.Primitive();
primitive.attributes = attributes;
primitive.indices = indices2;
primitive.featureIds = featureIds;
primitive.primitiveType = PrimitiveType_default.LINES;
primitive.material = material;
return primitive;
}
function createPointsPrimitive(features, toLocal, frameState) {
let vertexCount = 0;
const featureCount = features.length;
for (let i = 0; i < featureCount; i++) {
const feature = features[i];
if (defined_default(feature.points)) {
vertexCount += feature.points.length;
}
}
const positionsTypedArray = new Float32Array(vertexCount * 3);
const featureIdsTypedArray = new Float32Array(vertexCount);
const localMin = new Cartesian3_default(
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY
);
const localMax = new Cartesian3_default(
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY
);
let vertexCounter = 0;
for (let i = 0; i < featureCount; i++) {
const feature = features[i];
if (!defined_default(feature.points)) {
continue;
}
const pointsLength = feature.points.length;
for (let j = 0; j < pointsLength; j++) {
const cartographic2 = feature.points[j];
const globalCartesian = Cartesian3_default.fromDegrees(
cartographic2.x,
cartographic2.y,
cartographic2.z,
Ellipsoid_default.WGS84,
scratchCartesian7
);
const localCartesian = Matrix4_default.multiplyByPoint(
toLocal,
globalCartesian,
scratchCartesian7
);
Cartesian3_default.minimumByComponent(localMin, localCartesian, localMin);
Cartesian3_default.maximumByComponent(localMax, localCartesian, localMax);
Cartesian3_default.pack(localCartesian, positionsTypedArray, vertexCounter * 3);
featureIdsTypedArray[vertexCounter] = i;
vertexCounter++;
}
}
const positionBuffer = Buffer_default.createVertexBuffer({
typedArray: positionsTypedArray,
context: frameState.context,
usage: BufferUsage_default.STATIC_DRAW
});
positionBuffer.vertexArrayDestroyable = false;
const featureIdBuffer = Buffer_default.createVertexBuffer({
typedArray: featureIdsTypedArray,
context: frameState.context,
usage: BufferUsage_default.STATIC_DRAW
});
featureIdBuffer.vertexArrayDestroyable = false;
const positionAttribute = new ModelComponents_default.Attribute();
positionAttribute.semantic = VertexAttributeSemantic_default.POSITION;
positionAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
positionAttribute.type = AttributeType_default.VEC3;
positionAttribute.count = vertexCount;
positionAttribute.min = localMin;
positionAttribute.max = localMax;
positionAttribute.buffer = positionBuffer;
const featureIdAttribute = new ModelComponents_default.Attribute();
featureIdAttribute.semantic = VertexAttributeSemantic_default.FEATURE_ID;
featureIdAttribute.setIndex = 0;
featureIdAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
featureIdAttribute.type = AttributeType_default.SCALAR;
featureIdAttribute.count = vertexCount;
featureIdAttribute.buffer = featureIdBuffer;
const attributes = [positionAttribute, featureIdAttribute];
const material = new ModelComponents_default.Material();
material.unlit = true;
const featureId = new ModelComponents_default.FeatureIdAttribute();
featureId.featureCount = featureCount;
featureId.propertyTableId = 0;
featureId.setIndex = 0;
featureId.positionalLabel = "featureId_0";
const featureIds = [featureId];
const primitive = new ModelComponents_default.Primitive();
primitive.attributes = attributes;
primitive.featureIds = featureIds;
primitive.primitiveType = PrimitiveType_default.POINTS;
primitive.material = material;
return primitive;
}
function parse2(geoJson, frameState) {
const result = new ParseResult();
const parseFunction = geoJsonObjectTypes[geoJson.type];
if (defined_default(parseFunction)) {
parseFunction(geoJson, result);
}
const features = result.features;
const featureCount = features.length;
if (featureCount === 0) {
throw new RuntimeError_default("GeoJSON must have at least one feature");
}
const properties = {};
for (let i = 0; i < featureCount; i++) {
const feature = features[i];
const featureProperties = defaultValue_default(
feature.properties,
defaultValue_default.EMPTY_OBJECT
);
for (const propertyId in featureProperties) {
if (featureProperties.hasOwnProperty(propertyId)) {
if (!defined_default(properties[propertyId])) {
properties[propertyId] = new Array(featureCount);
}
}
}
}
for (let i = 0; i < featureCount; i++) {
const feature = features[i];
for (const propertyId in properties) {
if (properties.hasOwnProperty(propertyId)) {
const value = defaultValue_default(feature.properties[propertyId], "");
properties[propertyId][i] = value;
}
}
}
const jsonMetadataTable = new JsonMetadataTable_default({
count: featureCount,
properties
});
const propertyTable = new PropertyTable_default({
id: 0,
count: featureCount,
jsonMetadataTable
});
const propertyTables = [propertyTable];
const schema = MetadataSchema_default.fromJson({});
const structuralMetadata = new StructuralMetadata_default({
schema,
propertyTables
});
const cartographicMin = new Cartesian3_default(
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY
);
const cartographicMax = new Cartesian3_default(
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY
);
let hasLines = false;
let hasPoints = false;
for (let i = 0; i < featureCount; i++) {
const feature = features[i];
if (defined_default(feature.lines)) {
hasLines = true;
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_default.minimumByComponent(
cartographicMin,
line[k],
cartographicMin
);
Cartesian3_default.maximumByComponent(
cartographicMax,
line[k],
cartographicMax
);
}
}
}
if (defined_default(feature.points)) {
hasPoints = true;
const pointsLength = feature.points.length;
for (let j = 0; j < pointsLength; j++) {
const point = feature.points[j];
Cartesian3_default.minimumByComponent(cartographicMin, point, cartographicMin);
Cartesian3_default.maximumByComponent(cartographicMax, point, cartographicMax);
}
}
}
const cartographicCenter = Cartesian3_default.midpoint(
cartographicMin,
cartographicMax,
new Cartesian3_default()
);
const ecefCenter = Cartesian3_default.fromDegrees(
cartographicCenter.x,
cartographicCenter.y,
cartographicCenter.z,
Ellipsoid_default.WGS84,
new Cartesian3_default()
);
const toGlobal = Transforms_default.eastNorthUpToFixedFrame(
ecefCenter,
Ellipsoid_default.WGS84,
new Matrix4_default()
);
const toLocal = Matrix4_default.inverseTransformation(toGlobal, new Matrix4_default());
const primitives = [];
if (hasLines) {
primitives.push(createLinesPrimitive(features, toLocal, frameState));
}
if (hasPoints) {
primitives.push(createPointsPrimitive(features, toLocal, frameState));
}
const node = new ModelComponents_default.Node();
node.index = 0;
node.primitives = primitives;
const nodes = [node];
const scene = new ModelComponents_default.Scene();
scene.nodes = nodes;
const components = new ModelComponents_default.Components();
components.scene = scene;
components.nodes = nodes;
components.transform = toGlobal;
components.structuralMetadata = structuralMetadata;
return components;
}
GeoJsonLoader.prototype.unload = function() {
this._components = void 0;
};
var GeoJsonLoader_default = GeoJsonLoader;
// node_modules/@cesium/engine/Source/Scene/I3dmParser.js
var I3dmParser = {};
I3dmParser._deprecationWarning = deprecationWarning_default;
var sizeOfUint325 = Uint32Array.BYTES_PER_ELEMENT;
I3dmParser.parse = function(arrayBuffer, byteOffset) {
Check_default.defined("arrayBuffer", arrayBuffer);
const byteStart = defaultValue_default(byteOffset, 0);
byteOffset = byteStart;
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint325;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Instanced 3D Model version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint325;
const byteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint325;
const featureTableJsonByteLength = view.getUint32(byteOffset, true);
if (featureTableJsonByteLength === 0) {
throw new RuntimeError_default(
"featureTableJsonByteLength is zero, the feature table must be defined."
);
}
byteOffset += sizeOfUint325;
const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint325;
const batchTableJsonByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint325;
const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint325;
const gltfFormat = view.getUint32(byteOffset, true);
if (gltfFormat !== 1 && gltfFormat !== 0) {
throw new RuntimeError_default(
`Only glTF format 0 (uri) or 1 (embedded) are supported. Format ${gltfFormat} is not.`
);
}
byteOffset += sizeOfUint325;
const featureTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
featureTableJsonByteLength
);
byteOffset += featureTableJsonByteLength;
const featureTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
featureTableBinaryByteLength
);
byteOffset += featureTableBinaryByteLength;
let batchTableJson;
let batchTableBinary;
if (batchTableJsonByteLength > 0) {
batchTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
batchTableJsonByteLength
);
byteOffset += batchTableJsonByteLength;
if (batchTableBinaryByteLength > 0) {
batchTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
batchTableBinaryByteLength
);
batchTableBinary = new Uint8Array(batchTableBinary);
byteOffset += batchTableBinaryByteLength;
}
}
const gltfByteLength = byteStart + byteLength - byteOffset;
if (gltfByteLength === 0) {
throw new RuntimeError_default("glTF byte length must be greater than 0.");
}
let gltfView;
if (byteOffset % 4 === 0) {
gltfView = new Uint8Array(arrayBuffer, byteOffset, gltfByteLength);
} else {
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,
featureTableJson,
featureTableBinary,
batchTableJson,
batchTableBinary,
gltf: gltfView
};
};
var I3dmParser_default = I3dmParser;
// node_modules/@cesium/engine/Source/Scene/Model/I3dmLoader.js
var I3dmLoaderState = {
NOT_LOADED: 0,
LOADING: 1,
PROCESSING: 2,
POST_PROCESSING: 3,
READY: 4,
FAILED: 5,
UNLOADED: 6
};
var Attribute3 = ModelComponents_default.Attribute;
var FeatureIdAttribute4 = ModelComponents_default.FeatureIdAttribute;
var Instances3 = ModelComponents_default.Instances;
function I3dmLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const i3dmResource = options.i3dmResource;
const arrayBuffer = options.arrayBuffer;
let baseResource2 = options.baseResource;
const byteOffset = defaultValue_default(options.byteOffset, 0);
const releaseGltfJson = defaultValue_default(options.releaseGltfJson, false);
const asynchronous = defaultValue_default(options.asynchronous, true);
const incrementallyLoadTextures = defaultValue_default(
options.incrementallyLoadTextures,
true
);
const upAxis = defaultValue_default(options.upAxis, Axis_default.Y);
const forwardAxis = defaultValue_default(options.forwardAxis, Axis_default.X);
const loadAttributesAsTypedArray = defaultValue_default(
options.loadAttributesAsTypedArray,
false
);
const loadIndicesForWireframe = defaultValue_default(
options.loadIndicesForWireframe,
false
);
const loadPrimitiveOutline2 = defaultValue_default(options.loadPrimitiveOutline, true);
Check_default.typeOf.object("options.i3dmResource", i3dmResource);
Check_default.typeOf.object("options.arrayBuffer", arrayBuffer);
baseResource2 = defined_default(baseResource2) ? baseResource2 : i3dmResource.clone();
this._i3dmResource = i3dmResource;
this._baseResource = baseResource2;
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._loadPrimitiveOutline = loadPrimitiveOutline2;
this._state = I3dmLoaderState.NOT_LOADED;
this._promise = void 0;
this._gltfLoader = void 0;
this._buffers = [];
this._components = void 0;
this._transform = Matrix4_default.IDENTITY;
this._batchTable = void 0;
this._featureTable = void 0;
this._instancesLength = 0;
}
if (defined_default(Object.create)) {
I3dmLoader.prototype = Object.create(ResourceLoader_default.prototype);
I3dmLoader.prototype.constructor = I3dmLoader;
}
Object.defineProperties(I3dmLoader.prototype, {
texturesLoaded: {
get: function() {
var _a;
return (_a = this._gltfLoader) == null ? void 0 : _a.texturesLoaded;
}
},
cacheKey: {
get: function() {
return void 0;
}
},
components: {
get: function() {
return this._components;
}
}
});
I3dmLoader.prototype.load = function() {
if (defined_default(this._promise)) {
return this._promise;
}
const i3dm = I3dmParser_default.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;
const featureTable = new Cesium3DTileFeatureTable_default(
featureTableJson,
featureTableBinary
);
this._featureTable = featureTable;
const instancesLength = featureTable.getGlobalProperty("INSTANCES_LENGTH");
featureTable.featuresLength = instancesLength;
if (!defined_default(instancesLength)) {
throw new RuntimeError_default(
"Feature table global property: INSTANCES_LENGTH must be defined"
);
}
this._instancesLength = instancesLength;
const rtcCenter = featureTable.getGlobalProperty(
"RTC_CENTER",
ComponentDatatype_default.FLOAT,
3
);
if (defined_default(rtcCenter)) {
this._transform = Matrix4_default.fromTranslation(Cartesian3_default.fromArray(rtcCenter));
}
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,
loadPrimitiveOutline: this._loadPrimitiveOutline
};
if (gltfFormat === 0) {
let gltfUrl = getStringFromTypedArray_default(i3dm.gltf);
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;
}
const gltfLoader = new GltfLoader_default(loaderOptions);
this._gltfLoader = gltfLoader;
this._state = I3dmLoaderState.LOADING;
this._promise = gltfLoader.load().then(() => {
if (this.isDestroyed()) {
return;
}
this._state = I3dmLoaderState.PROCESSING;
return this;
}).catch((error) => {
if (this.isDestroyed()) {
return;
}
throw handleError8(this, error);
});
return this._promise;
};
function handleError8(i3dmLoader, error) {
i3dmLoader.unload();
i3dmLoader._state = I3dmLoaderState.FAILED;
const errorMessage = "Failed to load i3dm";
return i3dmLoader.getError(errorMessage, error);
}
I3dmLoader.prototype.process = function(frameState) {
Check_default.typeOf.object("frameState", frameState);
if (this._state === I3dmLoaderState.READY) {
return true;
}
const gltfLoader = this._gltfLoader;
let ready = false;
if (this._state === I3dmLoaderState.PROCESSING) {
ready = gltfLoader.process(frameState);
}
if (!ready) {
return false;
}
const components = gltfLoader.components;
components.transform = Matrix4_default.multiplyTransformation(
this._transform,
components.transform,
components.transform
);
createInstances(this, components, frameState);
createStructuralMetadata2(this, components);
this._components = components;
this._arrayBuffer = void 0;
this._state = I3dmLoaderState.READY;
return true;
};
function createStructuralMetadata2(loader, components) {
const batchTable = loader._batchTable;
const instancesLength = loader._instancesLength;
if (instancesLength === 0) {
return;
}
let structuralMetadata;
if (defined_default(batchTable.json)) {
structuralMetadata = parseBatchTable_default({
count: instancesLength,
batchTable: batchTable.json,
binaryBody: batchTable.binary
});
} else {
const emptyPropertyTable = new PropertyTable_default({
name: MetadataClass_default.BATCH_TABLE_CLASS_NAME,
count: instancesLength
});
structuralMetadata = new StructuralMetadata_default({
schema: {},
propertyTables: [emptyPropertyTable]
});
}
components.structuralMetadata = structuralMetadata;
}
var positionScratch4 = new Cartesian3_default();
var propertyScratch1 = new Array(4);
var transformScratch = new Matrix4_default();
function createInstances(loader, components, frameState) {
let i;
const featureTable = loader._featureTable;
const instancesLength = loader._instancesLength;
if (instancesLength === 0) {
return;
}
const rtcCenter = featureTable.getGlobalProperty(
"RTC_CENTER",
ComponentDatatype_default.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, instancesLength);
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_default.unpackArray(translationTypedArray);
let instancePosition = new Cartesian3_default();
const instanceNormalRight = new Cartesian3_default();
const instanceNormalUp = new Cartesian3_default();
const instanceNormalForward = new Cartesian3_default();
const instanceRotation = new Matrix3_default();
const instanceQuaternion = new Quaternion_default();
const instanceQuaternionArray = new Array(4);
const instanceScale = new Cartesian3_default();
const instanceScaleArray = new Array(3);
const instanceTransform = new Matrix4_default();
if (!defined_default(rtcCenter)) {
const positionBoundingSphere = BoundingSphere_default.fromPoints(instancePositions);
for (i = 0; i < instancePositions.length; i++) {
Cartesian3_default.subtract(
instancePositions[i],
positionBoundingSphere.center,
positionScratch4
);
translationTypedArray[3 * i + 0] = positionScratch4.x;
translationTypedArray[3 * i + 1] = positionScratch4.y;
translationTypedArray[3 * i + 2] = positionScratch4.z;
}
const centerTransform = Matrix4_default.fromTranslation(
positionBoundingSphere.center,
transformScratch
);
components.transform = Matrix4_default.multiplyTransformation(
centerTransform,
components.transform,
components.transform
);
}
for (i = 0; i < instancesLength; i++) {
instancePosition = Cartesian3_default.clone(instancePositions[i]);
if (defined_default(rtcCenter)) {
Cartesian3_default.add(
instancePosition,
Cartesian3_default.unpack(rtcCenter),
instancePosition
);
}
if (hasRotation) {
processRotation(
featureTable,
eastNorthUp,
i,
instanceQuaternion,
instancePosition,
instanceNormalUp,
instanceNormalRight,
instanceNormalForward,
instanceRotation,
instanceTransform
);
Quaternion_default.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];
}
if (hasScale) {
processScale(featureTable, i, instanceScale);
Cartesian3_default.pack(instanceScale, instanceScaleArray, 0);
scaleTypedArray[3 * i + 0] = instanceScaleArray[0];
scaleTypedArray[3 * i + 1] = instanceScaleArray[1];
scaleTypedArray[3 * i + 2] = instanceScaleArray[2];
}
let batchId = featureTable.getProperty(
"BATCH_ID",
ComponentDatatype_default.UNSIGNED_SHORT,
1,
i
);
if (!defined_default(batchId)) {
batchId = i;
}
featureIdArray[i] = batchId;
}
const instances = new Instances3();
instances.transformInWorldSpace = true;
const buffers = loader._buffers;
const translationAttribute = new Attribute3();
translationAttribute.name = "Instance Translation";
translationAttribute.semantic = InstanceAttributeSemantic_default.TRANSLATION;
translationAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
translationAttribute.type = AttributeType_default.VEC3;
translationAttribute.count = instancesLength;
translationAttribute.typedArray = translationTypedArray;
if (!hasRotation) {
const buffer2 = Buffer_default.createVertexBuffer({
context: frameState.context,
typedArray: translationTypedArray,
usage: BufferUsage_default.STATIC_DRAW
});
buffer2.vertexArrayDestroyable = false;
buffers.push(buffer2);
translationAttribute.buffer = buffer2;
}
instances.attributes.push(translationAttribute);
if (hasRotation) {
const rotationAttribute = new Attribute3();
rotationAttribute.name = "Instance Rotation";
rotationAttribute.semantic = InstanceAttributeSemantic_default.ROTATION;
rotationAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
rotationAttribute.type = AttributeType_default.VEC4;
rotationAttribute.count = instancesLength;
rotationAttribute.typedArray = rotationTypedArray;
instances.attributes.push(rotationAttribute);
}
if (hasScale) {
const scaleAttribute = new Attribute3();
scaleAttribute.name = "Instance Scale";
scaleAttribute.semantic = InstanceAttributeSemantic_default.SCALE;
scaleAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
scaleAttribute.type = AttributeType_default.VEC3;
scaleAttribute.count = instancesLength;
if (hasRotation) {
scaleAttribute.typedArray = scaleTypedArray;
} else {
const buffer2 = Buffer_default.createVertexBuffer({
context: frameState.context,
typedArray: scaleTypedArray,
usage: BufferUsage_default.STATIC_DRAW
});
buffer2.vertexArrayDestroyable = false;
buffers.push(buffer2);
scaleAttribute.buffer = buffer2;
}
instances.attributes.push(scaleAttribute);
}
const featureIdAttribute = new Attribute3();
featureIdAttribute.name = "Instance Feature ID";
featureIdAttribute.setIndex = 0;
featureIdAttribute.semantic = InstanceAttributeSemantic_default.FEATURE_ID;
featureIdAttribute.componentDatatype = ComponentDatatype_default.FLOAT;
featureIdAttribute.type = AttributeType_default.SCALAR;
featureIdAttribute.count = instancesLength;
const buffer = Buffer_default.createVertexBuffer({
context: frameState.context,
typedArray: featureIdArray,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
buffers.push(buffer);
featureIdAttribute.buffer = buffer;
instances.attributes.push(featureIdAttribute);
const featureIdInstanceAttribute = new FeatureIdAttribute4();
featureIdInstanceAttribute.propertyTableId = 0;
featureIdInstanceAttribute.setIndex = 0;
featureIdInstanceAttribute.positionalLabel = "instanceFeatureId_0";
instances.featureIds.push(featureIdInstanceAttribute);
const nodes = components.nodes;
const nodesLength = nodes.length;
let makeInstancesCopy = false;
for (i = 0; i < nodesLength; i++) {
const node = nodes[i];
if (node.primitives.length > 0) {
node.instances = makeInstancesCopy ? createInstancesCopy(instances) : instances;
makeInstancesCopy = true;
}
}
}
function createInstancesCopy(instances) {
const instancesCopy = new Instances3();
instancesCopy.transformInWorldSpace = instances.transformInWorldSpace;
const attributes = instances.attributes;
const attributesLength = attributes.length;
for (let i = 0; i < attributesLength; i++) {
const attributeCopy = clone_default(attributes[i], false);
instancesCopy.attributes.push(attributeCopy);
}
instancesCopy.featureIds = instances.featureIds;
return instancesCopy;
}
function getPositions(featureTable, instancesLength) {
if (featureTable.hasProperty("POSITION")) {
return featureTable.getPropertyArray(
"POSITION",
ComponentDatatype_default.FLOAT,
3
);
} else if (featureTable.hasProperty("POSITION_QUANTIZED")) {
const quantizedPositions = featureTable.getPropertyArray(
"POSITION_QUANTIZED",
ComponentDatatype_default.UNSIGNED_SHORT,
3
);
const quantizedVolumeOffset = featureTable.getGlobalProperty(
"QUANTIZED_VOLUME_OFFSET",
ComponentDatatype_default.FLOAT,
3
);
if (!defined_default(quantizedVolumeOffset)) {
throw new RuntimeError_default(
"Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
);
}
const quantizedVolumeScale = featureTable.getGlobalProperty(
"QUANTIZED_VOLUME_SCALE",
ComponentDatatype_default.FLOAT,
3
);
if (!defined_default(quantizedVolumeScale)) {
throw new RuntimeError_default(
"Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
);
}
const decodedPositions = new Float32Array(quantizedPositions.length);
for (let i = 0; i < quantizedPositions.length / 3; i++) {
for (let j = 0; j < 3; j++) {
const index = 3 * i + j;
decodedPositions[index] = quantizedPositions[index] / 65535 * quantizedVolumeScale[j] + quantizedVolumeOffset[j];
}
}
return decodedPositions;
} else {
throw new RuntimeError_default(
"Either POSITION or POSITION_QUANTIZED must be defined for each instance."
);
}
}
var propertyScratch2 = new Array(4);
function processRotation(featureTable, eastNorthUp, i, instanceQuaternion, instancePosition, instanceNormalUp, instanceNormalRight, instanceNormalForward, instanceRotation, instanceTransform) {
const normalUp = featureTable.getProperty(
"NORMAL_UP",
ComponentDatatype_default.FLOAT,
3,
i,
propertyScratch1
);
const normalRight = featureTable.getProperty(
"NORMAL_RIGHT",
ComponentDatatype_default.FLOAT,
3,
i,
propertyScratch2
);
let hasCustomOrientation = false;
if (defined_default(normalUp)) {
if (!defined_default(normalRight)) {
throw new RuntimeError_default(
"To define a custom orientation, both NORMAL_UP and NORMAL_RIGHT must be defined."
);
}
Cartesian3_default.unpack(normalUp, 0, instanceNormalUp);
Cartesian3_default.unpack(normalRight, 0, instanceNormalRight);
hasCustomOrientation = true;
} else {
const octNormalUp = featureTable.getProperty(
"NORMAL_UP_OCT32P",
ComponentDatatype_default.UNSIGNED_SHORT,
2,
i,
propertyScratch1
);
const octNormalRight = featureTable.getProperty(
"NORMAL_RIGHT_OCT32P",
ComponentDatatype_default.UNSIGNED_SHORT,
2,
i,
propertyScratch2
);
if (defined_default(octNormalUp)) {
if (!defined_default(octNormalRight)) {
throw new RuntimeError_default(
"To define a custom orientation with oct-encoded vectors, both NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P must be defined."
);
}
AttributeCompression_default.octDecodeInRange(
octNormalUp[0],
octNormalUp[1],
65535,
instanceNormalUp
);
AttributeCompression_default.octDecodeInRange(
octNormalRight[0],
octNormalRight[1],
65535,
instanceNormalRight
);
hasCustomOrientation = true;
} else if (eastNorthUp) {
Transforms_default.eastNorthUpToFixedFrame(
instancePosition,
Ellipsoid_default.WGS84,
instanceTransform
);
Matrix4_default.getMatrix3(instanceTransform, instanceRotation);
} else {
Matrix3_default.clone(Matrix3_default.IDENTITY, instanceRotation);
}
}
if (hasCustomOrientation) {
Cartesian3_default.cross(
instanceNormalRight,
instanceNormalUp,
instanceNormalForward
);
Cartesian3_default.normalize(instanceNormalForward, instanceNormalForward);
Matrix3_default.setColumn(
instanceRotation,
0,
instanceNormalRight,
instanceRotation
);
Matrix3_default.setColumn(instanceRotation, 1, instanceNormalUp, instanceRotation);
Matrix3_default.setColumn(
instanceRotation,
2,
instanceNormalForward,
instanceRotation
);
}
Quaternion_default.fromRotationMatrix(instanceRotation, instanceQuaternion);
}
function processScale(featureTable, i, instanceScale) {
instanceScale = Cartesian3_default.fromElements(1, 1, 1, instanceScale);
const scale = featureTable.getProperty(
"SCALE",
ComponentDatatype_default.FLOAT,
1,
i
);
if (defined_default(scale)) {
Cartesian3_default.multiplyByScalar(instanceScale, scale, instanceScale);
}
const nonUniformScale = featureTable.getProperty(
"SCALE_NON_UNIFORM",
ComponentDatatype_default.FLOAT,
3,
i,
propertyScratch1
);
if (defined_default(nonUniformScale)) {
instanceScale.x *= nonUniformScale[0];
instanceScale.y *= nonUniformScale[1];
instanceScale.z *= nonUniformScale[2];
}
}
function unloadBuffers(loader) {
const buffers = loader._buffers;
const length3 = buffers.length;
for (let i = 0; i < length3; i++) {
const buffer = buffers[i];
if (!buffer.isDestroyed()) {
buffer.destroy();
}
}
buffers.length = 0;
}
I3dmLoader.prototype.isUnloaded = function() {
return this._state === I3dmLoaderState.UNLOADED;
};
I3dmLoader.prototype.unload = function() {
if (defined_default(this._gltfLoader) && !this._gltfLoader.isDestroyed()) {
this._gltfLoader.unload();
}
unloadBuffers(this);
this._components = void 0;
this._arrayBuffer = void 0;
this._state = I3dmLoaderState.UNLOADED;
};
var I3dmLoader_default = I3dmLoader;
// node_modules/@cesium/engine/Source/Scene/ModelAnimationState.js
var ModelAnimationState = {
STOPPED: 0,
ANIMATING: 1
};
var ModelAnimationState_default = Object.freeze(ModelAnimationState);
// node_modules/@cesium/engine/Source/Core/Spline.js
function Spline() {
this.times = void 0;
this.points = void 0;
DeveloperError_default.throwInstantiationError();
}
Spline.getPointType = function(point) {
if (typeof point === "number") {
return Number;
}
if (point instanceof Cartesian3_default) {
return Cartesian3_default;
}
if (point instanceof Quaternion_default) {
return Quaternion_default;
}
throw new DeveloperError_default(
"point must be a Cartesian3, Quaternion, or number."
);
};
Spline.prototype.evaluate = DeveloperError_default.throwInstantiationError;
Spline.prototype.findTimeInterval = function(time, startIndex) {
const times = this.times;
const length3 = times.length;
Check_default.typeOf.number("time", time);
if (time < times[0] || time > times[length3 - 1]) {
throw new DeveloperError_default("time is out of range.");
}
startIndex = defaultValue_default(startIndex, 0);
if (time >= times[startIndex]) {
if (startIndex + 1 < length3 && time < times[startIndex + 1]) {
return startIndex;
} else if (startIndex + 2 < length3 && time < times[startIndex + 2]) {
return startIndex + 1;
}
} else if (startIndex - 1 >= 0 && time >= times[startIndex - 1]) {
return startIndex - 1;
}
let i;
if (time > times[startIndex]) {
for (i = startIndex; i < length3 - 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 === length3 - 1) {
i = length3 - 2;
}
return i;
};
Spline.prototype.wrapTime = function(time) {
Check_default.typeOf.number("time", time);
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;
};
Spline.prototype.clampTime = function(time) {
Check_default.typeOf.number("time", time);
const times = this.times;
return Math_default.clamp(time, times[0], times[times.length - 1]);
};
var Spline_default = Spline;
// node_modules/@cesium/engine/Source/Core/ConstantSpline.js
function ConstantSpline(value) {
this._value = value;
this._valueType = Spline_default.getPointType(value);
}
Object.defineProperties(ConstantSpline.prototype, {
value: {
get: function() {
return this._value;
}
}
});
ConstantSpline.prototype.findTimeInterval = function(time) {
throw new DeveloperError_default(
"findTimeInterval cannot be called on a ConstantSpline."
);
};
ConstantSpline.prototype.wrapTime = function(time) {
Check_default.typeOf.number("time", time);
return 0;
};
ConstantSpline.prototype.clampTime = function(time) {
Check_default.typeOf.number("time", time);
return 0;
};
ConstantSpline.prototype.evaluate = function(time, result) {
Check_default.typeOf.number("time", time);
const value = this._value;
const ValueType = this._valueType;
if (ValueType === Number) {
return value;
}
return ValueType.clone(value, result);
};
var ConstantSpline_default = ConstantSpline;
// node_modules/@cesium/engine/Source/Core/LinearSpline.js
function LinearSpline(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const points = options.points;
const times = options.times;
if (!defined_default(points) || !defined_default(times)) {
throw new DeveloperError_default("points and times are required.");
}
if (points.length < 2) {
throw new DeveloperError_default(
"points.length must be greater than or equal to 2."
);
}
if (times.length !== points.length) {
throw new DeveloperError_default("times.length must be equal to points.length.");
}
this._times = times;
this._points = points;
this._pointType = Spline_default.getPointType(points[0]);
this._lastTimeIndex = 0;
}
Object.defineProperties(LinearSpline.prototype, {
times: {
get: function() {
return this._times;
}
},
points: {
get: function() {
return this._points;
}
}
});
LinearSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval;
LinearSpline.prototype.wrapTime = Spline_default.prototype.wrapTime;
LinearSpline.prototype.clampTime = Spline_default.prototype.clampTime;
LinearSpline.prototype.evaluate = function(time, result) {
const points = this.points;
const times = this.times;
const i = this._lastTimeIndex = this.findTimeInterval(
time,
this._lastTimeIndex
);
const u3 = (time - times[i]) / (times[i + 1] - times[i]);
const PointType = this._pointType;
if (PointType === Number) {
return (1 - u3) * points[i] + u3 * points[i + 1];
}
if (!defined_default(result)) {
result = new Cartesian3_default();
}
return Cartesian3_default.lerp(points[i], points[i + 1], u3, result);
};
var LinearSpline_default = LinearSpline;
// node_modules/@cesium/engine/Source/Core/TridiagonalSystemSolver.js
var TridiagonalSystemSolver = {};
TridiagonalSystemSolver.solve = function(lower, diagonal, upper, right) {
if (!defined_default(lower) || !(lower instanceof Array)) {
throw new DeveloperError_default("The array lower is required.");
}
if (!defined_default(diagonal) || !(diagonal instanceof Array)) {
throw new DeveloperError_default("The array diagonal is required.");
}
if (!defined_default(upper) || !(upper instanceof Array)) {
throw new DeveloperError_default("The array upper is required.");
}
if (!defined_default(right) || !(right instanceof Array)) {
throw new DeveloperError_default("The array right is required.");
}
if (diagonal.length !== right.length) {
throw new DeveloperError_default("diagonal and right must have the same lengths.");
}
if (lower.length !== upper.length) {
throw new DeveloperError_default("lower and upper must have the same lengths.");
} else if (lower.length !== diagonal.length - 1) {
throw new DeveloperError_default(
"lower and upper must be one less than the length of diagonal."
);
}
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_default();
x[i] = new Cartesian3_default();
}
c[0] = upper[0] / diagonal[0];
d[0] = Cartesian3_default.multiplyByScalar(right[0], 1 / diagonal[0], d[0]);
let scalar;
for (i = 1; i < c.length; ++i) {
scalar = 1 / (diagonal[i] - c[i - 1] * lower[i - 1]);
c[i] = upper[i] * scalar;
d[i] = Cartesian3_default.subtract(
right[i],
Cartesian3_default.multiplyByScalar(d[i - 1], lower[i - 1], d[i]),
d[i]
);
d[i] = Cartesian3_default.multiplyByScalar(d[i], scalar, d[i]);
}
scalar = 1 / (diagonal[i] - c[i - 1] * lower[i - 1]);
d[i] = Cartesian3_default.subtract(
right[i],
Cartesian3_default.multiplyByScalar(d[i - 1], lower[i - 1], d[i]),
d[i]
);
d[i] = Cartesian3_default.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_default.subtract(
d[i],
Cartesian3_default.multiplyByScalar(x[i + 1], c[i], x[i]),
x[i]
);
}
return x;
};
var TridiagonalSystemSolver_default = TridiagonalSystemSolver;
// node_modules/@cesium/engine/Source/Core/HermiteSpline.js
var scratchLower = [];
var scratchDiagonal = [];
var scratchUpper = [];
var scratchRight = [];
function generateClamped(points, firstTangent, lastTangent) {
const l = scratchLower;
const u3 = scratchUpper;
const d = scratchDiagonal;
const r = scratchRight;
l.length = u3.length = points.length - 1;
d.length = r.length = points.length;
let i;
l[0] = d[0] = 1;
u3[0] = 0;
let right = r[0];
if (!defined_default(right)) {
right = r[0] = new Cartesian3_default();
}
Cartesian3_default.clone(firstTangent, right);
for (i = 1; i < l.length - 1; ++i) {
l[i] = u3[i] = 1;
d[i] = 4;
right = r[i];
if (!defined_default(right)) {
right = r[i] = new Cartesian3_default();
}
Cartesian3_default.subtract(points[i + 1], points[i - 1], right);
Cartesian3_default.multiplyByScalar(right, 3, right);
}
l[i] = 0;
u3[i] = 1;
d[i] = 4;
right = r[i];
if (!defined_default(right)) {
right = r[i] = new Cartesian3_default();
}
Cartesian3_default.subtract(points[i + 1], points[i - 1], right);
Cartesian3_default.multiplyByScalar(right, 3, right);
d[i + 1] = 1;
right = r[i + 1];
if (!defined_default(right)) {
right = r[i + 1] = new Cartesian3_default();
}
Cartesian3_default.clone(lastTangent, right);
return TridiagonalSystemSolver_default.solve(l, d, u3, r);
}
function generateNatural(points) {
const l = scratchLower;
const u3 = scratchUpper;
const d = scratchDiagonal;
const r = scratchRight;
l.length = u3.length = points.length - 1;
d.length = r.length = points.length;
let i;
l[0] = u3[0] = 1;
d[0] = 2;
let right = r[0];
if (!defined_default(right)) {
right = r[0] = new Cartesian3_default();
}
Cartesian3_default.subtract(points[1], points[0], right);
Cartesian3_default.multiplyByScalar(right, 3, right);
for (i = 1; i < l.length; ++i) {
l[i] = u3[i] = 1;
d[i] = 4;
right = r[i];
if (!defined_default(right)) {
right = r[i] = new Cartesian3_default();
}
Cartesian3_default.subtract(points[i + 1], points[i - 1], right);
Cartesian3_default.multiplyByScalar(right, 3, right);
}
d[i] = 2;
right = r[i];
if (!defined_default(right)) {
right = r[i] = new Cartesian3_default();
}
Cartesian3_default.subtract(points[i], points[i - 1], right);
Cartesian3_default.multiplyByScalar(right, 3, right);
return TridiagonalSystemSolver_default.solve(l, d, u3, r);
}
function HermiteSpline(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const points = options.points;
const times = options.times;
const inTangents = options.inTangents;
const outTangents = options.outTangents;
if (!defined_default(points) || !defined_default(times) || !defined_default(inTangents) || !defined_default(outTangents)) {
throw new DeveloperError_default(
"times, points, inTangents, and outTangents are required."
);
}
if (points.length < 2) {
throw new DeveloperError_default(
"points.length must be greater than or equal to 2."
);
}
if (times.length !== points.length) {
throw new DeveloperError_default("times.length must be equal to points.length.");
}
if (inTangents.length !== outTangents.length || inTangents.length !== points.length - 1) {
throw new DeveloperError_default(
"inTangents and outTangents must have a length equal to points.length - 1."
);
}
this._times = times;
this._points = points;
this._pointType = Spline_default.getPointType(points[0]);
if (this._pointType !== Spline_default.getPointType(inTangents[0]) || this._pointType !== Spline_default.getPointType(outTangents[0])) {
throw new DeveloperError_default(
"inTangents and outTangents must be of the same type as points."
);
}
this._inTangents = inTangents;
this._outTangents = outTangents;
this._lastTimeIndex = 0;
}
Object.defineProperties(HermiteSpline.prototype, {
times: {
get: function() {
return this._times;
}
},
points: {
get: function() {
return this._points;
}
},
inTangents: {
get: function() {
return this._inTangents;
}
},
outTangents: {
get: function() {
return this._outTangents;
}
}
});
HermiteSpline.createC1 = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const times = options.times;
const points = options.points;
const tangents = options.tangents;
if (!defined_default(points) || !defined_default(times) || !defined_default(tangents)) {
throw new DeveloperError_default("points, times and tangents are required.");
}
if (points.length < 2) {
throw new DeveloperError_default(
"points.length must be greater than or equal to 2."
);
}
if (times.length !== points.length || times.length !== tangents.length) {
throw new DeveloperError_default(
"times, points and tangents must have the same length."
);
}
const outTangents = tangents.slice(0, tangents.length - 1);
const inTangents = tangents.slice(1, tangents.length);
return new HermiteSpline({
times,
points,
inTangents,
outTangents
});
};
HermiteSpline.createNaturalCubic = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const times = options.times;
const points = options.points;
if (!defined_default(points) || !defined_default(times)) {
throw new DeveloperError_default("points and times are required.");
}
if (points.length < 2) {
throw new DeveloperError_default(
"points.length must be greater than or equal to 2."
);
}
if (times.length !== points.length) {
throw new DeveloperError_default("times.length must be equal to points.length.");
}
if (points.length < 3) {
return new LinearSpline_default({
points,
times
});
}
const tangents = generateNatural(points);
const outTangents = tangents.slice(0, tangents.length - 1);
const inTangents = tangents.slice(1, tangents.length);
return new HermiteSpline({
times,
points,
inTangents,
outTangents
});
};
HermiteSpline.createClampedCubic = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const times = options.times;
const points = options.points;
const firstTangent = options.firstTangent;
const lastTangent = options.lastTangent;
if (!defined_default(points) || !defined_default(times) || !defined_default(firstTangent) || !defined_default(lastTangent)) {
throw new DeveloperError_default(
"points, times, firstTangent and lastTangent are required."
);
}
if (points.length < 2) {
throw new DeveloperError_default(
"points.length must be greater than or equal to 2."
);
}
if (times.length !== points.length) {
throw new DeveloperError_default("times.length must be equal to points.length.");
}
const PointType = Spline_default.getPointType(points[0]);
if (PointType !== Spline_default.getPointType(firstTangent) || PointType !== Spline_default.getPointType(lastTangent)) {
throw new DeveloperError_default(
"firstTangent and lastTangent must be of the same type as points."
);
}
if (points.length < 3) {
return new LinearSpline_default({
points,
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,
points,
inTangents,
outTangents
});
};
HermiteSpline.hermiteCoefficientMatrix = new Matrix4_default(
2,
-3,
0,
1,
-2,
3,
0,
0,
1,
-2,
1,
0,
1,
-1,
0,
0
);
HermiteSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval;
var scratchTimeVec = new Cartesian4_default();
var scratchTemp = new Cartesian3_default();
HermiteSpline.prototype.wrapTime = Spline_default.prototype.wrapTime;
HermiteSpline.prototype.clampTime = Spline_default.prototype.clampTime;
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 u3 = (time - times[i]) / timesDelta;
const timeVec = scratchTimeVec;
timeVec.z = u3;
timeVec.y = u3 * u3;
timeVec.x = timeVec.y * u3;
timeVec.w = 1;
const coefs = Matrix4_default.multiplyByVector(
HermiteSpline.hermiteCoefficientMatrix,
timeVec,
timeVec
);
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_default(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);
};
var HermiteSpline_default = HermiteSpline;
// node_modules/@cesium/engine/Source/Core/SteppedSpline.js
function SteppedSpline(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const points = options.points;
const times = options.times;
if (!defined_default(points) || !defined_default(times)) {
throw new DeveloperError_default("points and times are required.");
}
if (points.length < 2) {
throw new DeveloperError_default(
"points.length must be greater than or equal to 2."
);
}
if (times.length !== points.length) {
throw new DeveloperError_default("times.length must be equal to points.length.");
}
this._times = times;
this._points = points;
this._pointType = Spline_default.getPointType(points[0]);
this._lastTimeIndex = 0;
}
Object.defineProperties(SteppedSpline.prototype, {
times: {
get: function() {
return this._times;
}
},
points: {
get: function() {
return this._points;
}
}
});
SteppedSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval;
SteppedSpline.prototype.wrapTime = Spline_default.prototype.wrapTime;
SteppedSpline.prototype.clampTime = Spline_default.prototype.clampTime;
SteppedSpline.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_default(result)) {
result = new PointType();
}
return PointType.clone(points[i], result);
};
var SteppedSpline_default = SteppedSpline;
// node_modules/@cesium/engine/Source/Core/QuaternionSpline.js
function createEvaluateFunction(spline) {
const points = spline.points;
const times = spline.times;
return function(time, result) {
if (!defined_default(result)) {
result = new Quaternion_default();
}
const i = spline._lastTimeIndex = spline.findTimeInterval(
time,
spline._lastTimeIndex
);
const u3 = (time - times[i]) / (times[i + 1] - times[i]);
const q0 = points[i];
const q12 = points[i + 1];
return Quaternion_default.fastSlerp(q0, q12, u3, result);
};
}
function QuaternionSpline(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const points = options.points;
const times = options.times;
if (!defined_default(points) || !defined_default(times)) {
throw new DeveloperError_default("points and times are required.");
}
if (points.length < 2) {
throw new DeveloperError_default(
"points.length must be greater than or equal to 2."
);
}
if (times.length !== points.length) {
throw new DeveloperError_default("times.length must be equal to points.length.");
}
this._times = times;
this._points = points;
this._evaluateFunction = createEvaluateFunction(this);
this._lastTimeIndex = 0;
}
Object.defineProperties(QuaternionSpline.prototype, {
times: {
get: function() {
return this._times;
}
},
points: {
get: function() {
return this._points;
}
}
});
QuaternionSpline.prototype.findTimeInterval = Spline_default.prototype.findTimeInterval;
QuaternionSpline.prototype.wrapTime = Spline_default.prototype.wrapTime;
QuaternionSpline.prototype.clampTime = Spline_default.prototype.clampTime;
QuaternionSpline.prototype.evaluate = function(time, result) {
return this._evaluateFunction(time, result);
};
var QuaternionSpline_default = QuaternionSpline;
// node_modules/@cesium/engine/Source/Scene/Model/ModelAnimationChannel.js
var AnimatedPropertyType3 = ModelComponents_default.AnimatedPropertyType;
function ModelAnimationChannel(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const channel = options.channel;
const runtimeAnimation = options.runtimeAnimation;
const runtimeNode = options.runtimeNode;
Check_default.typeOf.object("options.channel", channel);
Check_default.typeOf.object("options.runtimeAnimation", runtimeAnimation);
Check_default.typeOf.object("options.runtimeNode", runtimeNode);
this._channel = channel;
this._runtimeAnimation = runtimeAnimation;
this._runtimeNode = runtimeNode;
this._splines = [];
this._path = void 0;
initialize6(this);
}
Object.defineProperties(ModelAnimationChannel.prototype, {
channel: {
get: function() {
return this._channel;
}
},
runtimeAnimation: {
get: function() {
return this._runtimeAnimation;
}
},
runtimeNode: {
get: function() {
return this._runtimeNode;
}
},
splines: {
get: function() {
return this._splines;
}
}
});
function createCubicSpline(times, points) {
const cubicPoints = [];
const inTangents = [];
const outTangents = [];
const length3 = points.length;
for (let i = 0; i < length3; i += 3) {
inTangents.push(points[i]);
cubicPoints.push(points[i + 1]);
outTangents.push(points[i + 2]);
}
inTangents.splice(0, 1);
outTangents.length = outTangents.length - 1;
return new HermiteSpline_default({
times,
points: cubicPoints,
inTangents,
outTangents
});
}
function createSpline(times, points, interpolation, path) {
if (times.length === 1 && points.length === 1) {
return new ConstantSpline_default(points[0]);
}
switch (interpolation) {
case InterpolationType_default.STEP:
return new SteppedSpline_default({
times,
points
});
case InterpolationType_default.CUBICSPLINE:
return createCubicSpline(times, points);
case InterpolationType_default.LINEAR:
if (path === AnimatedPropertyType3.ROTATION) {
return new QuaternionSpline_default({
times,
points
});
}
return new LinearSpline_default({
times,
points
});
}
}
function createSplines(times, points, interpolation, path, count) {
const splines = [];
if (path === AnimatedPropertyType3.WEIGHTS) {
const pointsLength = points.length;
const outputLength = pointsLength / count;
let targetIndex, i;
for (targetIndex = 0; targetIndex < count; targetIndex++) {
const output = new Array(outputLength);
let pointsIndex = targetIndex;
if (interpolation === InterpolationType_default.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;
}
var scratchVariable;
function initialize6(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_default(runtimeNode.morphWeights) ? runtimeNode.morphWeights.length : 1;
const splines = createSplines(times, points, interpolation, path, count);
runtimeChannel._splines = splines;
runtimeChannel._path = path;
switch (path) {
case AnimatedPropertyType3.TRANSLATION:
case AnimatedPropertyType3.SCALE:
scratchVariable = new Cartesian3_default();
break;
case AnimatedPropertyType3.ROTATION:
scratchVariable = new Quaternion_default();
break;
case AnimatedPropertyType3.WEIGHTS:
break;
}
}
ModelAnimationChannel.prototype.animate = function(time) {
const splines = this._splines;
const path = this._path;
const model = this._runtimeAnimation.model;
const runtimeNode = this._runtimeNode;
if (path === AnimatedPropertyType3.WEIGHTS) {
const morphWeights = runtimeNode.morphWeights;
const length3 = morphWeights.length;
for (let i = 0; i < length3; i++) {
const spline = splines[i];
const localAnimationTime = model.clampAnimations ? spline.clampTime(time) : spline.wrapTime(time);
morphWeights[i] = spline.evaluate(localAnimationTime);
}
} else if (runtimeNode.userAnimated) {
return;
} else {
const spline = splines[0];
const localAnimationTime = model.clampAnimations ? spline.clampTime(time) : spline.wrapTime(time);
runtimeNode[path] = spline.evaluate(localAnimationTime, scratchVariable);
}
};
var ModelAnimationChannel_default = ModelAnimationChannel;
// node_modules/@cesium/engine/Source/Scene/Model/ModelAnimation.js
function ModelAnimation(model, animation, options) {
this._animation = animation;
this._name = animation.name;
this._runtimeChannels = void 0;
this._startTime = JulianDate_default.clone(options.startTime);
this._delay = defaultValue_default(options.delay, 0);
this._stopTime = JulianDate_default.clone(options.stopTime);
this.removeOnStop = defaultValue_default(options.removeOnStop, false);
this._multiplier = defaultValue_default(options.multiplier, 1);
this._reverse = defaultValue_default(options.reverse, false);
this._loop = defaultValue_default(options.loop, ModelAnimationLoop_default.NONE);
this._animationTime = options.animationTime;
this._prevAnimationDelta = void 0;
this.start = new Event_default();
this.update = new Event_default();
this.stop = new Event_default();
this._state = ModelAnimationState_default.STOPPED;
this._computedStartTime = void 0;
this._duration = void 0;
const that = this;
this._raiseStartEvent = function() {
that.start.raiseEvent(model, that);
};
this._updateEventTime = 0;
this._raiseUpdateEvent = function() {
that.update.raiseEvent(model, that, that._updateEventTime);
};
this._raiseStopEvent = function() {
that.stop.raiseEvent(model, that);
};
this._model = model;
this._localStartTime = void 0;
this._localStopTime = void 0;
initialize7(this);
}
Object.defineProperties(ModelAnimation.prototype, {
animation: {
get: function() {
return this._animation;
}
},
name: {
get: function() {
return this._name;
}
},
runtimeChannels: {
get: function() {
return this._runtimeChannels;
}
},
model: {
get: function() {
return this._model;
}
},
localStartTime: {
get: function() {
return this._localStartTime;
}
},
localStopTime: {
get: function() {
return this._localStopTime;
}
},
startTime: {
get: function() {
return this._startTime;
}
},
delay: {
get: function() {
return this._delay;
}
},
stopTime: {
get: function() {
return this._stopTime;
}
},
multiplier: {
get: function() {
return this._multiplier;
}
},
reverse: {
get: function() {
return this._reverse;
}
},
loop: {
get: function() {
return this._loop;
}
},
animationTime: {
get: function() {
return this._animationTime;
}
}
});
function initialize7(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 length3 = channels.length;
const runtimeChannels = [];
for (let i = 0; i < length3; i++) {
const channel = channels[i];
const target = channel.target;
if (!defined_default(target)) {
continue;
}
const nodeIndex = target.node.index;
const runtimeNode = sceneGraph._runtimeNodes[nodeIndex];
const runtimeChannel = new ModelAnimationChannel_default({
channel,
runtimeAnimation,
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;
}
ModelAnimation.prototype.animate = function(time) {
const runtimeChannels = this._runtimeChannels;
const length3 = runtimeChannels.length;
for (let i = 0; i < length3; i++) {
runtimeChannels[i].animate(time);
}
};
var ModelAnimation_default = ModelAnimation;
// node_modules/@cesium/engine/Source/Scene/Model/ModelAnimationCollection.js
function ModelAnimationCollection(model) {
this.animationAdded = new Event_default();
this.animationRemoved = new Event_default();
this.animateWhilePaused = false;
this._model = model;
this._runtimeAnimations = [];
this._previousTime = void 0;
}
Object.defineProperties(ModelAnimationCollection.prototype, {
length: {
get: function() {
return this._runtimeAnimations.length;
}
},
model: {
get: function() {
return this._model;
}
}
});
function addAnimation(collection, animation, options) {
const model = collection._model;
const runtimeAnimation = new ModelAnimation_default(model, animation, options);
collection._runtimeAnimations.push(runtimeAnimation);
collection.animationAdded.raiseEvent(model, runtimeAnimation);
return runtimeAnimation;
}
ModelAnimationCollection.prototype.add = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const model = this._model;
if (!model.ready) {
throw new DeveloperError_default(
"Animations are not loaded. Wait for Model.ready to be true."
);
}
const animations = model.sceneGraph.components.animations;
if (!defined_default(options.name) && !defined_default(options.index)) {
throw new DeveloperError_default(
"Either options.name or options.index must be defined."
);
}
if (defined_default(options.multiplier) && options.multiplier <= 0) {
throw new DeveloperError_default("options.multiplier must be greater than zero.");
}
if (defined_default(options.index) && (options.index >= animations.length || options.index < 0)) {
throw new DeveloperError_default("options.index must be a valid animation index.");
}
let index = options.index;
if (defined_default(index)) {
return addAnimation(this, animations[index], options);
}
const length3 = animations.length;
for (let i = 0; i < length3; ++i) {
if (animations[i].name === options.name) {
index = i;
break;
}
}
if (!defined_default(index)) {
throw new DeveloperError_default("options.name must be a valid animation name.");
}
return addAnimation(this, animations[index], options);
};
ModelAnimationCollection.prototype.addAll = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const model = this._model;
if (!model.ready) {
throw new DeveloperError_default(
"Animations are not loaded. Wait for Model.ready to be true."
);
}
if (defined_default(options.multiplier) && options.multiplier <= 0) {
throw new DeveloperError_default("options.multiplier must be greater than zero.");
}
const animations = model.sceneGraph.components.animations;
const addedAnimations = [];
const length3 = animations.length;
for (let i = 0; i < length3; ++i) {
const animation = addAnimation(this, animations[i], options);
addedAnimations.push(animation);
}
return addedAnimations;
};
ModelAnimationCollection.prototype.remove = function(runtimeAnimation) {
if (!defined_default(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;
};
ModelAnimationCollection.prototype.removeAll = function() {
const model = this._model;
const animations = this._runtimeAnimations;
const length3 = animations.length;
this._runtimeAnimations.length = 0;
for (let i = 0; i < length3; ++i) {
this.animationRemoved.raiseEvent(model, animations[i]);
}
};
ModelAnimationCollection.prototype.contains = function(runtimeAnimation) {
if (defined_default(runtimeAnimation)) {
return this._runtimeAnimations.indexOf(runtimeAnimation) !== -1;
}
return false;
};
ModelAnimationCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
if (index >= this._runtimeAnimations.length || index < 0) {
throw new DeveloperError_default(
"index must be valid within the range of the collection"
);
}
return this._runtimeAnimations[index];
};
var animationsToRemove = [];
function createAnimationRemovedFunction(modelAnimationCollection, model, animation) {
return function() {
modelAnimationCollection.animationRemoved.raiseEvent(model, animation);
};
}
ModelAnimationCollection.prototype.update = function(frameState) {
const runtimeAnimations = this._runtimeAnimations;
let length3 = runtimeAnimations.length;
if (length3 === 0) {
this._previousTime = void 0;
return false;
}
if (!this.animateWhilePaused && JulianDate_default.equals(frameState.time, this._previousTime)) {
return false;
}
this._previousTime = JulianDate_default.clone(frameState.time, this._previousTime);
let animationOccurred = false;
const sceneTime = frameState.time;
const model = this._model;
for (let i = 0; i < length3; ++i) {
const runtimeAnimation = runtimeAnimations[i];
if (!defined_default(runtimeAnimation._computedStartTime)) {
runtimeAnimation._computedStartTime = JulianDate_default.addSeconds(
defaultValue_default(runtimeAnimation.startTime, sceneTime),
runtimeAnimation.delay,
new JulianDate_default()
);
}
if (!defined_default(runtimeAnimation._duration)) {
runtimeAnimation._duration = runtimeAnimation.localStopTime * (1 / runtimeAnimation.multiplier);
}
const startTime = runtimeAnimation._computedStartTime;
const duration = runtimeAnimation._duration;
const stopTime = runtimeAnimation.stopTime;
const pastStartTime = JulianDate_default.lessThanOrEquals(startTime, sceneTime);
const reachedStopTime = defined_default(stopTime) && JulianDate_default.greaterThan(sceneTime, stopTime);
let delta = 0;
if (duration !== 0) {
const seconds = JulianDate_default.secondsDifference(
reachedStopTime ? stopTime : sceneTime,
startTime
);
delta = defined_default(runtimeAnimation._animationTime) ? runtimeAnimation._animationTime(duration, seconds) : seconds / duration;
}
const repeat = runtimeAnimation.loop === ModelAnimationLoop_default.REPEAT || runtimeAnimation.loop === ModelAnimationLoop_default.MIRRORED_REPEAT;
const play = (pastStartTime || repeat && !defined_default(runtimeAnimation.startTime)) && (delta <= 1 || repeat) && !reachedStopTime;
if (delta === runtimeAnimation._prevAnimationDelta) {
const animationStopped = runtimeAnimation._state === ModelAnimationState_default.STOPPED;
if (play !== animationStopped) {
continue;
}
}
runtimeAnimation._prevAnimationDelta = delta;
if (play || runtimeAnimation._state === ModelAnimationState_default.ANIMATING) {
if (play && runtimeAnimation._state === ModelAnimationState_default.STOPPED) {
runtimeAnimation._state = ModelAnimationState_default.ANIMATING;
if (runtimeAnimation.start.numberOfListeners > 0) {
frameState.afterRender.push(runtimeAnimation._raiseStartEvent);
}
}
if (runtimeAnimation.loop === ModelAnimationLoop_default.REPEAT) {
delta = delta - Math.floor(delta);
} else if (runtimeAnimation.loop === ModelAnimationLoop_default.MIRRORED_REPEAT) {
const floor = Math.floor(delta);
const fract2 = delta - floor;
delta = floor % 2 === 1 ? 1 - fract2 : fract2;
}
if (runtimeAnimation.reverse) {
delta = 1 - delta;
}
let localAnimationTime = delta * duration * runtimeAnimation.multiplier;
localAnimationTime = Math_default.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) {
runtimeAnimation._state = ModelAnimationState_default.STOPPED;
if (runtimeAnimation.stop.numberOfListeners > 0) {
frameState.afterRender.push(runtimeAnimation._raiseStopEvent);
}
if (runtimeAnimation.removeOnStop) {
animationsToRemove.push(runtimeAnimation);
}
}
}
}
length3 = animationsToRemove.length;
for (let j = 0; j < length3; ++j) {
const animationToRemove = animationsToRemove[j];
runtimeAnimations.splice(runtimeAnimations.indexOf(animationToRemove), 1);
frameState.afterRender.push(
createAnimationRemovedFunction(this, model, animationToRemove)
);
}
animationsToRemove.length = 0;
return animationOccurred;
};
var ModelAnimationCollection_default = ModelAnimationCollection;
// node_modules/@cesium/engine/Source/Scene/Model/ModelFeature.js
function ModelFeature(options) {
this._model = options.model;
this._featureTable = options.featureTable;
this._featureId = options.featureId;
this._color = void 0;
}
Object.defineProperties(ModelFeature.prototype, {
show: {
get: function() {
return this._featureTable.getShow(this._featureId);
},
set: function(value) {
this._featureTable.setShow(this._featureId, value);
}
},
color: {
get: function() {
if (!defined_default(this._color)) {
this._color = new Color_default();
}
return this._featureTable.getColor(this._featureId, this._color);
},
set: function(value) {
this._featureTable.setColor(this._featureId, value);
}
},
primitive: {
get: function() {
return this._model;
}
},
featureTable: {
get: function() {
return this._featureTable;
}
},
featureId: {
get: function() {
return this._featureId;
}
}
});
ModelFeature.prototype.hasProperty = function(name) {
return this._featureTable.hasProperty(this._featureId, name);
};
ModelFeature.prototype.getProperty = function(name) {
return this._featureTable.getProperty(this._featureId, name);
};
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);
};
ModelFeature.prototype.getPropertyIds = function(results) {
return this._featureTable.getPropertyIds(results);
};
ModelFeature.prototype.setProperty = function(name, value) {
return this._featureTable.setProperty(this._featureId, name, value);
};
var ModelFeature_default = ModelFeature;
// node_modules/@cesium/engine/Source/Scene/Model/StyleCommandsNeeded.js
var StyleCommandsNeeded2 = {
ALL_OPAQUE: 0,
ALL_TRANSLUCENT: 1,
OPAQUE_AND_TRANSLUCENT: 2
};
StyleCommandsNeeded2.getStyleCommandsNeeded = function(featuresLength, translucentFeaturesLength) {
if (translucentFeaturesLength === 0) {
return StyleCommandsNeeded2.ALL_OPAQUE;
} else if (translucentFeaturesLength === featuresLength) {
return StyleCommandsNeeded2.ALL_TRANSLUCENT;
}
return StyleCommandsNeeded2.OPAQUE_AND_TRANSLUCENT;
};
var StyleCommandsNeeded_default = Object.freeze(StyleCommandsNeeded2);
// node_modules/@cesium/engine/Source/Scene/Model/ModelType.js
var ModelType = {
GLTF: "GLTF",
TILE_GLTF: "TILE_GLTF",
TILE_B3DM: "B3DM",
TILE_I3DM: "I3DM",
TILE_PNTS: "PNTS",
TILE_GEOJSON: "TILE_GEOJSON"
};
ModelType.is3DTiles = function(modelType) {
Check_default.typeOf.string("modelType", modelType);
switch (modelType) {
case ModelType.TILE_GLTF:
case ModelType.TILE_B3DM:
case ModelType.TILE_I3DM:
case ModelType.TILE_PNTS:
case ModelType.TILE_GEOJSON:
return true;
case ModelType.GLTF:
return false;
default:
throw new DeveloperError_default("modelType is not a valid value.");
}
};
var ModelType_default = Object.freeze(ModelType);
// node_modules/@cesium/engine/Source/Scene/Model/ModelFeatureTable.js
function ModelFeatureTable(options) {
const model = options.model;
const propertyTable = options.propertyTable;
Check_default.typeOf.object("propertyTable", propertyTable);
Check_default.typeOf.object("model", model);
this._propertyTable = propertyTable;
this._model = model;
this._features = void 0;
this._featuresLength = 0;
this._batchTexture = void 0;
this._styleCommandsNeededDirty = false;
this._styleCommandsNeeded = StyleCommandsNeeded_default.ALL_OPAQUE;
initialize8(this);
}
Object.defineProperties(ModelFeatureTable.prototype, {
batchTexture: {
get: function() {
return this._batchTexture;
}
},
featuresLength: {
get: function() {
return this._featuresLength;
}
},
batchTextureByteLength: {
get: function() {
if (defined_default(this._batchTexture)) {
return this._batchTexture.byteLength;
}
return 0;
}
},
styleCommandsNeededDirty: {
get: function() {
return this._styleCommandsNeededDirty;
}
}
});
function initialize8(modelFeatureTable) {
const model = modelFeatureTable._model;
const is3DTiles = ModelType_default.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_default(content, i);
}
} else {
for (i = 0; i < featuresLength; i++) {
features[i] = new ModelFeature_default({
model,
featureId: i,
featureTable: modelFeatureTable
});
}
}
modelFeatureTable._features = features;
modelFeatureTable._featuresLength = featuresLength;
modelFeatureTable._batchTexture = new BatchTexture_default({
featuresLength,
owner: modelFeatureTable,
statistics: is3DTiles ? model.content.tileset.statistics : void 0
});
}
ModelFeatureTable.prototype.update = function(frameState) {
this._styleCommandsNeededDirty = false;
this._batchTexture.update(void 0, frameState);
const currentStyleCommandsNeeded = StyleCommandsNeeded_default.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);
};
ModelFeatureTable.prototype.isClass = function(featureId, className) {
return this._propertyTable.isClass(featureId, className);
};
ModelFeatureTable.prototype.isExactClass = function(featureId, className) {
return this._propertyTable.isExactClass(featureId, className);
};
ModelFeatureTable.prototype.getExactClassName = function(featureId) {
return this._propertyTable.getExactClassName(featureId);
};
var scratchColor6 = new Color_default();
ModelFeatureTable.prototype.applyStyle = function(style) {
if (!defined_default(style)) {
this.setAllColor(BatchTexture_default.DEFAULT_COLOR_VALUE);
this.setAllShow(BatchTexture_default.DEFAULT_SHOW_VALUE);
return;
}
for (let i = 0; i < this._featuresLength; i++) {
const feature = this.getFeature(i);
const color = defined_default(style.color) ? defaultValue_default(
style.color.evaluateColor(feature, scratchColor6),
BatchTexture_default.DEFAULT_COLOR_VALUE
) : BatchTexture_default.DEFAULT_COLOR_VALUE;
const show = defined_default(style.show) ? defaultValue_default(
style.show.evaluate(feature),
BatchTexture_default.DEFAULT_SHOW_VALUE
) : BatchTexture_default.DEFAULT_SHOW_VALUE;
this.setColor(i, color);
this.setShow(i, show);
}
};
ModelFeatureTable.prototype.isDestroyed = function() {
return false;
};
ModelFeatureTable.prototype.destroy = function(frameState) {
this._batchTexture = this._batchTexture && this._batchTexture.destroy();
destroyObject_default(this);
};
var ModelFeatureTable_default = ModelFeatureTable;
// node_modules/@cesium/engine/Source/Shaders/Model/ModelFS.js
var ModelFS_default = "#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\nczm_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\nvec4 handleAlpha(vec3 color, float alpha)\n{\n #ifdef ALPHA_MODE_MASK\n if (alpha < u_alphaCutoff) {\n discard;\n }\n #endif\n\n return vec4(color, alpha);\n}\n\nSelectedFeature selectedFeature;\n\nvoid main()\n{\n #ifdef HAS_MODEL_SPLITTER\n modelSplitterStage();\n #endif\n\n czm_modelMaterial material = defaultModelMaterial();\n\n ProcessedAttributes attributes;\n geometryStage(attributes);\n\n FeatureIds featureIds;\n featureIdStage(featureIds, attributes);\n\n Metadata metadata;\n MetadataClass metadataClass;\n MetadataStatistics metadataStatistics;\n metadataStage(metadata, metadataClass, metadataStatistics, attributes);\n\n #ifdef HAS_SELECTED_FEATURE_ID\n selectedFeatureIdStage(selectedFeature, featureIds);\n #endif\n\n #ifndef CUSTOM_SHADER_REPLACE_MATERIAL\n materialStage(material, attributes, selectedFeature);\n #endif\n\n #ifdef HAS_CUSTOM_FRAGMENT_SHADER\n customShaderStage(material, attributes, featureIds, metadata, metadataClass, metadataStatistics);\n #endif\n\n lightingStage(material, attributes);\n\n #ifdef HAS_SELECTED_FEATURE_ID\n cpuStylingStage(material, selectedFeature);\n #endif\n\n #ifdef HAS_MODEL_COLOR\n modelColorStage(material);\n #endif\n\n #ifdef HAS_PRIMITIVE_OUTLINE\n primitiveOutlineStage(material);\n #endif\n\n vec4 color = handleAlpha(material.diffuse, material.alpha);\n\n #ifdef HAS_CLIPPING_PLANES\n modelClippingPlanesStage(color);\n #endif\n\n #if defined(HAS_SILHOUETTE) && defined(HAS_NORMALS)\n silhouetteStage(color);\n #endif\n\n out_FragColor = color;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/ModelVS.js
var ModelVS_default = "precision highp float;\n\nczm_modelVertexOutput defaultVertexOutput(vec3 positionMC) {\n czm_modelVertexOutput vsOutput;\n vsOutput.positionMC = positionMC;\n vsOutput.pointSize = 1.0;\n return vsOutput;\n}\n\nvoid main() \n{\n // Initialize the attributes struct with all\n // attributes except quantized ones.\n ProcessedAttributes attributes;\n initializeAttributes(attributes);\n\n // Dequantize the quantized ones and add them to the\n // attributes struct.\n #ifdef USE_DEQUANTIZATION\n dequantizationStage(attributes);\n #endif\n\n #ifdef HAS_MORPH_TARGETS\n morphTargetsStage(attributes);\n #endif\n\n #ifdef HAS_SKINNING\n skinningStage(attributes);\n #endif\n\n #ifdef HAS_PRIMITIVE_OUTLINE\n primitiveOutlineStage();\n #endif\n\n // Compute the bitangent according to the formula in the glTF spec.\n // Normal and tangents can be affected by morphing and skinning, so\n // the bitangent should not be computed until their values are finalized.\n #ifdef HAS_BITANGENTS\n attributes.bitangentMC = normalize(cross(attributes.normalMC, attributes.tangentMC) * attributes.tangentSignMC);\n #endif\n\n FeatureIds featureIds;\n featureIdStage(featureIds, attributes);\n\n #ifdef HAS_SELECTED_FEATURE_ID\n SelectedFeature feature;\n selectedFeatureIdStage(feature, featureIds);\n // Handle any show properties that come from the style.\n cpuStylingStage(attributes.positionMC, feature);\n #endif\n\n #if defined(USE_2D_POSITIONS) || defined(USE_2D_INSTANCING)\n // The scene mode 2D pipeline stage and instancing stage add a different\n // model view matrix to accurately project the model to 2D. However, the\n // output positions and normals should be transformed by the 3D matrices\n // to keep the data the same for the fragment shader.\n mat4 modelView = czm_modelView3D;\n mat3 normal = czm_normal3D;\n #else\n // These are used for individual model projection because they will\n // automatically change based on the scene mode.\n mat4 modelView = czm_modelView;\n mat3 normal = czm_normal;\n #endif\n\n // Update the position for this instance in place\n #ifdef HAS_INSTANCING\n\n // The legacy instance stage is used when rendering i3dm models that \n // encode instances transforms in world space, as opposed to glTF models\n // that use EXT_mesh_gpu_instancing, where instance transforms are encoded\n // in object space.\n #ifdef USE_LEGACY_INSTANCING\n mat4 instanceModelView;\n mat3 instanceModelViewInverseTranspose;\n \n legacyInstancingStage(attributes, instanceModelView, instanceModelViewInverseTranspose);\n\n modelView = instanceModelView;\n normal = instanceModelViewInverseTranspose;\n #else\n instancingStage(attributes);\n #endif\n\n #ifdef USE_PICKING\n v_pickColor = a_pickColor;\n #endif\n\n #endif\n\n Metadata metadata;\n MetadataClass metadataClass;\n MetadataStatistics metadataStatistics;\n metadataStage(metadata, metadataClass, metadataStatistics, attributes);\n\n #ifdef HAS_CUSTOM_VERTEX_SHADER\n czm_modelVertexOutput vsOutput = defaultVertexOutput(attributes.positionMC);\n customShaderStage(vsOutput, attributes, featureIds, metadata, metadataClass, metadataStatistics);\n #endif\n\n // Compute the final position in each coordinate system needed.\n // This returns the value that will be assigned to gl_Position.\n vec4 positionClip = geometryStage(attributes, modelView, normal); \n\n #ifdef HAS_SILHOUETTE\n silhouetteStage(attributes, positionClip);\n #endif\n\n #ifdef HAS_POINT_CLOUD_SHOW_STYLE\n float show = pointCloudShowStylingStage(attributes, metadata);\n #else\n float show = 1.0;\n #endif\n\n #ifdef HAS_POINT_CLOUD_BACK_FACE_CULLING\n show *= pointCloudBackFaceCullingStage();\n #endif\n\n #ifdef HAS_POINT_CLOUD_COLOR_STYLE\n v_pointCloudColor = pointCloudColorStylingStage(attributes, metadata);\n #endif\n\n #ifdef PRIMITIVE_TYPE_POINTS\n #ifdef HAS_CUSTOM_VERTEX_SHADER\n gl_PointSize = vsOutput.pointSize;\n #elif defined(HAS_POINT_CLOUD_POINT_SIZE_STYLE) || defined(HAS_POINT_CLOUD_ATTENUATION)\n gl_PointSize = pointCloudPointSizeStylingStage(attributes, metadata);\n #else\n gl_PointSize = 1.0;\n #endif\n\n gl_PointSize *= show;\n #endif\n\n gl_Position = show * positionClip;\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/ClassificationModelDrawCommand.js
function ClassificationModelDrawCommand(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const command = options.command;
const renderResources = options.primitiveRenderResources;
Check_default.typeOf.object("options.command", command);
Check_default.typeOf.object("options.primitiveRenderResources", renderResources);
const model = renderResources.model;
this._command = command;
this._model = model;
this._runtimePrimitive = renderResources.runtimePrimitive;
this._modelMatrix = command.modelMatrix;
this._boundingVolume = command.boundingVolume;
this._cullFace = command.renderState.cull.face;
const type = model.classificationType;
this._classificationType = type;
this._classifiesTerrain = type !== ClassificationType_default.CESIUM_3D_TILE;
this._classifies3DTiles = type !== ClassificationType_default.TERRAIN;
this._useDebugWireframe = model._enableDebugWireframe && model.debugWireframe;
this._pickId = renderResources.pickId;
this._commandListTerrain = [];
this._commandList3DTiles = [];
this._commandListIgnoreShow = [];
this._commandListDebugWireframe = [];
this._commandListTerrainPicking = [];
this._commandList3DTilesPicking = [];
initialize9(this);
}
function getStencilDepthRenderState3(stencilFunction) {
return {
colorMask: {
red: false,
green: false,
blue: false,
alpha: false
},
stencilTest: {
enabled: true,
frontFunction: stencilFunction,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.DECREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
backFunction: stencilFunction,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.INCREMENT_WRAP,
zPass: StencilOperation_default.KEEP
},
reference: StencilConstants_default.CESIUM_3D_TILE_MASK,
mask: StencilConstants_default.CESIUM_3D_TILE_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: true,
func: DepthFunction_default.LESS_OR_EQUAL
},
depthMask: false
};
}
var colorRenderState2 = {
stencilTest: {
enabled: true,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false,
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND
};
var pickRenderState3 = {
stencilTest: {
enabled: true,
frontFunction: StencilFunction_default.NOT_EQUAL,
frontOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
backFunction: StencilFunction_default.NOT_EQUAL,
backOperation: {
fail: StencilOperation_default.ZERO,
zFail: StencilOperation_default.ZERO,
zPass: StencilOperation_default.ZERO
},
reference: 0,
mask: StencilConstants_default.CLASSIFICATION_MASK
},
stencilMask: StencilConstants_default.CLASSIFICATION_MASK,
depthTest: {
enabled: false
},
depthMask: false
};
var scratchDerivedCommands = [];
function initialize9(drawCommand) {
const command = drawCommand._command;
const derivedCommands = scratchDerivedCommands;
if (drawCommand._useDebugWireframe) {
command.pass = Pass_default.OPAQUE;
derivedCommands.length = 0;
derivedCommands.push(command);
drawCommand._commandListDebugWireframe = createBatchCommands(
drawCommand,
derivedCommands,
drawCommand._commandListDebugWireframe
);
const commandList = drawCommand._commandListDebugWireframe;
const length3 = commandList.length;
for (let i = 0; i < length3; i++) {
const command2 = commandList[i];
command2.count *= 2;
command2.offset *= 2;
}
return;
}
const model = drawCommand.model;
const allowPicking = model.allowPicking;
if (drawCommand._classifiesTerrain) {
const pass = Pass_default.TERRAIN_CLASSIFICATION;
const stencilDepthCommand = deriveStencilDepthCommand(command, pass);
const colorCommand = deriveColorCommand(command, pass);
derivedCommands.length = 0;
derivedCommands.push(stencilDepthCommand, colorCommand);
drawCommand._commandListTerrain = createBatchCommands(
drawCommand,
derivedCommands,
drawCommand._commandListTerrain
);
if (allowPicking) {
drawCommand._commandListTerrainPicking = createPickCommands3(
drawCommand,
derivedCommands,
drawCommand._commandListTerrainPicking
);
}
}
if (drawCommand._classifies3DTiles) {
const pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
const stencilDepthCommand = deriveStencilDepthCommand(command, pass);
const colorCommand = deriveColorCommand(command, pass);
derivedCommands.length = 0;
derivedCommands.push(stencilDepthCommand, colorCommand);
drawCommand._commandList3DTiles = createBatchCommands(
drawCommand,
derivedCommands,
drawCommand._commandList3DTiles
);
if (allowPicking) {
drawCommand._commandList3DTilesPicking = createPickCommands3(
drawCommand,
derivedCommands,
drawCommand._commandList3DTilesPicking
);
}
}
}
function createBatchCommands(drawCommand, derivedCommands, result) {
const runtimePrimitive = drawCommand._runtimePrimitive;
const batchLengths = runtimePrimitive.batchLengths;
const batchOffsets = runtimePrimitive.batchOffsets;
const numBatches = batchLengths.length;
const numDerivedCommands = derivedCommands.length;
for (let i = 0; i < numBatches; i++) {
const batchLength = batchLengths[i];
const batchOffset = batchOffsets[i];
for (let j = 0; j < numDerivedCommands; j++) {
const derivedCommand = derivedCommands[j];
const batchCommand = DrawCommand_default.shallowClone(derivedCommand);
batchCommand.count = batchLength;
batchCommand.offset = batchOffset;
result.push(batchCommand);
}
}
return result;
}
function deriveStencilDepthCommand(command, pass) {
const stencilDepthCommand = DrawCommand_default.shallowClone(command);
stencilDepthCommand.cull = false;
stencilDepthCommand.pass = pass;
const stencilFunction = pass === Pass_default.TERRAIN_CLASSIFICATION ? StencilFunction_default.ALWAYS : StencilFunction_default.EQUAL;
const renderState = getStencilDepthRenderState3(stencilFunction);
stencilDepthCommand.renderState = RenderState_default.fromCache(renderState);
return stencilDepthCommand;
}
function deriveColorCommand(command, pass) {
const colorCommand = DrawCommand_default.shallowClone(command);
colorCommand.cull = false;
colorCommand.pass = pass;
colorCommand.renderState = RenderState_default.fromCache(colorRenderState2);
return colorCommand;
}
var scratchPickCommands = [];
function createPickCommands3(drawCommand, derivedCommands, commandList) {
const renderState = RenderState_default.fromCache(pickRenderState3);
const stencilDepthCommand = derivedCommands[0];
const colorCommand = derivedCommands[1];
const pickStencilDepthCommand = DrawCommand_default.shallowClone(stencilDepthCommand);
pickStencilDepthCommand.cull = true;
pickStencilDepthCommand.pickOnly = true;
const pickColorCommand = DrawCommand_default.shallowClone(colorCommand);
pickColorCommand.cull = true;
pickColorCommand.pickOnly = true;
pickColorCommand.renderState = renderState;
pickColorCommand.pickId = drawCommand._pickId;
const pickCommands = scratchPickCommands;
pickCommands.length = 0;
pickCommands.push(pickStencilDepthCommand, pickColorCommand);
return createBatchCommands(drawCommand, pickCommands, commandList);
}
Object.defineProperties(ClassificationModelDrawCommand.prototype, {
command: {
get: function() {
return this._command;
}
},
runtimePrimitive: {
get: function() {
return this._runtimePrimitive;
}
},
batchLengths: {
get: function() {
return this._runtimePrimitive.batchLengths;
}
},
batchOffsets: {
get: function() {
return this._runtimePrimitive.batchOffsets;
}
},
model: {
get: function() {
return this._model;
}
},
classificationType: {
get: function() {
return this._classificationType;
}
},
modelMatrix: {
get: function() {
return this._modelMatrix;
},
set: function(value) {
this._modelMatrix = Matrix4_default.clone(value, this._modelMatrix);
const boundingSphere = this._runtimePrimitive.boundingSphere;
this._boundingVolume = BoundingSphere_default.transform(
boundingSphere,
this._modelMatrix,
this._boundingVolume
);
}
},
boundingVolume: {
get: function() {
return this._boundingVolume;
}
},
cullFace: {
get: function() {
return this._cullFace;
},
set: function(value) {
this._cullFace = value;
}
}
});
ClassificationModelDrawCommand.prototype.pushCommands = function(frameState, result) {
const passes = frameState.passes;
if (passes.render) {
if (this._useDebugWireframe) {
result.push.apply(result, this._commandListDebugWireframe);
return;
}
if (this._classifiesTerrain) {
result.push.apply(result, this._commandListTerrain);
}
if (this._classifies3DTiles) {
result.push.apply(result, this._commandList3DTiles);
}
const useIgnoreShowCommands = frameState.invertClassification && this._classifies3DTiles;
if (useIgnoreShowCommands) {
if (this._commandListIgnoreShow.length === 0) {
const pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW;
const command = deriveStencilDepthCommand(this._command, pass);
const derivedCommands = scratchDerivedCommands;
derivedCommands.length = 0;
derivedCommands.push(command);
this._commandListIgnoreShow = createBatchCommands(
this,
derivedCommands,
this._commandListIgnoreShow
);
}
result.push.apply(result, this._commandListIgnoreShow);
}
}
if (passes.pick) {
if (this._classifiesTerrain) {
result.push.apply(result, this._commandListTerrainPicking);
}
if (this._classifies3DTiles) {
result.push.apply(result, this._commandList3DTilesPicking);
}
}
return result;
};
var ClassificationModelDrawCommand_default = ClassificationModelDrawCommand;
// node_modules/@cesium/engine/Source/Scene/Model/ModelDrawCommand.js
function ModelDrawCommand(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const command = options.command;
const renderResources = options.primitiveRenderResources;
Check_default.typeOf.object("options.command", command);
Check_default.typeOf.object("options.primitiveRenderResources", renderResources);
const model = renderResources.model;
this._model = model;
const runtimePrimitive = renderResources.runtimePrimitive;
this._runtimePrimitive = runtimePrimitive;
const isTranslucent = command.pass === Pass_default.TRANSLUCENT;
const isDoubleSided = runtimePrimitive.primitive.material.doubleSided;
const usesBackFaceCulling = !isDoubleSided && !isTranslucent;
const hasSilhouette = renderResources.hasSilhouette;
const needsTranslucentCommand = !isTranslucent && !hasSilhouette;
const needsSkipLevelOfDetailCommands = renderResources.hasSkipLevelOfDetail && !isTranslucent;
const needsSilhouetteCommands = hasSilhouette;
this._command = command;
this._modelMatrix = Matrix4_default.clone(command.modelMatrix);
this._boundingVolume = BoundingSphere_default.clone(command.boundingVolume);
this._modelMatrix2D = new Matrix4_default();
this._boundingVolume2D = new BoundingSphere_default();
this._modelMatrix2DDirty = false;
this._backFaceCulling = command.renderState.cull.enabled;
this._cullFace = command.renderState.cull.face;
this._shadows = model.shadows;
this._debugShowBoundingVolume = command.debugShowBoundingVolume;
this._usesBackFaceCulling = usesBackFaceCulling;
this._needsTranslucentCommand = needsTranslucentCommand;
this._needsSkipLevelOfDetailCommands = needsSkipLevelOfDetailCommands;
this._needsSilhouetteCommands = needsSilhouetteCommands;
this._originalCommand = void 0;
this._translucentCommand = void 0;
this._skipLodBackfaceCommand = void 0;
this._skipLodStencilCommand = void 0;
this._silhouetteModelCommand = void 0;
this._silhouetteColorCommand = void 0;
this._derivedCommands = [];
this._has2DCommands = false;
initialize10(this);
}
function ModelDerivedCommand(options) {
this.command = options.command;
this.updateShadows = options.updateShadows;
this.updateBackFaceCulling = options.updateBackFaceCulling;
this.updateCullFace = options.updateCullFace;
this.updateDebugShowBoundingVolume = options.updateDebugShowBoundingVolume;
this.is2D = defaultValue_default(options.is2D, false);
this.derivedCommand2D = void 0;
}
ModelDerivedCommand.clone = function(derivedCommand) {
return new ModelDerivedCommand({
command: derivedCommand.command,
updateShadows: derivedCommand.updateShadows,
updateBackFaceCulling: derivedCommand.updateBackFaceCulling,
updateCullFace: derivedCommand.updateCullFace,
updateDebugShowBoundingVolume: derivedCommand.updateDebugShowBoundingVolume,
is2D: derivedCommand.is2D,
derivedCommand2D: derivedCommand.derivedCommand2D
});
};
function initialize10(drawCommand) {
const command = drawCommand._command;
command.modelMatrix = drawCommand._modelMatrix;
command.boundingVolume = drawCommand._boundingVolume;
const model = drawCommand._model;
const usesBackFaceCulling = drawCommand._usesBackFaceCulling;
const derivedCommands = drawCommand._derivedCommands;
drawCommand._originalCommand = new ModelDerivedCommand({
command,
updateShadows: true,
updateBackFaceCulling: usesBackFaceCulling,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: true,
is2D: false
});
derivedCommands.push(drawCommand._originalCommand);
if (drawCommand._needsTranslucentCommand) {
drawCommand._translucentCommand = new ModelDerivedCommand({
command: deriveTranslucentCommand2(command),
updateShadows: true,
updateBackFaceCulling: false,
updateCullFace: false,
updateDebugShowBoundingVolume: true
});
derivedCommands.push(drawCommand._translucentCommand);
}
if (drawCommand._needsSkipLevelOfDetailCommands) {
drawCommand._skipLodBackfaceCommand = new ModelDerivedCommand({
command: deriveSkipLodBackfaceCommand(command),
updateShadows: false,
updateBackFaceCulling: false,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: false
});
drawCommand._skipLodStencilCommand = new ModelDerivedCommand({
command: deriveSkipLodStencilCommand(command, model),
updateShadows: true,
updateBackFaceCulling: usesBackFaceCulling,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: true
});
derivedCommands.push(drawCommand._skipLodBackfaceCommand);
derivedCommands.push(drawCommand._skipLodStencilCommand);
}
if (drawCommand._needsSilhouetteCommands) {
drawCommand._silhouetteModelCommand = new ModelDerivedCommand({
command: deriveSilhouetteModelCommand(command, model),
updateShadows: true,
updateBackFaceCulling: usesBackFaceCulling,
updateCullFace: usesBackFaceCulling,
updateDebugShowBoundingVolume: true
});
drawCommand._silhouetteColorCommand = new ModelDerivedCommand({
command: deriveSilhouetteColorCommand(command, model),
updateShadows: false,
updateBackFaceCulling: false,
updateCullFace: false,
updateDebugShowBoundingVolume: false
});
derivedCommands.push(drawCommand._silhouetteModelCommand);
derivedCommands.push(drawCommand._silhouetteColorCommand);
}
}
Object.defineProperties(ModelDrawCommand.prototype, {
command: {
get: function() {
return this._command;
}
},
runtimePrimitive: {
get: function() {
return this._runtimePrimitive;
}
},
model: {
get: function() {
return this._model;
}
},
primitiveType: {
get: function() {
return this._command.primitiveType;
}
},
modelMatrix: {
get: function() {
return this._modelMatrix;
},
set: function(value) {
this._modelMatrix = Matrix4_default.clone(value, this._modelMatrix);
this._modelMatrix2DDirty = true;
this._boundingVolume = BoundingSphere_default.transform(
this.runtimePrimitive.boundingSphere,
this._modelMatrix,
this._boundingVolume
);
}
},
boundingVolume: {
get: function() {
return this._boundingVolume;
}
},
shadows: {
get: function() {
return this._shadows;
},
set: function(value) {
this._shadows = value;
updateShadows(this);
}
},
backFaceCulling: {
get: function() {
return this._backFaceCulling;
},
set: function(value) {
if (this._backFaceCulling === value) {
return;
}
this._backFaceCulling = value;
updateBackFaceCulling(this);
}
},
cullFace: {
get: function() {
return this._cullFace;
},
set: function(value) {
if (this._cullFace === value) {
return;
}
this._cullFace = value;
updateCullFace(this);
}
},
debugShowBoundingVolume: {
get: function() {
return this._debugShowBoundingVolume;
},
set: function(value) {
if (this._debugShowBoundingVolume === value) {
return;
}
this._debugShowBoundingVolume = value;
updateDebugShowBoundingVolume(this);
}
}
});
function updateModelMatrix2D(drawCommand, frameState) {
const modelMatrix = drawCommand._modelMatrix;
drawCommand._modelMatrix2D = Matrix4_default.clone(
modelMatrix,
drawCommand._modelMatrix2D
);
drawCommand._modelMatrix2D[13] -= Math_default.sign(modelMatrix[13]) * 2 * Math_default.PI * frameState.mapProjection.ellipsoid.maximumRadius;
drawCommand._boundingVolume2D = BoundingSphere_default.transform(
drawCommand.runtimePrimitive.boundingSphere,
drawCommand._modelMatrix2D,
drawCommand._boundingVolume2D
);
}
function updateShadows(drawCommand) {
const shadows = drawCommand.shadows;
const castShadows = ShadowMode_default.castShadows(shadows);
const receiveShadows = ShadowMode_default.receiveShadows(shadows);
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateShadows) {
const command = derivedCommand.command;
command.castShadows = castShadows;
command.receiveShadows = receiveShadows;
}
}
}
function updateBackFaceCulling(drawCommand) {
const backFaceCulling = drawCommand.backFaceCulling;
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateBackFaceCulling) {
const command = derivedCommand.command;
const renderState = clone_default(command.renderState, true);
renderState.cull.enabled = backFaceCulling;
command.renderState = RenderState_default.fromCache(renderState);
}
}
}
function updateCullFace(drawCommand) {
const cullFace = drawCommand.cullFace;
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateCullFace) {
const command = derivedCommand.command;
const renderState = clone_default(command.renderState, true);
renderState.cull.face = cullFace;
command.renderState = RenderState_default.fromCache(renderState);
}
}
}
function updateDebugShowBoundingVolume(drawCommand) {
const debugShowBoundingVolume2 = drawCommand.debugShowBoundingVolume;
const derivedCommands = drawCommand._derivedCommands;
for (let i = 0; i < derivedCommands.length; ++i) {
const derivedCommand = derivedCommands[i];
if (derivedCommand.updateDebugShowBoundingVolume) {
const command = derivedCommand.command;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
}
}
}
ModelDrawCommand.prototype.pushCommands = function(frameState, result) {
const use2D = shouldUse2DCommands(this, frameState);
if (use2D && !this._has2DCommands) {
derive2DCommands(this);
this._has2DCommands = true;
this._modelMatrix2DDirty = true;
}
if (this._modelMatrix2DDirty) {
updateModelMatrix2D(this, frameState);
this._modelMatrix2DDirty = false;
}
const styleCommandsNeeded = this.model.styleCommandsNeeded;
if (this._needsTranslucentCommand && defined_default(styleCommandsNeeded)) {
if (styleCommandsNeeded !== StyleCommandsNeeded_default.ALL_OPAQUE) {
pushCommand(result, this._translucentCommand, use2D);
}
if (styleCommandsNeeded === StyleCommandsNeeded_default.ALL_TRANSLUCENT) {
return;
}
}
if (this._needsSkipLevelOfDetailCommands) {
const { tileset, tile } = this._model.content;
if (tileset.hasMixedContent) {
if (!tile._finalResolution) {
pushCommand(
tileset._backfaceCommands,
this._skipLodBackfaceCommand,
use2D
);
}
updateSkipLodStencilCommand(this, tile, use2D);
pushCommand(result, this._skipLodStencilCommand, use2D);
return;
}
}
if (this._needsSilhouetteCommands) {
pushCommand(result, this._silhouetteModelCommand, use2D);
return;
}
pushCommand(result, this._originalCommand, use2D);
return result;
};
ModelDrawCommand.prototype.pushSilhouetteCommands = function(frameState, result) {
const use2D = shouldUse2DCommands(this, frameState);
pushCommand(result, this._silhouetteColorCommand, use2D);
return result;
};
function pushCommand(commandList, derivedCommand, use2D) {
commandList.push(derivedCommand.command);
if (use2D) {
commandList.push(derivedCommand.derivedCommand2D.command);
}
}
function shouldUse2DCommands(drawCommand, frameState) {
if (frameState.mode !== SceneMode_default.SCENE2D || drawCommand.model._projectTo2D) {
return false;
}
const model = drawCommand.model;
const boundingSphere = model.sceneGraph._boundingSphere2D;
const left = boundingSphere.center.y - boundingSphere.radius;
const right = boundingSphere.center.y + boundingSphere.radius;
const idl2D = frameState.mapProjection.ellipsoid.maximumRadius * Math_default.PI;
return left < idl2D && right > idl2D || left < -idl2D && right > -idl2D;
}
function derive2DCommand(drawCommand, derivedCommand) {
if (!defined_default(derivedCommand)) {
return;
}
const derivedCommand2D = ModelDerivedCommand.clone(derivedCommand);
const command2D = DrawCommand_default.shallowClone(derivedCommand.command);
command2D.modelMatrix = drawCommand._modelMatrix2D;
command2D.boundingVolume = drawCommand._boundingVolume2D;
derivedCommand2D.command = command2D;
derivedCommand2D.updateShadows = false;
derivedCommand2D.is2D = true;
derivedCommand.derivedCommand2D = derivedCommand2D;
drawCommand._derivedCommands.push(derivedCommand2D);
return derivedCommand2D;
}
function derive2DCommands(drawCommand) {
derive2DCommand(drawCommand, drawCommand._originalCommand);
derive2DCommand(drawCommand, drawCommand._translucentCommand);
derive2DCommand(drawCommand, drawCommand._skipLodBackfaceCommand);
derive2DCommand(drawCommand, drawCommand._skipLodStencilCommand);
derive2DCommand(drawCommand, drawCommand._silhouetteModelCommand);
derive2DCommand(drawCommand, drawCommand._silhouetteColorCommand);
}
function deriveTranslucentCommand2(command) {
const derivedCommand = DrawCommand_default.shallowClone(command);
derivedCommand.pass = Pass_default.TRANSLUCENT;
const rs = clone_default(command.renderState, true);
rs.cull.enabled = false;
rs.depthMask = false;
rs.blending = BlendingState_default.ALPHA_BLEND;
derivedCommand.renderState = RenderState_default.fromCache(rs);
return derivedCommand;
}
function deriveSilhouetteModelCommand(command, model) {
const stencilReference = model._silhouetteId % 255;
const silhouetteModelCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
renderState.stencilTest = {
enabled: true,
frontFunction: WebGLConstants_default.ALWAYS,
backFunction: WebGLConstants_default.ALWAYS,
reference: stencilReference,
mask: ~0,
frontOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.REPLACE
},
backOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.REPLACE
}
};
if (model.isInvisible()) {
renderState.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
}
silhouetteModelCommand.renderState = RenderState_default.fromCache(renderState);
return silhouetteModelCommand;
}
function deriveSilhouetteColorCommand(command, model) {
const stencilReference = model._silhouetteId % 255;
const silhouetteColorCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
renderState.cull.enabled = false;
const silhouetteTranslucent = command.pass === Pass_default.TRANSLUCENT || model.silhouetteColor.alpha < 1;
if (silhouetteTranslucent) {
silhouetteColorCommand.pass = Pass_default.TRANSLUCENT;
renderState.depthMask = false;
renderState.blending = BlendingState_default.ALPHA_BLEND;
}
renderState.stencilTest = {
enabled: true,
frontFunction: WebGLConstants_default.NOTEQUAL,
backFunction: WebGLConstants_default.NOTEQUAL,
reference: stencilReference,
mask: ~0,
frontOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.KEEP
},
backOperation: {
fail: WebGLConstants_default.KEEP,
zFail: WebGLConstants_default.KEEP,
zPass: WebGLConstants_default.KEEP
}
};
const uniformMap2 = clone_default(command.uniformMap);
uniformMap2.model_silhouettePass = function() {
return true;
};
silhouetteColorCommand.renderState = RenderState_default.fromCache(renderState);
silhouetteColorCommand.uniformMap = uniformMap2;
silhouetteColorCommand.castShadows = false;
silhouetteColorCommand.receiveShadows = false;
return silhouetteColorCommand;
}
function updateSkipLodStencilCommand(drawCommand, tile, use2D) {
const stencilDerivedComand = drawCommand._skipLodStencilCommand;
const stencilCommand = stencilDerivedComand.command;
const selectionDepth = tile._selectionDepth;
const lastSelectionDepth = getLastSelectionDepth2(stencilCommand);
if (selectionDepth !== lastSelectionDepth) {
const skipLodStencilReference = getStencilReference(selectionDepth);
const renderState = clone_default(stencilCommand.renderState, true);
renderState.stencilTest.reference = skipLodStencilReference;
stencilCommand.renderState = RenderState_default.fromCache(renderState);
if (use2D) {
stencilDerivedComand.derivedCommand2D.renderState = renderState;
}
}
}
function getLastSelectionDepth2(stencilCommand) {
const reference = stencilCommand.renderState.stencilTest.reference;
return (reference & StencilConstants_default.SKIP_LOD_MASK) >>> StencilConstants_default.SKIP_LOD_BIT_SHIFT;
}
function getStencilReference(selectionDepth) {
return StencilConstants_default.CESIUM_3D_TILE_MASK | selectionDepth << StencilConstants_default.SKIP_LOD_BIT_SHIFT;
}
function deriveSkipLodBackfaceCommand(command) {
const backfaceCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
renderState.cull.enabled = true;
renderState.cull.face = CullFace_default.FRONT;
renderState.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
renderState.polygonOffset = {
enabled: true,
factor: 5,
units: 5
};
const uniformMap2 = clone_default(backfaceCommand.uniformMap);
const polygonOffset = new Cartesian2_default(5, 5);
uniformMap2.u_polygonOffset = function() {
return polygonOffset;
};
backfaceCommand.renderState = RenderState_default.fromCache(renderState);
backfaceCommand.uniformMap = uniformMap2;
backfaceCommand.castShadows = false;
backfaceCommand.receiveShadows = false;
return backfaceCommand;
}
function deriveSkipLodStencilCommand(command) {
const stencilCommand = DrawCommand_default.shallowClone(command);
const renderState = clone_default(command.renderState, true);
const { stencilTest } = renderState;
stencilTest.enabled = true;
stencilTest.mask = StencilConstants_default.SKIP_LOD_MASK;
stencilTest.reference = StencilConstants_default.CESIUM_3D_TILE_MASK;
stencilTest.frontFunction = StencilFunction_default.GREATER_OR_EQUAL;
stencilTest.frontOperation.zPass = StencilOperation_default.REPLACE;
stencilTest.backFunction = StencilFunction_default.GREATER_OR_EQUAL;
stencilTest.backOperation.zPass = StencilOperation_default.REPLACE;
renderState.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK | StencilConstants_default.SKIP_LOD_MASK;
stencilCommand.renderState = RenderState_default.fromCache(renderState);
return stencilCommand;
}
var ModelDrawCommand_default = ModelDrawCommand;
// node_modules/@cesium/engine/Source/Scene/Model/buildDrawCommand.js
function buildDrawCommand(primitiveRenderResources, frameState) {
const shaderBuilder = primitiveRenderResources.shaderBuilder;
shaderBuilder.addVertexLines(ModelVS_default);
shaderBuilder.addFragmentLines(ModelFS_default);
const indexBuffer = getIndexBuffer(primitiveRenderResources);
const vertexArray = new VertexArray_default({
context: frameState.context,
indexBuffer,
attributes: primitiveRenderResources.attributes
});
const model = primitiveRenderResources.model;
model._pipelineResources.push(vertexArray);
const shaderProgram = shaderBuilder.buildShaderProgram(frameState.context);
model._pipelineResources.push(shaderProgram);
const pass = primitiveRenderResources.alphaOptions.pass;
const sceneGraph = model.sceneGraph;
const is3D = frameState.mode === SceneMode_default.SCENE3D;
let modelMatrix, boundingSphere;
if (!is3D && !frameState.scene3DOnly && model._projectTo2D) {
modelMatrix = Matrix4_default.multiplyTransformation(
sceneGraph._computedModelMatrix,
primitiveRenderResources.runtimeNode.computedTransform,
new Matrix4_default()
);
const runtimePrimitive = primitiveRenderResources.runtimePrimitive;
boundingSphere = runtimePrimitive.boundingSphere2D;
} else {
const computedModelMatrix = is3D ? sceneGraph._computedModelMatrix : sceneGraph._computedModelMatrix2D;
modelMatrix = Matrix4_default.multiplyTransformation(
computedModelMatrix,
primitiveRenderResources.runtimeNode.computedTransform,
new Matrix4_default()
);
boundingSphere = BoundingSphere_default.transform(
primitiveRenderResources.boundingSphere,
modelMatrix,
primitiveRenderResources.boundingSphere
);
}
let renderState = clone_default(
RenderState_default.fromCache(primitiveRenderResources.renderStateOptions),
true
);
renderState.cull.face = ModelUtility_default.getCullFace(
modelMatrix,
primitiveRenderResources.primitiveType
);
renderState = RenderState_default.fromCache(renderState);
const hasClassification = defined_default(model.classificationType);
const castShadows = hasClassification ? false : ShadowMode_default.castShadows(model.shadows);
const receiveShadows = hasClassification ? false : ShadowMode_default.receiveShadows(model.shadows);
const pickId = hasClassification ? void 0 : primitiveRenderResources.pickId;
const command = new DrawCommand_default({
boundingVolume: boundingSphere,
modelMatrix,
uniformMap: primitiveRenderResources.uniformMap,
renderState,
vertexArray,
shaderProgram,
cull: model.cull,
pass,
count: primitiveRenderResources.count,
owner: model,
pickId,
instanceCount: primitiveRenderResources.instanceCount,
primitiveType: primitiveRenderResources.primitiveType,
debugShowBoundingVolume: model.debugShowBoundingVolume,
castShadows,
receiveShadows
});
if (hasClassification) {
return new ClassificationModelDrawCommand_default({
primitiveRenderResources,
command
});
}
return new ModelDrawCommand_default({
primitiveRenderResources,
command
});
}
function getIndexBuffer(primitiveRenderResources) {
const wireframeIndexBuffer = primitiveRenderResources.wireframeIndexBuffer;
if (defined_default(wireframeIndexBuffer)) {
return wireframeIndexBuffer;
}
const indices2 = primitiveRenderResources.indices;
if (!defined_default(indices2)) {
return void 0;
}
if (!defined_default(indices2.buffer)) {
throw new DeveloperError_default("Indices must be provided as a Buffer");
}
return indices2.buffer;
}
var buildDrawCommand_default = buildDrawCommand;
// node_modules/@cesium/engine/Source/Scene/Model/TilesetPipelineStage.js
var TilesetPipelineStage = {
name: "TilesetPipelineStage"
};
TilesetPipelineStage.process = function(renderResources, model, frameState) {
if (model.hasSkipLevelOfDetail(frameState)) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"POLYGON_OFFSET",
void 0,
ShaderDestination_default.FRAGMENT
);
const uniformMap2 = {
u_polygonOffset: function() {
return Cartesian2_default.ZERO;
}
};
renderResources.uniformMap = combine_default(
uniformMap2,
renderResources.uniformMap
);
renderResources.hasSkipLevelOfDetail = true;
}
const renderStateOptions = renderResources.renderStateOptions;
renderStateOptions.stencilTest = StencilConstants_default.setCesium3DTileBit();
renderStateOptions.stencilMask = StencilConstants_default.CESIUM_3D_TILE_MASK;
};
var TilesetPipelineStage_default = TilesetPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/ImageBasedLightingStageFS.js
var ImageBasedLightingStageFS_default = "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\n float NdotL = clamp(dot(n, l), 0.001, 1.0);\n float NdotV = abs(dot(n, v)) + 0.001;\n\n // Figure out if the reflection vector hits the ellipsoid\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 // Flipping the X vector is a cheap way to get the inverse of czm_temeToPseudoFixed, since that's a rotation about Z.\n r.x = -r.x;\n r = -normalize(czm_temeToPseudoFixed * r);\n r.x = -r.x;\n\n vec3 diffuseColor = pbrParameters.diffuseColor;\n float roughness = pbrParameters.roughness;\n vec3 specularColor = pbrParameters.f0;\n\n float inverseRoughness = 1.04 - roughness;\n inverseRoughness *= inverseRoughness;\n vec3 sceneSkyBox = czm_textureCube(czm_environmentMap, r).rgb * inverseRoughness;\n\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\n // Luminance model from page 40 of http://silviojemma.com/public/papers/lighting/spherical-harmonic-lighting.pdf\n #ifdef USE_SUN_LUMINANCE \n // Angle between sun and zenith\n float LdotZenith = clamp(dot(normalize(czm_inverseViewRotation * l), vWC), 0.001, 1.0);\n float S = acos(LdotZenith);\n // Angle between zenith and current pixel\n float NdotZenith = clamp(dot(normalize(czm_inverseViewRotation * n), vWC), 0.001, 1.0);\n // Angle between sun and current pixel\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\n vec2 brdfLut = texture(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\n #ifdef USE_SUN_LUMINANCE \n iblColor *= luminance;\n #endif\n\n return iblColor;\n}\n\n#if defined(DIFFUSE_IBL) || defined(SPECULAR_IBL)\nvec3 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\n vec3 v = -positionEC;\n vec3 n = normalEC;\n vec3 l = normalize(lightDirectionEC);\n vec3 h = normalize(v + l);\n\n float NdotV = abs(dot(n, v)) + 0.001;\n float VdotH = clamp(dot(v, h), 0.0, 1.0);\n\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\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\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 \n vec2 brdfLut = texture(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\n return diffuseColor * diffuseIrradiance + specularColor * specularIBL;\n}\n#endif\n\nvec3 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 // Environment maps were provided, use them for IBL\n return textureIBL(\n positionEC,\n normalEC,\n lightDirectionEC,\n pbrParameters\n );\n #else\n // Use the procedural IBL if there are no environment maps\n return proceduralIBL(\n positionEC,\n normalEC,\n lightDirectionEC,\n lightColorHdr,\n pbrParameters\n );\n #endif\n}";
// node_modules/@cesium/engine/Source/Scene/Model/ImageBasedLightingPipelineStage.js
var ImageBasedLightingPipelineStage = {
name: "ImageBasedLightingPipelineStage"
};
ImageBasedLightingPipelineStage.process = function(renderResources, model, frameState) {
const imageBasedLighting = model.imageBasedLighting;
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"USE_IBL_LIGHTING",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec2",
"model_iblFactor",
ShaderDestination_default.FRAGMENT
);
if (OctahedralProjectedCubeMap_default.isSupported(frameState.context)) {
const addMatrix = imageBasedLighting.useSphericalHarmonics || imageBasedLighting.useSpecularEnvironmentMaps || imageBasedLighting.enabled;
if (addMatrix) {
shaderBuilder.addUniform(
"mat3",
"model_iblReferenceFrameMatrix",
ShaderDestination_default.FRAGMENT
);
}
if (defined_default(imageBasedLighting.sphericalHarmonicCoefficients)) {
shaderBuilder.addDefine(
"DIFFUSE_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CUSTOM_SPHERICAL_HARMONICS",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec3",
"model_sphericalHarmonicCoefficients[9]",
ShaderDestination_default.FRAGMENT
);
} else if (imageBasedLighting.useDefaultSphericalHarmonics) {
shaderBuilder.addDefine(
"DIFFUSE_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
}
if (defined_default(imageBasedLighting.specularEnvironmentMapAtlas) && imageBasedLighting.specularEnvironmentMapAtlas.ready) {
shaderBuilder.addDefine(
"SPECULAR_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CUSTOM_SPECULAR_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"sampler2D",
"model_specularEnvironmentMaps",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec2",
"model_specularEnvironmentMapsSize",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"float",
"model_specularEnvironmentMapsMaximumLOD",
ShaderDestination_default.FRAGMENT
);
} else if (model.useDefaultSpecularMaps) {
shaderBuilder.addDefine(
"SPECULAR_IBL",
void 0,
ShaderDestination_default.FRAGMENT
);
}
}
if (defined_default(imageBasedLighting.luminanceAtZenith)) {
shaderBuilder.addDefine(
"USE_SUN_LUMINANCE",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"float",
"model_luminanceAtZenith",
ShaderDestination_default.FRAGMENT
);
}
shaderBuilder.addFragmentLines(ImageBasedLightingStageFS_default);
const uniformMap2 = {
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_default(uniformMap2, renderResources.uniformMap);
};
var ImageBasedLightingPipelineStage_default = ImageBasedLightingPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/ModelArticulationStage.js
var articulationEpsilon = Math_default.EPSILON16;
function ModelArticulationStage(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const stage = options.stage;
const runtimeArticulation = options.runtimeArticulation;
Check_default.typeOf.object("options.stage", stage);
Check_default.typeOf.object("options.runtimeArticulation", runtimeArticulation);
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(ModelArticulationStage.prototype, {
stage: {
get: function() {
return this._stage;
}
},
runtimeArticulation: {
get: function() {
return this._runtimeArticulation;
}
},
name: {
get: function() {
return this._name;
}
},
type: {
get: function() {
return this._type;
}
},
minimumValue: {
get: function() {
return this._minimumValue;
}
},
maximumValue: {
get: function() {
return this._maximumValue;
}
},
currentValue: {
get: function() {
return this._currentValue;
},
set: function(value) {
Check_default.typeOf.number("value", value);
value = Math_default.clamp(value, this.minimumValue, this.maximumValue);
if (!Math_default.equalsEpsilon(
this._currentValue,
value,
articulationEpsilon
)) {
this._currentValue = value;
this.runtimeArticulation._dirty = true;
}
}
}
});
var scratchArticulationCartesian = new Cartesian3_default();
var scratchArticulationRotation = new Matrix3_default();
ModelArticulationStage.prototype.applyStageToMatrix = function(result) {
Check_default.typeOf.object("result", result);
const type = this.type;
const value = this.currentValue;
const cartesian11 = scratchArticulationCartesian;
let rotation;
switch (type) {
case ArticulationStageType_default.XROTATE:
rotation = Matrix3_default.fromRotationX(
Math_default.toRadians(value),
scratchArticulationRotation
);
result = Matrix4_default.multiplyByMatrix3(result, rotation, result);
break;
case ArticulationStageType_default.YROTATE:
rotation = Matrix3_default.fromRotationY(
Math_default.toRadians(value),
scratchArticulationRotation
);
result = Matrix4_default.multiplyByMatrix3(result, rotation, result);
break;
case ArticulationStageType_default.ZROTATE:
rotation = Matrix3_default.fromRotationZ(
Math_default.toRadians(value),
scratchArticulationRotation
);
result = Matrix4_default.multiplyByMatrix3(result, rotation, result);
break;
case ArticulationStageType_default.XTRANSLATE:
cartesian11.x = value;
cartesian11.y = 0;
cartesian11.z = 0;
result = Matrix4_default.multiplyByTranslation(result, cartesian11, result);
break;
case ArticulationStageType_default.YTRANSLATE:
cartesian11.x = 0;
cartesian11.y = value;
cartesian11.z = 0;
result = Matrix4_default.multiplyByTranslation(result, cartesian11, result);
break;
case ArticulationStageType_default.ZTRANSLATE:
cartesian11.x = 0;
cartesian11.y = 0;
cartesian11.z = value;
result = Matrix4_default.multiplyByTranslation(result, cartesian11, result);
break;
case ArticulationStageType_default.XSCALE:
cartesian11.x = value;
cartesian11.y = 1;
cartesian11.z = 1;
result = Matrix4_default.multiplyByScale(result, cartesian11, result);
break;
case ArticulationStageType_default.YSCALE:
cartesian11.x = 1;
cartesian11.y = value;
cartesian11.z = 1;
result = Matrix4_default.multiplyByScale(result, cartesian11, result);
break;
case ArticulationStageType_default.ZSCALE:
cartesian11.x = 1;
cartesian11.y = 1;
cartesian11.z = value;
result = Matrix4_default.multiplyByScale(result, cartesian11, result);
break;
case ArticulationStageType_default.UNIFORMSCALE:
result = Matrix4_default.multiplyByUniformScale(result, value, result);
break;
default:
break;
}
return result;
};
var ModelArticulationStage_default = ModelArticulationStage;
// node_modules/@cesium/engine/Source/Scene/Model/ModelArticulation.js
function ModelArticulation(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const articulation = options.articulation;
const sceneGraph = options.sceneGraph;
Check_default.typeOf.object("options.articulation", articulation);
Check_default.typeOf.object("options.sceneGraph", sceneGraph);
this._articulation = articulation;
this._sceneGraph = sceneGraph;
this._name = articulation.name;
this._runtimeStages = [];
this._runtimeStagesByName = {};
this._runtimeNodes = [];
this._dirty = true;
initialize11(this);
}
Object.defineProperties(ModelArticulation.prototype, {
articulation: {
get: function() {
return this._articulation;
}
},
sceneGraph: {
get: function() {
return this._sceneGraph;
}
},
name: {
get: function() {
return this._name;
}
},
runtimeStages: {
get: function() {
return this._runtimeStages;
}
},
runtimeNodes: {
get: function() {
return this._runtimeNodes;
}
}
});
function initialize11(runtimeArticulation) {
const articulation = runtimeArticulation.articulation;
const stages = articulation.stages;
const length3 = stages.length;
const runtimeStages = runtimeArticulation._runtimeStages;
const runtimeStagesByName = runtimeArticulation._runtimeStagesByName;
for (let i = 0; i < length3; i++) {
const stage = stages[i];
const runtimeStage = new ModelArticulationStage_default({
stage,
runtimeArticulation
});
runtimeStages.push(runtimeStage);
const stageName = stage.name;
runtimeStagesByName[stageName] = runtimeStage;
}
}
ModelArticulation.prototype.setArticulationStage = function(stageName, value) {
const stage = this._runtimeStagesByName[stageName];
if (defined_default(stage)) {
stage.currentValue = value;
}
};
var scratchArticulationMatrix = new Matrix4_default();
var scratchNodeMatrix = new Matrix4_default();
ModelArticulation.prototype.apply = function() {
if (!this._dirty) {
return;
}
this._dirty = false;
let articulationMatrix = Matrix4_default.clone(
Matrix4_default.IDENTITY,
scratchArticulationMatrix
);
let i;
const stages = this._runtimeStages;
const stagesLength = stages.length;
for (i = 0; i < stagesLength; i++) {
const stage = stages[i];
articulationMatrix = stage.applyStageToMatrix(articulationMatrix);
}
const nodes = this._runtimeNodes;
const nodesLength = nodes.length;
for (i = 0; i < nodesLength; i++) {
const node = nodes[i];
const transform3 = Matrix4_default.multiplyTransformation(
node.originalTransform,
articulationMatrix,
scratchNodeMatrix
);
node.transform = transform3;
}
};
var ModelArticulation_default = ModelArticulation;
// node_modules/@cesium/engine/Source/Shaders/Model/ModelColorStageFS.js
var ModelColorStageFS_default = "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}";
// node_modules/@cesium/engine/Source/Scene/Model/ModelColorPipelineStage.js
var ModelColorPipelineStage = {
name: "ModelColorPipelineStage",
COLOR_UNIFORM_NAME: "model_color",
COLOR_BLEND_UNIFORM_NAME: "model_colorBlend"
};
ModelColorPipelineStage.process = function(renderResources, model, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_MODEL_COLOR",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFragmentLines(ModelColorStageFS_default);
const stageUniforms = {};
const color = model.color;
if (color.alpha === 0 && !model.hasSilhouette(frameState)) {
renderResources.renderStateOptions.colorMask = {
red: false,
green: false,
blue: false,
alpha: false
};
}
if (color.alpha < 1) {
renderResources.alphaOptions.pass = Pass_default.TRANSLUCENT;
}
shaderBuilder.addUniform(
"vec4",
ModelColorPipelineStage.COLOR_UNIFORM_NAME,
ShaderDestination_default.FRAGMENT
);
stageUniforms[ModelColorPipelineStage.COLOR_UNIFORM_NAME] = function() {
return model.color;
};
shaderBuilder.addUniform(
"float",
ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME,
ShaderDestination_default.FRAGMENT
);
stageUniforms[ModelColorPipelineStage.COLOR_BLEND_UNIFORM_NAME] = function() {
return ColorBlendMode_default.getColorBlend(
model.colorBlendMode,
model.colorBlendAmount
);
};
renderResources.uniformMap = combine_default(
stageUniforms,
renderResources.uniformMap
);
};
var ModelColorPipelineStage_default = ModelColorPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/ModelClippingPlanesStageFS.js
var ModelClippingPlanesStageFS_default = "#ifdef USE_CLIPPING_PLANES_FLOAT_TEXTURE\nvec4 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; // sample from center of pixel\n float v = (float(pixY) + 0.5) * pixelHeight;\n vec4 plane = texture(packedClippingPlanes, vec2(u, v));\n return czm_transformPlane(plane, transform);\n}\n#else\n// Handle uint8 clipping texture instead\nvec4 getClippingPlane(\n highp sampler2D packedClippingPlanes,\n int clippingPlaneNumber,\n mat4 transform\n) {\n int clippingPlaneStartIndex = clippingPlaneNumber * 2; // clipping planes are two pixels each\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; // sample from center of pixel\n float v = (float(pixY) + 0.5) * pixelHeight;\n vec4 oct32 = texture(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(texture(packedClippingPlanes, vec2(u + pixelWidth, v)));\n return czm_transformPlane(plane, transform);\n}\n#endif\n\nfloat 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 \n #ifdef UNION_CLIPPING_REGIONS\n float clipAmount; // 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.\n #else\n float clipAmount = 0.0;\n bool clipped = true;\n #endif\n\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 \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\n #ifndef UNION_CLIPPING_REGIONS\n if (clipped) {\n discard;\n }\n #endif\n \n return clipAmount;\n}\n\nvoid 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 \n if (clipDistance > 0.0 && clipDistance < clippingPlanesEdgeWidth) {\n color = clippingPlanesEdgeColor;\n }\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/ModelClippingPlanesPipelineStage.js
var ModelClippingPlanesPipelineStage = {
name: "ModelClippingPlanesPipelineStage"
};
var textureResolutionScratch2 = new Cartesian2_default();
ModelClippingPlanesPipelineStage.process = function(renderResources, model, frameState) {
const clippingPlanes = model.clippingPlanes;
const context = frameState.context;
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_CLIPPING_PLANES",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CLIPPING_PLANES_LENGTH",
clippingPlanes.length,
ShaderDestination_default.FRAGMENT
);
if (clippingPlanes.unionClippingRegions) {
shaderBuilder.addDefine(
"UNION_CLIPPING_REGIONS",
void 0,
ShaderDestination_default.FRAGMENT
);
}
if (ClippingPlaneCollection_default.useFloatTexture(context)) {
shaderBuilder.addDefine(
"USE_CLIPPING_PLANES_FLOAT_TEXTURE",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const textureResolution = ClippingPlaneCollection_default.getTextureResolution(
clippingPlanes,
context,
textureResolutionScratch2
);
shaderBuilder.addDefine(
"CLIPPING_PLANES_TEXTURE_WIDTH",
textureResolution.x,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addDefine(
"CLIPPING_PLANES_TEXTURE_HEIGHT",
textureResolution.y,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"sampler2D",
"model_clippingPlanes",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec4",
"model_clippingPlanesEdgeStyle",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"mat4",
"model_clippingPlanesMatrix",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFragmentLines(ModelClippingPlanesStageFS_default);
const uniformMap2 = {
model_clippingPlanes: function() {
return clippingPlanes.texture;
},
model_clippingPlanesEdgeStyle: function() {
const style = Color_default.clone(clippingPlanes.edgeColor);
style.alpha = clippingPlanes.edgeWidth;
return style;
},
model_clippingPlanesMatrix: function() {
return model._clippingPlanesMatrix;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
var ModelClippingPlanesPipelineStage_default = ModelClippingPlanesPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/ModelNode.js
function ModelNode(model, runtimeNode) {
Check_default.typeOf.object("model", model);
Check_default.typeOf.object("runtimeNode", runtimeNode);
this._model = model;
this._runtimeNode = runtimeNode;
}
Object.defineProperties(ModelNode.prototype, {
name: {
get: function() {
return this._runtimeNode._name;
}
},
id: {
get: function() {
return this._runtimeNode._id;
}
},
show: {
get: function() {
return this._runtimeNode.show;
},
set: function(value) {
this._runtimeNode.show = value;
}
},
matrix: {
get: function() {
return this._runtimeNode.transform;
},
set: function(value) {
if (defined_default(value)) {
this._runtimeNode.transform = value;
this._runtimeNode.userAnimated = true;
this._model._userAnimationDirty = true;
} else {
this._runtimeNode.transform = this.originalMatrix;
this._runtimeNode.userAnimated = false;
}
}
},
originalMatrix: {
get: function() {
return this._runtimeNode.originalTransform;
}
}
});
var ModelNode_default = ModelNode;
// node_modules/@cesium/engine/Source/Shaders/Model/InstancingStageCommon.js
var InstancingStageCommon_default = "mat4 getInstancingTransform()\n{\n mat4 instancingTransform;\n\n #ifdef HAS_INSTANCE_MATRICES\n instancingTransform = mat4(\n a_instancingTransformRow0.x, a_instancingTransformRow1.x, a_instancingTransformRow2.x, 0.0, // Column 1\n a_instancingTransformRow0.y, a_instancingTransformRow1.y, a_instancingTransformRow2.y, 0.0, // Column 2\n a_instancingTransformRow0.z, a_instancingTransformRow1.z, a_instancingTransformRow2.z, 0.0, // Column 3\n a_instancingTransformRow0.w, a_instancingTransformRow1.w, a_instancingTransformRow2.w, 1.0 // Column 4\n );\n #else\n vec3 translation = vec3(0.0, 0.0, 0.0);\n vec3 scale = vec3(1.0, 1.0, 1.0);\n \n #ifdef HAS_INSTANCE_TRANSLATION\n translation = a_instanceTranslation;\n #endif\n #ifdef HAS_INSTANCE_SCALE\n scale = a_instanceScale;\n #endif\n\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\n return instancingTransform;\n}\n\n#ifdef USE_2D_INSTANCING\nmat4 getInstancingTransform2D()\n{\n mat4 instancingTransform2D;\n\n #ifdef HAS_INSTANCE_MATRICES\n instancingTransform2D = mat4(\n a_instancingTransform2DRow0.x, a_instancingTransform2DRow1.x, a_instancingTransform2DRow2.x, 0.0, // Column 1\n a_instancingTransform2DRow0.y, a_instancingTransform2DRow1.y, a_instancingTransform2DRow2.y, 0.0, // Column 2\n a_instancingTransform2DRow0.z, a_instancingTransform2DRow1.z, a_instancingTransform2DRow2.z, 0.0, // Column 3\n a_instancingTransform2DRow0.w, a_instancingTransform2DRow1.w, a_instancingTransform2DRow2.w, 1.0 // Column 4\n );\n #else\n vec3 translation2D = vec3(0.0, 0.0, 0.0);\n vec3 scale = vec3(1.0, 1.0, 1.0);\n \n #ifdef HAS_INSTANCE_TRANSLATION\n translation2D = a_instanceTranslation2D;\n #endif\n #ifdef HAS_INSTANCE_SCALE\n scale = a_instanceScale;\n #endif\n\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\n return instancingTransform2D;\n}\n#endif\n";
// node_modules/@cesium/engine/Source/Shaders/Model/InstancingStageVS.js
var InstancingStageVS_default = "void instancingStage(inout ProcessedAttributes attributes) \n{\n vec3 positionMC = attributes.positionMC;\n \n mat4 instancingTransform = getInstancingTransform();\n \n attributes.positionMC = (instancingTransform * vec4(positionMC, 1.0)).xyz;\n\n #ifdef HAS_NORMALS\n vec3 normalMC = attributes.normalMC;\n attributes.normalMC = (instancingTransform * vec4(normalMC, 0.0)).xyz;\n #endif\n\n #ifdef USE_2D_INSTANCING\n mat4 instancingTransform2D = getInstancingTransform2D();\n attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;\n #endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/LegacyInstancingStageVS.js
var LegacyInstancingStageVS_default = "void legacyInstancingStage(\n inout ProcessedAttributes attributes,\n out mat4 instanceModelView,\n out mat3 instanceModelViewInverseTranspose)\n{\n vec3 positionMC = attributes.positionMC;\n\n mat4 instancingTransform = getInstancingTransform();\n \n mat4 instanceModel = instancingTransform * u_instance_nodeTransform;\n instanceModelView = u_instance_modifiedModelView;\n instanceModelViewInverseTranspose = mat3(u_instance_modifiedModelView * instanceModel);\n\n attributes.positionMC = (instanceModel * vec4(positionMC, 1.0)).xyz;\n \n #ifdef USE_2D_INSTANCING\n mat4 instancingTransform2D = getInstancingTransform2D();\n attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;\n #endif\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/InstancingPipelineStage.js
var modelViewScratch = new Matrix4_default();
var nodeTransformScratch = new Matrix4_default();
var modelView2DScratch = new Matrix4_default();
var InstancingPipelineStage = {
name: "InstancingPipelineStage",
_getInstanceTransformsAsMatrices: getInstanceTransformsAsMatrices,
_transformsToTypedArray: transformsToTypedArray
};
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_default);
const model = renderResources.model;
const sceneGraph = model.sceneGraph;
const runtimeNode = renderResources.runtimeNode;
const use2D = frameState.mode !== SceneMode_default.SCENE3D && !frameState.scene3DOnly && model._projectTo2D;
const instancingVertexAttributes = [];
processTransformAttributes(
renderResources,
frameState,
instances,
instancingVertexAttributes,
use2D
);
processFeatureIdAttributes(
renderResources,
frameState,
instances,
instancingVertexAttributes
);
const uniformMap2 = {};
if (instances.transformInWorldSpace) {
shaderBuilder.addDefine(
"USE_LEGACY_INSTANCING",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addUniform(
"mat4",
"u_instance_modifiedModelView",
ShaderDestination_default.VERTEX
);
shaderBuilder.addUniform(
"mat4",
"u_instance_nodeTransform",
ShaderDestination_default.VERTEX
);
uniformMap2.u_instance_modifiedModelView = function() {
let modifiedModelMatrix = Matrix4_default.multiplyTransformation(
model.modelMatrix,
sceneGraph.components.transform,
modelViewScratch
);
if (use2D) {
return Matrix4_default.multiplyTransformation(
frameState.context.uniformState.view3D,
modifiedModelMatrix,
modelViewScratch
);
}
if (frameState.mode !== SceneMode_default.SCENE3D) {
modifiedModelMatrix = Transforms_default.basisTo2D(
frameState.mapProjection,
modifiedModelMatrix,
modelViewScratch
);
}
return Matrix4_default.multiplyTransformation(
frameState.context.uniformState.view,
modifiedModelMatrix,
modelViewScratch
);
};
uniformMap2.u_instance_nodeTransform = function() {
return Matrix4_default.multiplyTransformation(
sceneGraph.axisCorrectionMatrix,
runtimeNode.computedTransform,
nodeTransformScratch
);
};
shaderBuilder.addVertexLines(LegacyInstancingStageVS_default);
} else {
shaderBuilder.addVertexLines(InstancingStageVS_default);
}
if (use2D) {
shaderBuilder.addDefine(
"USE_2D_INSTANCING",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addUniform("mat4", "u_modelView2D", ShaderDestination_default.VERTEX);
const context = frameState.context;
const modelMatrix2D = Matrix4_default.fromTranslation(
runtimeNode.instancingReferencePoint2D,
new Matrix4_default()
);
uniformMap2.u_modelView2D = function() {
return Matrix4_default.multiplyTransformation(
context.uniformState.view,
modelMatrix2D,
modelView2DScratch
);
};
}
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
renderResources.instanceCount = count;
renderResources.attributes.push.apply(
renderResources.attributes,
instancingVertexAttributes
);
};
var projectedTransformScratch = new Matrix4_default();
var projectedPositionScratch = new Cartesian3_default();
function projectTransformTo2D(transform3, modelMatrix, nodeTransform, frameState, result) {
let projectedTransform = Matrix4_default.multiplyTransformation(
modelMatrix,
transform3,
projectedTransformScratch
);
projectedTransform = Matrix4_default.multiplyTransformation(
projectedTransform,
nodeTransform,
projectedTransformScratch
);
result = Transforms_default.basisTo2D(
frameState.mapProjection,
projectedTransform,
result
);
return result;
}
function projectPositionTo2D(position, modelMatrix, nodeTransform, frameState, result) {
const translationMatrix = Matrix4_default.fromTranslation(
position,
projectedTransformScratch
);
let projectedTransform = Matrix4_default.multiplyTransformation(
modelMatrix,
translationMatrix,
projectedTransformScratch
);
projectedTransform = Matrix4_default.multiplyTransformation(
projectedTransform,
nodeTransform,
projectedTransformScratch
);
const finalPosition = Matrix4_default.getTranslation(
projectedTransform,
projectedPositionScratch
);
result = SceneTransforms_default.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) {
modelMatrix = Matrix4_default.multiplyTransformation(
model.modelMatrix,
sceneGraph.components.transform,
modelMatrix
);
nodeComputedTransform = Matrix4_default.multiplyTransformation(
sceneGraph.axisCorrectionMatrix,
renderResources.runtimeNode.computedTransform,
nodeComputedTransform
);
} else {
modelMatrix = Matrix4_default.clone(sceneGraph.computedModelMatrix, modelMatrix);
modelMatrix = Matrix4_default.multiplyTransformation(
modelMatrix,
renderResources.runtimeNode.computedTransform,
modelMatrix
);
nodeComputedTransform = Matrix4_default.clone(
Matrix4_default.IDENTITY,
nodeComputedTransform
);
}
}
var modelMatrixScratch = new Matrix4_default();
var nodeComputedTransformScratch = new Matrix4_default();
var transformScratch2 = new Matrix4_default();
var positionScratch5 = new Cartesian3_default();
function projectTransformsTo2D(transforms, renderResources, frameState, result) {
const modelMatrix = modelMatrixScratch;
const nodeComputedTransform = nodeComputedTransformScratch;
getModelMatrixAndNodeTransform(
renderResources,
modelMatrix,
nodeComputedTransform
);
const runtimeNode = renderResources.runtimeNode;
const referencePoint = runtimeNode.instancingReferencePoint2D;
const count = transforms.length;
for (let i = 0; i < count; i++) {
const transform3 = transforms[i];
const projectedTransform = projectTransformTo2D(
transform3,
modelMatrix,
nodeComputedTransform,
frameState,
transformScratch2
);
const position = Matrix4_default.getTranslation(
projectedTransform,
positionScratch5
);
const finalTranslation = Cartesian3_default.subtract(
position,
referencePoint,
position
);
result[i] = Matrix4_default.setTranslation(
projectedTransform,
finalTranslation,
result[i]
);
}
return result;
}
function projectTranslationsTo2D(translations, renderResources, frameState, result) {
const modelMatrix = modelMatrixScratch;
const nodeComputedTransform = nodeComputedTransformScratch;
getModelMatrixAndNodeTransform(
renderResources,
modelMatrix,
nodeComputedTransform
);
const runtimeNode = renderResources.runtimeNode;
const referencePoint = runtimeNode.instancingReferencePoint2D;
const count = translations.length;
for (let i = 0; i < count; i++) {
const translation3 = translations[i];
const projectedPosition2 = projectPositionTo2D(
translation3,
modelMatrix,
nodeComputedTransform,
frameState,
translation3
);
result[i] = Cartesian3_default.subtract(
projectedPosition2,
referencePoint,
result[i]
);
}
return result;
}
var scratchProjectedMin = new Cartesian3_default();
var scratchProjectedMax = new Cartesian3_default();
function computeReferencePoint2D(renderResources, frameState) {
const runtimeNode = renderResources.runtimeNode;
const modelMatrix = renderResources.model.sceneGraph.computedModelMatrix;
const transformedPositionMin = Matrix4_default.multiplyByPoint(
modelMatrix,
runtimeNode.instancingTranslationMin,
scratchProjectedMin
);
const projectedMin = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPositionMin,
transformedPositionMin
);
const transformedPositionMax = Matrix4_default.multiplyByPoint(
modelMatrix,
runtimeNode.instancingTranslationMax,
scratchProjectedMax
);
const projectedMax = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPositionMax,
transformedPositionMax
);
runtimeNode.instancingReferencePoint2D = Cartesian3_default.lerp(
projectedMin,
projectedMax,
0.5,
new Cartesian3_default()
);
}
function transformsToTypedArray(transforms) {
const elements = 12;
const count = transforms.length;
const transformsTypedArray = new Float32Array(count * elements);
for (let i = 0; i < count; i++) {
const transform3 = transforms[i];
const offset2 = elements * i;
transformsTypedArray[offset2 + 0] = transform3[0];
transformsTypedArray[offset2 + 1] = transform3[4];
transformsTypedArray[offset2 + 2] = transform3[8];
transformsTypedArray[offset2 + 3] = transform3[12];
transformsTypedArray[offset2 + 4] = transform3[1];
transformsTypedArray[offset2 + 5] = transform3[5];
transformsTypedArray[offset2 + 6] = transform3[9];
transformsTypedArray[offset2 + 7] = transform3[13];
transformsTypedArray[offset2 + 8] = transform3[2];
transformsTypedArray[offset2 + 9] = transform3[6];
transformsTypedArray[offset2 + 10] = transform3[10];
transformsTypedArray[offset2 + 11] = transform3[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 translation3 = translations[i];
const offset2 = elements * i;
transationsTypedArray[offset2 + 0] = translation3[0];
transationsTypedArray[offset2 + 1] = translation3[4];
transationsTypedArray[offset2 + 2] = translation3[8];
}
return transationsTypedArray;
}
var translationScratch = new Cartesian3_default();
var rotationScratch = new Quaternion_default();
var scaleScratch = new Cartesian3_default();
function getInstanceTransformsAsMatrices(instances, count, renderResources) {
const transforms = new Array(count);
const translationAttribute = ModelUtility_default.getAttributeBySemantic(
instances,
InstanceAttributeSemantic_default.TRANSLATION
);
const rotationAttribute = ModelUtility_default.getAttributeBySemantic(
instances,
InstanceAttributeSemantic_default.ROTATION
);
const scaleAttribute = ModelUtility_default.getAttributeBySemantic(
instances,
InstanceAttributeSemantic_default.SCALE
);
const instancingTranslationMax = new Cartesian3_default(
-Number.MAX_VALUE,
-Number.MAX_VALUE,
-Number.MAX_VALUE
);
const instancingTranslationMin = new Cartesian3_default(
Number.MAX_VALUE,
Number.MAX_VALUE,
Number.MAX_VALUE
);
const hasTranslation = defined_default(translationAttribute);
const hasRotation = defined_default(rotationAttribute);
const hasScale = defined_default(scaleAttribute);
const translationTypedArray = hasTranslation ? translationAttribute.typedArray : new Float32Array(count * 3);
let rotationTypedArray = hasRotation ? rotationAttribute.typedArray : new Float32Array(count * 4);
if (hasRotation && rotationAttribute.normalized) {
rotationTypedArray = AttributeCompression_default.dequantize(
rotationTypedArray,
rotationAttribute.componentDatatype,
rotationAttribute.type,
count
);
}
let scaleTypedArray;
if (hasScale) {
scaleTypedArray = scaleAttribute.typedArray;
} else {
scaleTypedArray = new Float32Array(count * 3);
scaleTypedArray.fill(1);
}
for (let i = 0; i < count; i++) {
const translation3 = new Cartesian3_default(
translationTypedArray[i * 3],
translationTypedArray[i * 3 + 1],
translationTypedArray[i * 3 + 2],
translationScratch
);
Cartesian3_default.maximumByComponent(
instancingTranslationMax,
translation3,
instancingTranslationMax
);
Cartesian3_default.minimumByComponent(
instancingTranslationMin,
translation3,
instancingTranslationMin
);
const rotation = new Quaternion_default(
rotationTypedArray[i * 4],
rotationTypedArray[i * 4 + 1],
rotationTypedArray[i * 4 + 2],
hasRotation ? rotationTypedArray[i * 4 + 3] : 1,
rotationScratch
);
const scale = new Cartesian3_default(
scaleTypedArray[i * 3],
scaleTypedArray[i * 3 + 1],
scaleTypedArray[i * 3 + 2],
scaleScratch
);
const transform3 = Matrix4_default.fromTranslationQuaternionRotationScale(
translation3,
rotation,
scale,
new Matrix4_default()
);
transforms[i] = transform3;
}
const runtimeNode = renderResources.runtimeNode;
runtimeNode.instancingTranslationMin = instancingTranslationMin;
runtimeNode.instancingTranslationMax = instancingTranslationMax;
if (hasTranslation) {
translationAttribute.typedArray = void 0;
}
if (hasRotation) {
rotationAttribute.typedArray = void 0;
}
if (hasScale) {
scaleAttribute.typedArray = void 0;
}
return transforms;
}
function getInstanceTranslationsAsCartesian3s(translationAttribute, count, renderResources) {
const instancingTranslations = new Array(count);
const translationTypedArray = translationAttribute.typedArray;
const instancingTranslationMin = new Cartesian3_default(
Number.MAX_VALUE,
Number.MAX_VALUE,
Number.MAX_VALUE
);
const instancingTranslationMax = new Cartesian3_default(
-Number.MAX_VALUE,
-Number.MAX_VALUE,
-Number.MAX_VALUE
);
for (let i = 0; i < count; i++) {
const translation3 = new Cartesian3_default(
translationTypedArray[i * 3],
translationTypedArray[i * 3 + 1],
translationTypedArray[i * 3 + 2]
);
instancingTranslations[i] = translation3;
Cartesian3_default.minimumByComponent(
instancingTranslationMin,
translation3,
instancingTranslationMin
);
Cartesian3_default.maximumByComponent(
instancingTranslationMax,
translation3,
instancingTranslationMax
);
}
const runtimeNode = renderResources.runtimeNode;
runtimeNode.instancingTranslationMin = instancingTranslationMin;
runtimeNode.instancingTranslationMax = instancingTranslationMax;
translationAttribute.typedArray = void 0;
return instancingTranslations;
}
function createVertexBuffer2(typedArray, frameState) {
const buffer = Buffer_default.createVertexBuffer({
context: frameState.context,
typedArray,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
return buffer;
}
function processTransformAttributes(renderResources, frameState, instances, instancingVertexAttributes, use2D) {
const rotationAttribute = ModelUtility_default.getAttributeBySemantic(
instances,
InstanceAttributeSemantic_default.ROTATION
);
if (defined_default(rotationAttribute)) {
processTransformMatrixAttributes(
renderResources,
instances,
instancingVertexAttributes,
frameState,
use2D
);
} else {
processTransformVec3Attributes(
renderResources,
instances,
instancingVertexAttributes,
frameState,
use2D
);
}
}
function processTransformMatrixAttributes(renderResources, instances, instancingVertexAttributes, frameState, use2D) {
const shaderBuilder = renderResources.shaderBuilder;
const count = instances.attributes[0].count;
const model = renderResources.model;
const runtimeNode = renderResources.runtimeNode;
shaderBuilder.addDefine("HAS_INSTANCE_MATRICES");
const attributeString = "Transform";
let transforms;
let buffer = runtimeNode.instancingTransformsBuffer;
if (!defined_default(buffer)) {
transforms = getInstanceTransformsAsMatrices(
instances,
count,
renderResources
);
const transformsTypedArray = transformsToTypedArray(transforms);
buffer = createVertexBuffer2(transformsTypedArray, frameState);
model._modelResources.push(buffer);
runtimeNode.instancingTransformsBuffer = buffer;
}
processMatrixAttributes(
renderResources,
buffer,
instancingVertexAttributes,
attributeString
);
if (!use2D) {
return;
}
const frameStateCV = clone_default(frameState);
frameStateCV.mode = SceneMode_default.COLUMBUS_VIEW;
computeReferencePoint2D(renderResources, frameStateCV);
let buffer2D = runtimeNode.instancingTransformsBuffer2D;
if (!defined_default(buffer2D)) {
const projectedTransforms = projectTransformsTo2D(
transforms,
renderResources,
frameStateCV,
transforms
);
const projectedTypedArray = transformsToTypedArray(projectedTransforms);
buffer2D = createVertexBuffer2(projectedTypedArray, frameState);
model._modelResources.push(buffer2D);
runtimeNode.instancingTransformsBuffer2D = buffer2D;
}
const attributeString2D = "Transform2D";
processMatrixAttributes(
renderResources,
buffer2D,
instancingVertexAttributes,
attributeString2D
);
}
function processTransformVec3Attributes(renderResources, instances, instancingVertexAttributes, frameState, use2D) {
const shaderBuilder = renderResources.shaderBuilder;
const runtimeNode = renderResources.runtimeNode;
const translationAttribute = ModelUtility_default.getAttributeBySemantic(
instances,
InstanceAttributeSemantic_default.TRANSLATION
);
const scaleAttribute = ModelUtility_default.getAttributeBySemantic(
instances,
InstanceAttributeSemantic_default.SCALE
);
if (defined_default(scaleAttribute)) {
shaderBuilder.addDefine("HAS_INSTANCE_SCALE");
const attributeString2 = "Scale";
processVec3Attribute(
renderResources,
scaleAttribute.buffer,
scaleAttribute.byteOffset,
scaleAttribute.byteStride,
instancingVertexAttributes,
attributeString2
);
}
if (!defined_default(translationAttribute)) {
return;
}
let instancingTranslations;
const typedArray = translationAttribute.typedArray;
if (defined_default(typedArray)) {
instancingTranslations = getInstanceTranslationsAsCartesian3s(
translationAttribute,
translationAttribute.count,
renderResources
);
} else if (!defined_default(runtimeNode.instancingTranslationMin)) {
runtimeNode.instancingTranslationMin = translationAttribute.min;
runtimeNode.instancingTranslationMax = translationAttribute.max;
}
shaderBuilder.addDefine("HAS_INSTANCE_TRANSLATION");
const attributeString = "Translation";
processVec3Attribute(
renderResources,
translationAttribute.buffer,
translationAttribute.byteOffset,
translationAttribute.byteStride,
instancingVertexAttributes,
attributeString
);
if (!use2D) {
return;
}
const frameStateCV = clone_default(frameState);
frameStateCV.mode = SceneMode_default.COLUMBUS_VIEW;
computeReferencePoint2D(renderResources, frameStateCV);
let buffer2D = runtimeNode.instancingTranslationBuffer2D;
if (!defined_default(buffer2D)) {
const projectedTranslations = projectTranslationsTo2D(
instancingTranslations,
renderResources,
frameStateCV,
instancingTranslations
);
const projectedTypedArray = translationsToTypedArray(projectedTranslations);
buffer2D = createVertexBuffer2(projectedTypedArray, frameState);
renderResources.model._modelResources.push(buffer2D);
runtimeNode.instancingTranslationBuffer2D = buffer2D;
}
const byteOffset = 0;
const byteStride = void 0;
const attributeString2D = "Translation2D";
processVec3Attribute(
renderResources,
buffer2D,
byteOffset,
byteStride,
instancingVertexAttributes,
attributeString2D
);
}
function processMatrixAttributes(renderResources, buffer, instancingVertexAttributes, attributeString) {
const vertexSizeInFloats = 12;
const componentByteSize = ComponentDatatype_default.getSizeInBytes(
ComponentDatatype_default.FLOAT
);
const strideInBytes = componentByteSize * vertexSizeInFloats;
const matrixAttributes = [
{
index: renderResources.attributeIndex++,
vertexBuffer: buffer,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
normalize: false,
offsetInBytes: 0,
strideInBytes,
instanceDivisor: 1
},
{
index: renderResources.attributeIndex++,
vertexBuffer: buffer,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
normalize: false,
offsetInBytes: componentByteSize * 4,
strideInBytes,
instanceDivisor: 1
},
{
index: renderResources.attributeIndex++,
vertexBuffer: buffer,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
normalize: false,
offsetInBytes: componentByteSize * 8,
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_default.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 shaderBuilder = renderResources.shaderBuilder;
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
if (attribute.semantic !== InstanceAttributeSemantic_default.FEATURE_ID) {
continue;
}
if (attribute.setIndex >= renderResources.featureIdVertexAttributeSetIndex) {
renderResources.featureIdVertexAttributeSetIndex = attribute.setIndex + 1;
}
instancingVertexAttributes.push({
index: renderResources.attributeIndex++,
vertexBuffer: attribute.buffer,
componentsPerAttribute: AttributeType_default.getNumberOfComponents(
attribute.type
),
componentDatatype: attribute.componentDatatype,
normalize: false,
offsetInBytes: attribute.byteOffset,
strideInBytes: attribute.byteStride,
instanceDivisor: 1
});
shaderBuilder.addAttribute(
"float",
`a_instanceFeatureId_${attribute.setIndex}`
);
}
}
var InstancingPipelineStage_default = InstancingPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/ModelMatrixUpdateStage.js
var ModelMatrixUpdateStage = {};
ModelMatrixUpdateStage.name = "ModelMatrixUpdateStage";
ModelMatrixUpdateStage.update = function(runtimeNode, sceneGraph, frameState) {
const use2D = frameState.mode !== SceneMode_default.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;
}
};
function updateRuntimeNode(runtimeNode, sceneGraph, modelMatrix, transformToRoot) {
let i;
transformToRoot = Matrix4_default.multiplyTransformation(
transformToRoot,
runtimeNode.transform,
new Matrix4_default()
);
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_default.multiplyTransformation(
modelMatrix,
transformToRoot,
drawCommand.modelMatrix
);
drawCommand.cullFace = ModelUtility_default.getCullFace(
drawCommand.modelMatrix,
drawCommand.primitiveType
);
}
const childrenLength = runtimeNode.children.length;
for (i = 0; i < childrenLength; i++) {
const childRuntimeNode = sceneGraph._runtimeNodes[runtimeNode.children[i]];
childRuntimeNode._transformToRoot = Matrix4_default.clone(
transformToRoot,
childRuntimeNode._transformToRoot
);
updateRuntimeNode(
childRuntimeNode,
sceneGraph,
modelMatrix,
transformToRoot
);
childRuntimeNode._transformDirty = false;
}
}
var ModelMatrixUpdateStage_default = ModelMatrixUpdateStage;
// node_modules/@cesium/engine/Source/Scene/Model/NodeStatisticsPipelineStage.js
var NodeStatisticsPipelineStage = {
name: "NodeStatisticsPipelineStage",
_countInstancingAttributes: countInstancingAttributes,
_countGeneratedBuffers: countGeneratedBuffers
};
NodeStatisticsPipelineStage.process = function(renderResources, node, frameState) {
const statistics2 = renderResources.model.statistics;
const instances = node.instances;
const runtimeNode = renderResources.runtimeNode;
countInstancingAttributes(statistics2, instances);
countGeneratedBuffers(statistics2, runtimeNode);
};
function countInstancingAttributes(statistics2, instances) {
if (!defined_default(instances)) {
return;
}
const attributes = instances.attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; i++) {
const attribute = attributes[i];
if (defined_default(attribute.buffer)) {
const hasCpuCopy = false;
statistics2.addBuffer(attribute.buffer, hasCpuCopy);
}
}
}
function countGeneratedBuffers(statistics2, runtimeNode) {
if (defined_default(runtimeNode.instancingTransformsBuffer)) {
const hasCpuCopy = false;
statistics2.addBuffer(runtimeNode.instancingTransformsBuffer, hasCpuCopy);
}
if (defined_default(runtimeNode.instancingTransformsBuffer2D)) {
const hasCpuCopy = false;
statistics2.addBuffer(runtimeNode.instancingTransformsBuffer2D, hasCpuCopy);
}
if (defined_default(runtimeNode.instancingTranslationBuffer2D)) {
const hasCpuCopy = false;
statistics2.addBuffer(runtimeNode.instancingTranslationBuffer2D, hasCpuCopy);
}
}
var NodeStatisticsPipelineStage_default = NodeStatisticsPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/ModelRuntimeNode.js
function ModelRuntimeNode(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const node = options.node;
const transform3 = options.transform;
const transformToRoot = options.transformToRoot;
const sceneGraph = options.sceneGraph;
const children = options.children;
Check_default.typeOf.object("options.node", node);
Check_default.typeOf.object("options.transform", transform3);
Check_default.typeOf.object("options.transformToRoot", transformToRoot);
Check_default.typeOf.object("options.sceneGraph", sceneGraph);
Check_default.typeOf.object("options.children", children);
this._node = node;
this._name = node.name;
this._id = node.index;
this._sceneGraph = sceneGraph;
this._children = children;
this._originalTransform = Matrix4_default.clone(transform3, this._originalTransform);
this._transform = Matrix4_default.clone(transform3, this._transform);
this._transformToRoot = Matrix4_default.clone(transformToRoot, this._transformToRoot);
this._computedTransform = new Matrix4_default();
this._transformDirty = false;
this._transformParameters = void 0;
this._morphWeights = [];
this._runtimeSkin = void 0;
this._computedJointMatrices = [];
this.show = true;
this.userAnimated = false;
this.pipelineStages = [];
this.runtimePrimitives = [];
this.updateStages = [];
this.instancingTranslationMin = void 0;
this.instancingTranslationMax = void 0;
this.instancingTransformsBuffer = void 0;
this.instancingTransformsBuffer2D = void 0;
this.instancingTranslationBuffer2D = void 0;
this.instancingReferencePoint2D = void 0;
initialize12(this);
}
Object.defineProperties(ModelRuntimeNode.prototype, {
node: {
get: function() {
return this._node;
}
},
sceneGraph: {
get: function() {
return this._sceneGraph;
}
},
children: {
get: function() {
return this._children;
}
},
transform: {
get: function() {
return this._transform;
},
set: function(value) {
this._transformDirty = true;
this._transform = Matrix4_default.clone(value, this._transform);
}
},
transformToRoot: {
get: function() {
return this._transformToRoot;
}
},
computedTransform: {
get: function() {
return this._computedTransform;
}
},
originalTransform: {
get: function() {
return this._originalTransform;
}
},
translation: {
get: function() {
return defined_default(this._transformParameters) ? this._transformParameters.translation : void 0;
},
set: function(value) {
const transformParameters = this._transformParameters;
if (!defined_default(transformParameters)) {
throw new DeveloperError_default(
"The translation of a node cannot be set if it was defined using a matrix in the model."
);
}
const currentTranslation = transformParameters.translation;
if (Cartesian3_default.equals(currentTranslation, value)) {
return;
}
transformParameters.translation = Cartesian3_default.clone(
value,
transformParameters.translation
);
updateTransformFromParameters(this, transformParameters);
}
},
rotation: {
get: function() {
return defined_default(this._transformParameters) ? this._transformParameters.rotation : void 0;
},
set: function(value) {
const transformParameters = this._transformParameters;
if (!defined_default(transformParameters)) {
throw new DeveloperError_default(
"The rotation of a node cannot be set if it was defined using a matrix in the model."
);
}
const currentRotation = transformParameters.rotation;
if (Quaternion_default.equals(currentRotation, value)) {
return;
}
transformParameters.rotation = Quaternion_default.clone(
value,
transformParameters.rotation
);
updateTransformFromParameters(this, transformParameters);
}
},
scale: {
get: function() {
return defined_default(this._transformParameters) ? this._transformParameters.scale : void 0;
},
set: function(value) {
const transformParameters = this._transformParameters;
if (!defined_default(transformParameters)) {
throw new DeveloperError_default(
"The scale of a node cannot be set if it was defined using a matrix in the model."
);
}
const currentScale = transformParameters.scale;
if (Cartesian3_default.equals(currentScale, value)) {
return;
}
transformParameters.scale = Cartesian3_default.clone(
value,
transformParameters.scale
);
updateTransformFromParameters(this, transformParameters);
}
},
morphWeights: {
get: function() {
return this._morphWeights;
},
set: function(value) {
const valueLength = value.length;
if (this._morphWeights.length !== valueLength) {
throw new DeveloperError_default(
"value must have the same length as the original weights array."
);
}
for (let i = 0; i < valueLength; i++) {
this._morphWeights[i] = value[i];
}
}
},
runtimeSkin: {
get: function() {
return this._runtimeSkin;
}
},
computedJointMatrices: {
get: function() {
return this._computedJointMatrices;
}
}
});
function initialize12(runtimeNode) {
const transform3 = runtimeNode.transform;
const transformToRoot = runtimeNode.transformToRoot;
const computedTransform = runtimeNode._computedTransform;
runtimeNode._computedTransform = Matrix4_default.multiply(
transformToRoot,
transform3,
computedTransform
);
const node = runtimeNode.node;
if (!defined_default(node.matrix)) {
runtimeNode._transformParameters = new TranslationRotationScale_default(
node.translation,
node.rotation,
node.scale
);
}
if (defined_default(node.morphWeights)) {
runtimeNode._morphWeights = node.morphWeights.slice();
}
const articulationName = node.articulationName;
if (defined_default(articulationName)) {
const sceneGraph = runtimeNode.sceneGraph;
const runtimeArticulations = sceneGraph._runtimeArticulations;
const runtimeArticulation = runtimeArticulations[articulationName];
if (defined_default(runtimeArticulation)) {
runtimeArticulation.runtimeNodes.push(runtimeNode);
}
}
}
function updateTransformFromParameters(runtimeNode, transformParameters) {
runtimeNode._transformDirty = true;
runtimeNode._transform = Matrix4_default.fromTranslationRotationScale(
transformParameters,
runtimeNode._transform
);
}
ModelRuntimeNode.prototype.getChild = function(index) {
Check_default.typeOf.number("index", index);
if (index < 0 || index >= this.children.length) {
throw new DeveloperError_default(
"index must be greater than or equal to 0 and less than the number of children."
);
}
return this.sceneGraph._runtimeNodes[this.children[index]];
};
ModelRuntimeNode.prototype.configurePipeline = function() {
const node = this.node;
const pipelineStages = this.pipelineStages;
pipelineStages.length = 0;
const updateStages = this.updateStages;
updateStages.length = 0;
if (defined_default(node.instances)) {
pipelineStages.push(InstancingPipelineStage_default);
}
pipelineStages.push(NodeStatisticsPipelineStage_default);
updateStages.push(ModelMatrixUpdateStage_default);
};
ModelRuntimeNode.prototype.updateComputedTransform = function() {
this._computedTransform = Matrix4_default.multiply(
this._transformToRoot,
this._transform,
this._computedTransform
);
};
ModelRuntimeNode.prototype.updateJointMatrices = function() {
const runtimeSkin = this._runtimeSkin;
if (!defined_default(runtimeSkin)) {
return;
}
runtimeSkin.updateJointMatrices();
const computedJointMatrices = this._computedJointMatrices;
const skinJointMatrices = runtimeSkin.jointMatrices;
const length3 = skinJointMatrices.length;
for (let i = 0; i < length3; i++) {
if (!defined_default(computedJointMatrices[i])) {
computedJointMatrices[i] = new Matrix4_default();
}
const nodeWorldTransform = Matrix4_default.multiplyTransformation(
this.transformToRoot,
this.transform,
computedJointMatrices[i]
);
const inverseNodeWorldTransform = Matrix4_default.inverseTransformation(
nodeWorldTransform,
computedJointMatrices[i]
);
computedJointMatrices[i] = Matrix4_default.multiplyTransformation(
inverseNodeWorldTransform,
skinJointMatrices[i],
computedJointMatrices[i]
);
}
};
var ModelRuntimeNode_default = ModelRuntimeNode;
// node_modules/@cesium/engine/Source/Scene/Model/AlphaPipelineStage.js
var AlphaPipelineStage = {
name: "AlphaPipelineStage"
};
AlphaPipelineStage.process = function(renderResources, primitive, frameState) {
const alphaOptions = renderResources.alphaOptions;
const model = renderResources.model;
alphaOptions.pass = defaultValue_default(alphaOptions.pass, model.opaquePass);
const renderStateOptions = renderResources.renderStateOptions;
if (alphaOptions.pass === Pass_default.TRANSLUCENT) {
renderStateOptions.cull.enabled = false;
renderStateOptions.depthMask = false;
renderStateOptions.blending = BlendingState_default.ALPHA_BLEND;
}
const shaderBuilder = renderResources.shaderBuilder;
const uniformMap2 = renderResources.uniformMap;
if (defined_default(alphaOptions.alphaCutoff)) {
shaderBuilder.addDefine(
"ALPHA_MODE_MASK",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"float",
"u_alphaCutoff",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_alphaCutoff = function() {
return alphaOptions.alphaCutoff;
};
}
};
var AlphaPipelineStage_default = AlphaPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/BatchTexturePipelineStage.js
var BatchTexturePipelineStage = {
name: "BatchTexturePipelineStage"
};
BatchTexturePipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const batchTextureUniforms = {};
const model = renderResources.model;
const featureTable = model.featureTables[model.featureTableId];
const featuresLength = featureTable.featuresLength;
shaderBuilder.addUniform("int", "model_featuresLength");
batchTextureUniforms.model_featuresLength = function() {
return featuresLength;
};
const batchTexture = featureTable.batchTexture;
shaderBuilder.addUniform("sampler2D", "model_batchTexture");
batchTextureUniforms.model_batchTexture = function() {
return defaultValue_default(batchTexture.batchTexture, batchTexture.defaultTexture);
};
shaderBuilder.addUniform("vec4", "model_textureStep");
batchTextureUniforms.model_textureStep = function() {
return batchTexture.textureStep;
};
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_default(
batchTextureUniforms,
renderResources.uniformMap
);
};
var BatchTexturePipelineStage_default = BatchTexturePipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/ClassificationPipelineStage.js
var ClassificationPipelineStage = {
name: "ClassificationPipelineStage"
};
ClassificationPipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_CLASSIFICATION",
void 0,
ShaderDestination_default.BOTH
);
const runtimePrimitive = renderResources.runtimePrimitive;
if (!defined_default(runtimePrimitive.batchLengths)) {
createClassificationBatches(primitive, runtimePrimitive);
}
};
function createClassificationBatches(primitive, runtimePrimitive) {
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
if (!defined_default(positionAttribute)) {
throw new RuntimeError_default(
"Primitives must have a position attribute to be used for classification."
);
}
let indicesArray;
const indices2 = primitive.indices;
const hasIndices = defined_default(indices2);
if (hasIndices) {
indicesArray = indices2.typedArray;
indices2.typedArray = void 0;
}
const count = hasIndices ? indices2.count : positionAttribute.count;
const featureIdAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.FEATURE_ID,
0
);
if (!defined_default(featureIdAttribute)) {
runtimePrimitive.batchLengths = [count];
runtimePrimitive.batchOffsets = [0];
return;
}
const featureIds = featureIdAttribute.typedArray;
featureIdAttribute.typedArray = void 0;
const batchLengths = [];
const batchOffsets = [0];
const firstIndex = hasIndices ? indicesArray[0] : 0;
let currentBatchId = featureIds[firstIndex];
let currentOffset = 0;
for (let i = 1; i < count; i++) {
const index = hasIndices ? indicesArray[i] : i;
const batchId = featureIds[index];
if (batchId !== currentBatchId) {
const batchLength = i - currentOffset;
const newOffset = i;
batchLengths.push(batchLength);
batchOffsets.push(newOffset);
currentOffset = newOffset;
currentBatchId = batchId;
}
}
const finalBatchLength = count - currentOffset;
batchLengths.push(finalBatchLength);
runtimePrimitive.batchLengths = batchLengths;
runtimePrimitive.batchOffsets = batchOffsets;
}
var ClassificationPipelineStage_default = ClassificationPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/CPUStylingStageVS.js
var CPUStylingStageVS_default = "void filterByPassType(inout vec3 positionMC, vec4 featureColor)\n{\n bool styleTranslucent = (featureColor.a != 1.0);\n // Only render translucent features in the translucent pass (if the style or the original command has translucency).\n if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)\n {\n // If the model has a translucent silhouette, it needs to render during the silhouette color command,\n // (i.e. the command where model_silhouettePass = true), even if the model isn't translucent.\n #ifdef HAS_SILHOUETTE\n positionMC *= float(model_silhouettePass);\n #else\n positionMC *= 0.0;\n #endif\n }\n // If the current pass is not the translucent pass and the style is not translucent, don't render the feature.\n else if (czm_pass != czm_passTranslucent && styleTranslucent)\n {\n positionMC *= 0.0;\n }\n}\n\nvoid cpuStylingStage(inout vec3 positionMC, inout SelectedFeature feature)\n{\n float show = ceil(feature.color.a);\n positionMC *= show;\n\n #if defined(HAS_SELECTED_FEATURE_ID_ATTRIBUTE) && !defined(HAS_CLASSIFICATION)\n filterByPassType(positionMC, feature.color);\n #endif\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/CPUStylingStageFS.js
var CPUStylingStageFS_default = "void filterByPassType(vec4 featureColor)\n{\n bool styleTranslucent = (featureColor.a != 1.0);\n // Only render translucent features in the translucent pass (if the style or the original command has translucency).\n if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)\n { \n // If the model has a translucent silhouette, it needs to render during the silhouette color command,\n // (i.e. the command where model_silhouettePass = true), even if the model isn't translucent.\n #ifdef HAS_SILHOUETTE\n if(!model_silhouettePass) {\n discard;\n }\n #else\n discard;\n #endif\n }\n // If the current pass is not the translucent pass and the style is not translucent, don't render the feature.\n else if (czm_pass != czm_passTranslucent && styleTranslucent)\n {\n discard;\n }\n}\n\nvoid cpuStylingStage(inout czm_modelMaterial material, SelectedFeature feature)\n{\n vec4 featureColor = feature.color;\n if (featureColor.a == 0.0)\n {\n discard;\n }\n\n // If a feature ID vertex attribute is used, the pass type filter is applied in the vertex shader.\n // So, we only apply in in the fragment shader if the feature ID texture is used.\n #if defined(HAS_SELECTED_FEATURE_ID_TEXTURE) && !defined(HAS_CLASSIFICATION)\n filterByPassType(featureColor);\n #endif\n\n featureColor = czm_gammaCorrect(featureColor);\n\n // Classification models compute the diffuse differently.\n #ifdef HAS_CLASSIFICATION\n material.diffuse = featureColor.rgb * featureColor.a;\n #else\n float highlight = ceil(model_colorBlend);\n material.diffuse *= mix(featureColor.rgb, vec3(1.0), highlight);\n #endif\n \n material.alpha *= featureColor.a;\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/CPUStylingPipelineStage.js
var CPUStylingPipelineStage = {
name: "CPUStylingPipelineStage"
};
CPUStylingPipelineStage.process = function(renderResources, primitive, frameState) {
const model = renderResources.model;
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addVertexLines(CPUStylingStageVS_default);
shaderBuilder.addFragmentLines(CPUStylingStageFS_default);
shaderBuilder.addDefine("USE_CPU_STYLING", void 0, ShaderDestination_default.BOTH);
if (!defined_default(model.color)) {
shaderBuilder.addUniform(
"float",
ModelColorPipelineStage_default.COLOR_BLEND_UNIFORM_NAME,
ShaderDestination_default.FRAGMENT
);
renderResources.uniformMap[ModelColorPipelineStage_default.COLOR_BLEND_UNIFORM_NAME] = function() {
return ColorBlendMode_default.getColorBlend(
model.colorBlendMode,
model.colorBlendAmount
);
};
}
shaderBuilder.addUniform(
"bool",
"model_commandTranslucent",
ShaderDestination_default.BOTH
);
renderResources.uniformMap.model_commandTranslucent = function() {
return renderResources.alphaOptions.pass === Pass_default.TRANSLUCENT;
};
};
var CPUStylingPipelineStage_default = CPUStylingPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/CustomShaderMode.js
var CustomShaderMode = {
MODIFY_MATERIAL: "MODIFY_MATERIAL",
REPLACE_MATERIAL: "REPLACE_MATERIAL"
};
CustomShaderMode.getDefineName = function(customShaderMode) {
return `CUSTOM_SHADER_${customShaderMode}`;
};
var CustomShaderMode_default = Object.freeze(CustomShaderMode);
// node_modules/@cesium/engine/Source/Shaders/Model/CustomShaderStageVS.js
var CustomShaderStageVS_default = "void customShaderStage(\n inout czm_modelVertexOutput vsOutput, \n inout ProcessedAttributes attributes, \n FeatureIds featureIds,\n Metadata metadata,\n MetadataClass metadataClass,\n MetadataStatistics metadataStatistics\n) {\n // VertexInput and initializeInputStruct() are dynamically generated in JS, \n // see CustomShaderPipelineStage.js\n VertexInput vsInput;\n initializeInputStruct(vsInput, attributes);\n vsInput.featureIds = featureIds;\n vsInput.metadata = metadata;\n vsInput.metadataClass = metadataClass;\n vsInput.metadataStatistics = metadataStatistics;\n vertexMain(vsInput, vsOutput);\n attributes.positionMC = vsOutput.positionMC;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/CustomShaderStageFS.js
var CustomShaderStageFS_default = "void customShaderStage(\n inout czm_modelMaterial material,\n ProcessedAttributes attributes,\n FeatureIds featureIds,\n Metadata metadata,\n MetadataClass metadataClass,\n MetadataStatistics metadataStatistics\n) {\n // FragmentInput and initializeInputStruct() are dynamically generated in JS, \n // see CustomShaderPipelineStage.js\n FragmentInput fsInput;\n initializeInputStruct(fsInput, attributes);\n fsInput.featureIds = featureIds;\n fsInput.metadata = metadata;\n fsInput.metadataClass = metadataClass;\n fsInput.metadataStatistics = metadataStatistics;\n fragmentMain(fsInput, material);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/FeatureIdStageFS.js
var FeatureIdStageFS_default = "void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes) {\n initializeFeatureIds(featureIds, attributes);\n initializeFeatureIdAliases(featureIds);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/FeatureIdStageVS.js
var FeatureIdStageVS_default = "void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes) \n{\n initializeFeatureIds(featureIds, attributes);\n initializeFeatureIdAliases(featureIds);\n setFeatureIdVaryings();\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/FeatureIdPipelineStage.js
var FeatureIdPipelineStage = {
name: "FeatureIdPipelineStage",
STRUCT_ID_FEATURE_IDS_VS: "FeatureIdsVS",
STRUCT_ID_FEATURE_IDS_FS: "FeatureIdsFS",
STRUCT_NAME_FEATURE_IDS: "FeatureIds",
FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS: "initializeFeatureIdsVS",
FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS: "initializeFeatureIdsFS",
FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS: "initializeFeatureIdAliasesVS",
FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS: "initializeFeatureIdAliasesFS",
FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS: "void initializeFeatureIds(out FeatureIds featureIds, ProcessedAttributes attributes)",
FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES: "void initializeFeatureIdAliases(inout FeatureIds featureIds)",
FUNCTION_ID_SET_FEATURE_ID_VARYINGS: "setFeatureIdVaryings",
FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS: "void setFeatureIdVaryings()"
};
FeatureIdPipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
declareStructsAndFunctions(shaderBuilder);
const instances = renderResources.runtimeNode.node.instances;
if (defined_default(instances)) {
processInstanceFeatureIds(renderResources, instances, frameState);
}
processPrimitiveFeatureIds(renderResources, primitive, frameState);
shaderBuilder.addVertexLines(FeatureIdStageVS_default);
shaderBuilder.addFragmentLines(FeatureIdStageFS_default);
};
function declareStructsAndFunctions(shaderBuilder) {
shaderBuilder.addStruct(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS,
ShaderDestination_default.VERTEX
);
shaderBuilder.addStruct(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
FeatureIdPipelineStage.STRUCT_NAME_FEATURE_IDS,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFunction(
FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,
FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS,
ShaderDestination_default.VERTEX
);
shaderBuilder.addFunction(
FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,
FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFunction(
FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS,
FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES,
ShaderDestination_default.VERTEX
);
shaderBuilder.addFunction(
FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS,
FeatureIdPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFunction(
FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,
FeatureIdPipelineStage.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS,
ShaderDestination_default.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_default.FeatureIdAttribute) {
processInstanceAttribute(renderResources, featureIds, variableName);
} else {
const instanceDivisor = 1;
processImplicitRange(
renderResources,
featureIds,
variableName,
count,
instanceDivisor,
frameState
);
}
const label = featureIds.label;
if (defined_default(label)) {
addAlias(renderResources, variableName, label, ShaderDestination_default.BOTH);
}
}
}
function processPrimitiveFeatureIds(renderResources, primitive, frameState) {
const featureIdsArray = primitive.featureIds;
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
const count = positionAttribute.count;
for (let i = 0; i < featureIdsArray.length; i++) {
const featureIds = featureIdsArray[i];
const variableName = featureIds.positionalLabel;
let aliasDestination = ShaderDestination_default.BOTH;
if (featureIds instanceof ModelComponents_default.FeatureIdAttribute) {
processAttribute(renderResources, featureIds, variableName);
} else if (featureIds instanceof ModelComponents_default.FeatureIdImplicitRange) {
processImplicitRange(
renderResources,
featureIds,
variableName,
count,
void 0,
frameState
);
} else {
processTexture(renderResources, featureIds, variableName, i, frameState);
aliasDestination = ShaderDestination_default.FRAGMENT;
}
const label = featureIds.label;
if (defined_default(label)) {
addAlias(renderResources, variableName, label, aliasDestination);
}
}
}
function processInstanceAttribute(renderResources, featureIdAttribute, variableName) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
"int",
variableName
);
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
"int",
variableName
);
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]
);
shaderBuilder.addVarying("float", varyingName);
shaderBuilder.addFunctionLines(
FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,
[`${varyingName} = ${attributeName};`]
);
}
function processAttribute(renderResources, featureIdAttribute, variableName) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
"int",
variableName
);
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
"int",
variableName
);
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) {
generateImplicitFeatureIdAttribute(
renderResources,
implicitFeatureIds,
count,
instanceDivisor,
frameState
);
const shaderBuilder = renderResources.shaderBuilder;
const implicitAttributeName = `a_implicit_${variableName}`;
shaderBuilder.addAttribute("float", implicitAttributeName);
const implicitVaryingName = `v_implicit_${variableName}`;
shaderBuilder.addVarying("float", implicitVaryingName);
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
"int",
variableName
);
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
"int",
variableName
);
shaderBuilder.addFunctionLines(
FeatureIdPipelineStage.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,
[`${implicitVaryingName} = ${implicitAttributeName};`]
);
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(renderResources, featureIdTexture, variableName, index, frameState) {
const uniformName = `u_featureIdTexture_${index}`;
const uniformMap2 = renderResources.uniformMap;
const textureReader = featureIdTexture.textureReader;
uniformMap2[uniformName] = function() {
return defaultValue_default(
textureReader.texture,
frameState.context.defaultTexture
);
};
const channels = textureReader.channels;
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
"int",
variableName
);
shaderBuilder.addUniform(
"sampler2D",
uniformName,
ShaderDestination_default.FRAGMENT
);
const texCoord = `v_texCoord_${textureReader.texCoord}`;
const textureRead = `texture(${uniformName}, ${texCoord}).${channels}`;
const initializationLine = `featureIds.${variableName} = czm_unpackUint(${textureRead});`;
shaderBuilder.addFunctionLines(
FeatureIdPipelineStage.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,
[initializationLine]
);
}
function addAlias(renderResources, variableName, alias, shaderDestination) {
const shaderBuilder = renderResources.shaderBuilder;
const updateVS = ShaderDestination_default.includesVertexShader(shaderDestination);
if (updateVS) {
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_VS,
"int",
alias
);
}
shaderBuilder.addStructField(
FeatureIdPipelineStage.STRUCT_ID_FEATURE_IDS_FS,
"int",
alias
);
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_default(implicitFeatureIds.repeat)) {
const typedArray = generateImplicitFeatureIdTypedArray(
implicitFeatureIds,
count
);
vertexBuffer = Buffer_default.createVertexBuffer({
context: frameState.context,
typedArray,
usage: BufferUsage_default.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,
value,
vertexBuffer,
normalize: false,
componentsPerAttribute: 1,
componentDatatype: ComponentDatatype_default.FLOAT,
strideInBytes: ComponentDatatype_default.getSizeInBytes(ComponentDatatype_default.FLOAT),
offsetInBytes: 0
};
renderResources.attributes.push(generatedFeatureIdAttribute);
}
function generateImplicitFeatureIdTypedArray(implicitFeatureIds, count) {
const offset2 = implicitFeatureIds.offset;
const repeat = implicitFeatureIds.repeat;
const typedArray = new Float32Array(count);
for (let i = 0; i < count; i++) {
typedArray[i] = offset2 + Math.floor(i / repeat);
}
return typedArray;
}
var FeatureIdPipelineStage_default = FeatureIdPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/MetadataStageFS.js
var MetadataStageFS_default = "void metadataStage(\n out Metadata metadata,\n out MetadataClass metadataClass,\n out MetadataStatistics metadataStatistics,\n ProcessedAttributes attributes\n )\n{\n initializeMetadata(metadata, metadataClass, metadataStatistics, attributes);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/MetadataStageVS.js
var MetadataStageVS_default = "void metadataStage(\n out Metadata metadata,\n out MetadataClass metadataClass,\n out MetadataStatistics metadataStatistics,\n ProcessedAttributes attributes\n )\n{\n initializeMetadata(metadata, metadataClass, metadataStatistics, attributes);\n setMetadataVaryings();\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/MetadataPipelineStage.js
var MetadataPipelineStage = {
name: "MetadataPipelineStage",
STRUCT_ID_METADATA_VS: "MetadataVS",
STRUCT_ID_METADATA_FS: "MetadataFS",
STRUCT_NAME_METADATA: "Metadata",
STRUCT_ID_METADATA_CLASS_VS: "MetadataClassVS",
STRUCT_ID_METADATA_CLASS_FS: "MetadataClassFS",
STRUCT_NAME_METADATA_CLASS: "MetadataClass",
STRUCT_ID_METADATA_STATISTICS_VS: "MetadataStatisticsVS",
STRUCT_ID_METADATA_STATISTICS_FS: "MetadataStatisticsFS",
STRUCT_NAME_METADATA_STATISTICS: "MetadataStatistics",
FUNCTION_ID_INITIALIZE_METADATA_VS: "initializeMetadataVS",
FUNCTION_ID_INITIALIZE_METADATA_FS: "initializeMetadataFS",
FUNCTION_SIGNATURE_INITIALIZE_METADATA: "void initializeMetadata(out Metadata metadata, out MetadataClass metadataClass, out MetadataStatistics metadataStatistics, ProcessedAttributes attributes)",
FUNCTION_ID_SET_METADATA_VARYINGS: "setMetadataVaryings",
FUNCTION_SIGNATURE_SET_METADATA_VARYINGS: "void setMetadataVaryings()",
METADATA_CLASS_FIELDS: [
{ specName: "noData", shaderName: "noData" },
{ specName: "default", shaderName: "defaultValue" },
{ specName: "min", shaderName: "minValue" },
{ specName: "max", shaderName: "maxValue" }
],
METADATA_STATISTICS_FIELDS: [
{ specName: "min", shaderName: "minValue" },
{ specName: "max", shaderName: "maxValue" },
{ specName: "mean", shaderName: "mean", type: "float" },
{ specName: "median", shaderName: "median" },
{
specName: "standardDeviation",
shaderName: "standardDeviation",
type: "float"
},
{ specName: "variance", shaderName: "variance", type: "float" },
{ specName: "sum", shaderName: "sum" }
]
};
MetadataPipelineStage.process = function(renderResources, primitive, frameState) {
var _a;
const { shaderBuilder, model } = renderResources;
const { structuralMetadata = {}, content } = model;
const statistics2 = (_a = content == null ? void 0 : content.tileset.metadataExtension) == null ? void 0 : _a.statistics;
const propertyAttributesInfo = getPropertyAttributesInfo(
structuralMetadata.propertyAttributes,
primitive,
statistics2
);
const propertyTexturesInfo = getPropertyTexturesInfo(
structuralMetadata.propertyTextures,
statistics2
);
const allPropertyInfos = propertyAttributesInfo.concat(propertyTexturesInfo);
declareMetadataTypeStructs(shaderBuilder, allPropertyInfos);
declareStructsAndFunctions2(shaderBuilder);
shaderBuilder.addVertexLines(MetadataStageVS_default);
shaderBuilder.addFragmentLines(MetadataStageFS_default);
for (let i = 0; i < propertyAttributesInfo.length; i++) {
const info = propertyAttributesInfo[i];
processPropertyAttributeProperty(renderResources, info);
}
for (let i = 0; i < propertyTexturesInfo.length; i++) {
const info = propertyTexturesInfo[i];
processPropertyTextureProperty(renderResources, info);
}
};
function getPropertyAttributesInfo(propertyAttributes, primitive, statistics2) {
if (!defined_default(propertyAttributes)) {
return [];
}
return propertyAttributes.flatMap(
(propertyAttribute) => getPropertyAttributeInfo(propertyAttribute, primitive, statistics2)
);
}
function getPropertyAttributeInfo(propertyAttribute, primitive, statistics2) {
const {
getAttributeByName,
getAttributeInfo,
sanitizeGlslIdentifier
} = ModelUtility_default;
const classId = propertyAttribute.class.id;
const classStatistics = statistics2 == null ? void 0 : statistics2.classes[classId];
const propertiesArray = Object.entries(propertyAttribute.properties);
const infoArray = new Array(propertiesArray.length);
for (let i = 0; i < propertiesArray.length; i++) {
const [propertyId, property] = propertiesArray[i];
const modelAttribute = getAttributeByName(primitive, property.attribute);
const { glslType, variableName } = getAttributeInfo(modelAttribute);
infoArray[i] = {
metadataVariable: sanitizeGlslIdentifier(propertyId),
property,
type: property.classProperty.type,
glslType,
variableName,
propertyStatistics: classStatistics == null ? void 0 : classStatistics.properties[propertyId],
shaderDestination: ShaderDestination_default.BOTH
};
}
return infoArray;
}
function getPropertyTexturesInfo(propertyTextures, statistics2) {
if (!defined_default(propertyTextures)) {
return [];
}
return propertyTextures.flatMap(
(propertyTexture) => getPropertyTextureInfo(propertyTexture, statistics2)
);
}
function getPropertyTextureInfo(propertyTexture, statistics2) {
const { sanitizeGlslIdentifier } = ModelUtility_default;
const classId = propertyTexture.class.id;
const classStatistics = statistics2 == null ? void 0 : statistics2.classes[classId];
const propertiesArray = Object.entries(
propertyTexture.properties
).filter(([id, property]) => property.isGpuCompatible());
const infoArray = new Array(propertiesArray.length);
for (let i = 0; i < propertiesArray.length; i++) {
const [propertyId, property] = propertiesArray[i];
infoArray[i] = {
metadataVariable: sanitizeGlslIdentifier(propertyId),
property,
type: property.classProperty.type,
glslType: property.getGlslType(),
propertyStatistics: classStatistics == null ? void 0 : classStatistics.properties[propertyId],
shaderDestination: ShaderDestination_default.FRAGMENT
};
}
return infoArray;
}
function declareMetadataTypeStructs(shaderBuilder, propertyInfos) {
const classTypes = /* @__PURE__ */ new Set();
const statisticsTypes = /* @__PURE__ */ new Set();
for (let i = 0; i < propertyInfos.length; i++) {
const { type, glslType, propertyStatistics } = propertyInfos[i];
classTypes.add(glslType);
if (!defined_default(propertyStatistics)) {
continue;
}
if (type !== MetadataType_default.ENUM) {
statisticsTypes.add(glslType);
}
}
const classFields = MetadataPipelineStage.METADATA_CLASS_FIELDS;
for (const metadataType of classTypes) {
const classStructName = `${metadataType}MetadataClass`;
declareTypeStruct(classStructName, metadataType, classFields);
}
const statisticsFields = MetadataPipelineStage.METADATA_STATISTICS_FIELDS;
for (const metadataType of statisticsTypes) {
const statisticsStructName = `${metadataType}MetadataStatistics`;
declareTypeStruct(statisticsStructName, metadataType, statisticsFields);
}
function declareTypeStruct(structName, type, fields) {
shaderBuilder.addStruct(structName, structName, ShaderDestination_default.BOTH);
for (let i = 0; i < fields.length; i++) {
const { shaderName } = fields[i];
const shaderType = fields[i].type === "float" ? convertToFloatComponents(type) : type;
shaderBuilder.addStructField(structName, shaderType, shaderName);
}
}
}
var floatConversions = {
int: "float",
ivec2: "vec2",
ivec3: "vec3",
ivec4: "vec4"
};
function convertToFloatComponents(type) {
const converted = floatConversions[type];
return defined_default(converted) ? converted : type;
}
function declareStructsAndFunctions2(shaderBuilder) {
shaderBuilder.addStruct(
MetadataPipelineStage.STRUCT_ID_METADATA_VS,
MetadataPipelineStage.STRUCT_NAME_METADATA,
ShaderDestination_default.VERTEX
);
shaderBuilder.addStruct(
MetadataPipelineStage.STRUCT_ID_METADATA_FS,
MetadataPipelineStage.STRUCT_NAME_METADATA,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addStruct(
MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_VS,
MetadataPipelineStage.STRUCT_NAME_METADATA_CLASS,
ShaderDestination_default.VERTEX
);
shaderBuilder.addStruct(
MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_FS,
MetadataPipelineStage.STRUCT_NAME_METADATA_CLASS,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addStruct(
MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_VS,
MetadataPipelineStage.STRUCT_NAME_METADATA_STATISTICS,
ShaderDestination_default.VERTEX
);
shaderBuilder.addStruct(
MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_FS,
MetadataPipelineStage.STRUCT_NAME_METADATA_STATISTICS,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFunction(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS,
MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA,
ShaderDestination_default.VERTEX
);
shaderBuilder.addFunction(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
MetadataPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_METADATA,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFunction(
MetadataPipelineStage.FUNCTION_ID_SET_METADATA_VARYINGS,
MetadataPipelineStage.FUNCTION_SIGNATURE_SET_METADATA_VARYINGS,
ShaderDestination_default.VERTEX
);
}
function processPropertyAttributeProperty(renderResources, propertyInfo) {
addPropertyAttributePropertyMetadata(renderResources, propertyInfo);
addPropertyMetadataClass(renderResources.shaderBuilder, propertyInfo);
addPropertyMetadataStatistics(renderResources.shaderBuilder, propertyInfo);
}
function addPropertyAttributePropertyMetadata(renderResources, propertyInfo) {
const { shaderBuilder } = renderResources;
const { metadataVariable, property, glslType } = propertyInfo;
const valueExpression = addValueTransformUniforms({
valueExpression: `attributes.${propertyInfo.variableName}`,
renderResources,
glslType,
metadataVariable,
shaderDestination: ShaderDestination_default.BOTH,
property
});
shaderBuilder.addStructField(
MetadataPipelineStage.STRUCT_ID_METADATA_VS,
glslType,
metadataVariable
);
shaderBuilder.addStructField(
MetadataPipelineStage.STRUCT_ID_METADATA_FS,
glslType,
metadataVariable
);
const initializationLine = `metadata.${metadataVariable} = ${valueExpression};`;
shaderBuilder.addFunctionLines(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS,
[initializationLine]
);
shaderBuilder.addFunctionLines(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
[initializationLine]
);
}
function processPropertyTextureProperty(renderResources, propertyInfo) {
addPropertyTexturePropertyMetadata(renderResources, propertyInfo);
addPropertyMetadataClass(renderResources.shaderBuilder, propertyInfo);
addPropertyMetadataStatistics(renderResources.shaderBuilder, propertyInfo);
}
function addPropertyTexturePropertyMetadata(renderResources, propertyInfo) {
const { shaderBuilder, uniformMap: uniformMap2 } = renderResources;
const { metadataVariable, glslType, property } = propertyInfo;
const { texCoord, channels, index, texture } = property.textureReader;
const textureUniformName = `u_propertyTexture_${index}`;
if (!uniformMap2.hasOwnProperty(textureUniformName)) {
shaderBuilder.addUniform(
"sampler2D",
textureUniformName,
ShaderDestination_default.FRAGMENT
);
uniformMap2[textureUniformName] = () => texture;
}
shaderBuilder.addStructField(
MetadataPipelineStage.STRUCT_ID_METADATA_FS,
glslType,
metadataVariable
);
const texCoordVariable = `attributes.texCoord_${texCoord}`;
const valueExpression = `texture(${textureUniformName}, ${texCoordVariable}).${channels}`;
const unpackedValue = property.unpackInShader(valueExpression);
const transformedValue = addValueTransformUniforms({
valueExpression: unpackedValue,
renderResources,
glslType,
metadataVariable,
shaderDestination: ShaderDestination_default.FRAGMENT,
property
});
const initializationLine = `metadata.${metadataVariable} = ${transformedValue};`;
shaderBuilder.addFunctionLines(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
[initializationLine]
);
}
function addPropertyMetadataClass(shaderBuilder, propertyInfo) {
const { classProperty } = propertyInfo.property;
const { metadataVariable, glslType, shaderDestination } = propertyInfo;
const assignments = getStructAssignments(
MetadataPipelineStage.METADATA_CLASS_FIELDS,
classProperty,
`metadataClass.${metadataVariable}`,
glslType
);
const metadataType = `${glslType}MetadataClass`;
shaderBuilder.addStructField(
MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_FS,
metadataType,
metadataVariable
);
shaderBuilder.addFunctionLines(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
assignments
);
if (!ShaderDestination_default.includesVertexShader(shaderDestination)) {
return;
}
shaderBuilder.addStructField(
MetadataPipelineStage.STRUCT_ID_METADATA_CLASS_VS,
metadataType,
metadataVariable
);
shaderBuilder.addFunctionLines(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS,
assignments
);
}
function addPropertyMetadataStatistics(shaderBuilder, propertyInfo) {
const { propertyStatistics } = propertyInfo;
if (!defined_default(propertyStatistics)) {
return;
}
const { metadataVariable, type, glslType } = propertyInfo;
if (type === MetadataType_default.ENUM) {
return;
}
const fields = MetadataPipelineStage.METADATA_STATISTICS_FIELDS;
const struct = `metadataStatistics.${metadataVariable}`;
const assignments = getStructAssignments(
fields,
propertyStatistics,
struct,
glslType
);
const statisticsType = `${glslType}MetadataStatistics`;
shaderBuilder.addStructField(
MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_FS,
statisticsType,
metadataVariable
);
shaderBuilder.addFunctionLines(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_FS,
assignments
);
if (!ShaderDestination_default.includesVertexShader(propertyInfo.shaderDestination)) {
return;
}
shaderBuilder.addStructField(
MetadataPipelineStage.STRUCT_ID_METADATA_STATISTICS_VS,
statisticsType,
metadataVariable
);
shaderBuilder.addFunctionLines(
MetadataPipelineStage.FUNCTION_ID_INITIALIZE_METADATA_VS,
assignments
);
}
function getStructAssignments(fieldNames, values, struct, type) {
function constructAssignment(field) {
const value = values[field.specName];
if (defined_default(value)) {
return `${struct}.${field.shaderName} = ${type}(${value});`;
}
}
return defined_default(values) ? fieldNames.map(constructAssignment).filter(defined_default) : [];
}
function addValueTransformUniforms(options) {
const { valueExpression, property } = options;
if (!property.hasValueTransform) {
return valueExpression;
}
const metadataVariable = options.metadataVariable;
const offsetUniformName = `u_${metadataVariable}_offset`;
const scaleUniformName = `u_${metadataVariable}_scale`;
const { shaderBuilder, uniformMap: uniformMap2 } = options.renderResources;
const { glslType, shaderDestination } = options;
shaderBuilder.addUniform(glslType, offsetUniformName, shaderDestination);
shaderBuilder.addUniform(glslType, scaleUniformName, shaderDestination);
const { offset: offset2, scale } = property;
uniformMap2[offsetUniformName] = () => offset2;
uniformMap2[scaleUniformName] = () => scale;
return `czm_valueTransform(${offsetUniformName}, ${scaleUniformName}, ${valueExpression})`;
}
var MetadataPipelineStage_default = MetadataPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/CustomShaderTranslucencyMode.js
var CustomShaderTranslucencyMode = {
INHERIT: 0,
OPAQUE: 1,
TRANSLUCENT: 2
};
var CustomShaderTranslucencyMode_default = Object.freeze(CustomShaderTranslucencyMode);
// node_modules/@cesium/engine/Source/Scene/Model/CustomShaderPipelineStage.js
var CustomShaderPipelineStage = {
name: "CustomShaderPipelineStage",
STRUCT_ID_ATTRIBUTES_VS: "AttributesVS",
STRUCT_ID_ATTRIBUTES_FS: "AttributesFS",
STRUCT_NAME_ATTRIBUTES: "Attributes",
STRUCT_ID_VERTEX_INPUT: "VertexInput",
STRUCT_NAME_VERTEX_INPUT: "VertexInput",
STRUCT_ID_FRAGMENT_INPUT: "FragmentInput",
STRUCT_NAME_FRAGMENT_INPUT: "FragmentInput",
FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS: "initializeInputStructVS",
FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS: "void initializeInputStruct(out VertexInput vsInput, ProcessedAttributes attributes)",
FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS: "initializeInputStructFS",
FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS: "void initializeInputStruct(out FragmentInput fsInput, ProcessedAttributes attributes)",
_oneTimeWarning: oneTimeWarning_default
};
CustomShaderPipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const customShader = renderResources.model.customShader;
if (defined_default(customShader.lightingModel)) {
renderResources.lightingOptions.lightingModel = customShader.lightingModel;
}
const alphaOptions = renderResources.alphaOptions;
if (customShader.translucencyMode === CustomShaderTranslucencyMode_default.TRANSLUCENT) {
alphaOptions.pass = Pass_default.TRANSLUCENT;
} else if (customShader.translucencyMode === CustomShaderTranslucencyMode_default.OPAQUE) {
alphaOptions.pass = void 0;
}
const generatedCode = generateShaderLines(customShader, primitive);
if (!generatedCode.customShaderEnabled) {
return;
}
addLinesToShader(shaderBuilder, customShader, generatedCode);
if (generatedCode.shouldComputePositionWC) {
shaderBuilder.addDefine(
"COMPUTE_POSITION_WC_CUSTOM_SHADER",
void 0,
ShaderDestination_default.BOTH
);
}
if (defined_default(customShader.vertexShaderText)) {
shaderBuilder.addDefine(
"HAS_CUSTOM_VERTEX_SHADER",
void 0,
ShaderDestination_default.VERTEX
);
}
if (defined_default(customShader.fragmentShaderText)) {
shaderBuilder.addDefine(
"HAS_CUSTOM_FRAGMENT_SHADER",
void 0,
ShaderDestination_default.FRAGMENT
);
const shaderModeDefine = CustomShaderMode_default.getDefineName(customShader.mode);
shaderBuilder.addDefine(
shaderModeDefine,
void 0,
ShaderDestination_default.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_default(
renderResources.uniformMap,
customShader.uniformMap
);
};
function getAttributesByName(attributes) {
const names = {};
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
const attributeInfo = ModelUtility_default.getAttributeInfo(attribute);
names[attributeInfo.variableName] = attributeInfo;
}
return names;
}
var attributeTypeLUT = {
position: "vec3",
normal: "vec3",
tangent: "vec3",
bitangent: "vec3",
texCoord: "vec2",
color: "vec4",
joints: "ivec4",
weights: "vec4"
};
var 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) {
let trimmed = attributeName.replace(/_[0-9]+$/, "");
trimmed = trimmed.replace(/(MC|EC)$/, "");
const glslType = attributeTypeLUT[trimmed];
const value = attributeDefaultValueLUT[trimmed];
if (!defined_default(glslType)) {
return void 0;
}
return {
attributeField: [glslType, attributeName],
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);
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_default(attributeDefaults)) {
CustomShaderPipelineStage._oneTimeWarning(
"CustomShaderPipelineStage.incompatiblePrimitiveVS",
`Primitive is missing attribute ${variableName}, disabling custom 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;
if (usedVariables.hasOwnProperty("positionWC")) {
attributeFields.push(["vec3", "positionWC"]);
initializationLines.push(
"fsInput.attributes.positionWC = attributes.positionWC;"
);
}
if (usedVariables.hasOwnProperty("positionEC")) {
attributeFields.push(["vec3", "positionEC"]);
initializationLines.push(
"fsInput.attributes.positionEC = attributes.positionEC;"
);
}
return {
attributeFields,
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);
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_default(attributeDefaults)) {
CustomShaderPipelineStage._oneTimeWarning(
"CustomShaderPipelineStage.incompatiblePrimitiveFS",
`Primitive is missing attribute ${variableName}, disabling custom fragment shader.`
);
return;
}
attributeFields.push(attributeDefaults.attributeField);
fragmentInitialization = `fsInput.attributes.${variableName} = ${attributeDefaults.value};`;
initializationLines.push(fragmentInitialization);
}
const positionBuiltins = generatePositionBuiltins(customShader);
fragmentLines.enabled = true;
fragmentLines.attributeFields = attributeFields.concat(
positionBuiltins.attributeFields
);
fragmentLines.initializationLines = positionBuiltins.initializationLines.concat(
initializationLines
);
}
var builtinAttributes = {
positionWC: true,
positionEC: true
};
function partitionAttributes(primitiveAttributes, shaderAttributeSet, isFragmentShader) {
let renamed;
let attributeName;
const addToShader = {};
for (attributeName in primitiveAttributes) {
if (primitiveAttributes.hasOwnProperty(attributeName)) {
const attribute = primitiveAttributes[attributeName];
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)) {
continue;
}
renamed = attributeName;
if (isFragmentShader && attributeName === "normalEC") {
renamed = "normalMC";
} else if (isFragmentShader && attributeName === "tangentEC") {
renamed = "tangentMC";
}
if (!primitiveAttributes.hasOwnProperty(renamed)) {
missingAttributes.push(attributeName);
}
}
}
return {
addToShader,
missingAttributes
};
}
function generateShaderLines(customShader, primitive) {
const vertexLines = {
enabled: false
};
const fragmentLines = {
enabled: false
};
const attributesByName = getAttributesByName(primitive.attributes);
if (defined_default(customShader.vertexShaderText)) {
generateVertexShaderLines(customShader, attributesByName, vertexLines);
}
if (defined_default(customShader.fragmentShaderText)) {
generateFragmentShaderLines(customShader, attributesByName, fragmentLines);
}
const attributeSetFS = customShader.usedVariablesFragment.attributeSet;
const shouldComputePositionWC = attributeSetFS.hasOwnProperty("positionWC") && fragmentLines.enabled;
return {
vertexLines,
fragmentLines,
vertexLinesEnabled: vertexLines.enabled,
fragmentLinesEnabled: fragmentLines.enabled,
customShaderEnabled: vertexLines.enabled || fragmentLines.enabled,
shouldComputePositionWC
};
}
function addVertexLinesToShader(shaderBuilder, vertexLines) {
let i;
let structId = CustomShaderPipelineStage.STRUCT_ID_ATTRIBUTES_VS;
shaderBuilder.addStruct(
structId,
CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES,
ShaderDestination_default.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);
}
structId = CustomShaderPipelineStage.STRUCT_ID_VERTEX_INPUT;
shaderBuilder.addStruct(
structId,
CustomShaderPipelineStage.STRUCT_NAME_VERTEX_INPUT,
ShaderDestination_default.VERTEX
);
shaderBuilder.addStructField(
structId,
CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES,
"attributes"
);
shaderBuilder.addStructField(
structId,
FeatureIdPipelineStage_default.STRUCT_NAME_FEATURE_IDS,
"featureIds"
);
shaderBuilder.addStructField(
structId,
MetadataPipelineStage_default.STRUCT_NAME_METADATA,
"metadata"
);
shaderBuilder.addStructField(
structId,
MetadataPipelineStage_default.STRUCT_NAME_METADATA_CLASS,
"metadataClass"
);
shaderBuilder.addStructField(
structId,
MetadataPipelineStage_default.STRUCT_NAME_METADATA_STATISTICS,
"metadataStatistics"
);
const functionId = CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_VS;
shaderBuilder.addFunction(
functionId,
CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_VS,
ShaderDestination_default.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_default.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_default.FRAGMENT
);
shaderBuilder.addStructField(
structId,
CustomShaderPipelineStage.STRUCT_NAME_ATTRIBUTES,
"attributes"
);
shaderBuilder.addStructField(
structId,
FeatureIdPipelineStage_default.STRUCT_NAME_FEATURE_IDS,
"featureIds"
);
shaderBuilder.addStructField(
structId,
MetadataPipelineStage_default.STRUCT_NAME_METADATA,
"metadata"
);
shaderBuilder.addStructField(
structId,
MetadataPipelineStage_default.STRUCT_NAME_METADATA_CLASS,
"metadataClass"
);
shaderBuilder.addStructField(
structId,
MetadataPipelineStage_default.STRUCT_NAME_METADATA_STATISTICS,
"metadataStatistics"
);
const functionId = CustomShaderPipelineStage.FUNCTION_ID_INITIALIZE_INPUT_STRUCT_FS;
shaderBuilder.addFunction(
functionId,
CustomShaderPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_INPUT_STRUCT_FS,
ShaderDestination_default.FRAGMENT
);
const initializationLines = fragmentLines.initializationLines;
shaderBuilder.addFunctionLines(functionId, initializationLines);
}
var scratchShaderLines = [];
function addLinesToShader(shaderBuilder, customShader, generatedCode) {
const vertexLines = generatedCode.vertexLines;
const shaderLines = scratchShaderLines;
if (vertexLines.enabled) {
addVertexLinesToShader(shaderBuilder, vertexLines);
shaderLines.length = 0;
shaderLines.push(
"#line 0",
customShader.vertexShaderText,
CustomShaderStageVS_default
);
shaderBuilder.addVertexLines(shaderLines);
}
const fragmentLines = generatedCode.fragmentLines;
if (fragmentLines.enabled) {
addFragmentLinesToShader(shaderBuilder, fragmentLines);
shaderLines.length = 0;
shaderLines.push(
"#line 0",
customShader.fragmentShaderText,
CustomShaderStageFS_default
);
shaderBuilder.addFragmentLines(shaderLines);
}
}
var CustomShaderPipelineStage_default = CustomShaderPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/DequantizationPipelineStage.js
var DequantizationPipelineStage = {
name: "DequantizationPipelineStage",
FUNCTION_ID_DEQUANTIZATION_STAGE_VS: "dequantizationStage",
FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS: "void dequantizationStage(inout ProcessedAttributes attributes)"
};
DequantizationPipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const model = renderResources.model;
const hasClassification = defined_default(model.classificationType);
shaderBuilder.addDefine(
"USE_DEQUANTIZATION",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addFunction(
DequantizationPipelineStage.FUNCTION_ID_DEQUANTIZATION_STAGE_VS,
DequantizationPipelineStage.FUNCTION_SIGNATURE_DEQUANTIZATION_STAGE_VS,
ShaderDestination_default.VERTEX
);
const attributes = primitive.attributes;
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes[i];
const quantization = attribute.quantization;
if (!defined_default(quantization)) {
continue;
}
const isPositionAttribute = attribute.semantic === VertexAttributeSemantic_default.POSITION;
const isTexcoordAttribute = attribute.semantic === VertexAttributeSemantic_default.TEXCOORD;
if (hasClassification && !isPositionAttribute && !isTexcoordAttribute) {
continue;
}
const attributeInfo = ModelUtility_default.getAttributeInfo(attribute);
updateDequantizationFunction(shaderBuilder, attributeInfo);
addDequantizationUniforms(renderResources, attributeInfo);
}
};
function addDequantizationUniforms(renderResources, attributeInfo) {
const shaderBuilder = renderResources.shaderBuilder;
const uniformMap2 = renderResources.uniformMap;
const variableName = attributeInfo.variableName;
const quantization = attributeInfo.attribute.quantization;
if (quantization.octEncoded) {
const normalizationRange = `model_normalizationRange_${variableName}`;
shaderBuilder.addUniform(
"float",
normalizationRange,
ShaderDestination_default.VERTEX
);
uniformMap2[normalizationRange] = function() {
return quantization.normalizationRange;
};
} else {
const offset2 = `model_quantizedVolumeOffset_${variableName}`;
const stepSize = `model_quantizedVolumeStepSize_${variableName}`;
const glslType = attributeInfo.glslType;
shaderBuilder.addUniform(glslType, offset2, ShaderDestination_default.VERTEX);
shaderBuilder.addUniform(glslType, stepSize, ShaderDestination_default.VERTEX);
let quantizedVolumeOffset = quantization.quantizedVolumeOffset;
let quantizedVolumeStepSize = quantization.quantizedVolumeStepSize;
if (/^color_\d+$/.test(variableName)) {
quantizedVolumeOffset = promoteToVec4(quantizedVolumeOffset, 0);
quantizedVolumeStepSize = promoteToVec4(quantizedVolumeStepSize, 1);
}
uniformMap2[offset2] = function() {
return quantizedVolumeOffset;
};
uniformMap2[stepSize] = function() {
return quantizedVolumeStepSize;
};
}
}
function promoteToVec4(value, defaultAlpha) {
if (value instanceof Cartesian4_default) {
return value;
}
return new Cartesian4_default(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}`;
const swizzle = quantization.octEncodedZXY ? ".zxy" : ".xyz";
return `${structField} = czm_octDecode(${quantizedAttribute}, ${normalizationRange})${swizzle};`;
}
function generateDequantizeLine(variableName) {
const structField = `attributes.${variableName}`;
const quantizedAttribute = `a_quantized_${variableName}`;
const offset2 = `model_quantizedVolumeOffset_${variableName}`;
const stepSize = `model_quantizedVolumeStepSize_${variableName}`;
return `${structField} = ${offset2} + ${quantizedAttribute} * ${stepSize};`;
}
var DequantizationPipelineStage_default = DequantizationPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/GeometryStageFS.js
var GeometryStageFS_default = "void geometryStage(out ProcessedAttributes attributes)\n{\n attributes.positionMC = v_positionMC;\n attributes.positionEC = v_positionEC;\n\n #ifdef COMPUTE_POSITION_WC_CUSTOM_SHADER\n attributes.positionWC = v_positionWC;\n #endif\n\n #ifdef HAS_NORMALS\n // renormalize after interpolation\n attributes.normalEC = normalize(v_normalEC);\n #endif\n\n #ifdef HAS_TANGENTS\n attributes.tangentEC = normalize(v_tangentEC);\n #endif\n\n #ifdef HAS_BITANGENTS\n attributes.bitangentEC = normalize(v_bitangentEC);\n #endif\n\n // Everything else is dynamically generated in GeometryPipelineStage\n setDynamicVaryings(attributes);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/GeometryStageVS.js
var GeometryStageVS_default = "vec4 geometryStage(inout ProcessedAttributes attributes, mat4 modelView, mat3 normal) \n{\n vec4 computedPosition;\n\n // Compute positions in different coordinate systems\n vec3 positionMC = attributes.positionMC;\n v_positionMC = positionMC;\n v_positionEC = (modelView * vec4(positionMC, 1.0)).xyz;\n\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 computedPosition = czm_projection * vec4(positionEC, 1.0);\n #else\n computedPosition = czm_projection * vec4(v_positionEC, 1.0);\n #endif\n\n // Sometimes the custom shader and/or style needs this\n #if defined(COMPUTE_POSITION_WC_CUSTOM_SHADER) || defined(COMPUTE_POSITION_WC_STYLE)\n // Note that this is a 32-bit position which may result in jitter on small\n // scales.\n v_positionWC = (czm_model * vec4(positionMC, 1.0)).xyz;\n #endif\n\n #ifdef HAS_NORMALS\n v_normalEC = normalize(normal * attributes.normalMC);\n #endif\n\n #ifdef HAS_TANGENTS\n v_tangentEC = normalize(normal * attributes.tangentMC); \n #endif\n\n #ifdef HAS_BITANGENTS\n v_bitangentEC = normalize(normal * attributes.bitangentMC);\n #endif\n\n // All other varyings need to be dynamically generated in\n // GeometryPipelineStage\n setDynamicVaryings(attributes);\n \n return computedPosition;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/SelectedFeatureIdStageCommon.js
var SelectedFeatureIdStageCommon_default = "vec2 computeSt(float featureId)\n{\n float stepX = model_textureStep.x;\n float centerX = model_textureStep.y;\n\n #ifdef MULTILINE_BATCH_TEXTURE\n float stepY = model_textureStep.z;\n float centerY = model_textureStep.w;\n\n float xId = mod(featureId, model_textureDimensions.x); \n float yId = floor(featureId / model_textureDimensions.x);\n \n return vec2(centerX + (xId * stepX), centerY + (yId * stepY));\n #else\n return vec2(centerX + (featureId * stepX), 0.5);\n #endif\n}\n\nvoid selectedFeatureIdStage(out SelectedFeature feature, FeatureIds featureIds)\n{ \n int featureId = featureIds.SELECTED_FEATURE_ID;\n\n\n if (featureId < model_featuresLength)\n {\n vec2 featureSt = computeSt(float(featureId));\n\n feature.id = featureId;\n feature.st = featureSt;\n feature.color = texture(model_batchTexture, featureSt);\n }\n // Floating point comparisons can be unreliable in GLSL, so we\n // increment the feature ID to make sure it's always greater\n // then the model_featuresLength - a condition we check for in the\n // pick ID, to avoid sampling the pick texture if the feature ID is\n // greater than the number of features.\n else\n {\n feature.id = model_featuresLength + 1;\n feature.st = vec2(0.0);\n feature.color = vec4(1.0);\n }\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";
// node_modules/@cesium/engine/Source/Scene/Model/SelectedFeatureIdPipelineStage.js
var SelectedFeatureIdPipelineStage = {
name: "SelectedFeatureIdPipelineStage",
STRUCT_ID_SELECTED_FEATURE: "SelectedFeature",
STRUCT_NAME_SELECTED_FEATURE: "SelectedFeature",
FUNCTION_ID_FEATURE_VARYINGS_VS: "updateFeatureStructVS",
FUNCTION_ID_FEATURE_VARYINGS_FS: "updateFeatureStructFS",
FUNCTION_SIGNATURE_UPDATE_FEATURE: "void updateFeatureStruct(inout SelectedFeature feature)"
};
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",
void 0,
shaderDestination
);
shaderBuilder.addDefine(
"SELECTED_FEATURE_ID",
selectedFeatureIds.variableName,
shaderDestination
);
shaderBuilder.addDefine(
selectedFeatureIds.featureIdDefine,
void 0,
shaderDestination
);
updateFeatureStruct(shaderBuilder);
const nullFeatureId = selectedFeatureIds.featureIds.nullFeatureId;
const uniformMap2 = renderResources.uniformMap;
if (defined_default(nullFeatureId)) {
shaderBuilder.addDefine(
"HAS_NULL_FEATURE_ID",
void 0,
shaderDestination
);
shaderBuilder.addUniform("int", "model_nullFeatureId", shaderDestination);
uniformMap2.model_nullFeatureId = function() {
return nullFeatureId;
};
}
if (selectedFeatureIds.shaderDestination === ShaderDestination_default.BOTH) {
shaderBuilder.addVertexLines(SelectedFeatureIdStageCommon_default);
}
shaderBuilder.addFragmentLines(SelectedFeatureIdStageCommon_default);
};
function getFeatureIdDefine(featureIds) {
if (featureIds instanceof ModelComponents_default.FeatureIdTexture) {
return "HAS_SELECTED_FEATURE_ID_TEXTURE";
}
return "HAS_SELECTED_FEATURE_ID_ATTRIBUTE";
}
function getShaderDestination(featureIds) {
if (featureIds instanceof ModelComponents_default.FeatureIdTexture) {
return ShaderDestination_default.FRAGMENT;
}
return ShaderDestination_default.BOTH;
}
function getSelectedFeatureIds(model, node, primitive) {
let variableName;
let featureIds;
if (defined_default(node.instances)) {
featureIds = ModelUtility_default.getFeatureIdsByLabel(
node.instances.featureIds,
model.instanceFeatureIdLabel
);
if (defined_default(featureIds)) {
variableName = defaultValue_default(featureIds.label, featureIds.positionalLabel);
return {
featureIds,
variableName,
shaderDestination: getShaderDestination(featureIds),
featureIdDefine: getFeatureIdDefine(featureIds)
};
}
}
featureIds = ModelUtility_default.getFeatureIdsByLabel(
primitive.featureIds,
model.featureIdLabel
);
variableName = defaultValue_default(featureIds.label, featureIds.positionalLabel);
return {
featureIds,
variableName,
shaderDestination: getShaderDestination(featureIds),
featureIdDefine: getFeatureIdDefine(featureIds)
};
}
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"
);
}
var SelectedFeatureIdPipelineStage_default = SelectedFeatureIdPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/GeometryPipelineStage.js
var GeometryPipelineStage = {
name: "GeometryPipelineStage",
STRUCT_ID_PROCESSED_ATTRIBUTES_VS: "ProcessedAttributesVS",
STRUCT_ID_PROCESSED_ATTRIBUTES_FS: "ProcessedAttributesFS",
STRUCT_NAME_PROCESSED_ATTRIBUTES: "ProcessedAttributes",
FUNCTION_ID_INITIALIZE_ATTRIBUTES: "initializeAttributes",
FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES: "void initializeAttributes(out ProcessedAttributes attributes)",
FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS: "setDynamicVaryingsVS",
FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS: "setDynamicVaryingsFS",
FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS: "void setDynamicVaryings(inout ProcessedAttributes attributes)"
};
GeometryPipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const model = renderResources.model;
shaderBuilder.addStruct(
GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_VS,
"ProcessedAttributes",
ShaderDestination_default.VERTEX
);
shaderBuilder.addStruct(
GeometryPipelineStage.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,
"ProcessedAttributes",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addStruct(
SelectedFeatureIdPipelineStage_default.STRUCT_ID_SELECTED_FEATURE,
SelectedFeatureIdPipelineStage_default.STRUCT_NAME_SELECTED_FEATURE,
ShaderDestination_default.BOTH
);
shaderBuilder.addFunction(
GeometryPipelineStage.FUNCTION_ID_INITIALIZE_ATTRIBUTES,
GeometryPipelineStage.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES,
ShaderDestination_default.VERTEX
);
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"
);
shaderBuilder.addFunction(
GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS,
GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS,
ShaderDestination_default.VERTEX
);
shaderBuilder.addFunction(
GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS,
GeometryPipelineStage.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS,
ShaderDestination_default.FRAGMENT
);
const modelType = model.type;
if (modelType === ModelType_default.TILE_PNTS) {
shaderBuilder.addDefine(
"HAS_SRGB_COLOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const use2D = frameState.mode !== SceneMode_default.SCENE3D && !frameState.scene3DOnly && model._projectTo2D;
const instanced = defined_default(renderResources.runtimeNode.node.instances);
const incrementIndexFor2D = use2D && !instanced;
const length3 = primitive.attributes.length;
for (let i = 0; i < length3; i++) {
const attribute = primitive.attributes[i];
const attributeLocationCount = AttributeType_default.getAttributeLocationCount(
attribute.type
);
if (!defined_default(attribute.buffer) && !defined_default(attribute.constant)) {
throw new DeveloperError_default(
"Attributes must be provided as a Buffer or constant value"
);
}
const isPositionAttribute = attribute.semantic === VertexAttributeSemantic_default.POSITION;
let index;
if (attributeLocationCount > 1) {
index = renderResources.attributeIndex;
renderResources.attributeIndex += attributeLocationCount;
} else if (isPositionAttribute && !incrementIndexFor2D) {
index = 0;
} else {
index = renderResources.attributeIndex++;
}
processAttribute2(
renderResources,
attribute,
index,
attributeLocationCount,
use2D,
instanced
);
}
handleBitangents(shaderBuilder, primitive.attributes);
if (primitive.primitiveType === PrimitiveType_default.POINTS) {
shaderBuilder.addDefine("PRIMITIVE_TYPE_POINTS");
}
shaderBuilder.addVertexLines(GeometryStageVS_default);
shaderBuilder.addFragmentLines(GeometryStageFS_default);
};
function processAttribute2(renderResources, attribute, attributeIndex, attributeLocationCount, use2D, instanced) {
const shaderBuilder = renderResources.shaderBuilder;
const attributeInfo = ModelUtility_default.getAttributeInfo(attribute);
const modifyFor2D = use2D && !instanced;
if (attributeLocationCount > 1) {
addMatrixAttributeToRenderResources(
renderResources,
attribute,
attributeIndex,
attributeLocationCount
);
} else {
addAttributeToRenderResources(
renderResources,
attribute,
attributeIndex,
modifyFor2D
);
}
addAttributeDeclaration(shaderBuilder, attributeInfo, modifyFor2D);
addVaryingDeclaration(shaderBuilder, attributeInfo);
if (defined_default(attribute.semantic)) {
addSemanticDefine(shaderBuilder, attribute);
}
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_default.NORMAL:
shaderBuilder.addDefine("HAS_NORMALS");
break;
case VertexAttributeSemantic_default.TANGENT:
shaderBuilder.addDefine("HAS_TANGENTS");
break;
case VertexAttributeSemantic_default.FEATURE_ID:
shaderBuilder.addDefine(`HAS${semantic}_${setIndex}`);
break;
case VertexAttributeSemantic_default.TEXCOORD:
case VertexAttributeSemantic_default.COLOR:
shaderBuilder.addDefine(`HAS_${semantic}_${setIndex}`);
}
}
function addAttributeToRenderResources(renderResources, attribute, attributeIndex, modifyFor2D) {
const quantization = attribute.quantization;
let type;
let componentDatatype;
if (defined_default(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_default.FEATURE_ID && setIndex >= renderResources.featureIdVertexAttributeSetIndex) {
renderResources.featureIdVertexAttributeSetIndex = setIndex + 1;
}
const isPositionAttribute = semantic === VertexAttributeSemantic_default.POSITION;
const index = isPositionAttribute ? 0 : attributeIndex;
const componentsPerAttribute = AttributeType_default.getNumberOfComponents(type);
const vertexAttribute = {
index,
value: defined_default(attribute.buffer) ? void 0 : attribute.constant,
vertexBuffer: attribute.buffer,
count: attribute.count,
componentsPerAttribute,
componentDatatype,
offsetInBytes: attribute.byteOffset,
strideInBytes: attribute.byteStride,
normalize: attribute.normalized
};
renderResources.attributes.push(vertexAttribute);
if (!isPositionAttribute || !modifyFor2D) {
return;
}
const buffer2D = renderResources.runtimePrimitive.positionBuffer2D;
const positionAttribute2D = {
index: attributeIndex,
vertexBuffer: buffer2D,
count: attribute.count,
componentsPerAttribute,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: 0,
strideInBytes: void 0,
normalize: attribute.normalized
};
renderResources.attributes.push(positionAttribute2D);
}
function addMatrixAttributeToRenderResources(renderResources, attribute, attributeIndex, columnCount) {
const quantization = attribute.quantization;
let type;
let componentDatatype;
if (defined_default(quantization)) {
type = quantization.type;
componentDatatype = quantization.componentDatatype;
} else {
type = attribute.type;
componentDatatype = attribute.componentDatatype;
}
const normalized = attribute.normalized;
const componentCount = AttributeType_default.getNumberOfComponents(type);
const componentsPerColumn = componentCount / columnCount;
const componentSizeInBytes = ComponentDatatype_default.getSizeInBytes(
componentDatatype
);
const columnLengthInBytes = componentsPerColumn * componentSizeInBytes;
const strideInBytes = attribute.byteStride;
for (let i = 0; i < columnCount; i++) {
const offsetInBytes = attribute.byteOffset + i * columnLengthInBytes;
const columnAttribute = {
index: attributeIndex + i,
vertexBuffer: attribute.buffer,
componentsPerAttribute: componentsPerColumn,
componentDatatype,
offsetInBytes,
strideInBytes,
normalize: normalized
};
renderResources.attributes.push(columnAttribute);
}
}
function addVaryingDeclaration(shaderBuilder, attributeInfo) {
const variableName = attributeInfo.variableName;
let varyingName = `v_${variableName}`;
let glslType;
if (variableName === "normalMC") {
varyingName = "v_normalEC";
glslType = attributeInfo.glslType;
} else if (variableName === "tangentMC") {
glslType = "vec3";
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_default.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") {
shaderBuilder.addStructField(vsStructId, "vec3", "tangentMC");
shaderBuilder.addStructField(vsStructId, "float", "tangentSignMC");
shaderBuilder.addStructField(fsStructId, "vec3", "tangentEC");
} else if (variableName === "normalMC") {
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;
const use2DPosition = variableName === "positionMC" && use2D;
if (use2DPosition) {
const line = "attributes.position2D = a_position2D;";
shaderBuilder.addFunctionLines(functionId, [line]);
}
if (attributeInfo.isQuantized) {
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_default(semantic) && !defined_default(setIndex)) {
return;
}
let functionId = GeometryPipelineStage.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS;
const variableName = attributeInfo.variableName;
let line = `v_${variableName} = attributes.${variableName};`;
shaderBuilder.addFunctionLines(functionId, [line]);
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_default.NORMAL) {
hasNormals = true;
} else if (attribute.semantic === VertexAttributeSemantic_default.TANGENT) {
hasTangents = true;
}
}
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"
);
}
var GeometryPipelineStage_default = GeometryPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/LightingStageFS.js
var LightingStageFS_default = "#ifdef LIGHTING_PBR\nvec3 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 \n #ifdef USE_CUSTOM_LIGHT_COLOR\n vec3 lightColorHdr = model_lightColorHdr;\n #else\n vec3 lightColorHdr = czm_lightColorHdr;\n #endif\n\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\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\n color *= inputMaterial.occlusion;\n color += inputMaterial.emissive;\n\n // In HDR mode, the frame buffer is in linear color space. The\n // post-processing stages (see PostProcessStageCollection) will handle\n // tonemapping. However, if HDR is not enabled, we must tonemap else large\n // values may be clamped to 1.0\n #ifndef HDR \n color = czm_acesTonemapping(color);\n #endif \n\n return color;\n}\n#endif\n\nvoid lightingStage(inout czm_modelMaterial material, ProcessedAttributes attributes)\n{\n // Even though the lighting will only set the diffuse color,\n // pass all other properties so further stages have access to them.\n vec3 color = vec3(0.0);\n\n #ifdef LIGHTING_PBR\n color = computePbrLighting(material, attributes);\n #else // unlit\n color = material.diffuse;\n #endif\n\n #ifdef HAS_POINT_CLOUD_COLOR_STYLE\n // The colors resulting from point cloud styles are adjusted differently.\n color = czm_gammaCorrect(color);\n #elif !defined(HDR)\n // If HDR is not enabled, the frame buffer stores sRGB colors rather than\n // linear colors so the linear value must be converted.\n color = czm_linearToSrgb(color);\n #endif\n\n material.diffuse = color;\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/LightingModel.js
var LightingModel = {
UNLIT: 0,
PBR: 1
};
var LightingModel_default = Object.freeze(LightingModel);
// node_modules/@cesium/engine/Source/Scene/Model/LightingPipelineStage.js
var LightingPipelineStage = {
name: "LightingPipelineStage"
};
LightingPipelineStage.process = function(renderResources, primitive) {
const model = renderResources.model;
const lightingOptions = renderResources.lightingOptions;
const shaderBuilder = renderResources.shaderBuilder;
if (defined_default(model.lightColor)) {
shaderBuilder.addDefine(
"USE_CUSTOM_LIGHT_COLOR",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"vec3",
"model_lightColorHdr",
ShaderDestination_default.FRAGMENT
);
const uniformMap2 = renderResources.uniformMap;
uniformMap2.model_lightColorHdr = function() {
return model.lightColor;
};
}
const lightingModel = lightingOptions.lightingModel;
if (lightingModel === LightingModel_default.PBR) {
shaderBuilder.addDefine(
"LIGHTING_PBR",
void 0,
ShaderDestination_default.FRAGMENT
);
} else {
shaderBuilder.addDefine(
"LIGHTING_UNLIT",
void 0,
ShaderDestination_default.FRAGMENT
);
}
shaderBuilder.addFragmentLines(LightingStageFS_default);
};
var LightingPipelineStage_default = LightingPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/MaterialStageFS.js
var MaterialStageFS_default = "// If the style color is white, it implies the feature has not been styled.\nbool isDefaultStyleColor(vec3 color)\n{\n return all(greaterThan(color, vec3(1.0 - czm_epsilon3)));\n}\n\nvec3 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\nvec2 computeTextureTransform(vec2 texCoord, mat3 textureTransform)\n{\n return vec2(textureTransform * vec3(texCoord, 1.0));\n}\n\n#ifdef HAS_NORMALS\nvec3 computeNormal(ProcessedAttributes attributes)\n{\n // Geometry normal. This is already normalized \n vec3 ng = attributes.normalEC;\n\n vec3 normal = ng;\n #if defined(HAS_NORMAL_TEXTURE) && !defined(HAS_WIREFRAME)\n vec2 normalTexCoords = TEXCOORD_NORMAL;\n #ifdef HAS_NORMAL_TEXTURE_TRANSFORM\n normalTexCoords = computeTextureTransform(normalTexCoords, u_normalTextureTransform);\n #endif\n\n // If HAS_BITANGENTS is set, then HAS_TANGENTS is also set\n #ifdef HAS_BITANGENTS\n vec3 t = attributes.tangentEC;\n vec3 b = attributes.bitangentEC;\n mat3 tbn = mat3(t, b, ng);\n vec3 n = texture(u_normalTexture, normalTexCoords).rgb;\n normal = normalize(tbn * (2.0 * n - 1.0));\n #elif (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))\n // If derivatives are available (not IE 10), compute tangents\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 = texture(u_normalTexture, normalTexCoords).rgb;\n normal = normalize(tbn * (2.0 * n - 1.0));\n #endif\n #endif\n\n #ifdef HAS_DOUBLE_SIDED_MATERIAL\n if (czm_backFacing()) {\n normal = -normal;\n }\n #endif\n\n return normal;\n}\n#endif\n\nvoid materialStage(inout czm_modelMaterial material, ProcessedAttributes attributes, SelectedFeature feature)\n{\n #ifdef HAS_NORMALS\n material.normalEC = computeNormal(attributes);\n #endif\n\n vec4 baseColorWithAlpha = vec4(1.0);\n // Regardless of whether we use PBR, set a base color\n #ifdef HAS_BASE_COLOR_TEXTURE\n vec2 baseColorTexCoords = TEXCOORD_BASE_COLOR;\n\n #ifdef HAS_BASE_COLOR_TEXTURE_TRANSFORM\n baseColorTexCoords = computeTextureTransform(baseColorTexCoords, u_baseColorTextureTransform);\n #endif\n\n baseColorWithAlpha = czm_srgbToLinear(texture(u_baseColorTexture, baseColorTexCoords));\n\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\n #ifdef HAS_POINT_CLOUD_COLOR_STYLE\n baseColorWithAlpha = v_pointCloudColor;\n #elif defined(HAS_COLOR_0)\n vec4 color = attributes.color_0;\n // .pnts files store colors in the sRGB color space\n #ifdef HAS_SRGB_COLOR\n color = czm_srgbToLinear(color);\n #endif\n baseColorWithAlpha *= color;\n #endif\n\n material.diffuse = baseColorWithAlpha.rgb;\n material.alpha = baseColorWithAlpha.a;\n\n #ifdef USE_CPU_STYLING\n material.diffuse = blend(material.diffuse, feature.color.rgb, model_colorBlend);\n #endif\n\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 = texture(u_occlusionTexture, occlusionTexCoords).r;\n #endif\n\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\n vec3 emissive = czm_srgbToLinear(texture(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\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\n vec4 specularGlossiness = czm_srgbToLinear(texture(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\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\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\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\n vec4 diffuse = czm_srgbToLinear(texture(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 // the specular glossiness extension's alpha overrides anything set\n // by the base material.\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\n vec3 metallicRoughness = texture(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\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\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";
// node_modules/@cesium/engine/Source/Scene/Model/MaterialPipelineStage.js
var Material4 = ModelComponents_default.Material;
var MetallicRoughness3 = ModelComponents_default.MetallicRoughness;
var SpecularGlossiness3 = ModelComponents_default.SpecularGlossiness;
var MaterialPipelineStage = {
name: "MaterialPipelineStage",
_processTexture: processTexture2,
_processTextureTransform: processTextureTransform
};
MaterialPipelineStage.process = function(renderResources, primitive, frameState) {
const material = primitive.material;
const model = renderResources.model;
const hasClassification = defined_default(model.classificationType);
const disableTextures = hasClassification;
const uniformMap2 = renderResources.uniformMap;
const shaderBuilder = renderResources.shaderBuilder;
const defaultTexture = frameState.context.defaultTexture;
const defaultNormalTexture = frameState.context.defaultNormalTexture;
const defaultEmissiveTexture = frameState.context.defaultEmissiveTexture;
processMaterialUniforms(
material,
uniformMap2,
shaderBuilder,
defaultTexture,
defaultNormalTexture,
defaultEmissiveTexture,
disableTextures
);
if (defined_default(material.specularGlossiness)) {
processSpecularGlossinessUniforms(
material,
uniformMap2,
shaderBuilder,
defaultTexture,
disableTextures
);
} else {
processMetallicRoughnessUniforms(
material,
uniformMap2,
shaderBuilder,
defaultTexture,
disableTextures
);
}
const hasNormals = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.NORMAL
);
const lightingOptions = renderResources.lightingOptions;
if (material.unlit || !hasNormals || hasClassification) {
lightingOptions.lightingModel = LightingModel_default.UNLIT;
} else {
lightingOptions.lightingModel = LightingModel_default.PBR;
}
const cull = model.backFaceCulling && !material.doubleSided;
renderResources.renderStateOptions.cull.enabled = cull;
const alphaOptions = renderResources.alphaOptions;
if (material.alphaMode === AlphaMode_default.BLEND) {
alphaOptions.pass = Pass_default.TRANSLUCENT;
} else if (material.alphaMode === AlphaMode_default.MASK) {
alphaOptions.alphaCutoff = material.alphaCutoff;
}
shaderBuilder.addFragmentLines(MaterialStageFS_default);
if (material.doubleSided) {
shaderBuilder.addDefine(
"HAS_DOUBLE_SIDED_MATERIAL",
void 0,
ShaderDestination_default.BOTH
);
}
};
function processTextureTransform(shaderBuilder, uniformMap2, textureReader, uniformName, defineName) {
const transformDefine = `HAS_${defineName}_TEXTURE_TRANSFORM`;
shaderBuilder.addDefine(
transformDefine,
void 0,
ShaderDestination_default.FRAGMENT
);
const transformUniformName = `${uniformName}Transform`;
shaderBuilder.addUniform(
"mat3",
transformUniformName,
ShaderDestination_default.FRAGMENT
);
uniformMap2[transformUniformName] = function() {
return textureReader.transform;
};
}
function processTexture2(shaderBuilder, uniformMap2, textureReader, uniformName, defineName, defaultTexture) {
shaderBuilder.addUniform(
"sampler2D",
uniformName,
ShaderDestination_default.FRAGMENT
);
uniformMap2[uniformName] = function() {
return defaultValue_default(textureReader.texture, defaultTexture);
};
const textureDefine = `HAS_${defineName}_TEXTURE`;
shaderBuilder.addDefine(textureDefine, void 0, ShaderDestination_default.FRAGMENT);
const texCoordIndex = textureReader.texCoord;
const texCoordVarying = `v_texCoord_${texCoordIndex}`;
const texCoordDefine = `TEXCOORD_${defineName}`;
shaderBuilder.addDefine(
texCoordDefine,
texCoordVarying,
ShaderDestination_default.FRAGMENT
);
const textureTransform = textureReader.transform;
if (defined_default(textureTransform) && !Matrix3_default.equals(textureTransform, Matrix3_default.IDENTITY)) {
processTextureTransform(
shaderBuilder,
uniformMap2,
textureReader,
uniformName,
defineName
);
}
}
function processMaterialUniforms(material, uniformMap2, shaderBuilder, defaultTexture, defaultNormalTexture, defaultEmissiveTexture, disableTextures) {
const emissiveFactor = material.emissiveFactor;
if (defined_default(emissiveFactor) && !Cartesian3_default.equals(emissiveFactor, Material4.DEFAULT_EMISSIVE_FACTOR)) {
shaderBuilder.addUniform(
"vec3",
"u_emissiveFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_emissiveFactor = function() {
return material.emissiveFactor;
};
shaderBuilder.addDefine(
"HAS_EMISSIVE_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
const emissiveTexture = material.emissiveTexture;
if (defined_default(emissiveTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
emissiveTexture,
"u_emissiveTexture",
"EMISSIVE",
defaultEmissiveTexture
);
}
}
const normalTexture = material.normalTexture;
if (defined_default(normalTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
normalTexture,
"u_normalTexture",
"NORMAL",
defaultNormalTexture
);
}
const occlusionTexture = material.occlusionTexture;
if (defined_default(occlusionTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
occlusionTexture,
"u_occlusionTexture",
"OCCLUSION",
defaultTexture
);
}
}
function processSpecularGlossinessUniforms(material, uniformMap2, shaderBuilder, defaultTexture, disableTextures) {
const specularGlossiness = material.specularGlossiness;
shaderBuilder.addDefine(
"USE_SPECULAR_GLOSSINESS",
void 0,
ShaderDestination_default.FRAGMENT
);
const diffuseTexture = specularGlossiness.diffuseTexture;
if (defined_default(diffuseTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
diffuseTexture,
"u_diffuseTexture",
"DIFFUSE",
defaultTexture
);
}
const diffuseFactor = specularGlossiness.diffuseFactor;
if (defined_default(diffuseFactor) && !Cartesian4_default.equals(diffuseFactor, SpecularGlossiness3.DEFAULT_DIFFUSE_FACTOR)) {
shaderBuilder.addUniform(
"vec4",
"u_diffuseFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_diffuseFactor = function() {
return specularGlossiness.diffuseFactor;
};
shaderBuilder.addDefine(
"HAS_DIFFUSE_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const specularGlossinessTexture = specularGlossiness.specularGlossinessTexture;
if (defined_default(specularGlossinessTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
specularGlossinessTexture,
"u_specularGlossinessTexture",
"SPECULAR_GLOSSINESS",
defaultTexture
);
}
const specularFactor = specularGlossiness.specularFactor;
if (defined_default(specularFactor) && !Cartesian3_default.equals(
specularFactor,
SpecularGlossiness3.DEFAULT_SPECULAR_FACTOR
)) {
shaderBuilder.addUniform(
"vec3",
"u_specularFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_specularFactor = function() {
return specularGlossiness.specularFactor;
};
shaderBuilder.addDefine(
"HAS_SPECULAR_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const glossinessFactor = specularGlossiness.glossinessFactor;
if (defined_default(glossinessFactor) && glossinessFactor !== SpecularGlossiness3.DEFAULT_GLOSSINESS_FACTOR) {
shaderBuilder.addUniform(
"float",
"u_glossinessFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_glossinessFactor = function() {
return specularGlossiness.glossinessFactor;
};
shaderBuilder.addDefine(
"HAS_GLOSSINESS_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
}
function processMetallicRoughnessUniforms(material, uniformMap2, shaderBuilder, defaultTexture, disableTextures) {
const metallicRoughness = material.metallicRoughness;
shaderBuilder.addDefine(
"USE_METALLIC_ROUGHNESS",
void 0,
ShaderDestination_default.FRAGMENT
);
const baseColorTexture = metallicRoughness.baseColorTexture;
if (defined_default(baseColorTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
baseColorTexture,
"u_baseColorTexture",
"BASE_COLOR",
defaultTexture
);
}
const baseColorFactor = metallicRoughness.baseColorFactor;
if (defined_default(baseColorFactor) && !Cartesian4_default.equals(
baseColorFactor,
MetallicRoughness3.DEFAULT_BASE_COLOR_FACTOR
)) {
shaderBuilder.addUniform(
"vec4",
"u_baseColorFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_baseColorFactor = function() {
return metallicRoughness.baseColorFactor;
};
shaderBuilder.addDefine(
"HAS_BASE_COLOR_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const metallicRoughnessTexture = metallicRoughness.metallicRoughnessTexture;
if (defined_default(metallicRoughnessTexture) && !disableTextures) {
processTexture2(
shaderBuilder,
uniformMap2,
metallicRoughnessTexture,
"u_metallicRoughnessTexture",
"METALLIC_ROUGHNESS",
defaultTexture
);
}
const metallicFactor = metallicRoughness.metallicFactor;
if (defined_default(metallicFactor) && metallicFactor !== MetallicRoughness3.DEFAULT_METALLIC_FACTOR) {
shaderBuilder.addUniform(
"float",
"u_metallicFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_metallicFactor = function() {
return metallicRoughness.metallicFactor;
};
shaderBuilder.addDefine(
"HAS_METALLIC_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
const roughnessFactor = metallicRoughness.roughnessFactor;
if (defined_default(roughnessFactor) && roughnessFactor !== MetallicRoughness3.DEFAULT_ROUGHNESS_FACTOR) {
shaderBuilder.addUniform(
"float",
"u_roughnessFactor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.u_roughnessFactor = function() {
return metallicRoughness.roughnessFactor;
};
shaderBuilder.addDefine(
"HAS_ROUGHNESS_FACTOR",
void 0,
ShaderDestination_default.FRAGMENT
);
}
}
var MaterialPipelineStage_default = MaterialPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/MorphTargetsStageVS.js
var MorphTargetsStageVS_default = "void morphTargetsStage(inout ProcessedAttributes attributes) \n{\n vec3 positionMC = attributes.positionMC;\n attributes.positionMC = getMorphedPosition(positionMC);\n\n #ifdef HAS_NORMALS\n vec3 normalMC = attributes.normalMC;\n attributes.normalMC = getMorphedNormal(normalMC);\n #endif\n\n #ifdef HAS_TANGENTS\n vec3 tangentMC = attributes.tangentMC;\n attributes.tangentMC = getMorphedTangent(tangentMC);\n #endif\n}";
// node_modules/@cesium/engine/Source/Scene/Model/MorphTargetsPipelineStage.js
var MorphTargetsPipelineStage = {
name: "MorphTargetsPipelineStage",
FUNCTION_ID_GET_MORPHED_POSITION: "getMorphedPosition",
FUNCTION_SIGNATURE_GET_MORPHED_POSITION: "vec3 getMorphedPosition(in vec3 position)",
FUNCTION_ID_GET_MORPHED_NORMAL: "getMorphedNormal",
FUNCTION_SIGNATURE_GET_MORPHED_NORMAL: "vec3 getMorphedNormal(in vec3 normal)",
FUNCTION_ID_GET_MORPHED_TANGENT: "getMorphedTangent",
FUNCTION_SIGNATURE_GET_MORPHED_TANGENT: "vec3 getMorphedTangent(in vec3 tangent)"
};
MorphTargetsPipelineStage.process = function(renderResources, primitive) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_MORPH_TARGETS",
void 0,
ShaderDestination_default.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;
if (semantic !== VertexAttributeSemantic_default.POSITION && semantic !== VertexAttributeSemantic_default.NORMAL && semantic !== VertexAttributeSemantic_default.TANGENT) {
continue;
}
processMorphTargetAttribute(
renderResources,
attribute,
renderResources.attributeIndex,
i
);
renderResources.attributeIndex++;
}
}
addGetMorphedAttributeFunctionReturns(shaderBuilder);
const weights2 = renderResources.runtimeNode.morphWeights;
const weightsLength = weights2.length;
shaderBuilder.addUniform(
"float",
`u_morphWeights[${weightsLength}]`,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(MorphTargetsStageVS_default);
const uniformMap2 = {
u_morphWeights: function() {
return renderResources.runtimeNode.morphWeights;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
var scratchAttributeInfo = {
attributeString: void 0,
functionId: void 0
};
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_default(attribute.buffer) ? void 0 : attribute.constant,
vertexBuffer: attribute.buffer,
componentsPerAttribute: AttributeType_default.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_default.POSITION:
result.attributeString = "Position";
result.functionId = MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_POSITION;
break;
case VertexAttributeSemantic_default.NORMAL:
result.attributeString = "Normal";
result.functionId = MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_NORMAL;
break;
case VertexAttributeSemantic_default.TANGENT:
result.attributeString = "Tangent";
result.functionId = MorphTargetsPipelineStage.FUNCTION_ID_GET_MORPHED_TANGENT;
break;
default:
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_default.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_default.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_default.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]
);
}
var MorphTargetsPipelineStage_default = MorphTargetsPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/PickingPipelineStage.js
var PickingPipelineStage = {
name: "PickingPipelineStage"
};
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, context);
} else if (defined_default(instances)) {
processInstancedPickIds(renderResources, context);
} else {
const pickObject = buildPickObject(renderResources);
const pickId = context.createPickId(pickObject);
model._pipelineResources.push(pickId);
model._pickIds.push(pickId);
shaderBuilder.addUniform(
"vec4",
"czm_pickColor",
ShaderDestination_default.FRAGMENT
);
const uniformMap2 = renderResources.uniformMap;
uniformMap2.czm_pickColor = function() {
return pickId.color;
};
renderResources.pickId = "czm_pickColor";
}
};
function buildPickObject(renderResources, instanceId) {
const model = renderResources.model;
if (defined_default(model.pickObject)) {
return model.pickObject;
}
const detailPickObject = {
model,
node: renderResources.runtimeNode,
primitive: renderResources.runtimePrimitive
};
let pickObject;
if (ModelType_default.is3DTiles(model.type)) {
const content = model.content;
pickObject = {
content,
primitive: content.tileset,
detail: detailPickObject
};
} else {
pickObject = {
primitive: model,
detail: detailPickObject
};
}
pickObject.id = model.id;
if (defined_default(instanceId)) {
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_default(model.featureTableId)) {
featureTableId = model.featureTableId;
} else if (defined_default(instances)) {
featureIdAttribute = ModelUtility_default.getFeatureIdsByLabel(
instances.featureIds,
instanceFeatureIdLabel
);
featureTableId = featureIdAttribute.propertyTableId;
} else {
featureIdAttribute = ModelUtility_default.getFeatureIdsByLabel(
primitive.featureIds,
featureIdLabel
);
featureTableId = featureIdAttribute.propertyTableId;
}
const featureTable = model.featureTables[featureTableId];
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addUniform(
"sampler2D",
"model_pickTexture",
ShaderDestination_default.FRAGMENT
);
const batchTexture = featureTable.batchTexture;
renderResources.uniformMap.model_pickTexture = function() {
return defaultValue_default(batchTexture.pickTexture, batchTexture.defaultTexture);
};
renderResources.pickId = "((selectedFeature.id < int(model_featuresLength)) ? texture(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_default.floatToByte(pickColor.red);
pickIdsTypedArray[i * 4 + 1] = Color_default.floatToByte(pickColor.green);
pickIdsTypedArray[i * 4 + 2] = Color_default.floatToByte(pickColor.blue);
pickIdsTypedArray[i * 4 + 3] = Color_default.floatToByte(pickColor.alpha);
}
model._pickIds = pickIds;
const pickIdsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: pickIdsTypedArray,
usage: BufferUsage_default.STATIC_DRAW
});
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_default.UNSIGNED_BYTE,
normalize: true,
offsetInBytes: 0,
strideInBytes: 0,
instanceDivisor: 1
};
renderResources.attributes.push(pickIdsVertexAttribute);
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine("USE_PICKING", void 0, ShaderDestination_default.BOTH);
shaderBuilder.addAttribute("vec4", "a_pickColor");
shaderBuilder.addVarying("vec4", "v_pickColor");
renderResources.pickId = "v_pickColor";
}
var PickingPipelineStage_default = PickingPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileRefine.js
var Cesium3DTileRefine = {
ADD: 0,
REPLACE: 1
};
var Cesium3DTileRefine_default = Object.freeze(Cesium3DTileRefine);
// node_modules/@cesium/engine/Source/Shaders/Model/PointCloudStylingStageVS.js
var PointCloudStylingStageVS_default = "float getPointSizeFromAttenuation(vec3 positionEC) {\n // Variables are packed into a single vector to minimize gl.uniformXXX() calls\n float pointSize = model_pointCloudParameters.x;\n float geometricError = model_pointCloudParameters.y;\n float depthMultiplier = model_pointCloudParameters.z;\n\n float depth = -positionEC.z;\n return min((geometricError / depth) * depthMultiplier, pointSize);\n}\n\n#ifdef HAS_POINT_CLOUD_SHOW_STYLE\nfloat pointCloudShowStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n float tiles3d_tileset_time = model_pointCloudParameters.w;\n return float(getShowFromStyle(attributes, metadata, tiles3d_tileset_time));\n}\n#endif\n\n#ifdef HAS_POINT_CLOUD_COLOR_STYLE\nvec4 pointCloudColorStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n float tiles3d_tileset_time = model_pointCloudParameters.w;\n return getColorFromStyle(attributes, metadata, tiles3d_tileset_time);\n}\n#endif\n\n#ifdef HAS_POINT_CLOUD_POINT_SIZE_STYLE\nfloat pointCloudPointSizeStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n float tiles3d_tileset_time = model_pointCloudParameters.w;\n return float(getPointSizeFromStyle(attributes, metadata, tiles3d_tileset_time));\n}\n#elif defined(HAS_POINT_CLOUD_ATTENUATION)\nfloat pointCloudPointSizeStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {\n return getPointSizeFromAttenuation(v_positionEC);\n}\n#endif\n\n#ifdef HAS_POINT_CLOUD_BACK_FACE_CULLING\nfloat pointCloudBackFaceCullingStage() {\n #if defined(HAS_NORMALS) && !defined(HAS_DOUBLE_SIDED_MATERIAL)\n // This needs to be computed in eye coordinates so we can't use attributes.normalMC\n return step(-v_normalEC.z, 0.0);\n #else\n return 1.0;\n #endif\n}\n#endif";
// node_modules/@cesium/engine/Source/Scene/Model/PointCloudStylingPipelineStage.js
var scratchUniform = new Cartesian4_default();
var PointCloudStylingPipelineStage = {
name: "PointCloudStylingPipelineStage"
};
PointCloudStylingPipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const model = renderResources.model;
const style = model.style;
const structuralMetadata = model.structuralMetadata;
const propertyAttributes = defined_default(structuralMetadata) ? structuralMetadata.propertyAttributes : void 0;
const hasFeatureTable = defined_default(model.featureTableId) && model.featureTables[model.featureTableId].featuresLength > 0;
const hasBatchTable = !defined_default(propertyAttributes) && hasFeatureTable;
if (defined_default(style) && !hasBatchTable) {
const variableSubstitutionMap = getVariableSubstitutionMap(
propertyAttributes
);
const shaderFunctionInfo = getStyleShaderFunctionInfo(
style,
variableSubstitutionMap
);
addShaderFunctionsAndDefines(shaderBuilder, shaderFunctionInfo);
const propertyNames = getPropertyNames(shaderFunctionInfo);
const usesNormalSemantic = propertyNames.indexOf("normalMC") >= 0;
const hasNormals = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.NORMAL
);
if (usesNormalSemantic && !hasNormals) {
throw new RuntimeError_default(
"Style references the NORMAL semantic but the point cloud does not have normals"
);
}
shaderBuilder.addDefine(
"COMPUTE_POSITION_WC_STYLE",
void 0,
ShaderDestination_default.VERTEX
);
const styleTranslucent = shaderFunctionInfo.styleTranslucent;
if (styleTranslucent) {
renderResources.alphaOptions.pass = Pass_default.TRANSLUCENT;
}
}
const pointCloudShading = model.pointCloudShading;
if (pointCloudShading.attenuation) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_ATTENUATION",
void 0,
ShaderDestination_default.VERTEX
);
}
if (pointCloudShading.backFaceCulling) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_BACK_FACE_CULLING",
void 0,
ShaderDestination_default.VERTEX
);
}
let content;
let is3DTiles;
let usesAddRefinement;
if (ModelType_default.is3DTiles(model.type)) {
is3DTiles = true;
content = model.content;
usesAddRefinement = content.tile.refine === Cesium3DTileRefine_default.ADD;
}
shaderBuilder.addUniform(
"vec4",
"model_pointCloudParameters",
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(PointCloudStylingStageVS_default);
const uniformMap2 = renderResources.uniformMap;
uniformMap2.model_pointCloudParameters = function() {
const vec4 = scratchUniform;
let defaultPointSize = 1;
if (is3DTiles) {
defaultPointSize = usesAddRefinement ? 5 : content.tileset.maximumScreenSpaceError;
}
vec4.x = defaultValue_default(
pointCloudShading.maximumAttenuation,
defaultPointSize
);
vec4.x *= frameState.pixelRatio;
const geometricError = getGeometricError2(
renderResources,
primitive,
pointCloudShading,
content
);
vec4.y = geometricError * pointCloudShading.geometricErrorScale;
const context = frameState.context;
const frustum = frameState.camera.frustum;
let depthMultiplier;
if (frameState.mode === SceneMode_default.SCENE2D || frustum instanceof OrthographicFrustum_default) {
depthMultiplier = Number.POSITIVE_INFINITY;
} else {
depthMultiplier = context.drawingBufferHeight / frameState.camera.frustum.sseDenominator;
}
vec4.z = depthMultiplier;
if (is3DTiles) {
vec4.w = content.tileset.timeSinceLoad;
}
return vec4;
};
};
var scratchDimensions = new Cartesian3_default();
function getGeometricError2(renderResources, primitive, pointCloudShading, content) {
if (defined_default(content)) {
const geometricError = content.tile.geometricError;
if (geometricError > 0) {
return geometricError;
}
}
if (defined_default(pointCloudShading.baseResolution)) {
return pointCloudShading.baseResolution;
}
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
const pointsLength = positionAttribute.count;
const nodeTransform = renderResources.runtimeNode.transform;
let dimensions = Cartesian3_default.subtract(
positionAttribute.max,
positionAttribute.min,
scratchDimensions
);
dimensions = Matrix4_default.multiplyByPointAsVector(
nodeTransform,
dimensions,
scratchDimensions
);
const volume = dimensions.x * dimensions.y * dimensions.z;
const geometricErrorEstimate = Math_default.cbrt(volume / pointsLength);
return geometricErrorEstimate;
}
var scratchShaderFunctionInfo = {
colorStyleFunction: void 0,
showStyleFunction: void 0,
pointSizeStyleFunction: void 0,
styleTranslucent: false
};
var builtinVariableSubstitutionMap = {
POSITION: "attributes.positionMC",
POSITION_ABSOLUTE: "v_positionWC",
COLOR: "attributes.color_0",
NORMAL: "attributes.normalMC"
};
function getVariableSubstitutionMap(propertyAttributes) {
const variableSubstitutionMap = clone_default(builtinVariableSubstitutionMap);
if (!defined_default(propertyAttributes)) {
return variableSubstitutionMap;
}
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)) {
variableSubstitutionMap[propertyId] = `metadata.${propertyId}`;
}
}
}
return variableSubstitutionMap;
}
var parameterList = "ProcessedAttributes attributes, Metadata metadata, float tiles3d_tileset_time";
function getStyleShaderFunctionInfo(style, variableSubstitutionMap) {
const info = scratchShaderFunctionInfo;
const shaderState = {
translucent: false
};
info.colorStyleFunction = style.getColorShaderFunction(
`getColorFromStyle(${parameterList})`,
variableSubstitutionMap,
shaderState
);
info.showStyleFunction = style.getShowShaderFunction(
`getShowFromStyle(${parameterList})`,
variableSubstitutionMap,
shaderState
);
info.pointSizeStyleFunction = style.getPointSizeShaderFunction(
`getPointSizeFromStyle(${parameterList})`,
variableSubstitutionMap,
shaderState
);
info.styleTranslucent = defined_default(info.colorStyleFunction) && shaderState.translucent;
return info;
}
function addShaderFunctionsAndDefines(shaderBuilder, shaderFunctionInfo) {
const colorStyleFunction = shaderFunctionInfo.colorStyleFunction;
if (defined_default(colorStyleFunction)) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_COLOR_STYLE",
void 0,
ShaderDestination_default.BOTH
);
shaderBuilder.addVertexLines(colorStyleFunction);
shaderBuilder.addVarying("vec4", "v_pointCloudColor");
}
const showStyleFunction = shaderFunctionInfo.showStyleFunction;
if (defined_default(showStyleFunction)) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_SHOW_STYLE",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(showStyleFunction);
}
const pointSizeStyleFunction = shaderFunctionInfo.pointSizeStyleFunction;
if (defined_default(pointSizeStyleFunction)) {
shaderBuilder.addDefine(
"HAS_POINT_CLOUD_POINT_SIZE_STYLE",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(pointSizeStyleFunction);
}
}
function getBuiltinPropertyNames(source, propertyNames) {
const regex = /attributes\.(\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 getPropertyNames(shaderFunctionInfo) {
const colorStyleFunction = shaderFunctionInfo.colorStyleFunction;
const showStyleFunction = shaderFunctionInfo.showStyleFunction;
const pointSizeStyleFunction = shaderFunctionInfo.pointSizeStyleFunction;
const builtinPropertyNames = [];
if (defined_default(colorStyleFunction)) {
getBuiltinPropertyNames(colorStyleFunction, builtinPropertyNames);
}
if (defined_default(showStyleFunction)) {
getBuiltinPropertyNames(showStyleFunction, builtinPropertyNames);
}
if (defined_default(pointSizeStyleFunction)) {
getBuiltinPropertyNames(pointSizeStyleFunction, builtinPropertyNames);
}
return builtinPropertyNames;
}
var PointCloudStylingPipelineStage_default = PointCloudStylingPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/PrimitiveOutlineStageVS.js
var PrimitiveOutlineStageVS_default = "void primitiveOutlineStage() {\n v_outlineCoordinates = a_outlineCoordinates;\n}\n";
// node_modules/@cesium/engine/Source/Shaders/Model/PrimitiveOutlineStageFS.js
var PrimitiveOutlineStageFS_default = "void primitiveOutlineStage(inout czm_modelMaterial material) {\n if (!model_showOutline) {\n return;\n }\n\n float outlineX = \n texture(model_outlineTexture, vec2(v_outlineCoordinates.x, 0.5)).r;\n float outlineY = \n texture(model_outlineTexture, vec2(v_outlineCoordinates.y, 0.5)).r;\n float outlineZ = \n texture(model_outlineTexture, vec2(v_outlineCoordinates.z, 0.5)).r;\n float outlineness = max(outlineX, max(outlineY, outlineZ));\n\n material.diffuse = mix(material.diffuse, model_outlineColor.rgb, model_outlineColor.a * outlineness);\n}\n\n";
// node_modules/@cesium/engine/Source/Scene/Model/PrimitiveOutlinePipelineStage.js
var PrimitiveOutlinePipelineStage = {
name: "PrimitiveOutlinePipelineStage"
};
PrimitiveOutlinePipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
const uniformMap2 = renderResources.uniformMap;
shaderBuilder.addDefine(
"HAS_PRIMITIVE_OUTLINE",
void 0,
ShaderDestination_default.BOTH
);
shaderBuilder.addAttribute("vec3", "a_outlineCoordinates");
shaderBuilder.addVarying("vec3", "v_outlineCoordinates");
const outlineCoordinates = primitive.outlineCoordinates;
const vertexAttribute = {
index: renderResources.attributeIndex++,
vertexBuffer: outlineCoordinates.buffer,
componentsPerAttribute: AttributeType_default.getNumberOfComponents(
outlineCoordinates.type
),
componentDatatype: outlineCoordinates.componentDatatype,
offsetInBytes: outlineCoordinates.byteOffset,
strideInBytes: outlineCoordinates.byteStride,
normalize: outlineCoordinates.normalized
};
renderResources.attributes.push(vertexAttribute);
shaderBuilder.addUniform(
"sampler2D",
"model_outlineTexture",
ShaderDestination_default.FRAGMENT
);
const outlineTexture = PrimitiveOutlineGenerator_default.createTexture(
frameState.context
);
uniformMap2.model_outlineTexture = function() {
return outlineTexture;
};
const model = renderResources.model;
shaderBuilder.addUniform(
"vec4",
"model_outlineColor",
ShaderDestination_default.FRAGMENT
);
uniformMap2.model_outlineColor = function() {
return model.outlineColor;
};
shaderBuilder.addUniform(
"bool",
"model_showOutline",
ShaderDestination_default.FRAGMENT
);
uniformMap2.model_showOutline = function() {
return model.showOutline;
};
shaderBuilder.addVertexLines(PrimitiveOutlineStageVS_default);
shaderBuilder.addFragmentLines(PrimitiveOutlineStageFS_default);
};
var PrimitiveOutlinePipelineStage_default = PrimitiveOutlinePipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/PrimitiveStatisticsPipelineStage.js
var PrimitiveStatisticsPipelineStage = {
name: "PrimitiveStatisticsPipelineStage",
_countGeometry: countGeometry,
_count2DPositions: count2DPositions,
_countMorphTargetAttributes: countMorphTargetAttributes,
_countMaterialTextures: countMaterialTextures,
_countFeatureIdTextures: countFeatureIdTextures,
_countBinaryMetadata: countBinaryMetadata
};
PrimitiveStatisticsPipelineStage.process = function(renderResources, primitive, frameState) {
const model = renderResources.model;
const statistics2 = model.statistics;
countGeometry(statistics2, primitive);
count2DPositions(statistics2, renderResources.runtimePrimitive);
countMorphTargetAttributes(statistics2, primitive);
countMaterialTextures(statistics2, primitive.material);
countFeatureIdTextures(statistics2, primitive.featureIds);
countBinaryMetadata(statistics2, model);
};
function countGeometry(statistics2, primitive) {
const indicesCount = defined_default(primitive.indices) ? primitive.indices.count : ModelUtility_default.getAttributeBySemantic(primitive, "POSITION").count;
const primitiveType = primitive.primitiveType;
if (primitiveType === PrimitiveType_default.POINTS) {
statistics2.pointsLength += indicesCount;
} else if (PrimitiveType_default.isTriangles(primitiveType)) {
statistics2.trianglesLength += countTriangles(primitiveType, indicesCount);
}
const attributes = primitive.attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; i++) {
const attribute = attributes[i];
if (defined_default(attribute.buffer)) {
const hasCpuCopy = defined_default(attribute.typedArray);
statistics2.addBuffer(attribute.buffer, hasCpuCopy);
}
}
const outlineCoordinates = primitive.outlineCoordinates;
if (defined_default(outlineCoordinates) && defined_default(outlineCoordinates.buffer)) {
const hasCpuCopy = false;
statistics2.addBuffer(outlineCoordinates.buffer, hasCpuCopy);
}
const indices2 = primitive.indices;
if (defined_default(indices2) && defined_default(indices2.buffer)) {
const hasCpuCopy = defined_default(indices2.typedArray);
statistics2.addBuffer(indices2.buffer, hasCpuCopy);
}
}
function countTriangles(primitiveType, indicesCount) {
switch (primitiveType) {
case PrimitiveType_default.TRIANGLES:
return indicesCount / 3;
case PrimitiveType_default.TRIANGLE_STRIP:
case PrimitiveType_default.TRIANGLE_FAN:
return Math.max(indicesCount - 2, 0);
default:
return 0;
}
}
function count2DPositions(statistics2, runtimePrimitive) {
const buffer2D = runtimePrimitive.positionBuffer2D;
if (defined_default(buffer2D)) {
const hasCpuCopy = true;
statistics2.addBuffer(buffer2D, hasCpuCopy);
}
}
function countMorphTargetAttributes(statistics2, primitive) {
const morphTargets = primitive.morphTargets;
if (!defined_default(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_default(attribute.buffer)) {
statistics2.addBuffer(attribute.buffer, hasCpuCopy);
}
}
}
}
function countMaterialTextures(statistics2, material) {
const textureReaders = getAllTextureReaders(material);
const length3 = textureReaders.length;
for (let i = 0; i < length3; i++) {
const textureReader = textureReaders[i];
if (defined_default(textureReader) && defined_default(textureReader.texture)) {
statistics2.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_default(specularGlossiness)) {
textureReaders.push(specularGlossiness.diffuseTexture);
textureReaders.push(specularGlossiness.specularGlossinessTexture);
}
return textureReaders;
}
function countFeatureIdTextures(statistics2, featureIdSets) {
const length3 = featureIdSets.length;
for (let i = 0; i < length3; i++) {
const featureIds = featureIdSets[i];
if (featureIds instanceof ModelComponents_default.FeatureIdTexture) {
const textureReader = featureIds.textureReader;
if (defined_default(textureReader.texture)) {
statistics2.addTexture(textureReader.texture);
}
}
}
}
function countBinaryMetadata(statistics2, model) {
const structuralMetadata = model.structuralMetadata;
if (defined_default(structuralMetadata)) {
countPropertyTextures(statistics2, structuralMetadata);
statistics2.propertyTablesByteLength += structuralMetadata.propertyTablesByteLength;
}
const featureTables = model.featureTables;
if (!defined_default(featureTables)) {
return;
}
const length3 = featureTables.length;
for (let i = 0; i < length3; i++) {
const featureTable = featureTables[i];
statistics2.addBatchTexture(featureTable.batchTexture);
}
}
function countPropertyTextures(statistics2, structuralMetadata) {
const propertyTextures = structuralMetadata.propertyTextures;
if (!defined_default(propertyTextures)) {
return;
}
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_default(textureReader.texture)) {
statistics2.addTexture(textureReader.texture);
}
}
}
}
}
var PrimitiveStatisticsPipelineStage_default = PrimitiveStatisticsPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/SceneMode2DPipelineStage.js
var scratchModelMatrix = new Matrix4_default();
var scratchModelView2D = new Matrix4_default();
var SceneMode2DPipelineStage = {
name: "SceneMode2DPipelineStage"
};
SceneMode2DPipelineStage.process = function(renderResources, primitive, frameState) {
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
const shaderBuilder = renderResources.shaderBuilder;
const model = renderResources.model;
const modelMatrix = model.sceneGraph.computedModelMatrix;
const nodeComputedTransform = renderResources.runtimeNode.computedTransform;
const computedModelMatrix = Matrix4_default.multiplyTransformation(
modelMatrix,
nodeComputedTransform,
scratchModelMatrix
);
const boundingSphere2D = computeBoundingSphere2D(
renderResources,
computedModelMatrix,
frameState
);
const runtimePrimitive = renderResources.runtimePrimitive;
runtimePrimitive.boundingSphere2D = boundingSphere2D;
const instances = renderResources.runtimeNode.node.instances;
if (defined_default(instances)) {
return;
}
if (defined_default(positionAttribute.typedArray)) {
const buffer2D = createPositionBufferFor2D(
positionAttribute,
computedModelMatrix,
boundingSphere2D,
frameState
);
runtimePrimitive.positionBuffer2D = buffer2D;
model._modelResources.push(buffer2D);
positionAttribute.typedArray = void 0;
}
shaderBuilder.addDefine(
"USE_2D_POSITIONS",
void 0,
ShaderDestination_default.VERTEX
);
shaderBuilder.addUniform("mat4", "u_modelView2D", ShaderDestination_default.VERTEX);
const modelMatrix2D = Matrix4_default.fromTranslation(
boundingSphere2D.center,
new Matrix4_default()
);
const context = frameState.context;
const uniformMap2 = {
u_modelView2D: function() {
return Matrix4_default.multiplyTransformation(
context.uniformState.view,
modelMatrix2D,
scratchModelView2D
);
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
var scratchProjectedMin2 = new Cartesian3_default();
var scratchProjectedMax2 = new Cartesian3_default();
function computeBoundingSphere2D(renderResources, modelMatrix, frameState) {
const transformedPositionMin = Matrix4_default.multiplyByPoint(
modelMatrix,
renderResources.positionMin,
scratchProjectedMin2
);
const projectedMin = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPositionMin,
transformedPositionMin
);
const transformedPositionMax = Matrix4_default.multiplyByPoint(
modelMatrix,
renderResources.positionMax,
scratchProjectedMax2
);
const projectedMax = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPositionMax,
transformedPositionMax
);
return BoundingSphere_default.fromCornerPoints(
projectedMin,
projectedMax,
new BoundingSphere_default()
);
}
var scratchPosition2 = new Cartesian3_default();
function dequantizePositionsTypedArray(typedArray, quantization) {
const length3 = typedArray.length;
const dequantizedArray = new Float32Array(length3);
const quantizedVolumeOffset = quantization.quantizedVolumeOffset;
const quantizedVolumeStepSize = quantization.quantizedVolumeStepSize;
for (let i = 0; i < length3; i += 3) {
const initialPosition = Cartesian3_default.fromArray(
typedArray,
i,
scratchPosition2
);
const scaledPosition = Cartesian3_default.multiplyComponents(
initialPosition,
quantizedVolumeStepSize,
initialPosition
);
const dequantizedPosition = Cartesian3_default.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) {
let result;
if (defined_default(attribute.quantization)) {
result = dequantizePositionsTypedArray(
attribute.typedArray,
attribute.quantization
);
} else {
result = attribute.typedArray.slice();
}
const startIndex = attribute.byteOffset / Float32Array.BYTES_PER_ELEMENT;
const length3 = result.length;
const stride = defined_default(attribute.byteStride) ? attribute.byteStride / Float32Array.BYTES_PER_ELEMENT : 3;
for (let i = startIndex; i < length3; i += stride) {
const initialPosition = Cartesian3_default.fromArray(result, i, scratchPosition2);
if (isNaN(initialPosition.x) || isNaN(initialPosition.y) || isNaN(initialPosition.z)) {
continue;
}
const transformedPosition = Matrix4_default.multiplyByPoint(
modelMatrix,
initialPosition,
initialPosition
);
const projectedPosition2 = SceneTransforms_default.computeActualWgs84Position(
frameState,
transformedPosition,
transformedPosition
);
const relativePosition = Cartesian3_default.subtract(
projectedPosition2,
referencePoint,
projectedPosition2
);
result[i] = relativePosition.x;
result[i + 1] = relativePosition.y;
result[i + 2] = relativePosition.z;
}
return result;
}
function createPositionBufferFor2D(positionAttribute, modelMatrix, boundingSphere2D, frameState) {
const frameStateCV = clone_default(frameState);
frameStateCV.mode = SceneMode_default.COLUMBUS_VIEW;
const referencePoint = boundingSphere2D.center;
const projectedPositions = createPositionsTypedArrayFor2D(
positionAttribute,
modelMatrix,
referencePoint,
frameStateCV
);
const buffer = Buffer_default.createVertexBuffer({
context: frameState.context,
typedArray: projectedPositions,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
return buffer;
}
var SceneMode2DPipelineStage_default = SceneMode2DPipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/SkinningStageVS.js
var SkinningStageVS_default = "void skinningStage(inout ProcessedAttributes attributes) \n{\n mat4 skinningMatrix = getSkinningMatrix();\n mat3 skinningMatrixMat3 = mat3(skinningMatrix);\n\n vec4 positionMC = vec4(attributes.positionMC, 1.0);\n attributes.positionMC = vec3(skinningMatrix * positionMC);\n\n #ifdef HAS_NORMALS\n vec3 normalMC = attributes.normalMC;\n attributes.normalMC = skinningMatrixMat3 * normalMC;\n #endif\n\n #ifdef HAS_TANGENTS\n vec3 tangentMC = attributes.tangentMC;\n attributes.tangentMC = skinningMatrixMat3 * tangentMC;\n #endif\n}";
// node_modules/@cesium/engine/Source/Scene/Model/SkinningPipelineStage.js
var SkinningPipelineStage = {
name: "SkinningPipelineStage",
FUNCTION_ID_GET_SKINNING_MATRIX: "getSkinningMatrix",
FUNCTION_SIGNATURE_GET_SKINNING_MATRIX: "mat4 getSkinningMatrix()"
};
SkinningPipelineStage.process = function(renderResources, primitive) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine("HAS_SKINNING", void 0, ShaderDestination_default.VERTEX);
addGetSkinningMatrixFunction(shaderBuilder, primitive);
const runtimeNode = renderResources.runtimeNode;
const jointMatrices = runtimeNode.computedJointMatrices;
shaderBuilder.addUniform(
"mat4",
`u_jointMatrices[${jointMatrices.length}]`,
ShaderDestination_default.VERTEX
);
shaderBuilder.addVertexLines(SkinningStageVS_default);
const uniformMap2 = {
u_jointMatrices: function() {
return runtimeNode.computedJointMatrices;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
};
function getMaximumAttributeSetIndex(primitive) {
let setIndex = -1;
const attributes = primitive.attributes;
const length3 = attributes.length;
for (let i = 0; i < length3; i++) {
const attribute = attributes[i];
const isJointsOrWeights = attribute.semantic === VertexAttributeSemantic_default.JOINTS || attribute.semantic === VertexAttributeSemantic_default.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_default.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];
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]
);
}
var SkinningPipelineStage_default = SkinningPipelineStage;
// node_modules/@cesium/engine/Source/Core/WireframeIndexGenerator.js
var WireframeIndexGenerator = {};
function createWireframeFromTriangles(vertexCount) {
const wireframeIndices = IndexDatatype_default.createTypedArray(
vertexCount,
vertexCount * 2
);
const length3 = vertexCount;
let index = 0;
for (let i = 0; i < length3; 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_default.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_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
wireframeIndices[index++] = 0;
wireframeIndices[index++] = 1;
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_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
wireframeIndices[index++] = originalIndices[0];
wireframeIndices[index++] = originalIndices[1];
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_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
wireframeIndices[index++] = 0;
wireframeIndices[index++] = 1;
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_default.createTypedArray(
vertexCount,
wireframeIndicesCount
);
let index = 0;
const firstPoint = originalIndices[0];
wireframeIndices[index++] = firstPoint;
wireframeIndices[index++] = originalIndices[1];
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;
}
WireframeIndexGenerator.createWireframeIndices = function(primitiveType, vertexCount, originalIndices) {
const hasOriginalIndices = defined_default(originalIndices);
if (primitiveType === PrimitiveType_default.TRIANGLES) {
return hasOriginalIndices ? createWireframeFromTriangleIndices(vertexCount, originalIndices) : createWireframeFromTriangles(vertexCount);
}
if (primitiveType === PrimitiveType_default.TRIANGLE_STRIP) {
return hasOriginalIndices ? createWireframeFromTriangleStripIndices(vertexCount, originalIndices) : createWireframeFromTriangleStrip(vertexCount);
}
if (primitiveType === PrimitiveType_default.TRIANGLE_FAN) {
return hasOriginalIndices ? createWireframeFromTriangleFanIndices(vertexCount, originalIndices) : createWireframeFromTriangleFan(vertexCount);
}
return void 0;
};
WireframeIndexGenerator.getWireframeIndicesCount = function(primitiveType, originalCount) {
if (primitiveType === PrimitiveType_default.TRIANGLES) {
return originalCount * 2;
}
if (primitiveType === PrimitiveType_default.TRIANGLE_STRIP || primitiveType === PrimitiveType_default.TRIANGLE_FAN) {
const numberOfTriangles = originalCount - 2;
return 2 + numberOfTriangles * 4;
}
return originalCount;
};
var WireframeIndexGenerator_default = WireframeIndexGenerator;
// node_modules/@cesium/engine/Source/Scene/Model/WireframePipelineStage.js
var WireframePipelineStage = {
name: "WireframePipelineStage"
};
WireframePipelineStage.process = function(renderResources, primitive, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_WIREFRAME",
void 0,
ShaderDestination_default.FRAGMENT
);
const model = renderResources.model;
const wireframeIndexBuffer = createWireframeIndexBuffer(
primitive,
renderResources.indices,
frameState
);
model._pipelineResources.push(wireframeIndexBuffer);
renderResources.wireframeIndexBuffer = wireframeIndexBuffer;
const hasCpuCopy = false;
model.statistics.addBuffer(wireframeIndexBuffer, hasCpuCopy);
const originalPrimitiveType = renderResources.primitiveType;
const originalCount = renderResources.count;
renderResources.primitiveType = PrimitiveType_default.LINES;
renderResources.count = WireframeIndexGenerator_default.getWireframeIndicesCount(
originalPrimitiveType,
originalCount
);
};
function createWireframeIndexBuffer(primitive, indices2, frameState) {
const positionAttribute = ModelUtility_default.getAttributeBySemantic(
primitive,
VertexAttributeSemantic_default.POSITION
);
const vertexCount = positionAttribute.count;
const webgl2 = frameState.context.webgl2;
let originalIndices;
if (defined_default(indices2)) {
const indicesBuffer = indices2.buffer;
const indicesCount = indices2.count;
if (defined_default(indicesBuffer) && webgl2) {
const useUint8Array = indicesBuffer.sizeInBytes === indicesCount;
originalIndices = useUint8Array ? new Uint8Array(indicesCount) : IndexDatatype_default.createTypedArray(vertexCount, indicesCount);
indicesBuffer.getBufferData(originalIndices);
} else {
originalIndices = indices2.typedArray;
}
}
const primitiveType = primitive.primitiveType;
const wireframeIndices = WireframeIndexGenerator_default.createWireframeIndices(
primitiveType,
vertexCount,
originalIndices
);
const indexDatatype = IndexDatatype_default.fromSizeInBytes(
wireframeIndices.BYTES_PER_ELEMENT
);
return Buffer_default.createIndexBuffer({
context: frameState.context,
typedArray: wireframeIndices,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype
});
}
var WireframePipelineStage_default = WireframePipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/ModelRuntimePrimitive.js
function ModelRuntimePrimitive(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const primitive = options.primitive;
const node = options.node;
const model = options.model;
Check_default.typeOf.object("options.primitive", primitive);
Check_default.typeOf.object("options.node", node);
Check_default.typeOf.object("options.model", model);
this.primitive = primitive;
this.node = node;
this.model = model;
this.pipelineStages = [];
this.drawCommand = void 0;
this.boundingSphere = void 0;
this.boundingSphere2D = void 0;
this.positionBuffer2D = void 0;
this.batchLengths = void 0;
this.batchOffsets = void 0;
this.updateStages = [];
}
ModelRuntimePrimitive.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 style = model.style;
const useWebgl2 = frameState.context.webgl2;
const mode2 = frameState.mode;
const use2D = mode2 !== SceneMode_default.SCENE3D && !frameState.scene3DOnly && model._projectTo2D;
const hasMorphTargets = defined_default(primitive.morphTargets) && primitive.morphTargets.length > 0;
const hasSkinning = defined_default(node.skin);
const hasCustomShader = defined_default(customShader);
const hasCustomFragmentShader = hasCustomShader && defined_default(customShader.fragmentShaderText);
const materialsEnabled = !hasCustomFragmentShader || customShader.mode !== CustomShaderMode_default.REPLACE_MATERIAL;
const hasQuantization = ModelUtility_default.hasQuantizedAttributes(
primitive.attributes
);
const generateWireframeIndices = model.debugWireframe && PrimitiveType_default.isTriangles(primitive.primitiveType) && (model._enableDebugWireframe || useWebgl2);
const pointCloudShading = model.pointCloudShading;
const hasAttenuation = defined_default(pointCloudShading) && pointCloudShading.attenuation;
const hasPointCloudBackFaceCulling = defined_default(pointCloudShading) && pointCloudShading.backFaceCulling;
const hasPointCloudStyle = primitive.primitiveType === PrimitiveType_default.POINTS && (defined_default(style) || hasAttenuation || hasPointCloudBackFaceCulling);
const hasOutlines = model._enableShowOutline && defined_default(primitive.outlineCoordinates);
const featureIdFlags = inspectFeatureIds(model, node, primitive);
const hasClassification = defined_default(model.classificationType);
if (use2D) {
pipelineStages.push(SceneMode2DPipelineStage_default);
}
pipelineStages.push(GeometryPipelineStage_default);
if (generateWireframeIndices) {
pipelineStages.push(WireframePipelineStage_default);
}
if (hasClassification) {
pipelineStages.push(ClassificationPipelineStage_default);
}
if (hasMorphTargets) {
pipelineStages.push(MorphTargetsPipelineStage_default);
}
if (hasSkinning) {
pipelineStages.push(SkinningPipelineStage_default);
}
if (hasPointCloudStyle) {
pipelineStages.push(PointCloudStylingPipelineStage_default);
}
if (hasQuantization) {
pipelineStages.push(DequantizationPipelineStage_default);
}
if (materialsEnabled) {
pipelineStages.push(MaterialPipelineStage_default);
}
pipelineStages.push(FeatureIdPipelineStage_default);
pipelineStages.push(MetadataPipelineStage_default);
if (featureIdFlags.hasPropertyTable) {
pipelineStages.push(SelectedFeatureIdPipelineStage_default);
pipelineStages.push(BatchTexturePipelineStage_default);
pipelineStages.push(CPUStylingPipelineStage_default);
}
if (hasCustomShader) {
pipelineStages.push(CustomShaderPipelineStage_default);
}
pipelineStages.push(LightingPipelineStage_default);
if (model.allowPicking) {
pipelineStages.push(PickingPipelineStage_default);
}
if (hasOutlines) {
pipelineStages.push(PrimitiveOutlinePipelineStage_default);
}
pipelineStages.push(AlphaPipelineStage_default);
pipelineStages.push(PrimitiveStatisticsPipelineStage_default);
return;
};
function inspectFeatureIds(model, node, primitive) {
let featureIds;
if (defined_default(node.instances)) {
featureIds = ModelUtility_default.getFeatureIdsByLabel(
node.instances.featureIds,
model.instanceFeatureIdLabel
);
if (defined_default(featureIds)) {
return {
hasFeatureIds: true,
hasPropertyTable: defined_default(featureIds.propertyTableId)
};
}
}
featureIds = ModelUtility_default.getFeatureIdsByLabel(
primitive.featureIds,
model.featureIdLabel
);
if (defined_default(featureIds)) {
return {
hasFeatureIds: true,
hasPropertyTable: defined_default(featureIds.propertyTableId)
};
}
return {
hasFeatureIds: false,
hasPropertyTable: false
};
}
var ModelRuntimePrimitive_default = ModelRuntimePrimitive;
// node_modules/@cesium/engine/Source/Scene/Model/ModelSkin.js
function ModelSkin(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.skin", options.skin);
Check_default.typeOf.object("options.sceneGraph", options.sceneGraph);
this._sceneGraph = options.sceneGraph;
const skin = options.skin;
this._skin = skin;
this._inverseBindMatrices = void 0;
this._joints = [];
this._jointMatrices = [];
initialize13(this);
}
Object.defineProperties(ModelSkin.prototype, {
skin: {
get: function() {
return this._skin;
}
},
sceneGraph: {
get: function() {
return this._sceneGraph;
}
},
inverseBindMatrices: {
get: function() {
return this._inverseBindMatrices;
}
},
joints: {
get: function() {
return this._joints;
}
},
jointMatrices: {
get: function() {
return this._jointMatrices;
}
}
});
function initialize13(runtimeSkin) {
const skin = runtimeSkin.skin;
const inverseBindMatrices = skin.inverseBindMatrices;
runtimeSkin._inverseBindMatrices = inverseBindMatrices;
const joints = skin.joints;
const length3 = joints.length;
const runtimeNodes = runtimeSkin.sceneGraph._runtimeNodes;
const runtimeJoints = runtimeSkin.joints;
const runtimeJointMatrices = runtimeSkin._jointMatrices;
for (let i = 0; i < length3; i++) {
const jointIndex = joints[i].index;
const runtimeNode = runtimeNodes[jointIndex];
runtimeJoints.push(runtimeNode);
const inverseBindMatrix = inverseBindMatrices[i];
const jointMatrix = computeJointMatrix(
runtimeNode,
inverseBindMatrix,
new Matrix4_default()
);
runtimeJointMatrices.push(jointMatrix);
}
}
function computeJointMatrix(joint, inverseBindMatrix, result) {
const jointWorldTransform = Matrix4_default.multiplyTransformation(
joint.transformToRoot,
joint.transform,
result
);
result = Matrix4_default.multiplyTransformation(
jointWorldTransform,
inverseBindMatrix,
result
);
return result;
}
ModelSkin.prototype.updateJointMatrices = function() {
const jointMatrices = this._jointMatrices;
const length3 = jointMatrices.length;
for (let i = 0; i < length3; i++) {
const joint = this.joints[i];
const inverseBindMatrix = this.inverseBindMatrices[i];
jointMatrices[i] = computeJointMatrix(
joint,
inverseBindMatrix,
jointMatrices[i]
);
}
};
var ModelSkin_default = ModelSkin;
// node_modules/@cesium/engine/Source/Scene/Model/ModelAlphaOptions.js
function ModelAlphaOptions() {
this.pass = void 0;
this.alphaCutoff = void 0;
}
var ModelAlphaOptions_default = ModelAlphaOptions;
// node_modules/@cesium/engine/Source/Scene/Model/ModelRenderResources.js
function ModelRenderResources(model) {
Check_default.typeOf.object("model", model);
this.shaderBuilder = new ShaderBuilder_default();
this.model = model;
this.uniformMap = {};
this.alphaOptions = new ModelAlphaOptions_default();
this.renderStateOptions = RenderState_default.getState(
RenderState_default.fromCache({
depthTest: {
enabled: true,
func: DepthFunction_default.LESS_OR_EQUAL
}
})
);
this.hasSilhouette = false;
this.hasSkipLevelOfDetail = false;
}
var ModelRenderResources_default = ModelRenderResources;
// node_modules/@cesium/engine/Source/Shaders/Model/ModelSilhouetteStageFS.js
var ModelSilhouetteStageFS_default = "void silhouetteStage(inout vec4 color) {\n if(model_silhouettePass) {\n color = czm_gammaCorrect(model_silhouetteColor);\n }\n}";
// node_modules/@cesium/engine/Source/Shaders/Model/ModelSilhouetteStageVS.js
var ModelSilhouetteStageVS_default = "void silhouetteStage(in ProcessedAttributes attributes, inout vec4 positionClip) {\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 positionClip.xy += normal.xy * positionClip.w * model_silhouetteSize * czm_pixelRatio / czm_viewport.z;\n }\n #endif\n}\n";
// node_modules/@cesium/engine/Source/Scene/Model/ModelSilhouettePipelineStage.js
var ModelSilhouettePipelineStage = {
name: "ModelSilhouettePipelineStage"
};
ModelSilhouettePipelineStage.silhouettesLength = 0;
ModelSilhouettePipelineStage.process = function(renderResources, model, frameState) {
if (!defined_default(model._silhouetteId)) {
model._silhouetteId = ++ModelSilhouettePipelineStage.silhouettesLength;
}
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine("HAS_SILHOUETTE", void 0, ShaderDestination_default.BOTH);
shaderBuilder.addVertexLines(ModelSilhouetteStageVS_default);
shaderBuilder.addFragmentLines(ModelSilhouetteStageFS_default);
shaderBuilder.addUniform(
"vec4",
"model_silhouetteColor",
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addUniform(
"float",
"model_silhouetteSize",
ShaderDestination_default.VERTEX
);
shaderBuilder.addUniform(
"bool",
"model_silhouettePass",
ShaderDestination_default.BOTH
);
const uniformMap2 = {
model_silhouetteColor: function() {
return model.silhouetteColor;
},
model_silhouetteSize: function() {
return model.silhouetteSize;
},
model_silhouettePass: function() {
return false;
}
};
renderResources.uniformMap = combine_default(uniformMap2, renderResources.uniformMap);
renderResources.hasSilhouette = true;
};
var ModelSilhouettePipelineStage_default = ModelSilhouettePipelineStage;
// node_modules/@cesium/engine/Source/Shaders/Model/ModelSplitterStageFS.js
var ModelSplitterStageFS_default = "void modelSplitterStage()\n{\n // Don't split when rendering the shadow map, because it is rendered from\n // the perspective of a totally different camera.\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";
// node_modules/@cesium/engine/Source/Scene/Model/ModelSplitterPipelineStage.js
var ModelSplitterPipelineStage = {
name: "ModelSplitterPipelineStage",
SPLIT_DIRECTION_UNIFORM_NAME: "model_splitDirection"
};
ModelSplitterPipelineStage.process = function(renderResources, model, frameState) {
const shaderBuilder = renderResources.shaderBuilder;
shaderBuilder.addDefine(
"HAS_MODEL_SPLITTER",
void 0,
ShaderDestination_default.FRAGMENT
);
shaderBuilder.addFragmentLines(ModelSplitterStageFS_default);
const stageUniforms = {};
shaderBuilder.addUniform(
"float",
ModelSplitterPipelineStage.SPLIT_DIRECTION_UNIFORM_NAME,
ShaderDestination_default.FRAGMENT
);
stageUniforms[ModelSplitterPipelineStage.SPLIT_DIRECTION_UNIFORM_NAME] = function() {
return model.splitDirection;
};
renderResources.uniformMap = combine_default(
stageUniforms,
renderResources.uniformMap
);
};
var ModelSplitterPipelineStage_default = ModelSplitterPipelineStage;
// node_modules/@cesium/engine/Source/Scene/Model/NodeRenderResources.js
function NodeRenderResources(modelRenderResources, runtimeNode) {
Check_default.typeOf.object("modelRenderResources", modelRenderResources);
Check_default.typeOf.object("runtimeNode", runtimeNode);
this.model = modelRenderResources.model;
this.shaderBuilder = modelRenderResources.shaderBuilder.clone();
this.uniformMap = clone_default(modelRenderResources.uniformMap);
this.alphaOptions = clone_default(modelRenderResources.alphaOptions);
this.renderStateOptions = clone_default(
modelRenderResources.renderStateOptions,
true
);
this.hasSilhouette = modelRenderResources.hasSilhouette;
this.hasSkipLevelOfDetail = modelRenderResources.hasSkipLevelOfDetail;
this.runtimeNode = runtimeNode;
this.attributes = [];
this.attributeIndex = 1;
this.featureIdVertexAttributeSetIndex = 0;
this.instanceCount = 0;
}
var NodeRenderResources_default = NodeRenderResources;
// node_modules/@cesium/engine/Source/Scene/Model/ModelLightingOptions.js
function ModelLightingOptions(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.lightingModel = defaultValue_default(options.lightingModel, LightingModel_default.UNLIT);
}
var ModelLightingOptions_default = ModelLightingOptions;
// node_modules/@cesium/engine/Source/Scene/Model/PrimitiveRenderResources.js
function PrimitiveRenderResources(nodeRenderResources, runtimePrimitive) {
Check_default.typeOf.object("nodeRenderResources", nodeRenderResources);
Check_default.typeOf.object("runtimePrimitive", runtimePrimitive);
this.model = nodeRenderResources.model;
this.runtimeNode = nodeRenderResources.runtimeNode;
this.attributes = nodeRenderResources.attributes.slice();
this.attributeIndex = nodeRenderResources.attributeIndex;
this.featureIdVertexAttributeSetIndex = nodeRenderResources.featureIdVertexAttributeSetIndex;
this.uniformMap = clone_default(nodeRenderResources.uniformMap);
this.alphaOptions = clone_default(nodeRenderResources.alphaOptions);
this.renderStateOptions = clone_default(nodeRenderResources.renderStateOptions, true);
this.hasSilhouette = nodeRenderResources.hasSilhouette;
this.hasSkipLevelOfDetail = nodeRenderResources.hasSkipLevelOfDetail;
this.shaderBuilder = nodeRenderResources.shaderBuilder.clone();
this.instanceCount = nodeRenderResources.instanceCount;
this.runtimePrimitive = runtimePrimitive;
const primitive = runtimePrimitive.primitive;
this.count = defined_default(primitive.indices) ? primitive.indices.count : ModelUtility_default.getAttributeBySemantic(primitive, "POSITION").count;
this.hasPropertyTable = false;
this.indices = primitive.indices;
this.wireframeIndexBuffer = void 0;
this.primitiveType = primitive.primitiveType;
const positionMinMax = ModelUtility_default.getPositionMinMax(
primitive,
this.runtimeNode.instancingTranslationMin,
this.runtimeNode.instancingTranslationMax
);
this.positionMin = Cartesian3_default.clone(positionMinMax.min, new Cartesian3_default());
this.positionMax = Cartesian3_default.clone(positionMinMax.max, new Cartesian3_default());
this.boundingSphere = BoundingSphere_default.fromCornerPoints(
this.positionMin,
this.positionMax,
new BoundingSphere_default()
);
this.lightingOptions = new ModelLightingOptions_default();
this.pickId = void 0;
}
var PrimitiveRenderResources_default = PrimitiveRenderResources;
// node_modules/@cesium/engine/Source/Scene/Model/ModelSceneGraph.js
function ModelSceneGraph(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const components = options.modelComponents;
Check_default.typeOf.object("options.model", options.model);
Check_default.typeOf.object("options.modelComponents", components);
this._model = options.model;
this._components = components;
this._pipelineStages = [];
this._updateStages = [];
this._runtimeNodes = [];
this._rootNodes = [];
this._skinnedNodes = [];
this._runtimeSkins = [];
this.modelPipelineStages = [];
this._boundingSphere = void 0;
this._boundingSphere2D = void 0;
this._computedModelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._computedModelMatrix2D = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._axisCorrectionMatrix = ModelUtility_default.getAxisCorrectionMatrix(
components.upAxis,
components.forwardAxis,
new Matrix4_default()
);
this._runtimeArticulations = {};
initialize14(this);
}
Object.defineProperties(ModelSceneGraph.prototype, {
components: {
get: function() {
return this._components;
}
},
computedModelMatrix: {
get: function() {
return this._computedModelMatrix;
}
},
axisCorrectionMatrix: {
get: function() {
return this._axisCorrectionMatrix;
}
},
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
function initialize14(sceneGraph) {
const components = sceneGraph._components;
const scene = components.scene;
const model = sceneGraph._model;
const modelMatrix = 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 ModelArticulation_default({
articulation,
sceneGraph
});
const name = runtimeArticulation.name;
runtimeArticulations[name] = runtimeArticulation;
}
const nodes = components.nodes;
const nodesLength = nodes.length;
sceneGraph._runtimeNodes = new Array(nodesLength);
const rootNodes = scene.nodes;
const rootNodesLength = rootNodes.length;
const transformToRoot = Matrix4_default.IDENTITY;
for (let i = 0; i < rootNodesLength; i++) {
const rootNode = scene.nodes[i];
const rootNodeIndex = traverseAndCreateSceneGraph(
sceneGraph,
rootNode,
transformToRoot
);
sceneGraph._rootNodes.push(rootNodeIndex);
}
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 ModelSkin_default({
skin,
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];
const skin = nodes[skinnedNodeIndex].skin;
const skinIndex = skin.index;
skinnedNode._runtimeSkin = runtimeSkins[skinIndex];
skinnedNode.updateJointMatrices();
}
sceneGraph.applyArticulations();
}
function computeModelMatrix(sceneGraph, modelMatrix) {
const components = sceneGraph._components;
const model = sceneGraph._model;
sceneGraph._computedModelMatrix = Matrix4_default.multiplyTransformation(
modelMatrix,
components.transform,
sceneGraph._computedModelMatrix
);
sceneGraph._computedModelMatrix = Matrix4_default.multiplyTransformation(
sceneGraph._computedModelMatrix,
sceneGraph._axisCorrectionMatrix,
sceneGraph._computedModelMatrix
);
sceneGraph._computedModelMatrix = Matrix4_default.multiplyByUniformScale(
sceneGraph._computedModelMatrix,
model.computedScale,
sceneGraph._computedModelMatrix
);
}
var scratchComputedTranslation = new Cartesian3_default();
function computeModelMatrix2D(sceneGraph, frameState) {
const computedModelMatrix = sceneGraph._computedModelMatrix;
const translation3 = Matrix4_default.getTranslation(
computedModelMatrix,
scratchComputedTranslation
);
if (!Cartesian3_default.equals(translation3, Cartesian3_default.ZERO)) {
sceneGraph._computedModelMatrix2D = Transforms_default.basisTo2D(
frameState.mapProjection,
computedModelMatrix,
sceneGraph._computedModelMatrix2D
);
} else {
const center = sceneGraph.boundingSphere.center;
const to2D = Transforms_default.wgs84To2DModelMatrix(
frameState.mapProjection,
center,
sceneGraph._computedModelMatrix2D
);
sceneGraph._computedModelMatrix2D = Matrix4_default.multiply(
to2D,
computedModelMatrix,
sceneGraph._computedModelMatrix2D
);
}
sceneGraph._boundingSphere2D = BoundingSphere_default.transform(
sceneGraph._boundingSphere,
sceneGraph._computedModelMatrix2D,
sceneGraph._boundingSphere2D
);
}
function traverseAndCreateSceneGraph(sceneGraph, node, transformToRoot) {
const childrenIndices = [];
const transform3 = ModelUtility_default.getNodeTransform(node);
const childrenLength = node.children.length;
for (let i = 0; i < childrenLength; i++) {
const childNode = node.children[i];
const childNodeTransformToRoot = Matrix4_default.multiplyTransformation(
transformToRoot,
transform3,
new Matrix4_default()
);
const childIndex = traverseAndCreateSceneGraph(
sceneGraph,
childNode,
childNodeTransformToRoot
);
childrenIndices.push(childIndex);
}
const runtimeNode = new ModelRuntimeNode_default({
node,
transform: transform3,
transformToRoot,
children: childrenIndices,
sceneGraph
});
const primitivesLength = node.primitives.length;
for (let i = 0; i < primitivesLength; i++) {
runtimeNode.runtimePrimitives.push(
new ModelRuntimePrimitive_default({
primitive: node.primitives[i],
node,
model: sceneGraph._model
})
);
}
const index = node.index;
sceneGraph._runtimeNodes[index] = runtimeNode;
if (defined_default(node.skin)) {
sceneGraph._skinnedNodes.push(index);
}
const name = node.name;
if (defined_default(name)) {
const model = sceneGraph._model;
const publicNode = new ModelNode_default(model, runtimeNode);
model._nodesByName[name] = publicNode;
}
return index;
}
var scratchModelPositionMin = new Cartesian3_default();
var scratchModelPositionMax = new Cartesian3_default();
var scratchPrimitivePositionMin = new Cartesian3_default();
var scratchPrimitivePositionMax = new Cartesian3_default();
ModelSceneGraph.prototype.buildDrawCommands = function(frameState) {
const model = this._model;
const modelRenderResources = new ModelRenderResources_default(model);
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_default.fromElements(
Number.MAX_VALUE,
Number.MAX_VALUE,
Number.MAX_VALUE,
scratchModelPositionMin
);
const modelPositionMax = Cartesian3_default.fromElements(
-Number.MAX_VALUE,
-Number.MAX_VALUE,
-Number.MAX_VALUE,
scratchModelPositionMax
);
for (i = 0; i < this._runtimeNodes.length; i++) {
const runtimeNode = this._runtimeNodes[i];
if (!defined_default(runtimeNode)) {
continue;
}
runtimeNode.configurePipeline();
const nodePipelineStages = runtimeNode.pipelineStages;
const nodeRenderResources = new NodeRenderResources_default(
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_default(
nodeRenderResources,
runtimePrimitive
);
for (k = 0; k < primitivePipelineStages.length; k++) {
const primitivePipelineStage = primitivePipelineStages[k];
primitivePipelineStage.process(
primitiveRenderResources,
runtimePrimitive.primitive,
frameState
);
}
runtimePrimitive.boundingSphere = BoundingSphere_default.clone(
primitiveRenderResources.boundingSphere,
new BoundingSphere_default()
);
const primitivePositionMin = Matrix4_default.multiplyByPoint(
nodeTransform,
primitiveRenderResources.positionMin,
scratchPrimitivePositionMin
);
const primitivePositionMax = Matrix4_default.multiplyByPoint(
nodeTransform,
primitiveRenderResources.positionMax,
scratchPrimitivePositionMax
);
Cartesian3_default.minimumByComponent(
modelPositionMin,
primitivePositionMin,
modelPositionMin
);
Cartesian3_default.maximumByComponent(
modelPositionMax,
primitivePositionMax,
modelPositionMax
);
const drawCommand = buildDrawCommand_default(
primitiveRenderResources,
frameState
);
runtimePrimitive.drawCommand = drawCommand;
}
}
this._boundingSphere = BoundingSphere_default.fromCornerPoints(
modelPositionMin,
modelPositionMax,
new BoundingSphere_default()
);
this._boundingSphere = BoundingSphere_default.transformWithoutScale(
this._boundingSphere,
this._axisCorrectionMatrix,
this._boundingSphere
);
this._boundingSphere = BoundingSphere_default.transform(
this._boundingSphere,
this._components.transform,
this._boundingSphere
);
model._boundingSphere = BoundingSphere_default.transform(
this._boundingSphere,
model.modelMatrix,
model._boundingSphere
);
model._initialRadius = model._boundingSphere.radius;
model._boundingSphere.radius *= model._clampedScale;
};
ModelSceneGraph.prototype.configurePipeline = function(frameState) {
const modelPipelineStages = this.modelPipelineStages;
modelPipelineStages.length = 0;
const model = this._model;
if (defined_default(model.color)) {
modelPipelineStages.push(ModelColorPipelineStage_default);
}
if (defined_default(model.classificationType)) {
return;
}
if (model.imageBasedLighting.enabled) {
modelPipelineStages.push(ImageBasedLightingPipelineStage_default);
}
if (model.isClippingEnabled()) {
modelPipelineStages.push(ModelClippingPlanesPipelineStage_default);
}
if (model.hasSilhouette(frameState)) {
modelPipelineStages.push(ModelSilhouettePipelineStage_default);
}
if (defined_default(model.splitDirection) && model.splitDirection !== SplitDirection_default.NONE) {
modelPipelineStages.push(ModelSplitterPipelineStage_default);
}
if (ModelType_default.is3DTiles(model.type)) {
modelPipelineStages.push(TilesetPipelineStage_default);
}
};
ModelSceneGraph.prototype.update = function(frameState, updateForAnimations) {
let i, j, k;
for (i = 0; i < this._runtimeNodes.length; i++) {
const runtimeNode = this._runtimeNodes[i];
if (!defined_default(runtimeNode)) {
continue;
}
for (j = 0; j < runtimeNode.updateStages.length; j++) {
const nodeUpdateStage = runtimeNode.updateStages[j];
nodeUpdateStage.update(runtimeNode, this, frameState);
}
const disableAnimations = frameState.mode !== SceneMode_default.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);
}
}
}
};
ModelSceneGraph.prototype.updateModelMatrix = function(modelMatrix, frameState) {
computeModelMatrix(this, modelMatrix);
if (frameState.mode !== SceneMode_default.SCENE3D) {
computeModelMatrix2D(this, frameState);
}
const rootNodes = this._rootNodes;
for (let i = 0; i < rootNodes.length; i++) {
const node = this._runtimeNodes[rootNodes[i]];
node._transformDirty = true;
}
};
ModelSceneGraph.prototype.updateJointMatrices = function() {
const skinnedNodes = this._skinnedNodes;
const length3 = skinnedNodes.length;
for (let i = 0; i < length3; i++) {
const nodeIndex = skinnedNodes[i];
const runtimeNode = this._runtimeNodes[nodeIndex];
runtimeNode.updateJointMatrices();
}
};
function traverseSceneGraph(sceneGraph, runtimeNode, visibleNodesOnly, callback, callbackOptions) {
if (visibleNodesOnly && !runtimeNode.show) {
return;
}
const childrenLength = runtimeNode.children.length;
for (let i = 0; i < childrenLength; i++) {
const childRuntimeNode = runtimeNode.getChild(i);
traverseSceneGraph(
sceneGraph,
childRuntimeNode,
visibleNodesOnly,
callback,
callbackOptions
);
}
const runtimePrimitives = runtimeNode.runtimePrimitives;
const runtimePrimitivesLength = runtimePrimitives.length;
for (let j = 0; j < runtimePrimitivesLength; j++) {
const runtimePrimitive = runtimePrimitives[j];
callback(runtimePrimitive, callbackOptions);
}
}
function forEachRuntimePrimitive(sceneGraph, visibleNodesOnly, callback, callbackOptions) {
const rootNodes = sceneGraph._rootNodes;
const rootNodesLength = rootNodes.length;
for (let i = 0; i < rootNodesLength; i++) {
const rootNodeIndex = rootNodes[i];
const runtimeNode = sceneGraph._runtimeNodes[rootNodeIndex];
traverseSceneGraph(
sceneGraph,
runtimeNode,
visibleNodesOnly,
callback,
callbackOptions
);
}
}
var scratchBackFaceCullingOptions = {
backFaceCulling: void 0
};
ModelSceneGraph.prototype.updateBackFaceCulling = function(backFaceCulling) {
const backFaceCullingOptions = scratchBackFaceCullingOptions;
backFaceCullingOptions.backFaceCulling = backFaceCulling;
forEachRuntimePrimitive(
this,
false,
updatePrimitiveBackFaceCulling,
backFaceCullingOptions
);
};
function updatePrimitiveBackFaceCulling(runtimePrimitive, options) {
const drawCommand = runtimePrimitive.drawCommand;
drawCommand.backFaceCulling = options.backFaceCulling;
}
var scratchShadowOptions = {
shadowMode: void 0
};
ModelSceneGraph.prototype.updateShadows = function(shadowMode) {
const shadowOptions = scratchShadowOptions;
shadowOptions.shadowMode = shadowMode;
forEachRuntimePrimitive(this, false, updatePrimitiveShadows, shadowOptions);
};
function updatePrimitiveShadows(runtimePrimitive, options) {
const drawCommand = runtimePrimitive.drawCommand;
drawCommand.shadows = options.shadowMode;
}
var scratchShowBoundingVolumeOptions = {
debugShowBoundingVolume: void 0
};
ModelSceneGraph.prototype.updateShowBoundingVolume = function(debugShowBoundingVolume2) {
const showBoundingVolumeOptions = scratchShowBoundingVolumeOptions;
showBoundingVolumeOptions.debugShowBoundingVolume = debugShowBoundingVolume2;
forEachRuntimePrimitive(
this,
false,
updatePrimitiveShowBoundingVolume,
showBoundingVolumeOptions
);
};
function updatePrimitiveShowBoundingVolume(runtimePrimitive, options) {
const drawCommand = runtimePrimitive.drawCommand;
drawCommand.debugShowBoundingVolume = options.debugShowBoundingVolume;
}
var scratchSilhouetteCommands = [];
var scratchPushDrawCommandOptions = {
frameState: void 0,
hasSilhouette: void 0
};
ModelSceneGraph.prototype.pushDrawCommands = function(frameState) {
const silhouetteCommands = scratchSilhouetteCommands;
silhouetteCommands.length = 0;
const pushDrawCommandOptions = scratchPushDrawCommandOptions;
pushDrawCommandOptions.hasSilhouette = this._model.hasSilhouette(frameState);
pushDrawCommandOptions.frameState = frameState;
forEachRuntimePrimitive(
this,
true,
pushPrimitiveDrawCommands,
pushDrawCommandOptions
);
frameState.commandList.push.apply(frameState.commandList, silhouetteCommands);
};
function pushPrimitiveDrawCommands(runtimePrimitive, options) {
const frameState = options.frameState;
const hasSilhouette = options.hasSilhouette;
const passes = frameState.passes;
const silhouetteCommands = scratchSilhouetteCommands;
const primitiveDrawCommand = runtimePrimitive.drawCommand;
primitiveDrawCommand.pushCommands(frameState, frameState.commandList);
if (hasSilhouette && !passes.pick) {
primitiveDrawCommand.pushSilhouetteCommands(frameState, silhouetteCommands);
}
}
ModelSceneGraph.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_default(runtimeArticulation)) {
runtimeArticulation.setArticulationStage(stageName, value);
}
};
ModelSceneGraph.prototype.applyArticulations = function() {
const runtimeArticulations = this._runtimeArticulations;
for (const articulationName in runtimeArticulations) {
if (runtimeArticulations.hasOwnProperty(articulationName)) {
const articulation = runtimeArticulations[articulationName];
articulation.apply();
}
}
};
var ModelSceneGraph_default = ModelSceneGraph;
// node_modules/@cesium/engine/Source/Scene/Model/ModelStatistics.js
function ModelStatistics() {
this.pointsLength = 0;
this.trianglesLength = 0;
this.geometryByteLength = 0;
this.texturesByteLength = 0;
this.propertyTablesByteLength = 0;
this._bufferIdSet = {};
this._textureIdSet = {};
this._batchTextureIdMap = new AssociativeArray_default();
}
Object.defineProperties(ModelStatistics.prototype, {
batchTexturesByteLength: {
get: function() {
const length3 = this._batchTextureIdMap.length;
const values = this._batchTextureIdMap.values;
let memory = 0;
for (let i = 0; i < length3; i++) {
memory += values[i].byteLength;
}
return memory;
}
}
});
ModelStatistics.prototype.clear = function() {
this.pointsLength = 0;
this.trianglesLength = 0;
this.geometryByteLength = 0;
this.texturesByteLength = 0;
this.propertyTablesByteLength = 0;
this._bufferIdSet = {};
this._textureIdSet = {};
this._batchTextureIdMap.removeAll();
};
ModelStatistics.prototype.addBuffer = function(buffer, hasCpuCopy) {
Check_default.typeOf.object("buffer", buffer);
Check_default.typeOf.bool("hasCpuCopy", hasCpuCopy);
if (!this._bufferIdSet.hasOwnProperty(buffer._id)) {
const copies = hasCpuCopy ? 2 : 1;
this.geometryByteLength += buffer.sizeInBytes * copies;
}
this._bufferIdSet[buffer._id] = true;
};
ModelStatistics.prototype.addTexture = function(texture) {
Check_default.typeOf.object("texture", texture);
if (!this._textureIdSet.hasOwnProperty(texture._id)) {
this.texturesByteLength += texture.sizeInBytes;
}
this._textureIdSet[texture._id] = true;
};
ModelStatistics.prototype.addBatchTexture = function(batchTexture) {
Check_default.typeOf.object("batchTexture", batchTexture);
if (!this._batchTextureIdMap.contains(batchTexture._id)) {
this._batchTextureIdMap.set(batchTexture._id, batchTexture);
}
};
var ModelStatistics_default = ModelStatistics;
// node_modules/@cesium/engine/Source/Scene/Model/PntsLoader.js
var import_mersenne_twister2 = __toESM(require_mersenne_twister(), 1);
// node_modules/@cesium/engine/Source/Scene/PntsParser.js
var PntsParser = {};
var sizeOfUint326 = Uint32Array.BYTES_PER_ELEMENT;
PntsParser.parse = function(arrayBuffer, byteOffset) {
byteOffset = defaultValue_default(byteOffset, 0);
Check_default.defined("arrayBuffer", arrayBuffer);
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint326;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Point Cloud tile version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint326;
byteOffset += sizeOfUint326;
const featureTableJsonByteLength = view.getUint32(byteOffset, true);
if (featureTableJsonByteLength === 0) {
throw new RuntimeError_default(
"Feature table must have a byte length greater than zero"
);
}
byteOffset += sizeOfUint326;
const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint326;
const batchTableJsonByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint326;
const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint326;
const featureTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
featureTableJsonByteLength
);
byteOffset += featureTableJsonByteLength;
const featureTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
featureTableBinaryByteLength
);
byteOffset += featureTableBinaryByteLength;
let batchTableJson;
let batchTableBinary;
if (batchTableJsonByteLength > 0) {
batchTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
batchTableJsonByteLength
);
byteOffset += batchTableJsonByteLength;
if (batchTableBinaryByteLength > 0) {
batchTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
batchTableBinaryByteLength
);
byteOffset += batchTableBinaryByteLength;
}
}
const featureTable = new Cesium3DTileFeatureTable_default(
featureTableJson,
featureTableBinary
);
const pointsLength = featureTable.getGlobalProperty("POINTS_LENGTH");
featureTable.featuresLength = pointsLength;
if (!defined_default(pointsLength)) {
throw new RuntimeError_default(
"Feature table global property: POINTS_LENGTH must be defined"
);
}
let rtcCenter = featureTable.getGlobalProperty(
"RTC_CENTER",
ComponentDatatype_default.FLOAT,
3
);
if (defined_default(rtcCenter)) {
rtcCenter = Cartesian3_default.unpack(rtcCenter);
}
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_default(positions);
}
if (!parsedContent.hasPositions) {
throw new RuntimeError_default(
"Either POSITION or POSITION_QUANTIZED must be defined."
);
}
if (!parsedContent.hasNormals) {
const normals = parseNormals(featureTable);
parsedContent.normals = normals;
parsedContent.hasNormals = parsedContent.hasNormals || defined_default(normals);
}
if (!parsedContent.hasColors) {
const colors = parseColors(featureTable);
parsedContent.colors = colors;
parsedContent.hasColors = parsedContent.hasColors || defined_default(colors);
parsedContent.hasConstantColor = defined_default(parsedContent.constantColor);
parsedContent.isTranslucent = defined_default(colors) && colors.isTranslucent;
}
if (!parsedContent.hasBatchIds) {
const batchIds = parseBatchIds(featureTable);
parsedContent.batchIds = batchIds;
parsedContent.hasBatchIds = parsedContent.hasBatchIds || defined_default(batchIds);
}
if (parsedContent.hasBatchIds) {
const batchLength = featureTable.getGlobalProperty("BATCH_LENGTH");
if (!defined_default(batchLength)) {
throw new RuntimeError_default(
"Global property: BATCH_LENGTH must be defined when BATCH_ID is defined."
);
}
parsedContent.batchLength = batchLength;
}
if (defined_default(batchTableBinary)) {
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_default(featureTableJson.extensions) ? featureTableJson.extensions["3DTILES_draco_point_compression"] : void 0;
const batchTableDraco = defined_default(batchTableJson) && defined_default(batchTableJson.extensions) ? batchTableJson.extensions["3DTILES_draco_point_compression"] : void 0;
if (defined_default(batchTableDraco)) {
dracoBatchTableProperties = batchTableDraco.properties;
}
let hasPositions;
let hasColors;
let hasNormals;
let hasBatchIds;
let isTranslucent;
if (defined_default(featureTableDraco)) {
dracoFeatureTableProperties = featureTableDraco.properties;
const dracoByteOffset = featureTableDraco.byteOffset;
const dracoByteLength = featureTableDraco.byteLength;
if (!defined_default(dracoFeatureTableProperties) || !defined_default(dracoByteOffset) || !defined_default(dracoByteLength)) {
throw new RuntimeError_default(
"Draco properties, byteOffset, and byteLength must be defined"
);
}
dracoBuffer = featureTable.buffer.slice(
dracoByteOffset,
dracoByteOffset + dracoByteLength
);
hasPositions = defined_default(dracoFeatureTableProperties.POSITION);
hasColors = defined_default(dracoFeatureTableProperties.RGB) || defined_default(dracoFeatureTableProperties.RGBA);
hasNormals = defined_default(dracoFeatureTableProperties.NORMAL);
hasBatchIds = defined_default(dracoFeatureTableProperties.BATCH_ID);
isTranslucent = defined_default(dracoFeatureTableProperties.RGBA);
}
let draco;
if (defined_default(dracoBuffer)) {
draco = {
buffer: dracoBuffer,
featureTableProperties: dracoFeatureTableProperties,
batchTableProperties: dracoBatchTableProperties,
properties: combine_default(
dracoFeatureTableProperties,
dracoBatchTableProperties
),
dequantizeInShader: true
};
}
return {
draco,
hasPositions,
hasColors,
isTranslucent,
hasNormals,
hasBatchIds
};
}
function parsePositions(featureTable) {
const featureTableJson = featureTable.json;
let positions;
if (defined_default(featureTableJson.POSITION)) {
positions = featureTable.getPropertyArray(
"POSITION",
ComponentDatatype_default.FLOAT,
3
);
return {
name: VertexAttributeSemantic_default.POSITION,
semantic: VertexAttributeSemantic_default.POSITION,
typedArray: positions,
isQuantized: false,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3
};
} else if (defined_default(featureTableJson.POSITION_QUANTIZED)) {
positions = featureTable.getPropertyArray(
"POSITION_QUANTIZED",
ComponentDatatype_default.UNSIGNED_SHORT,
3
);
const quantizedVolumeScale = featureTable.getGlobalProperty(
"QUANTIZED_VOLUME_SCALE",
ComponentDatatype_default.FLOAT,
3
);
if (!defined_default(quantizedVolumeScale)) {
throw new RuntimeError_default(
"Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
);
}
const quantizedRange = (1 << 16) - 1;
const quantizedVolumeOffset = featureTable.getGlobalProperty(
"QUANTIZED_VOLUME_OFFSET",
ComponentDatatype_default.FLOAT,
3
);
if (!defined_default(quantizedVolumeOffset)) {
throw new RuntimeError_default(
"Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
);
}
return {
name: VertexAttributeSemantic_default.POSITION,
semantic: VertexAttributeSemantic_default.POSITION,
typedArray: positions,
isQuantized: true,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
quantizedRange,
quantizedVolumeOffset: Cartesian3_default.unpack(quantizedVolumeOffset),
quantizedVolumeScale: Cartesian3_default.unpack(quantizedVolumeScale),
quantizedComponentDatatype: ComponentDatatype_default.UNSIGNED_SHORT,
quantizedType: AttributeType_default.VEC3
};
}
}
function parseColors(featureTable) {
const featureTableJson = featureTable.json;
let colors;
if (defined_default(featureTableJson.RGBA)) {
colors = featureTable.getPropertyArray(
"RGBA",
ComponentDatatype_default.UNSIGNED_BYTE,
4
);
return {
name: VertexAttributeSemantic_default.COLOR,
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: colors,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC4,
normalized: true,
isRGB565: false,
isTranslucent: true
};
} else if (defined_default(featureTableJson.RGB)) {
colors = featureTable.getPropertyArray(
"RGB",
ComponentDatatype_default.UNSIGNED_BYTE,
3
);
return {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: colors,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC3,
normalized: true,
isRGB565: false,
isTranslucent: false
};
} else if (defined_default(featureTableJson.RGB565)) {
colors = featureTable.getPropertyArray(
"RGB565",
ComponentDatatype_default.UNSIGNED_SHORT,
1
);
return {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: colors,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
normalized: false,
isRGB565: true,
isTranslucent: false
};
} else if (defined_default(featureTableJson.CONSTANT_RGBA)) {
const constantRGBA = featureTable.getGlobalProperty(
"CONSTANT_RGBA",
ComponentDatatype_default.UNSIGNED_BYTE,
4
);
const alpha = constantRGBA[3];
const constantColor = Color_default.fromBytes(
constantRGBA[0],
constantRGBA[1],
constantRGBA[2],
alpha
);
const isTranslucent = alpha < 255;
return {
name: VertexAttributeSemantic_default.COLOR,
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
constantColor,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC4,
isQuantized: false,
isTranslucent
};
}
return void 0;
}
function parseNormals(featureTable) {
const featureTableJson = featureTable.json;
let normals;
if (defined_default(featureTableJson.NORMAL)) {
normals = featureTable.getPropertyArray(
"NORMAL",
ComponentDatatype_default.FLOAT,
3
);
return {
name: VertexAttributeSemantic_default.NORMAL,
semantic: VertexAttributeSemantic_default.NORMAL,
typedArray: normals,
octEncoded: false,
octEncodedZXY: false,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3
};
} else if (defined_default(featureTableJson.NORMAL_OCT16P)) {
normals = featureTable.getPropertyArray(
"NORMAL_OCT16P",
ComponentDatatype_default.UNSIGNED_BYTE,
2
);
const quantizationBits = 8;
return {
name: VertexAttributeSemantic_default.NORMAL,
semantic: VertexAttributeSemantic_default.NORMAL,
typedArray: normals,
octEncoded: true,
octEncodedZXY: false,
quantizedRange: (1 << quantizationBits) - 1,
quantizedType: AttributeType_default.VEC2,
quantizedComponentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3
};
}
return void 0;
}
function parseBatchIds(featureTable) {
const featureTableJson = featureTable.json;
if (defined_default(featureTableJson.BATCH_ID)) {
const batchIds = featureTable.getPropertyArray(
"BATCH_ID",
ComponentDatatype_default.UNSIGNED_SHORT,
1
);
return {
name: VertexAttributeSemantic_default.FEATURE_ID,
semantic: VertexAttributeSemantic_default.FEATURE_ID,
setIndex: 0,
typedArray: batchIds,
componentDatatype: ComponentDatatype_default.fromTypedArray(batchIds),
type: AttributeType_default.SCALAR
};
}
return void 0;
}
var PntsParser_default = PntsParser;
// node_modules/@cesium/engine/Source/Scene/Model/PntsLoader.js
var Components3 = ModelComponents_default.Components;
var Scene3 = ModelComponents_default.Scene;
var Node5 = ModelComponents_default.Node;
var Primitive4 = ModelComponents_default.Primitive;
var Attribute4 = ModelComponents_default.Attribute;
var Quantization2 = ModelComponents_default.Quantization;
var FeatureIdAttribute5 = ModelComponents_default.FeatureIdAttribute;
var Material5 = ModelComponents_default.Material;
var MetallicRoughness4 = ModelComponents_default.MetallicRoughness;
function PntsLoader(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const arrayBuffer = options.arrayBuffer;
const byteOffset = defaultValue_default(options.byteOffset, 0);
Check_default.typeOf.object("options.arrayBuffer", arrayBuffer);
this._arrayBuffer = arrayBuffer;
this._byteOffset = byteOffset;
this._loadAttributesFor2D = defaultValue_default(options.loadAttributesFor2D, false);
this._parsedContent = void 0;
this._decodePromise = void 0;
this._decodedAttributes = void 0;
this._promise = void 0;
this._error = void 0;
this._state = ResourceLoaderState_default.UNLOADED;
this._buffers = [];
this._components = void 0;
this._transform = Matrix4_default.IDENTITY;
}
if (defined_default(Object.create)) {
PntsLoader.prototype = Object.create(ResourceLoader_default.prototype);
PntsLoader.prototype.constructor = PntsLoader;
}
Object.defineProperties(PntsLoader.prototype, {
cacheKey: {
get: function() {
return void 0;
}
},
components: {
get: function() {
return this._components;
}
},
transform: {
get: function() {
return this._transform;
}
}
});
PntsLoader.prototype.load = function() {
if (defined_default(this._promise)) {
return this._promise;
}
this._parsedContent = PntsParser_default.parse(this._arrayBuffer, this._byteOffset);
this._state = ResourceLoaderState_default.PROCESSING;
this._promise = Promise.resolve(this);
};
PntsLoader.prototype.process = function(frameState) {
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
if (this._state === ResourceLoaderState_default.READY) {
return true;
}
if (this._state === ResourceLoaderState_default.PROCESSING) {
if (defined_default(this._decodePromise)) {
return false;
}
this._decodePromise = decodeDraco(this, frameState.context);
}
return false;
};
function decodeDraco(loader, context) {
const parsedContent = loader._parsedContent;
const draco = parsedContent.draco;
let decodePromise;
if (!defined_default(draco)) {
decodePromise = Promise.resolve();
} else {
decodePromise = DracoLoader_default.decodePointCloud(draco, context);
}
if (!defined_default(decodePromise)) {
return;
}
loader._decodePromise = decodePromise;
return decodePromise.then(function(decodeDracoResult) {
if (loader.isDestroyed()) {
return;
}
if (defined_default(decodeDracoResult)) {
processDracoAttributes(loader, draco, decodeDracoResult);
}
makeComponents(loader, context);
loader._state = ResourceLoaderState_default.READY;
return loader;
}).catch(function(error) {
loader.unload();
loader._state = ResourceLoaderState_default.FAILED;
const errorMessage = "Failed to load Draco pnts";
loader._error = loader.getError(errorMessage, error);
});
}
function processDracoAttributes(loader, draco, result) {
loader._state = ResourceLoaderState_default.READY;
const parsedContent = loader._parsedContent;
let attribute;
if (defined_default(result.POSITION)) {
attribute = {
name: "POSITION",
semantic: VertexAttributeSemantic_default.POSITION,
typedArray: result.POSITION.array,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
isQuantized: false
};
if (defined_default(result.POSITION.data.quantization)) {
const quantization = result.POSITION.data.quantization;
const range = quantization.range;
const quantizedVolumeScale = Cartesian3_default.fromElements(range, range, range);
const quantizedVolumeOffset = Cartesian3_default.unpack(quantization.minValues);
const quantizedRange = (1 << quantization.quantizationBits) - 1;
attribute.isQuantized = true;
attribute.quantizedRange = quantizedRange;
attribute.quantizedVolumeOffset = quantizedVolumeOffset;
attribute.quantizedVolumeScale = quantizedVolumeScale;
attribute.quantizedComponentDatatype = quantizedRange <= 255 ? ComponentDatatype_default.UNSIGNED_BYTE : ComponentDatatype_default.UNSIGNED_SHORT;
attribute.quantizedType = AttributeType_default.VEC3;
}
parsedContent.positions = attribute;
}
if (defined_default(result.NORMAL)) {
attribute = {
name: "NORMAL",
semantic: VertexAttributeSemantic_default.NORMAL,
typedArray: result.NORMAL.array,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC3,
isQuantized: false,
octEncoded: false,
octEncodedZXY: false
};
if (defined_default(result.NORMAL.data.quantization)) {
const octEncodedRange = (1 << result.NORMAL.data.quantization.quantizationBits) - 1;
attribute.quantizedRange = octEncodedRange;
attribute.octEncoded = true;
attribute.octEncodedZXY = true;
attribute.quantizedComponentDatatype = ComponentDatatype_default.UNSIGNED_BYTE;
attribute.quantizedType = AttributeType_default.VEC2;
}
parsedContent.normals = attribute;
}
if (defined_default(result.RGBA)) {
parsedContent.colors = {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: result.RGBA.array,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC4,
normalized: true,
isTranslucent: true
};
} else if (defined_default(result.RGB)) {
parsedContent.colors = {
name: "COLOR",
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
typedArray: result.RGB.array,
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
type: AttributeType_default.VEC3,
normalized: true,
isTranslucent: false
};
}
if (defined_default(result.BATCH_ID)) {
const batchIds = result.BATCH_ID.array;
parsedContent.batchIds = {
name: "_FEATURE_ID",
semantic: VertexAttributeSemantic_default.FEATURE_ID,
setIndex: 0,
typedArray: batchIds,
componentDatatype: ComponentDatatype_default.fromTypedArray(batchIds),
type: AttributeType_default.SCALAR
};
}
let batchTableJson = parsedContent.batchTableJson;
const batchTableProperties = draco.batchTableProperties;
for (const name in batchTableProperties) {
if (batchTableProperties.hasOwnProperty(name)) {
const property = result[name];
if (!defined_default(batchTableJson)) {
batchTableJson = {};
}
parsedContent.hasDracoBatchTable = true;
const data = property.data;
batchTableJson[name] = {
byteOffset: data.byteOffset,
type: transcodeAttributeType(data.componentsPerAttribute),
componentType: transcodeComponentType2(data.componentDatatype),
typedArray: property.array
};
}
}
parsedContent.batchTableJson = batchTableJson;
}
function transcodeAttributeType(componentsPerAttribute) {
switch (componentsPerAttribute) {
case 1:
return "SCALAR";
case 2:
return "VEC2";
case 3:
return "VEC3";
case 4:
return "VEC4";
default:
throw new DeveloperError_default(
"componentsPerAttribute must be a number from 1-4"
);
}
}
function transcodeComponentType2(value) {
switch (value) {
case WebGLConstants_default.BYTE:
return "BYTE";
case WebGLConstants_default.UNSIGNED_BYTE:
return "UNSIGNED_BYTE";
case WebGLConstants_default.SHORT:
return "SHORT";
case WebGLConstants_default.UNSIGNED_SHORT:
return "UNSIGNED_SHORT";
case WebGLConstants_default.INT:
return "INT";
case WebGLConstants_default.UNSIGNED_INT:
return "UNSIGNED_INT";
case WebGLConstants_default.DOUBLE:
return "DOUBLE";
case WebGLConstants_default.FLOAT:
return "FLOAT";
default:
throw new DeveloperError_default("value is not a valid WebGL constant");
}
}
function makeAttribute(loader, attributeInfo, context) {
let typedArray = attributeInfo.typedArray;
let quantization;
if (attributeInfo.octEncoded) {
quantization = new Quantization2();
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 Quantization2();
const normalizationRange = attributeInfo.quantizedRange;
quantization.normalizationRange = normalizationRange;
quantization.quantizedVolumeOffset = Cartesian3_default.ZERO;
const quantizedVolumeDimensions = attributeInfo.quantizedVolumeScale;
quantization.quantizedVolumeDimensions = quantizedVolumeDimensions;
quantization.quantizedVolumeStepSize = Cartesian3_default.divideByScalar(
quantizedVolumeDimensions,
normalizationRange,
new Cartesian3_default()
);
quantization.componentDatatype = attributeInfo.quantizedComponentDatatype;
quantization.type = attributeInfo.quantizedType;
}
const attribute = new Attribute4();
attribute.name = attributeInfo.name;
attribute.semantic = attributeInfo.semantic;
attribute.setIndex = attributeInfo.setIndex;
attribute.componentDatatype = attributeInfo.componentDatatype;
attribute.type = attributeInfo.type;
attribute.normalized = defaultValue_default(attributeInfo.normalized, false);
attribute.min = attributeInfo.min;
attribute.max = attributeInfo.max;
attribute.quantization = quantization;
if (attributeInfo.isRGB565) {
typedArray = AttributeCompression_default.decodeRGB565(typedArray);
}
if (defined_default(attributeInfo.constantColor)) {
const packedColor = new Array(4);
attribute.constant = Color_default.pack(attributeInfo.constantColor, packedColor);
} else {
const buffer = Buffer_default.createVertexBuffer({
typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
loader._buffers.push(buffer);
attribute.buffer = buffer;
}
const loadAttributesFor2D = loader._loadAttributesFor2D;
if (attribute.semantic === VertexAttributeSemantic_default.POSITION && loadAttributesFor2D) {
attribute.typedArray = typedArray;
}
return attribute;
}
var randomNumberGenerator2;
var randomValues;
function getRandomValues(samplesLength) {
if (!defined_default(randomValues)) {
randomNumberGenerator2 = new import_mersenne_twister2.default(0);
randomValues = new Array(samplesLength);
for (let i = 0; i < samplesLength; ++i) {
randomValues[i] = randomNumberGenerator2.random();
}
}
return randomValues;
}
var scratchMin3 = new Cartesian3_default();
var scratchMax3 = new Cartesian3_default();
var scratchPosition3 = new Cartesian3_default();
function computeApproximateExtrema(positions) {
const positionsArray = positions.typedArray;
const maximumSamplesLength = 20;
const pointsLength = positionsArray.length / 3;
const samplesLength = Math.min(pointsLength, maximumSamplesLength);
const randomValues3 = getRandomValues(maximumSamplesLength);
const maxValue = Number.MAX_VALUE;
const minValue = -Number.MAX_VALUE;
let min3 = Cartesian3_default.fromElements(maxValue, maxValue, maxValue, scratchMin3);
let max3 = Cartesian3_default.fromElements(minValue, minValue, minValue, scratchMax3);
let i;
let index;
let position;
if (positions.isQuantized) {
min3 = Cartesian3_default.ZERO;
max3 = positions.quantizedVolumeScale;
} else {
for (i = 0; i < samplesLength; ++i) {
index = Math.floor(randomValues3[i] * pointsLength);
position = Cartesian3_default.unpack(positionsArray, index * 3, scratchPosition3);
Cartesian3_default.minimumByComponent(min3, position, min3);
Cartesian3_default.maximumByComponent(max3, position, max3);
}
}
positions.min = Cartesian3_default.clone(min3);
positions.max = Cartesian3_default.clone(max3);
}
var defaultColorAttribute = {
name: VertexAttributeSemantic_default.COLOR,
semantic: VertexAttributeSemantic_default.COLOR,
setIndex: 0,
constantColor: Color_default.DARKGRAY,
componentDatatype: ComponentDatatype_default.FLOAT,
type: AttributeType_default.VEC4,
isQuantized: false,
isTranslucent: false
};
function makeAttributes(loader, parsedContent, context) {
const attributes = [];
let attribute;
const positions = parsedContent.positions;
if (defined_default(positions)) {
computeApproximateExtrema(positions);
attribute = makeAttribute(loader, positions, context);
attribute.count = parsedContent.pointsLength;
attributes.push(attribute);
}
if (defined_default(parsedContent.normals)) {
attribute = makeAttribute(loader, parsedContent.normals, context);
attributes.push(attribute);
}
if (defined_default(parsedContent.colors)) {
attribute = makeAttribute(loader, parsedContent.colors, context);
attributes.push(attribute);
} else {
attribute = makeAttribute(loader, defaultColorAttribute, context);
attributes.push(attribute);
}
if (defined_default(parsedContent.batchIds)) {
attribute = makeAttribute(loader, parsedContent.batchIds, context);
attributes.push(attribute);
}
return attributes;
}
function makeStructuralMetadata(parsedContent, customAttributeOutput) {
const batchLength = parsedContent.batchLength;
const pointsLength = parsedContent.pointsLength;
const batchTableBinary = parsedContent.batchTableBinary;
const parseAsPropertyAttributes = !defined_default(parsedContent.batchIds);
if (defined_default(batchTableBinary) || parsedContent.hasDracoBatchTable) {
const count = defaultValue_default(batchLength, pointsLength);
return parseBatchTable_default({
count,
batchTable: parsedContent.batchTableJson,
binaryBody: batchTableBinary,
parseAsPropertyAttributes,
customAttributeOutput
});
}
return new StructuralMetadata_default({
schema: {},
propertyTables: []
});
}
function makeComponents(loader, context) {
const parsedContent = loader._parsedContent;
const metallicRoughness = new MetallicRoughness4();
metallicRoughness.metallicFactor = 0;
metallicRoughness.roughnessFactor = 0.9;
const material = new Material5();
material.metallicRoughness = metallicRoughness;
const colors = parsedContent.colors;
if (defined_default(colors) && colors.isTranslucent) {
material.alphaMode = AlphaMode_default.BLEND;
}
const isUnlit = !defined_default(parsedContent.normals);
material.unlit = isUnlit;
const primitive = new Primitive4();
primitive.attributes = makeAttributes(loader, parsedContent, context);
primitive.primitiveType = PrimitiveType_default.POINTS;
primitive.material = material;
if (defined_default(parsedContent.batchIds)) {
const featureIdAttribute = new FeatureIdAttribute5();
featureIdAttribute.propertyTableId = 0;
featureIdAttribute.setIndex = 0;
featureIdAttribute.positionalLabel = "featureId_0";
primitive.featureIds.push(featureIdAttribute);
}
const node = new Node5();
node.index = 0;
node.primitives = [primitive];
const scene = new Scene3();
scene.nodes = [node];
scene.upAxis = Axis_default.Z;
scene.forwardAxis = Axis_default.X;
const components = new Components3();
components.scene = scene;
components.nodes = [node];
const customAttributeOutput = [];
components.structuralMetadata = makeStructuralMetadata(
parsedContent,
customAttributeOutput
);
if (customAttributeOutput.length > 0) {
addPropertyAttributesToPrimitive(
loader,
primitive,
customAttributeOutput,
context
);
}
if (defined_default(parsedContent.rtcCenter)) {
components.transform = Matrix4_default.multiplyByTranslation(
components.transform,
parsedContent.rtcCenter,
components.transform
);
}
const positions = parsedContent.positions;
if (defined_default(positions) && positions.isQuantized) {
components.transform = Matrix4_default.multiplyByTranslation(
components.transform,
positions.quantizedVolumeOffset,
components.transform
);
}
loader._components = components;
loader._parsedContent = void 0;
loader._arrayBuffer = void 0;
}
function addPropertyAttributesToPrimitive(loader, primitive, customAttributes, context) {
const attributes = primitive.attributes;
const length3 = customAttributes.length;
for (let i = 0; i < length3; i++) {
const customAttribute = customAttributes[i];
const buffer = Buffer_default.createVertexBuffer({
typedArray: customAttribute.typedArray,
context,
usage: BufferUsage_default.STATIC_DRAW
});
buffer.vertexArrayDestroyable = false;
loader._buffers.push(buffer);
customAttribute.buffer = buffer;
customAttribute.typedArray = void 0;
attributes.push(customAttribute);
}
primitive.propertyAttributeIds = [0];
}
PntsLoader.prototype.unload = function() {
const buffers = this._buffers;
for (let i = 0; i < buffers.length; i++) {
buffers[i].destroy();
}
buffers.length = 0;
this._components = void 0;
this._parsedContent = void 0;
this._arrayBuffer = void 0;
};
var PntsLoader_default = PntsLoader;
// node_modules/@cesium/engine/Source/Scene/Model/Model.js
function Model(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.loader", options.loader);
Check_default.typeOf.object("options.resource", options.resource);
this._loader = options.loader;
this._resource = options.resource;
this.type = defaultValue_default(options.type, ModelType_default.GLTF);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = Matrix4_default.clone(this.modelMatrix);
this._scale = defaultValue_default(options.scale, 1);
this._minimumPixelSize = defaultValue_default(options.minimumPixelSize, 0);
this._maximumScale = options.maximumScale;
this._clampedScale = defined_default(this._maximumScale) ? Math.min(this._scale, this._maximumScale) : this._scale;
this._computedScale = this._clampedScale;
this._updateModelMatrix = false;
this.referenceMatrix = void 0;
this._iblReferenceFrameMatrix = Matrix3_default.clone(Matrix3_default.IDENTITY);
this._resourcesLoaded = false;
this._drawCommandsBuilt = false;
this._ready = false;
this._customShader = options.customShader;
this._content = options.content;
this._texturesLoaded = false;
this._defaultTexture = void 0;
this._activeAnimations = new ModelAnimationCollection_default(this);
this._clampAnimations = defaultValue_default(options.clampAnimations, true);
this._userAnimationDirty = false;
this._id = options.id;
this._idDirty = false;
this._color = Color_default.clone(options.color);
this._colorBlendMode = defaultValue_default(
options.colorBlendMode,
ColorBlendMode_default.HIGHLIGHT
);
this._colorBlendAmount = defaultValue_default(options.colorBlendAmount, 0.5);
const silhouetteColor = defaultValue_default(options.silhouetteColor, Color_default.RED);
this._silhouetteColor = Color_default.clone(silhouetteColor);
this._silhouetteSize = defaultValue_default(options.silhouetteSize, 0);
this._silhouetteDirty = false;
this._silhouetteId = void 0;
this._cull = defaultValue_default(options.cull, true);
this._opaquePass = defaultValue_default(options.opaquePass, Pass_default.OPAQUE);
this._allowPicking = defaultValue_default(options.allowPicking, true);
this._show = defaultValue_default(options.show, true);
this._style = void 0;
this._styleDirty = false;
this._styleCommandsNeeded = void 0;
let featureIdLabel = defaultValue_default(options.featureIdLabel, "featureId_0");
if (typeof featureIdLabel === "number") {
featureIdLabel = `featureId_${featureIdLabel}`;
}
this._featureIdLabel = featureIdLabel;
let instanceFeatureIdLabel = defaultValue_default(
options.instanceFeatureIdLabel,
"instanceFeatureId_0"
);
if (typeof instanceFeatureIdLabel === "number") {
instanceFeatureIdLabel = `instanceFeatureId_${instanceFeatureIdLabel}`;
}
this._instanceFeatureIdLabel = instanceFeatureIdLabel;
this._featureTables = [];
this._featureTableId = void 0;
this._featureTableIdDirty = true;
this._pipelineResources = [];
this._modelResources = [];
this._pickIds = [];
this._boundingSphere = new BoundingSphere_default();
this._initialRadius = void 0;
this._heightReference = defaultValue_default(
options.heightReference,
HeightReference_default.NONE
);
this._heightDirty = this._heightReference !== HeightReference_default.NONE;
this._removeUpdateHeightCallback = void 0;
this._clampedModelMatrix = void 0;
const scene = options.scene;
if (defined_default(scene) && defined_default(scene.terrainProviderChanged)) {
this._terrainProviderChangedCallback = scene.terrainProviderChanged.addEventListener(
function() {
this._heightDirty = true;
},
this
);
}
this._scene = scene;
this._distanceDisplayCondition = options.distanceDisplayCondition;
const pointCloudShading = new PointCloudShading_default(options.pointCloudShading);
this._pointCloudShading = pointCloudShading;
this._attenuation = pointCloudShading.attenuation;
this._pointCloudBackFaceCulling = pointCloudShading.backFaceCulling;
const clippingPlanes = options.clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.owner === void 0) {
ClippingPlaneCollection_default.setOwner(clippingPlanes, this, "_clippingPlanes");
} else {
this._clippingPlanes = clippingPlanes;
}
this._clippingPlanesState = 0;
this._clippingPlanesMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this._lightColor = Cartesian3_default.clone(options.lightColor);
this._imageBasedLighting = defined_default(options.imageBasedLighting) ? options.imageBasedLighting : new ImageBasedLighting_default();
this._shouldDestroyImageBasedLighting = !defined_default(options.imageBasedLighting);
this._backFaceCulling = defaultValue_default(options.backFaceCulling, true);
this._backFaceCullingDirty = false;
this._shadows = defaultValue_default(options.shadows, ShadowMode_default.ENABLED);
this._shadowsDirty = false;
this._debugShowBoundingVolumeDirty = false;
this._debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this._enableDebugWireframe = defaultValue_default(
options.enableDebugWireframe,
false
);
this._enableShowOutline = defaultValue_default(options.enableShowOutline, true);
this._debugWireframe = defaultValue_default(options.debugWireframe, false);
if (this._debugWireframe === true && this._enableDebugWireframe === false && this.type === ModelType_default.GLTF) {
oneTimeWarning_default(
"model-debug-wireframe-ignored",
"enableDebugWireframe must be set to true in Model.fromGltf, otherwise debugWireframe will be ignored."
);
}
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
this._credit = credit;
this._resourceCredits = [];
this._gltfCredits = [];
this._showCreditsOnScreen = defaultValue_default(options.showCreditsOnScreen, false);
this._showCreditsOnScreenDirty = true;
this._splitDirection = defaultValue_default(
options.splitDirection,
SplitDirection_default.NONE
);
this._enableShowOutline = defaultValue_default(options.enableShowOutline, true);
this.showOutline = defaultValue_default(options.showOutline, true);
this.outlineColor = defaultValue_default(options.outlineColor, Color_default.BLACK);
this._classificationType = options.classificationType;
this._statistics = new ModelStatistics_default();
this._sceneMode = void 0;
this._projectTo2D = defaultValue_default(options.projectTo2D, false);
this._skipLevelOfDetail = false;
this._ignoreCommands = defaultValue_default(options.ignoreCommands, false);
this._texturesLoadedPromise = void 0;
this._completeLoad = void 0;
this._rejectLoad = void 0;
this._completeTexturesLoad = void 0;
this._rejectTexturesLoad = void 0;
if (!defined_default(this._loader._promise)) {
this._readyPromise = new Promise((resolve2, reject) => {
this._completeLoad = () => {
resolve2(this);
return false;
};
this._rejectLoad = (error) => {
reject(error);
return false;
};
});
if (this._loader instanceof PntsLoader_default) {
this._texturesLoadedPromise = Promise.resolve(this);
} else {
this._texturesLoadedPromise = new Promise((resolve2, reject) => {
this._completeTexturesLoad = () => {
resolve2(this);
return false;
};
this._rejectTexturesLoad = (error) => {
reject(error);
return false;
};
});
}
this._loader.load().catch((error) => {
if (this.isDestroyed() || !defined_default(this._loader) || this._loader.isDestroyed()) {
return;
}
this._rejectLoad = this._rejectLoad(
ModelUtility_default.getError("model", this._resource, error)
);
});
} else {
this._readyPromise = Promise.resolve(this);
this._texturesLoadedPromise = Promise.resolve(this);
}
this._errorEvent = new Event_default();
this._readyEvent = new Event_default();
this._texturesReadyEvent = new Event_default();
this._sceneGraph = void 0;
this._nodesByName = {};
this.pickObject = options.pickObject;
}
function handleError9(model, error) {
if (model._errorEvent.numberOfListeners > 0) {
model._errorEvent.raiseEvent(error);
return;
}
console.log(error);
}
function createModelFeatureTables(model, structuralMetadata) {
const featureTables = model._featureTables;
const propertyTables = structuralMetadata.propertyTables;
const length3 = propertyTables.length;
for (let i = 0; i < length3; i++) {
const propertyTable = propertyTables[i];
const modelFeatureTable = new ModelFeatureTable_default({
model,
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;
for (i = 0; i < components.nodes.length; i++) {
node = components.nodes[i];
if (defined_default(node.instances)) {
featureIdAttribute = ModelUtility_default.getFeatureIdsByLabel(
node.instances.featureIds,
instanceFeatureIdLabel
);
if (defined_default(featureIdAttribute) && defined_default(featureIdAttribute.propertyTableId)) {
return featureIdAttribute.propertyTableId;
}
}
}
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 = ModelUtility_default.getFeatureIdsByLabel(
primitive.featureIds,
featureIdLabel
);
if (defined_default(featureIds)) {
return featureIds.propertyTableId;
}
}
}
if (model._featureTables.length === 1) {
return 0;
}
}
function isColorAlphaDirty(currentColor, previousColor) {
if (!defined_default(currentColor) && !defined_default(previousColor)) {
return false;
}
if (defined_default(currentColor) !== defined_default(previousColor)) {
return true;
}
const currentAlpha = currentColor.alpha;
const previousAlpha = previousColor.alpha;
return Math.floor(currentAlpha) !== Math.floor(previousAlpha) || Math.ceil(currentAlpha) !== Math.ceil(previousAlpha);
}
Object.defineProperties(Model.prototype, {
ready: {
get: function() {
return this._ready;
}
},
errorEvent: {
get: function() {
return this._errorEvent;
}
},
readyEvent: {
get: function() {
return this._readyEvent;
}
},
incrementallyLoadTextures: {
get: function() {
return defaultValue_default(this._loader.incrementallyLoadTextures, false);
}
},
texturesReadyEvent: {
get: function() {
return this._texturesReadyEvent;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Model.readyPromise",
"Model.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Model.fromGltfAsync and Model.readyEvent instead."
);
return this._readyPromise;
}
},
texturesLoadedPromise: {
get: function() {
deprecationWarning_default(
"Model.texturesLoadedPromise",
"Model.texturesLoadedPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Model.fromGltfAsync and Model.texturesReadyEvent instead."
);
return this._texturesLoadedPromise;
}
},
loader: {
get: function() {
return this._loader;
}
},
statistics: {
get: function() {
return this._statistics;
}
},
activeAnimations: {
get: function() {
return this._activeAnimations;
}
},
clampAnimations: {
get: function() {
return this._clampAnimations;
},
set: function(value) {
this._clampAnimations = value;
}
},
cull: {
get: function() {
return this._cull;
}
},
opaquePass: {
get: function() {
return this._opaquePass;
}
},
pointCloudShading: {
get: function() {
return this._pointCloudShading;
},
set: function(value) {
Check_default.defined("pointCloudShading", value);
if (value !== this._pointCloudShading) {
this.resetDrawCommands();
}
this._pointCloudShading = value;
}
},
customShader: {
get: function() {
return this._customShader;
},
set: function(value) {
if (value !== this._customShader) {
this.resetDrawCommands();
}
this._customShader = value;
}
},
sceneGraph: {
get: function() {
return this._sceneGraph;
}
},
content: {
get: function() {
return this._content;
}
},
heightReference: {
get: function() {
return this._heightReference;
},
set: function(value) {
if (value !== this._heightReference) {
this._heightDirty = true;
}
this._heightReference = value;
}
},
distanceDisplayCondition: {
get: function() {
return this._distanceDisplayCondition;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default("far must be greater than near");
}
this._distanceDisplayCondition = DistanceDisplayCondition_default.clone(
value,
this._distanceDisplayCondition
);
}
},
structuralMetadata: {
get: function() {
return this._sceneGraph.components.structuralMetadata;
}
},
featureTableId: {
get: function() {
return this._featureTableId;
},
set: function(value) {
this._featureTableId = value;
}
},
featureTables: {
get: function() {
return this._featureTables;
},
set: function(value) {
this._featureTables = value;
}
},
id: {
get: function() {
return this._id;
},
set: function(value) {
if (value !== this._id) {
this._idDirty = true;
}
this._id = value;
}
},
allowPicking: {
get: function() {
return this._allowPicking;
}
},
style: {
get: function() {
return this._style;
},
set: function(value) {
this._style = value;
this._styleDirty = true;
}
},
color: {
get: function() {
return this._color;
},
set: function(value) {
if (isColorAlphaDirty(value, this._color)) {
this.resetDrawCommands();
}
this._color = Color_default.clone(value, this._color);
}
},
colorBlendMode: {
get: function() {
return this._colorBlendMode;
},
set: function(value) {
this._colorBlendMode = value;
}
},
colorBlendAmount: {
get: function() {
return this._colorBlendAmount;
},
set: function(value) {
this._colorBlendAmount = value;
}
},
silhouetteColor: {
get: function() {
return this._silhouetteColor;
},
set: function(value) {
if (!Color_default.equals(value, this._silhouetteColor)) {
const alphaDirty = isColorAlphaDirty(value, this._silhouetteColor);
this._silhouetteDirty = this._silhouetteDirty || alphaDirty;
}
this._silhouetteColor = Color_default.clone(value, this._silhouetteColor);
}
},
silhouetteSize: {
get: function() {
return this._silhouetteSize;
},
set: function(value) {
if (value !== this._silhouetteSize) {
const currentSize = this._silhouetteSize;
const sizeDirty = value > 0 && currentSize === 0 || value === 0 && currentSize > 0;
this._silhouetteDirty = this._silhouetteDirty || sizeDirty;
this._backFaceCullingDirty = this._backFaceCullingDirty || sizeDirty;
}
this._silhouetteSize = value;
}
},
boundingSphere: {
get: function() {
if (!this._ready) {
throw new DeveloperError_default(
"The model is not loaded. Use Model.readyEvent or wait for Model.ready to be true."
);
}
const modelMatrix = defined_default(this._clampedModelMatrix) ? this._clampedModelMatrix : this.modelMatrix;
updateBoundingSphere(this, modelMatrix);
return this._boundingSphere;
}
},
debugShowBoundingVolume: {
get: function() {
return this._debugShowBoundingVolume;
},
set: function(value) {
if (this._debugShowBoundingVolume !== value) {
this._debugShowBoundingVolumeDirty = true;
}
this._debugShowBoundingVolume = value;
}
},
debugWireframe: {
get: function() {
return this._debugWireframe;
},
set: function(value) {
if (this._debugWireframe !== value) {
this.resetDrawCommands();
}
this._debugWireframe = value;
if (this._debugWireframe === true && this._enableDebugWireframe === false && this.type === ModelType_default.GLTF) {
oneTimeWarning_default(
"model-debug-wireframe-ignored",
"enableDebugWireframe must be set to true in Model.fromGltfAsync, otherwise debugWireframe will be ignored."
);
}
}
},
show: {
get: function() {
return this._show;
},
set: function(value) {
this._show = value;
}
},
featureIdLabel: {
get: function() {
return this._featureIdLabel;
},
set: function(value) {
if (typeof value === "number") {
value = `featureId_${value}`;
}
Check_default.typeOf.string("value", value);
if (value !== this._featureIdLabel) {
this._featureTableIdDirty = true;
}
this._featureIdLabel = value;
}
},
instanceFeatureIdLabel: {
get: function() {
return this._instanceFeatureIdLabel;
},
set: function(value) {
if (typeof value === "number") {
value = `instanceFeatureId_${value}`;
}
Check_default.typeOf.string("value", value);
if (value !== this._instanceFeatureIdLabel) {
this._featureTableIdDirty = true;
}
this._instanceFeatureIdLabel = value;
}
},
clippingPlanes: {
get: function() {
return this._clippingPlanes;
},
set: function(value) {
if (value !== this._clippingPlanes) {
ClippingPlaneCollection_default.setOwner(value, this, "_clippingPlanes");
this.resetDrawCommands();
}
}
},
lightColor: {
get: function() {
return this._lightColor;
},
set: function(value) {
if (defined_default(value) !== defined_default(this._lightColor)) {
this.resetDrawCommands();
}
this._lightColor = Cartesian3_default.clone(value, this._lightColor);
}
},
imageBasedLighting: {
get: function() {
return this._imageBasedLighting;
},
set: function(value) {
Check_default.typeOf.object("imageBasedLighting", this._imageBasedLighting);
if (value !== this._imageBasedLighting) {
if (this._shouldDestroyImageBasedLighting && !this._imageBasedLighting.isDestroyed()) {
this._imageBasedLighting.destroy();
}
this._imageBasedLighting = value;
this._shouldDestroyImageBasedLighting = false;
this.resetDrawCommands();
}
}
},
backFaceCulling: {
get: function() {
return this._backFaceCulling;
},
set: function(value) {
if (value !== this._backFaceCulling) {
this._backFaceCullingDirty = true;
}
this._backFaceCulling = value;
}
},
scale: {
get: function() {
return this._scale;
},
set: function(value) {
if (value !== this._scale) {
this._updateModelMatrix = true;
}
this._scale = value;
}
},
computedScale: {
get: function() {
return this._computedScale;
}
},
minimumPixelSize: {
get: function() {
return this._minimumPixelSize;
},
set: function(value) {
if (value !== this._minimumPixelSize) {
this._updateModelMatrix = true;
}
this._minimumPixelSize = value;
}
},
maximumScale: {
get: function() {
return this._maximumScale;
},
set: function(value) {
if (value !== this._maximumScale) {
this._updateModelMatrix = true;
}
this._maximumScale = value;
}
},
shadows: {
get: function() {
return this._shadows;
},
set: function(value) {
if (value !== this._shadows) {
this._shadowsDirty = true;
}
this._shadows = value;
}
},
credit: {
get: function() {
return this._credit;
}
},
showCreditsOnScreen: {
get: function() {
return this._showCreditsOnScreen;
},
set: function(value) {
if (this._showCreditsOnScreen !== value) {
this._showCreditsOnScreenDirty = true;
}
this._showCreditsOnScreen = value;
}
},
splitDirection: {
get: function() {
return this._splitDirection;
},
set: function(value) {
if (this._splitDirection !== value) {
this.resetDrawCommands();
}
this._splitDirection = value;
}
},
classificationType: {
get: function() {
return this._classificationType;
}
},
pickIds: {
get: function() {
return this._pickIds;
}
},
styleCommandsNeeded: {
get: function() {
return this._styleCommandsNeeded;
}
}
});
Model.prototype.getNode = function(name) {
if (!this._ready) {
throw new DeveloperError_default(
"The model is not loaded. Use Model.readyEvent or wait for Model.ready to be true."
);
}
Check_default.typeOf.string("name", name);
return this._nodesByName[name];
};
Model.prototype.setArticulationStage = function(articulationStageKey, value) {
Check_default.typeOf.number("value", value);
if (!this._ready) {
throw new DeveloperError_default(
"The model is not loaded. Use Model.readyEvent or wait for Model.ready to be true."
);
}
this._sceneGraph.setArticulationStage(articulationStageKey, value);
};
Model.prototype.applyArticulations = function() {
if (!this._ready) {
throw new DeveloperError_default(
"The model is not loaded. Use Model.readyEvent or wait for Model.ready to be true."
);
}
this._sceneGraph.applyArticulations();
};
Model.prototype.makeStyleDirty = function() {
this._styleDirty = true;
};
Model.prototype.resetDrawCommands = function() {
this._drawCommandsBuilt = false;
};
var scratchIBLReferenceFrameMatrix4 = new Matrix4_default();
var scratchIBLReferenceFrameMatrix3 = new Matrix3_default();
var scratchClippingPlanesMatrix = new Matrix4_default();
Model.prototype.update = function(frameState) {
let finishedProcessing = false;
try {
finishedProcessing = processLoader(this, frameState);
} catch (error) {
if (!this._loader.incrementallyLoadTextures) {
const runtimeError = ModelUtility_default.getError(
"model",
this._resource,
error
);
handleError9(this, runtimeError);
this._rejectLoad = this._rejectLoad && this._rejectLoad(runtimeError);
this._rejectTexturesLoad = this._rejectTexturesLoad && this._rejectTexturesLoad(runtimeError);
} else if (error.name === "TextureError") {
handleError9(this, error);
this._rejectTexturesLoad = this._rejectTexturesLoad && this._rejectTexturesLoad(error);
} else {
const runtimeError = ModelUtility_default.getError(
"model",
this._resource,
error
);
handleError9(this, runtimeError);
this._rejectLoad = this._rejectLoad && this._rejectLoad(runtimeError);
}
}
updateCustomShader(this, frameState);
updateImageBasedLighting(this, frameState);
if (!this._resourcesLoaded && finishedProcessing) {
this._resourcesLoaded = true;
const components = this._loader.components;
if (!defined_default(components)) {
if (this._loader.isUnloaded()) {
return;
}
const error = ModelUtility_default.getError(
"model",
this._resource,
new RuntimeError_default("Failed to load model.")
);
handleError9(error);
this._rejectLoad = this._rejectLoad && this._rejectLoad(error);
}
const structuralMetadata = components.structuralMetadata;
if (defined_default(structuralMetadata) && structuralMetadata.propertyTableCount > 0) {
createModelFeatureTables(this, structuralMetadata);
}
const sceneGraph = new ModelSceneGraph_default({
model: this,
modelComponents: components
});
this._sceneGraph = sceneGraph;
this._gltfCredits = sceneGraph.components.asset.credits;
}
if (!this._resourcesLoaded || frameState.mode === SceneMode_default.MORPHING) {
return;
}
updateFeatureTableId(this);
updateStyle(this);
updateFeatureTables(this, frameState);
updatePointCloudShading(this);
updateSilhouette(this, frameState);
updateSkipLevelOfDetail(this, frameState);
updateClippingPlanes(this, frameState);
updateSceneMode(this, frameState);
this._defaultTexture = frameState.context.defaultTexture;
buildDrawCommands(this, frameState);
updateModelMatrix(this, frameState);
updateClamping(this);
updateBoundingSphereAndScale(this, frameState);
updateReferenceMatrices(this, frameState);
if (!this._ready) {
frameState.afterRender.push(() => {
this._ready = true;
this._readyEvent.raiseEvent(this);
this._completeLoad = this._completeLoad && this._completeLoad();
if (!this._loader.incrementallyLoadTextures) {
this._texturesLoaded = true;
this._texturesReadyEvent.raiseEvent(this);
this._completeTexturesLoad = this._completeTexturesLoad && this._completeTexturesLoad();
}
});
return;
}
if (this._loader.incrementallyLoadTextures && !this._texturesLoaded && this._loader.texturesLoaded) {
this.resetDrawCommands();
this._texturesLoaded = true;
this._texturesReadyEvent.raiseEvent(this);
this._completeTexturesLoad = this._completeTexturesLoad && this._completeTexturesLoad();
}
updatePickIds(this);
updateSceneGraph(this, frameState);
updateShowCreditsOnScreen(this);
submitDrawCommands(this, frameState);
};
function processLoader(model, frameState) {
if (!model._resourcesLoaded || !model._texturesLoaded) {
frameState.afterRender.push(() => true);
return model._loader.process(frameState);
}
return true;
}
function updateCustomShader(model, frameState) {
if (defined_default(model._customShader)) {
model._customShader.update(frameState);
}
}
function updateImageBasedLighting(model, frameState) {
model._imageBasedLighting.update(frameState);
if (model._imageBasedLighting.shouldRegenerateShaders) {
model.resetDrawCommands();
}
}
function updateFeatureTableId(model) {
if (!model._featureTableIdDirty) {
return;
}
model._featureTableIdDirty = false;
const components = model._sceneGraph.components;
const structuralMetadata = components.structuralMetadata;
if (defined_default(structuralMetadata) && structuralMetadata.propertyTableCount > 0) {
model.featureTableId = selectFeatureTableId(components, model);
model._styleDirty = true;
model.resetDrawCommands();
}
}
function updateStyle(model) {
if (model._styleDirty) {
model.applyStyle(model._style);
model._styleDirty = false;
}
}
function updateFeatureTables(model, frameState) {
const featureTables = model._featureTables;
const length3 = featureTables.length;
let styleCommandsNeededDirty = false;
for (let i = 0; i < length3; i++) {
featureTables[i].update(frameState);
if (featureTables[i].styleCommandsNeededDirty) {
styleCommandsNeededDirty = true;
}
}
if (styleCommandsNeededDirty) {
updateStyleCommandsNeeded(model);
}
}
function updateStyleCommandsNeeded(model) {
const featureTable = model.featureTables[model.featureTableId];
model._styleCommandsNeeded = StyleCommandsNeeded_default.getStyleCommandsNeeded(
featureTable.featuresLength,
featureTable.batchTexture.translucentFeaturesLength
);
}
function updatePointCloudShading(model) {
const pointCloudShading = model.pointCloudShading;
if (pointCloudShading.attenuation !== model._attenuation) {
model.resetDrawCommands();
model._attenuation = pointCloudShading.attenuation;
}
if (pointCloudShading.backFaceCulling !== model._pointCloudBackFaceCulling) {
model.resetDrawCommands();
model._pointCloudBackFaceCulling = pointCloudShading.backFaceCulling;
}
}
function updateSilhouette(model, frameState) {
if (model._silhouetteDirty) {
if (supportsSilhouettes(frameState)) {
model.resetDrawCommands();
}
model._silhouetteDirty = false;
}
}
function updateSkipLevelOfDetail(model, frameState) {
const skipLevelOfDetail = model.hasSkipLevelOfDetail(frameState);
if (skipLevelOfDetail !== model._skipLevelOfDetail) {
model.resetDrawCommands();
model._skipLevelOfDetail = skipLevelOfDetail;
}
}
function updateClippingPlanes(model, frameState) {
let currentClippingPlanesState = 0;
if (model.isClippingEnabled()) {
if (model._clippingPlanes.owner === model) {
model._clippingPlanes.update(frameState);
}
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 buildDrawCommands(model, frameState) {
if (!model._drawCommandsBuilt) {
model.destroyPipelineResources();
model._sceneGraph.buildDrawCommands(frameState);
model._drawCommandsBuilt = true;
}
}
function updateModelMatrix(model, frameState) {
if (!Matrix4_default.equals(model.modelMatrix, model._modelMatrix)) {
if (frameState.mode !== SceneMode_default.SCENE3D && model._projectTo2D) {
throw new DeveloperError_default(
"Model.modelMatrix cannot be changed in 2D or Columbus View if projectTo2D is true."
);
}
model._updateModelMatrix = true;
model._modelMatrix = Matrix4_default.clone(model.modelMatrix, model._modelMatrix);
}
}
var scratchPosition4 = new Cartesian3_default();
var scratchCartographic3 = new Cartographic_default();
function updateClamping(model) {
if (!model._updateModelMatrix && !model._heightDirty && model._minimumPixelSize === 0) {
return;
}
if (defined_default(model._removeUpdateHeightCallback)) {
model._removeUpdateHeightCallback();
model._removeUpdateHeightCallback = void 0;
}
const scene = model._scene;
if (!defined_default(scene) || !defined_default(scene.globe) || model.heightReference === HeightReference_default.NONE) {
if (model.heightReference !== HeightReference_default.NONE) {
throw new DeveloperError_default(
"Height reference is not supported without a scene and globe."
);
}
model._clampedModelMatrix = void 0;
return;
}
const globe = scene.globe;
const ellipsoid = globe.ellipsoid;
const modelMatrix = model.modelMatrix;
scratchPosition4.x = modelMatrix[12];
scratchPosition4.y = modelMatrix[13];
scratchPosition4.z = modelMatrix[14];
const cartoPosition = ellipsoid.cartesianToCartographic(scratchPosition4);
if (!defined_default(model._clampedModelMatrix)) {
model._clampedModelMatrix = Matrix4_default.clone(modelMatrix, new Matrix4_default());
}
const surface = globe._surface;
model._removeUpdateHeightCallback = surface.updateHeight(
cartoPosition,
getUpdateHeightCallback(model, ellipsoid, cartoPosition)
);
const height = globe.getHeight(cartoPosition);
if (defined_default(height)) {
const callback = getUpdateHeightCallback(model, ellipsoid, cartoPosition);
Cartographic_default.clone(cartoPosition, scratchCartographic3);
scratchCartographic3.height = height;
ellipsoid.cartographicToCartesian(scratchCartographic3, scratchPosition4);
callback(scratchPosition4);
}
model._heightDirty = false;
model._updateModelMatrix = true;
}
function updateBoundingSphereAndScale(model, frameState) {
if (!model._updateModelMatrix && model._minimumPixelSize === 0) {
return;
}
const modelMatrix = defined_default(model._clampedModelMatrix) ? model._clampedModelMatrix : model.modelMatrix;
updateBoundingSphere(model, modelMatrix);
updateComputedScale(model, modelMatrix, frameState);
}
function updateBoundingSphere(model, modelMatrix) {
model._clampedScale = defined_default(model._maximumScale) ? Math.min(model._scale, model._maximumScale) : model._scale;
model._boundingSphere.center = Cartesian3_default.multiplyByScalar(
model._sceneGraph.boundingSphere.center,
model._clampedScale,
model._boundingSphere.center
);
model._boundingSphere.radius = model._initialRadius * model._clampedScale;
model._boundingSphere = BoundingSphere_default.transform(
model._boundingSphere,
modelMatrix,
model._boundingSphere
);
}
function updateComputedScale(model, modelMatrix, frameState) {
let scale = model.scale;
if (model.minimumPixelSize !== 0 && !model._projectTo2D) {
const context = frameState.context;
const maxPixelSize = Math.max(
context.drawingBufferWidth,
context.drawingBufferHeight
);
Matrix4_default.getTranslation(modelMatrix, scratchPosition4);
if (model._sceneMode !== SceneMode_default.SCENE3D) {
SceneTransforms_default.computeActualWgs84Position(
frameState,
scratchPosition4,
scratchPosition4
);
}
const radius = model._boundingSphere.radius;
const metersPerPixel = scaleInPixels(scratchPosition4, radius, frameState);
const pixelsPerMeter = 1 / metersPerPixel;
const diameterInPixels = Math.min(
pixelsPerMeter * (2 * radius),
maxPixelSize
);
if (diameterInPixels < model.minimumPixelSize) {
scale = model.minimumPixelSize * metersPerPixel / (2 * model._initialRadius);
}
}
model._computedScale = defined_default(model.maximumScale) ? Math.min(model.maximumScale, scale) : scale;
}
function updatePickIds(model) {
if (!model._idDirty) {
return;
}
model._idDirty = false;
const id = model._id;
const pickIds = model._pickIds;
const length3 = pickIds.length;
for (let i = 0; i < length3; ++i) {
pickIds[i].object.id = id;
}
}
function updateReferenceMatrices(model, frameState) {
const modelMatrix = defined_default(model._clampedModelMatrix) ? model._clampedModelMatrix : model.modelMatrix;
const referenceMatrix = defaultValue_default(model.referenceMatrix, modelMatrix);
const context = frameState.context;
const ibl = model._imageBasedLighting;
if (ibl.useSphericalHarmonicCoefficients || ibl.useSpecularEnvironmentMaps) {
let iblReferenceFrameMatrix3 = scratchIBLReferenceFrameMatrix3;
let iblReferenceFrameMatrix4 = scratchIBLReferenceFrameMatrix4;
iblReferenceFrameMatrix4 = Matrix4_default.multiply(
context.uniformState.view3D,
referenceMatrix,
iblReferenceFrameMatrix4
);
iblReferenceFrameMatrix3 = Matrix4_default.getMatrix3(
iblReferenceFrameMatrix4,
iblReferenceFrameMatrix3
);
iblReferenceFrameMatrix3 = Matrix3_default.getRotation(
iblReferenceFrameMatrix3,
iblReferenceFrameMatrix3
);
model._iblReferenceFrameMatrix = Matrix3_default.transpose(
iblReferenceFrameMatrix3,
model._iblReferenceFrameMatrix
);
}
if (model.isClippingEnabled()) {
let clippingPlanesMatrix = scratchClippingPlanesMatrix;
clippingPlanesMatrix = Matrix4_default.multiply(
context.uniformState.view3D,
referenceMatrix,
clippingPlanesMatrix
);
clippingPlanesMatrix = Matrix4_default.multiply(
clippingPlanesMatrix,
model._clippingPlanes.modelMatrix,
clippingPlanesMatrix
);
model._clippingPlanesMatrix = Matrix4_default.inverseTranspose(
clippingPlanesMatrix,
model._clippingPlanesMatrix
);
}
}
function updateSceneGraph(model, frameState) {
const sceneGraph = model._sceneGraph;
if (model._updateModelMatrix || model._minimumPixelSize !== 0) {
const modelMatrix = defined_default(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;
}
let updateForAnimations = false;
if (!defined_default(model.classificationType)) {
updateForAnimations = model._userAnimationDirty || model._activeAnimations.update(frameState);
}
sceneGraph.update(frameState, updateForAnimations);
model._userAnimationDirty = false;
}
function updateShowCreditsOnScreen(model) {
if (!model._showCreditsOnScreenDirty) {
return;
}
model._showCreditsOnScreenDirty = false;
const showOnScreen = model._showCreditsOnScreen;
if (defined_default(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) {
const displayConditionPassed = passesDistanceDisplayCondition(
model,
frameState
);
const invisible = model.isInvisible();
const silhouette = model.hasSilhouette(frameState);
const showModel = model._show && model._computedScale !== 0 && displayConditionPassed && (!invisible || silhouette);
const passes = frameState.passes;
const submitCommandsForPass = passes.render || passes.pick && model.allowPicking;
if (showModel && !model._ignoreCommands && submitCommandsForPass) {
addCreditsToCreditDisplay(model, frameState);
model._sceneGraph.pushDrawCommands(frameState);
}
}
var scratchBoundingSphere4 = new BoundingSphere_default();
function scaleInPixels(positionWC2, radius, frameState) {
scratchBoundingSphere4.center = positionWC2;
scratchBoundingSphere4.radius = radius;
return frameState.camera.getPixelSize(
scratchBoundingSphere4,
frameState.context.drawingBufferWidth,
frameState.context.drawingBufferHeight
);
}
function getUpdateHeightCallback(model, ellipsoid, cartoPosition) {
return function(clampedPosition) {
if (model.heightReference === HeightReference_default.RELATIVE_TO_GROUND) {
const clampedCart = ellipsoid.cartesianToCartographic(
clampedPosition,
scratchCartographic3
);
clampedCart.height += cartoPosition.height;
ellipsoid.cartographicToCartesian(clampedCart, clampedPosition);
}
const clampedModelMatrix = model._clampedModelMatrix;
Matrix4_default.clone(model.modelMatrix, clampedModelMatrix);
clampedModelMatrix[12] = clampedPosition.x;
clampedModelMatrix[13] = clampedPosition.y;
clampedModelMatrix[14] = clampedPosition.z;
model._heightDirty = true;
};
}
var scratchDisplayConditionCartesian = new Cartesian3_default();
function passesDistanceDisplayCondition(model, frameState) {
const condition = model.distanceDisplayCondition;
if (!defined_default(condition)) {
return true;
}
const nearSquared = condition.near * condition.near;
const farSquared = condition.far * condition.far;
let distanceSquared;
if (frameState.mode === SceneMode_default.SCENE2D) {
const frustum2DWidth = frameState.camera.frustum.right - frameState.camera.frustum.left;
const distance2 = frustum2DWidth * 0.5;
distanceSquared = distance2 * distance2;
} else {
const position = Matrix4_default.getTranslation(
model.modelMatrix,
scratchDisplayConditionCartesian
);
SceneTransforms_default.computeActualWgs84Position(frameState, position, position);
distanceSquared = Cartesian3_default.distanceSquared(
position,
frameState.camera.positionWC
);
}
return distanceSquared >= nearSquared && distanceSquared <= farSquared;
}
function addCreditsToCreditDisplay(model, frameState) {
const creditDisplay = frameState.creditDisplay;
const credit = model._credit;
if (defined_default(credit)) {
creditDisplay.addCreditToNextFrame(credit);
}
const resourceCredits = model._resourceCredits;
const resourceCreditsLength = resourceCredits.length;
for (let c = 0; c < resourceCreditsLength; c++) {
creditDisplay.addCreditToNextFrame(resourceCredits[c]);
}
const gltfCredits = model._gltfCredits;
const gltfCreditsLength = gltfCredits.length;
for (let c = 0; c < gltfCreditsLength; c++) {
creditDisplay.addCreditToNextFrame(gltfCredits[c]);
}
}
Model.prototype.isTranslucent = function() {
const color = this.color;
return defined_default(color) && color.alpha > 0 && color.alpha < 1;
};
Model.prototype.isInvisible = function() {
const color = this.color;
return defined_default(color) && color.alpha === 0;
};
function supportsSilhouettes(frameState) {
return frameState.context.stencilBuffer;
}
Model.prototype.hasSilhouette = function(frameState) {
return supportsSilhouettes(frameState) && this._silhouetteSize > 0 && this._silhouetteColor.alpha > 0 && !defined_default(this._classificationType);
};
Model.prototype.hasSkipLevelOfDetail = function(frameState) {
if (!ModelType_default.is3DTiles(this.type)) {
return false;
}
const supportsSkipLevelOfDetail = frameState.context.stencilBuffer;
const tileset = this._content.tileset;
return supportsSkipLevelOfDetail && tileset.isSkippingLevelOfDetail;
};
Model.prototype.isClippingEnabled = function() {
const clippingPlanes = this._clippingPlanes;
return defined_default(clippingPlanes) && clippingPlanes.enabled && clippingPlanes.length !== 0;
};
Model.prototype.isDestroyed = function() {
return false;
};
Model.prototype.destroy = function() {
const loader = this._loader;
if (defined_default(loader)) {
loader.destroy();
}
const featureTables = this._featureTables;
if (defined_default(featureTables)) {
const length3 = featureTables.length;
for (let i = 0; i < length3; i++) {
featureTables[i].destroy();
}
}
this.destroyPipelineResources();
this.destroyModelResources();
if (defined_default(this._removeUpdateHeightCallback)) {
this._removeUpdateHeightCallback();
this._removeUpdateHeightCallback = void 0;
}
if (defined_default(this._terrainProviderChangedCallback)) {
this._terrainProviderChangedCallback();
this._terrainProviderChangedCallback = void 0;
}
const clippingPlaneCollection = this._clippingPlanes;
if (defined_default(clippingPlaneCollection) && !clippingPlaneCollection.isDestroyed() && clippingPlaneCollection.owner === this) {
clippingPlaneCollection.destroy();
}
this._clippingPlanes = void 0;
if (this._shouldDestroyImageBasedLighting && !this._imageBasedLighting.isDestroyed()) {
this._imageBasedLighting.destroy();
}
this._imageBasedLighting = void 0;
destroyObject_default(this);
};
Model.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;
};
Model.prototype.destroyModelResources = function() {
const resources = this._modelResources;
for (let i = 0; i < resources.length; i++) {
resources[i].destroy();
}
this._modelResources.length = 0;
};
Model.fromGltf = function(options) {
deprecationWarning_default(
"Model.fromGltf",
"Model.fromGltf was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Model.fromGltfAsync instead."
);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.url) && !defined_default(options.gltf)) {
throw new DeveloperError_default("options.url is required.");
}
const gltf = defaultValue_default(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,
loadPrimitiveOutline: options.enableShowOutline,
loadForClassification: defined_default(options.classificationType)
};
const basePath = defaultValue_default(options.basePath, "");
const baseResource2 = Resource_default.createIfNeeded(basePath);
if (defined_default(gltf.asset)) {
loaderOptions.gltfJson = gltf;
loaderOptions.baseResource = baseResource2;
loaderOptions.gltfResource = baseResource2;
} else if (gltf instanceof Uint8Array) {
loaderOptions.typedArray = gltf;
loaderOptions.baseResource = baseResource2;
loaderOptions.gltfResource = baseResource2;
} else {
loaderOptions.gltfResource = Resource_default.createIfNeeded(gltf);
}
const loader = new GltfLoader_default(loaderOptions);
const is3DTiles = defined_default(options.content);
const type = is3DTiles ? ModelType_default.TILE_GLTF : ModelType_default.GLTF;
const modelOptions = makeModelOptions(loader, type, options);
modelOptions.resource = loaderOptions.gltfResource;
const model = new Model(modelOptions);
return model;
};
Model.fromGltfAsync = async function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.url) && !defined_default(options.gltf)) {
throw new DeveloperError_default("options.url is required.");
}
const gltf = defaultValue_default(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,
loadPrimitiveOutline: options.enableShowOutline,
loadForClassification: defined_default(options.classificationType)
};
const basePath = defaultValue_default(options.basePath, "");
const baseResource2 = Resource_default.createIfNeeded(basePath);
if (defined_default(gltf.asset)) {
loaderOptions.gltfJson = gltf;
loaderOptions.baseResource = baseResource2;
loaderOptions.gltfResource = baseResource2;
} else if (gltf instanceof Uint8Array) {
loaderOptions.typedArray = gltf;
loaderOptions.baseResource = baseResource2;
loaderOptions.gltfResource = baseResource2;
} else {
loaderOptions.gltfResource = Resource_default.createIfNeeded(gltf);
}
const loader = new GltfLoader_default(loaderOptions);
const is3DTiles = defined_default(options.content);
const type = is3DTiles ? ModelType_default.TILE_GLTF : ModelType_default.GLTF;
const resource = loaderOptions.gltfResource;
const modelOptions = makeModelOptions(loader, type, options);
modelOptions.resource = resource;
try {
await loader.load();
} catch (error) {
loader.destroy();
throw ModelUtility_default.getError("model", resource, error);
}
const gltfCallback = options.gltfCallback;
if (defined_default(gltfCallback)) {
Check_default.typeOf.func("options.gltfCallback", gltfCallback);
gltfCallback(loader.gltfJson);
}
const model = new Model(modelOptions);
const resourceCredits = model._resource.credits;
if (defined_default(resourceCredits)) {
const length3 = resourceCredits.length;
for (let i = 0; i < length3; i++) {
model._resourceCredits.push(resourceCredits[i]);
}
}
return model;
};
Model.fromB3dm = async 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,
loadPrimitiveOutline: options.enableShowOutline,
loadForClassification: defined_default(options.classificationType)
};
const loader = new B3dmLoader_default(loaderOptions);
try {
await loader.load();
const modelOptions = makeModelOptions(loader, ModelType_default.TILE_B3DM, options);
const model = new Model(modelOptions);
return model;
} catch (error) {
loader.destroy();
throw error;
}
};
Model.fromPnts = async function(options) {
const loaderOptions = {
arrayBuffer: options.arrayBuffer,
byteOffset: options.byteOffset,
loadAttributesFor2D: options.projectTo2D
};
const loader = new PntsLoader_default(loaderOptions);
try {
await loader.load();
const modelOptions = makeModelOptions(loader, ModelType_default.TILE_PNTS, options);
const model = new Model(modelOptions);
return model;
} catch (error) {
loader.destroy();
throw error;
}
};
Model.fromI3dm = async 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,
loadPrimitiveOutline: options.enableShowOutline
};
const loader = new I3dmLoader_default(loaderOptions);
try {
await loader.load();
const modelOptions = makeModelOptions(loader, ModelType_default.TILE_I3DM, options);
const model = new Model(modelOptions);
return model;
} catch (error) {
loader.destroy();
throw error;
}
};
Model.fromGeoJson = async function(options) {
const loaderOptions = {
geoJson: options.geoJson
};
const loader = new GeoJsonLoader_default(loaderOptions);
const modelOptions = makeModelOptions(
loader,
ModelType_default.TILE_GEOJSON,
options
);
const model = new Model(modelOptions);
return model;
};
Model.prototype.applyColorAndShow = function(style) {
const previousColor = this._color;
const hasColorStyle = defined_default(style) && defined_default(style.color);
const hasShowStyle = defined_default(style) && defined_default(style.show);
this._color = hasColorStyle ? style.color.evaluateColor(void 0, this._color) : Color_default.clone(Color_default.WHITE, this._color);
this._show = hasShowStyle ? style.show.evaluate(void 0) : true;
if (isColorAlphaDirty(previousColor, this._color)) {
this.resetDrawCommands();
}
};
Model.prototype.applyStyle = function(style) {
const isPnts = this.type === ModelType_default.TILE_PNTS;
const hasFeatureTable = defined_default(this.featureTableId) && this.featureTables[this.featureTableId].featuresLength > 0;
const propertyAttributes = defined_default(this.structuralMetadata) ? this.structuralMetadata.propertyAttributes : void 0;
const hasPropertyAttributes = defined_default(propertyAttributes) && defined_default(propertyAttributes[0]);
if (isPnts && (!hasFeatureTable || hasPropertyAttributes)) {
this.resetDrawCommands();
return;
}
if (hasFeatureTable) {
const featureTable = this.featureTables[this.featureTableId];
featureTable.applyStyle(style);
updateStyleCommandsNeeded(this, style);
} else {
this.applyColorAndShow(style);
this._styleCommandsNeeded = void 0;
}
};
function makeModelOptions(loader, modelType, options) {
return {
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,
enableShowOutline: options.enableShowOutline,
showOutline: options.showOutline,
outlineColor: options.outlineColor,
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,
classificationType: options.classificationType,
pickObject: options.pickObject
};
}
var Model_default = Model;
// node_modules/@cesium/engine/Source/Scene/Model/Model3DTileContent.js
function Model3DTileContent(tileset, tile, resource) {
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
this._model = void 0;
this._metadata = void 0;
this._group = void 0;
this._ready = false;
this._resolveContent = void 0;
this._readyPromise = void 0;
}
Object.defineProperties(Model3DTileContent.prototype, {
featuresLength: {
get: function() {
const model = this._model;
const featureTables = model.featureTables;
const featureTableId = model.featureTableId;
if (defined_default(featureTables) && defined_default(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() {
const statistics2 = this._model.statistics;
return statistics2.propertyTablesByteLength + statistics2.batchTexturesByteLength;
}
},
innerContents: {
get: function() {
return void 0;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Model3DTileContent.readyPromise",
"Model3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Model3DTileContent.ready to return true instead."
);
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() {
const model = this._model;
const featureTables = model.featureTables;
const featureTableId = model.featureTableId;
if (defined_default(featureTables) && defined_default(featureTables[featureTableId])) {
return featureTables[featureTableId];
}
return void 0;
}
},
metadata: {
get: function() {
return this._metadata;
},
set: function(value) {
this._metadata = value;
}
},
group: {
get: function() {
return this._group;
},
set: function(value) {
this._group = value;
}
}
});
Model3DTileContent.prototype.getFeature = function(featureId) {
const model = this._model;
const featureTableId = model.featureTableId;
if (!defined_default(featureTableId)) {
throw new DeveloperError_default(
"No feature ID set is selected. Make sure Cesium3DTileset.featureIdLabel or Cesium3DTileset.instanceFeatureIdLabel is defined"
);
}
const featureTable = model.featureTables[featureTableId];
if (!defined_default(featureTable)) {
throw new DeveloperError_default(
"No feature table found for the selected feature ID set"
);
}
const featuresLength = featureTable.featuresLength;
if (!defined_default(featureId) || featureId < 0 || featureId >= featuresLength) {
throw new DeveloperError_default(
`featureId is required and must be between 0 and featuresLength - 1 (${featuresLength - 1}).`
);
}
return featureTable.getFeature(featureId);
};
Model3DTileContent.prototype.hasProperty = function(featureId, name) {
const model = this._model;
const featureTableId = model.featureTableId;
if (!defined_default(featureTableId)) {
return false;
}
const featureTable = model.featureTables[featureTableId];
return featureTable.hasProperty(featureId, name);
};
Model3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
color = enabled ? color : Color_default.WHITE;
if (this.featuresLength === 0) {
this._model.color = color;
} else if (defined_default(this.batchTable)) {
this.batchTable.setAllColor(color);
}
};
Model3DTileContent.prototype.applyStyle = function(style) {
this._model.style = style;
};
Model3DTileContent.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.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;
model.showOutline = tileset.showOutline;
model.outlineColor = tileset.outlineColor;
model.pointCloudShading = tileset.pointCloudShading;
const tilesetClippingPlanes = tileset.clippingPlanes;
model.referenceMatrix = tileset.clippingPlanesOriginMatrix;
if (defined_default(tilesetClippingPlanes) && tile.clippingPlanesDirty) {
model._clippingPlanes = tilesetClippingPlanes.enabled && tile._isClipped ? tilesetClippingPlanes : void 0;
}
if (defined_default(tilesetClippingPlanes) && defined_default(model._clippingPlanes) && model._clippingPlanes !== tilesetClippingPlanes) {
model._clippingPlanes = tilesetClippingPlanes;
model._clippingPlanesState = 0;
}
model.update(frameState);
if (!this._ready && model.ready) {
model.activeAnimations.addAll({
loop: ModelAnimationLoop_default.REPEAT
});
this._ready = true;
this._resolveContent = this._resolveContent && this._resolveContent(this);
}
};
Model3DTileContent.prototype.isDestroyed = function() {
return false;
};
Model3DTileContent.prototype.destroy = function() {
this._model = this._model && this._model.destroy();
return destroyObject_default(this);
};
Model3DTileContent.fromGltf = async function(tileset, tile, resource, gltf) {
const content = new Model3DTileContent(tileset, tile, resource);
const additionalOptions = {
gltf,
basePath: resource
};
const modelOptions = makeModelOptions2(
tileset,
tile,
content,
additionalOptions
);
const classificationType = tileset.vectorClassificationOnly ? void 0 : tileset.classificationType;
modelOptions.classificationType = classificationType;
const model = await Model_default.fromGltfAsync(modelOptions);
content._model = model;
content._readyPromise = new Promise((resolve2) => {
content._resolveContent = resolve2;
});
return content;
};
Model3DTileContent.fromB3dm = async function(tileset, tile, resource, arrayBuffer, byteOffset) {
const content = new Model3DTileContent(tileset, tile, resource);
const additionalOptions = {
arrayBuffer,
byteOffset,
resource
};
const modelOptions = makeModelOptions2(
tileset,
tile,
content,
additionalOptions
);
const classificationType = tileset.vectorClassificationOnly ? void 0 : tileset.classificationType;
modelOptions.classificationType = classificationType;
const model = await Model_default.fromB3dm(modelOptions);
content._model = model;
content._readyPromise = new Promise((resolve2) => {
content._resolveContent = resolve2;
});
return content;
};
Model3DTileContent.fromI3dm = async function(tileset, tile, resource, arrayBuffer, byteOffset) {
const content = new Model3DTileContent(tileset, tile, resource);
const additionalOptions = {
arrayBuffer,
byteOffset,
resource
};
const modelOptions = makeModelOptions2(
tileset,
tile,
content,
additionalOptions
);
const model = await Model_default.fromI3dm(modelOptions);
content._model = model;
content._readyPromise = new Promise((resolve2) => {
content._resolveContent = resolve2;
});
return content;
};
Model3DTileContent.fromPnts = async function(tileset, tile, resource, arrayBuffer, byteOffset) {
const content = new Model3DTileContent(tileset, tile, resource);
const additionalOptions = {
arrayBuffer,
byteOffset,
resource
};
const modelOptions = makeModelOptions2(
tileset,
tile,
content,
additionalOptions
);
const model = await Model_default.fromPnts(modelOptions);
content._model = model;
content._readyPromise = new Promise((resolve2) => {
content._resolveContent = resolve2;
});
return content;
};
Model3DTileContent.fromGeoJson = async function(tileset, tile, resource, geoJson) {
const content = new Model3DTileContent(tileset, tile, resource);
const additionalOptions = {
geoJson,
resource
};
const modelOptions = makeModelOptions2(
tileset,
tile,
content,
additionalOptions
);
const model = await Model_default.fromGeoJson(modelOptions);
content._model = model;
content._readyPromise = new Promise((resolve2) => {
content._resolveContent = resolve2;
});
return content;
};
function makeModelOptions2(tileset, tile, content, additionalOptions) {
const mainOptions = {
cull: false,
releaseGltfJson: true,
opaquePass: Pass_default.CESIUM_3D_TILE,
modelMatrix: tile.computedTransform,
upAxis: tileset._modelUpAxis,
forwardAxis: tileset._modelForwardAxis,
incrementallyLoadTextures: false,
customShader: tileset.customShader,
content,
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,
enableShowOutline: tileset._enableShowOutline,
showOutline: tileset.showOutline,
outlineColor: tileset.outlineColor
};
return combine_default(additionalOptions, mainOptions);
}
var Model3DTileContent_default = Model3DTileContent;
// node_modules/@cesium/engine/Source/Scene/Tileset3DTileContent.js
function Tileset3DTileContent(tileset, tile, resource) {
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
this.featurePropertiesDirty = false;
this._metadata = void 0;
this._group = void 0;
this._ready = false;
this._readyPromise = Promise.resolve(this);
}
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 void 0;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Tileset3DTileContent.readyPromise",
"Tileset3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Tileset3DTileContent.ready to return true instead."
);
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 void 0;
}
},
metadata: {
get: function() {
return this._metadata;
},
set: function(value) {
this._metadata = value;
}
},
group: {
get: function() {
return this._group;
},
set: function(value) {
this._group = value;
}
}
});
Tileset3DTileContent.fromJson = function(tileset, tile, resource, json) {
const content = new Tileset3DTileContent(tileset, tile, resource);
content._tileset.loadTileset(content._resource, json, content._tile);
content._ready = true;
return content;
};
Tileset3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Tileset3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
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_default(this);
};
var Tileset3DTileContent_default = Tileset3DTileContent;
// node_modules/@cesium/engine/Source/Shaders/BillboardCollectionFS.js
var BillboardCollectionFS_default = `#ifdef GL_OES_standard_derivatives
#extension GL_OES_standard_derivatives : enable
#endif
uniform sampler2D u_atlas;
#ifdef VECTOR_TILE
uniform vec4 u_highlightColor;
#endif
in vec2 v_textureCoordinates;
in vec4 v_pickColor;
in vec4 v_color;
#ifdef SDF
in vec4 v_outlineColor;
in float v_outlineWidth;
#endif
#ifdef FRAGMENT_DEPTH_CHECK
in vec4 v_textureCoordinateBounds; // the min and max x and y values for the texture coordinates
in vec4 v_originTextureCoordinateAndTranslate; // texture coordinate at the origin, billboard translate (used for label glyphs)
in vec4 v_compressed; // x: eyeDepth, y: applyTranslate & enableDepthCheck, z: dimensions, w: imageSize
in mat2 v_rotationMatrix;
const float SHIFT_LEFT12 = 4096.0;
const float SHIFT_LEFT1 = 2.0;
const float SHIFT_RIGHT12 = 1.0 / 4096.0;
const float SHIFT_RIGHT1 = 1.0 / 2.0;
float getGlobeDepth(vec2 adjustedST, vec2 depthLookupST, bool applyTranslate, vec2 dimensions, vec2 imageSize)
{
vec2 lookupVector = imageSize * (depthLookupST - adjustedST);
lookupVector = v_rotationMatrix * lookupVector;
vec2 labelOffset = (dimensions - imageSize) * (depthLookupST - vec2(0.0, v_originTextureCoordinateAndTranslate.y)); // aligns label glyph with bounding rectangle. Will be zero for billboards because dimensions and imageSize will be equal
vec2 translation = v_originTextureCoordinateAndTranslate.zw;
if (applyTranslate)
{
// this is only needed for labels where the horizontal origin is not LEFT
// it moves the label back to where the "origin" should be since all label glyphs are set to HorizontalOrigin.LEFT
translation += (dimensions * v_originTextureCoordinateAndTranslate.xy * vec2(1.0, 0.0));
}
vec2 st = ((lookupVector - translation + labelOffset) + gl_FragCoord.xy) / czm_viewport.zw;
float logDepthOrDepth = czm_unpackDepth(texture(czm_globeDepthTexture, st));
if (logDepthOrDepth == 0.0)
{
return 0.0; // not on the globe
}
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);
return eyeCoordinate.z / eyeCoordinate.w;
}
#endif
#ifdef SDF
// Get the distance from the edge of a glyph at a given position sampling an SDF texture.
float getDistance(vec2 position)
{
return texture(u_atlas, position).r;
}
// Samples the sdf texture at the given position and produces a color based on the fill color and the outline.
vec4 getSDFColor(vec2 position, float outlineWidth, vec4 outlineColor, float smoothing)
{
float distance = getDistance(position);
if (outlineWidth > 0.0)
{
// Don't get the outline edge exceed the SDF_EDGE
float outlineEdge = clamp(SDF_EDGE - outlineWidth, 0.0, SDF_EDGE);
float outlineFactor = smoothstep(SDF_EDGE - smoothing, SDF_EDGE + smoothing, distance);
vec4 sdfColor = mix(outlineColor, v_color, outlineFactor);
float alpha = smoothstep(outlineEdge - smoothing, outlineEdge + smoothing, distance);
return vec4(sdfColor.rgb, sdfColor.a * alpha);
}
else
{
float alpha = smoothstep(SDF_EDGE - smoothing, SDF_EDGE + smoothing, distance);
return vec4(v_color.rgb, v_color.a * alpha);
}
}
#endif
void main()
{
vec4 color = texture(u_atlas, v_textureCoordinates);
#ifdef SDF
float outlineWidth = v_outlineWidth;
vec4 outlineColor = v_outlineColor;
// Get the current distance
float distance = getDistance(v_textureCoordinates);
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
float smoothing = fwidth(distance);
// Get an offset that is approximately half the distance to the neighbor pixels
// 0.354 is approximately half of 1/sqrt(2)
vec2 sampleOffset = 0.354 * vec2(dFdx(v_textureCoordinates) + dFdy(v_textureCoordinates));
// Sample the center point
vec4 center = getSDFColor(v_textureCoordinates, outlineWidth, outlineColor, smoothing);
// Sample the 4 neighbors
vec4 color1 = getSDFColor(v_textureCoordinates + vec2(sampleOffset.x, sampleOffset.y), outlineWidth, outlineColor, smoothing);
vec4 color2 = getSDFColor(v_textureCoordinates + vec2(-sampleOffset.x, sampleOffset.y), outlineWidth, outlineColor, smoothing);
vec4 color3 = getSDFColor(v_textureCoordinates + vec2(-sampleOffset.x, -sampleOffset.y), outlineWidth, outlineColor, smoothing);
vec4 color4 = getSDFColor(v_textureCoordinates + vec2(sampleOffset.x, -sampleOffset.y), outlineWidth, outlineColor, smoothing);
// Equally weight the center sample and the 4 neighboring samples
color = (center + color1 + color2 + color3 + color4)/5.0;
#else
// If no derivatives available (IE 10?), just do a single sample
float smoothing = 1.0/32.0;
color = getSDFColor(v_textureCoordinates, outlineWidth, outlineColor, smoothing);
#endif
color = czm_gammaCorrect(color);
#else
color = czm_gammaCorrect(color);
color *= czm_gammaCorrect(v_color);
#endif
// Fully transparent parts of the billboard are not pickable.
#if !defined(OPAQUE) && !defined(TRANSLUCENT)
if (color.a < 0.005) // matches 0/255 and 1/255
{
discard;
}
#else
// The billboard is rendered twice. The opaque pass discards translucent fragments
// and the translucent pass discards opaque fragments.
#ifdef OPAQUE
if (color.a < 0.995) // matches < 254/255
{
discard;
}
#else
if (color.a >= 0.995) // matches 254/255 and 255/255
{
discard;
}
#endif
#endif
#ifdef VECTOR_TILE
color *= u_highlightColor;
#endif
out_FragColor = color;
#ifdef LOG_DEPTH
czm_writeLogDepth();
#endif
#ifdef FRAGMENT_DEPTH_CHECK
float temp = v_compressed.y;
temp = temp * SHIFT_RIGHT1;
float temp2 = (temp - floor(temp)) * SHIFT_LEFT1;
bool enableDepthTest = temp2 != 0.0;
bool applyTranslate = floor(temp) != 0.0;
if (enableDepthTest) {
temp = v_compressed.z;
temp = temp * SHIFT_RIGHT12;
vec2 dimensions;
dimensions.y = (temp - floor(temp)) * SHIFT_LEFT12;
dimensions.x = floor(temp);
temp = v_compressed.w;
temp = temp * SHIFT_RIGHT12;
vec2 imageSize;
imageSize.y = (temp - floor(temp)) * SHIFT_LEFT12;
imageSize.x = floor(temp);
vec2 adjustedST = v_textureCoordinates - v_textureCoordinateBounds.xy;
adjustedST = adjustedST / vec2(v_textureCoordinateBounds.z - v_textureCoordinateBounds.x, v_textureCoordinateBounds.w - v_textureCoordinateBounds.y);
float epsilonEyeDepth = v_compressed.x + czm_epsilon1;
float globeDepth1 = getGlobeDepth(adjustedST, v_originTextureCoordinateAndTranslate.xy, applyTranslate, dimensions, imageSize);
// negative values go into the screen
if (globeDepth1 != 0.0 && globeDepth1 > epsilonEyeDepth)
{
float globeDepth2 = getGlobeDepth(adjustedST, vec2(0.0, 1.0), applyTranslate, dimensions, imageSize); // top left corner
if (globeDepth2 != 0.0 && globeDepth2 > epsilonEyeDepth)
{
float globeDepth3 = getGlobeDepth(adjustedST, vec2(1.0, 1.0), applyTranslate, dimensions, imageSize); // top right corner
if (globeDepth3 != 0.0 && globeDepth3 > epsilonEyeDepth)
{
discard;
}
}
}
}
#endif
}
`;
// node_modules/@cesium/engine/Source/Shaders/BillboardCollectionVS.js
var BillboardCollectionVS_default = `#ifdef INSTANCED
in vec2 direction;
#endif
in vec4 positionHighAndScale;
in vec4 positionLowAndRotation;
in vec4 compressedAttribute0; // pixel offset, translate, horizontal origin, vertical origin, show, direction, texture coordinates (texture offset)
in vec4 compressedAttribute1; // aligned axis, translucency by distance, image width
in vec4 compressedAttribute2; // label horizontal origin, image height, color, pick color, size in meters, valid aligned axis, 13 bits free
in vec4 eyeOffset; // eye offset in meters, 4 bytes free (texture range)
in vec4 scaleByDistance; // near, nearScale, far, farScale
in vec4 pixelOffsetScaleByDistance; // near, nearScale, far, farScale
in vec4 compressedAttribute3; // distance display condition near, far, disableDepthTestDistance, dimensions
in vec2 sdf; // sdf outline color (rgb) and width (w)
#if defined(VERTEX_DEPTH_CHECK) || defined(FRAGMENT_DEPTH_CHECK)
in vec4 textureCoordinateBoundsOrLabelTranslate; // the min and max x and y values for the texture coordinates
#endif
#ifdef VECTOR_TILE
in float a_batchId;
#endif
out vec2 v_textureCoordinates;
#ifdef FRAGMENT_DEPTH_CHECK
out vec4 v_textureCoordinateBounds;
out vec4 v_originTextureCoordinateAndTranslate;
out vec4 v_compressed; // x: eyeDepth, y: applyTranslate & enableDepthCheck, z: dimensions, w: imageSize
out mat2 v_rotationMatrix;
#endif
out vec4 v_pickColor;
out vec4 v_color;
#ifdef SDF
out vec4 v_outlineColor;
out float v_outlineWidth;
#endif
const float UPPER_BOUND = 32768.0;
const float SHIFT_LEFT16 = 65536.0;
const float SHIFT_LEFT12 = 4096.0;
const float SHIFT_LEFT8 = 256.0;
const float SHIFT_LEFT7 = 128.0;
const float SHIFT_LEFT5 = 32.0;
const float SHIFT_LEFT3 = 8.0;
const float SHIFT_LEFT2 = 4.0;
const float SHIFT_LEFT1 = 2.0;
const float SHIFT_RIGHT12 = 1.0 / 4096.0;
const float SHIFT_RIGHT8 = 1.0 / 256.0;
const float SHIFT_RIGHT7 = 1.0 / 128.0;
const float SHIFT_RIGHT5 = 1.0 / 32.0;
const float SHIFT_RIGHT3 = 1.0 / 8.0;
const float SHIFT_RIGHT2 = 1.0 / 4.0;
const float SHIFT_RIGHT1 = 1.0 / 2.0;
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)
{
// Note the halfSize cannot be computed in JavaScript because it is sent via
// compressed vertex attributes that coerce it to an integer.
vec2 halfSize = imageSize * scale * 0.5;
halfSize *= ((direction * 2.0) - 1.0);
vec2 originTranslate = origin * abs(halfSize);
#if defined(ROTATION) || defined(ALIGNED_AXIS)
if (validAlignedAxis || rotation != 0.0)
{
float angle = rotation;
if (validAlignedAxis)
{
vec4 projectedAlignedAxis = czm_modelView3D * vec4(alignedAxis, 0.0);
angle += sign(-projectedAlignedAxis.x) * acos(sign(projectedAlignedAxis.y) * (projectedAlignedAxis.y * projectedAlignedAxis.y) /
(projectedAlignedAxis.x * projectedAlignedAxis.x + projectedAlignedAxis.y * projectedAlignedAxis.y));
}
float cosTheta = cos(angle);
float sinTheta = sin(angle);
rotationMatrix = mat2(cosTheta, sinTheta, -sinTheta, cosTheta);
halfSize = rotationMatrix * halfSize;
}
else
{
rotationMatrix = mat2(1.0, 0.0, 0.0, 1.0);
}
#endif
mpp = czm_metersPerPixel(positionEC);
positionEC.xy += (originTranslate + halfSize) * czm_branchFreeTernary(sizeInMeters, 1.0, mpp);
positionEC.xy += (translate + pixelOffset) * mpp;
return positionEC;
}
#ifdef VERTEX_DEPTH_CHECK
float getGlobeDepth(vec4 positionEC)
{
vec4 posWC = czm_eyeToWindowCoordinates(positionEC);
float globeDepth = czm_unpackDepth(texture(czm_globeDepthTexture, posWC.xy / czm_viewport.zw));
if (globeDepth == 0.0)
{
return 0.0; // not on the globe
}
vec4 eyeCoordinate = czm_windowToEyeCoordinates(posWC.xy, globeDepth);
return eyeCoordinate.z / eyeCoordinate.w;
}
#endif
void main()
{
// Modifying this shader may also require modifications to Billboard._computeScreenSpacePosition
// unpack attributes
vec3 positionHigh = positionHighAndScale.xyz;
vec3 positionLow = positionLowAndRotation.xyz;
float scale = positionHighAndScale.w;
#if defined(ROTATION) || defined(ALIGNED_AXIS)
float rotation = positionLowAndRotation.w;
#else
float rotation = 0.0;
#endif
float compressed = compressedAttribute0.x;
vec2 pixelOffset;
pixelOffset.x = floor(compressed * SHIFT_RIGHT7);
compressed -= pixelOffset.x * SHIFT_LEFT7;
pixelOffset.x -= UPPER_BOUND;
vec2 origin;
origin.x = floor(compressed * SHIFT_RIGHT5);
compressed -= origin.x * SHIFT_LEFT5;
origin.y = floor(compressed * SHIFT_RIGHT3);
compressed -= origin.y * SHIFT_LEFT3;
#ifdef FRAGMENT_DEPTH_CHECK
vec2 depthOrigin = origin.xy;
#endif
origin -= vec2(1.0);
float show = floor(compressed * SHIFT_RIGHT2);
compressed -= show * SHIFT_LEFT2;
#ifdef INSTANCED
vec2 textureCoordinatesBottomLeft = czm_decompressTextureCoordinates(compressedAttribute0.w);
vec2 textureCoordinatesRange = czm_decompressTextureCoordinates(eyeOffset.w);
vec2 textureCoordinates = textureCoordinatesBottomLeft + direction * textureCoordinatesRange;
#else
vec2 direction;
direction.x = floor(compressed * SHIFT_RIGHT1);
direction.y = compressed - direction.x * SHIFT_LEFT1;
vec2 textureCoordinates = czm_decompressTextureCoordinates(compressedAttribute0.w);
#endif
float temp = compressedAttribute0.y * SHIFT_RIGHT8;
pixelOffset.y = -(floor(temp) - UPPER_BOUND);
vec2 translate;
translate.y = (temp - floor(temp)) * SHIFT_LEFT16;
temp = compressedAttribute0.z * SHIFT_RIGHT8;
translate.x = floor(temp) - UPPER_BOUND;
translate.y += (temp - floor(temp)) * SHIFT_LEFT8;
translate.y -= UPPER_BOUND;
temp = compressedAttribute1.x * SHIFT_RIGHT8;
float temp2 = floor(compressedAttribute2.w * SHIFT_RIGHT2);
vec2 imageSize = vec2(floor(temp), temp2);
#ifdef FRAGMENT_DEPTH_CHECK
float labelHorizontalOrigin = floor(compressedAttribute2.w - (temp2 * SHIFT_LEFT2));
float applyTranslate = 0.0;
if (labelHorizontalOrigin != 0.0) // is a billboard, so set apply translate to false
{
applyTranslate = 1.0;
labelHorizontalOrigin -= 2.0;
depthOrigin.x = labelHorizontalOrigin + 1.0;
}
depthOrigin = vec2(1.0) - (depthOrigin * 0.5);
#endif
#ifdef EYE_DISTANCE_TRANSLUCENCY
vec4 translucencyByDistance;
translucencyByDistance.x = compressedAttribute1.z;
translucencyByDistance.z = compressedAttribute1.w;
translucencyByDistance.y = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;
temp = compressedAttribute1.y * SHIFT_RIGHT8;
translucencyByDistance.w = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;
#endif
#if defined(VERTEX_DEPTH_CHECK) || defined(FRAGMENT_DEPTH_CHECK)
temp = compressedAttribute3.w;
temp = temp * SHIFT_RIGHT12;
vec2 dimensions;
dimensions.y = (temp - floor(temp)) * SHIFT_LEFT12;
dimensions.x = floor(temp);
#endif
#ifdef ALIGNED_AXIS
vec3 alignedAxis = czm_octDecode(floor(compressedAttribute1.y * SHIFT_RIGHT8));
temp = compressedAttribute2.z * SHIFT_RIGHT5;
bool validAlignedAxis = (temp - floor(temp)) * SHIFT_LEFT1 > 0.0;
#else
vec3 alignedAxis = vec3(0.0);
bool validAlignedAxis = false;
#endif
vec4 pickColor;
vec4 color;
temp = compressedAttribute2.y;
temp = temp * SHIFT_RIGHT8;
pickColor.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
pickColor.g = (temp - floor(temp)) * SHIFT_LEFT8;
pickColor.r = floor(temp);
temp = compressedAttribute2.x;
temp = temp * SHIFT_RIGHT8;
color.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
color.g = (temp - floor(temp)) * SHIFT_LEFT8;
color.r = floor(temp);
temp = compressedAttribute2.z * SHIFT_RIGHT8;
bool sizeInMeters = floor((temp - floor(temp)) * SHIFT_LEFT7) > 0.0;
temp = floor(temp) * SHIFT_RIGHT8;
pickColor.a = (temp - floor(temp)) * SHIFT_LEFT8;
pickColor /= 255.0;
color.a = floor(temp);
color /= 255.0;
///////////////////////////////////////////////////////////////////////////
vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
vec4 positionEC = czm_modelViewRelativeToEye * p;
#if defined(FRAGMENT_DEPTH_CHECK) || defined(VERTEX_DEPTH_CHECK)
float eyeDepth = positionEC.z;
#endif
positionEC = czm_eyeOffset(positionEC, eyeOffset.xyz);
positionEC.xyz *= show;
///////////////////////////////////////////////////////////////////////////
#if defined(EYE_DISTANCE_SCALING) || defined(EYE_DISTANCE_TRANSLUCENCY) || defined(EYE_DISTANCE_PIXEL_OFFSET) || defined(DISTANCE_DISPLAY_CONDITION) || defined(DISABLE_DEPTH_DISTANCE)
float lengthSq;
if (czm_sceneMode == czm_sceneMode2D)
{
// 2D camera distance is a special case
// treat all billboards as flattened to the z=0.0 plane
lengthSq = czm_eyeHeight2D.y;
}
else
{
lengthSq = dot(positionEC.xyz, positionEC.xyz);
}
#endif
#ifdef EYE_DISTANCE_SCALING
float distanceScale = czm_nearFarScalar(scaleByDistance, lengthSq);
scale *= distanceScale;
translate *= distanceScale;
// push vertex behind near plane for clipping
if (scale == 0.0)
{
positionEC.xyz = vec3(0.0);
}
#endif
float translucency = 1.0;
#ifdef EYE_DISTANCE_TRANSLUCENCY
translucency = czm_nearFarScalar(translucencyByDistance, lengthSq);
// push vertex behind near plane for clipping
if (translucency == 0.0)
{
positionEC.xyz = vec3(0.0);
}
#endif
#ifdef EYE_DISTANCE_PIXEL_OFFSET
float pixelOffsetScale = czm_nearFarScalar(pixelOffsetScaleByDistance, lengthSq);
pixelOffset *= pixelOffsetScale;
#endif
#ifdef DISTANCE_DISPLAY_CONDITION
float nearSq = compressedAttribute3.x;
float farSq = compressedAttribute3.y;
if (lengthSq < nearSq || lengthSq > farSq)
{
positionEC.xyz = vec3(0.0);
}
#endif
mat2 rotationMatrix;
float mpp;
#ifdef DISABLE_DEPTH_DISTANCE
float disableDepthTestDistance = compressedAttribute3.z;
#endif
#ifdef VERTEX_DEPTH_CHECK
if (lengthSq < disableDepthTestDistance) {
float depthsilon = 10.0;
vec2 labelTranslate = textureCoordinateBoundsOrLabelTranslate.xy;
vec4 pEC1 = addScreenSpaceOffset(positionEC, dimensions, scale, vec2(0.0), origin, labelTranslate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);
float globeDepth1 = getGlobeDepth(pEC1);
if (globeDepth1 != 0.0 && pEC1.z + depthsilon < globeDepth1)
{
vec4 pEC2 = addScreenSpaceOffset(positionEC, dimensions, scale, vec2(0.0, 1.0), origin, labelTranslate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);
float globeDepth2 = getGlobeDepth(pEC2);
if (globeDepth2 != 0.0 && pEC2.z + depthsilon < globeDepth2)
{
vec4 pEC3 = addScreenSpaceOffset(positionEC, dimensions, scale, vec2(1.0), origin, labelTranslate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);
float globeDepth3 = getGlobeDepth(pEC3);
if (globeDepth3 != 0.0 && pEC3.z + depthsilon < globeDepth3)
{
positionEC.xyz = vec3(0.0);
}
}
}
}
#endif
positionEC = addScreenSpaceOffset(positionEC, imageSize, scale, direction, origin, translate, pixelOffset, alignedAxis, validAlignedAxis, rotation, sizeInMeters, rotationMatrix, mpp);
gl_Position = czm_projection * positionEC;
v_textureCoordinates = textureCoordinates;
#ifdef LOG_DEPTH
czm_vertexLogDepth();
#endif
#ifdef DISABLE_DEPTH_DISTANCE
if (disableDepthTestDistance == 0.0 && czm_minimumDisableDepthTestDistance != 0.0)
{
disableDepthTestDistance = czm_minimumDisableDepthTestDistance;
}
if (disableDepthTestDistance != 0.0)
{
// Don't try to "multiply both sides" by w. Greater/less-than comparisons won't work for negative values of w.
float zclip = gl_Position.z / gl_Position.w;
bool clipped = (zclip < -1.0 || zclip > 1.0);
if (!clipped && (disableDepthTestDistance < 0.0 || (lengthSq > 0.0 && lengthSq < disableDepthTestDistance)))
{
// Position z on the near plane.
gl_Position.z = -gl_Position.w;
#ifdef LOG_DEPTH
v_depthFromNearPlusOne = 1.0;
#endif
}
}
#endif
#ifdef FRAGMENT_DEPTH_CHECK
if (sizeInMeters) {
translate /= mpp;
dimensions /= mpp;
imageSize /= mpp;
}
#if defined(ROTATION) || defined(ALIGNED_AXIS)
v_rotationMatrix = rotationMatrix;
#else
v_rotationMatrix = mat2(1.0, 0.0, 0.0, 1.0);
#endif
float enableDepthCheck = 0.0;
if (lengthSq < disableDepthTestDistance)
{
enableDepthCheck = 1.0;
}
float dw = floor(clamp(dimensions.x, 0.0, SHIFT_LEFT12));
float dh = floor(clamp(dimensions.y, 0.0, SHIFT_LEFT12));
float iw = floor(clamp(imageSize.x, 0.0, SHIFT_LEFT12));
float ih = floor(clamp(imageSize.y, 0.0, SHIFT_LEFT12));
v_compressed.x = eyeDepth;
v_compressed.y = applyTranslate * SHIFT_LEFT1 + enableDepthCheck;
v_compressed.z = dw * SHIFT_LEFT12 + dh;
v_compressed.w = iw * SHIFT_LEFT12 + ih;
v_originTextureCoordinateAndTranslate.xy = depthOrigin;
v_originTextureCoordinateAndTranslate.zw = translate;
v_textureCoordinateBounds = textureCoordinateBoundsOrLabelTranslate;
#endif
#ifdef SDF
vec4 outlineColor;
float outlineWidth;
temp = sdf.x;
temp = temp * SHIFT_RIGHT8;
outlineColor.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
outlineColor.g = (temp - floor(temp)) * SHIFT_LEFT8;
outlineColor.r = floor(temp);
temp = sdf.y;
temp = temp * SHIFT_RIGHT8;
float temp3 = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
outlineWidth = (temp - floor(temp)) * SHIFT_LEFT8;
outlineColor.a = floor(temp);
outlineColor /= 255.0;
v_outlineWidth = outlineWidth / 255.0;
v_outlineColor = outlineColor;
v_outlineColor.a *= translucency;
#endif
v_pickColor = pickColor;
v_color = color;
v_color.a *= translucency;
}
`;
// node_modules/@cesium/engine/Source/Scene/Billboard.js
function Billboard(options, billboardCollection) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (defined_default(options.disableDepthTestDistance) && options.disableDepthTestDistance < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than or equal to 0.0."
);
}
let translucencyByDistance = options.translucencyByDistance;
let pixelOffsetScaleByDistance = options.pixelOffsetScaleByDistance;
let scaleByDistance = options.scaleByDistance;
let distanceDisplayCondition = options.distanceDisplayCondition;
if (defined_default(translucencyByDistance)) {
if (translucencyByDistance.far <= translucencyByDistance.near) {
throw new DeveloperError_default(
"translucencyByDistance.far must be greater than translucencyByDistance.near."
);
}
translucencyByDistance = NearFarScalar_default.clone(translucencyByDistance);
}
if (defined_default(pixelOffsetScaleByDistance)) {
if (pixelOffsetScaleByDistance.far <= pixelOffsetScaleByDistance.near) {
throw new DeveloperError_default(
"pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near."
);
}
pixelOffsetScaleByDistance = NearFarScalar_default.clone(
pixelOffsetScaleByDistance
);
}
if (defined_default(scaleByDistance)) {
if (scaleByDistance.far <= scaleByDistance.near) {
throw new DeveloperError_default(
"scaleByDistance.far must be greater than scaleByDistance.near."
);
}
scaleByDistance = NearFarScalar_default.clone(scaleByDistance);
}
if (defined_default(distanceDisplayCondition)) {
if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
throw new DeveloperError_default(
"distanceDisplayCondition.far must be greater than distanceDisplayCondition.near."
);
}
distanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition
);
}
this._show = defaultValue_default(options.show, true);
this._position = Cartesian3_default.clone(
defaultValue_default(options.position, Cartesian3_default.ZERO)
);
this._actualPosition = Cartesian3_default.clone(this._position);
this._pixelOffset = Cartesian2_default.clone(
defaultValue_default(options.pixelOffset, Cartesian2_default.ZERO)
);
this._translate = new Cartesian2_default(0, 0);
this._eyeOffset = Cartesian3_default.clone(
defaultValue_default(options.eyeOffset, Cartesian3_default.ZERO)
);
this._heightReference = defaultValue_default(
options.heightReference,
HeightReference_default.NONE
);
this._verticalOrigin = defaultValue_default(
options.verticalOrigin,
VerticalOrigin_default.CENTER
);
this._horizontalOrigin = defaultValue_default(
options.horizontalOrigin,
HorizontalOrigin_default.CENTER
);
this._scale = defaultValue_default(options.scale, 1);
this._color = Color_default.clone(defaultValue_default(options.color, Color_default.WHITE));
this._rotation = defaultValue_default(options.rotation, 0);
this._alignedAxis = Cartesian3_default.clone(
defaultValue_default(options.alignedAxis, Cartesian3_default.ZERO)
);
this._width = options.width;
this._height = options.height;
this._scaleByDistance = scaleByDistance;
this._translucencyByDistance = translucencyByDistance;
this._pixelOffsetScaleByDistance = pixelOffsetScaleByDistance;
this._sizeInMeters = defaultValue_default(options.sizeInMeters, false);
this._distanceDisplayCondition = distanceDisplayCondition;
this._disableDepthTestDistance = options.disableDepthTestDistance;
this._id = options.id;
this._collection = defaultValue_default(options.collection, billboardCollection);
this._pickId = void 0;
this._pickPrimitive = defaultValue_default(options._pickPrimitive, this);
this._billboardCollection = billboardCollection;
this._dirty = false;
this._index = -1;
this._batchIndex = void 0;
this._imageIndex = -1;
this._imageIndexPromise = void 0;
this._imageId = void 0;
this._image = void 0;
this._imageSubRegion = void 0;
this._imageWidth = void 0;
this._imageHeight = void 0;
this._labelDimensions = void 0;
this._labelHorizontalOrigin = void 0;
this._labelTranslate = void 0;
const image = options.image;
let imageId = options.imageId;
if (defined_default(image)) {
if (!defined_default(imageId)) {
if (typeof image === "string") {
imageId = image;
} else if (defined_default(image.src)) {
imageId = image.src;
} else {
imageId = createGuid_default();
}
}
this._imageId = imageId;
this._image = image;
}
if (defined_default(options.imageSubRegion)) {
this._imageId = imageId;
this._imageSubRegion = options.imageSubRegion;
}
if (defined_default(this._billboardCollection._textureAtlas)) {
this._loadImage();
}
this._actualClampedPosition = void 0;
this._removeCallbackFunc = void 0;
this._mode = SceneMode_default.SCENE3D;
this._clusterShow = true;
this._outlineColor = Color_default.clone(
defaultValue_default(options.outlineColor, Color_default.BLACK)
);
this._outlineWidth = defaultValue_default(options.outlineWidth, 0);
this._updateClamping();
}
var SHOW_INDEX = Billboard.SHOW_INDEX = 0;
var POSITION_INDEX = Billboard.POSITION_INDEX = 1;
var PIXEL_OFFSET_INDEX = Billboard.PIXEL_OFFSET_INDEX = 2;
var EYE_OFFSET_INDEX = Billboard.EYE_OFFSET_INDEX = 3;
var HORIZONTAL_ORIGIN_INDEX = Billboard.HORIZONTAL_ORIGIN_INDEX = 4;
var VERTICAL_ORIGIN_INDEX = Billboard.VERTICAL_ORIGIN_INDEX = 5;
var SCALE_INDEX = Billboard.SCALE_INDEX = 6;
var IMAGE_INDEX_INDEX = Billboard.IMAGE_INDEX_INDEX = 7;
var COLOR_INDEX = Billboard.COLOR_INDEX = 8;
var ROTATION_INDEX = Billboard.ROTATION_INDEX = 9;
var ALIGNED_AXIS_INDEX = Billboard.ALIGNED_AXIS_INDEX = 10;
var SCALE_BY_DISTANCE_INDEX = Billboard.SCALE_BY_DISTANCE_INDEX = 11;
var TRANSLUCENCY_BY_DISTANCE_INDEX = Billboard.TRANSLUCENCY_BY_DISTANCE_INDEX = 12;
var PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX = Billboard.PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX = 13;
var DISTANCE_DISPLAY_CONDITION = Billboard.DISTANCE_DISPLAY_CONDITION = 14;
var DISABLE_DEPTH_DISTANCE = Billboard.DISABLE_DEPTH_DISTANCE = 15;
Billboard.TEXTURE_COORDINATE_BOUNDS = 16;
var SDF_INDEX = Billboard.SDF_INDEX = 17;
Billboard.NUMBER_OF_PROPERTIES = 18;
function makeDirty(billboard, propertyChanged) {
const billboardCollection = billboard._billboardCollection;
if (defined_default(billboardCollection)) {
billboardCollection._updateBillboard(billboard, propertyChanged);
billboard._dirty = true;
}
}
Object.defineProperties(Billboard.prototype, {
show: {
get: function() {
return this._show;
},
set: function(value) {
Check_default.typeOf.bool("value", value);
if (this._show !== value) {
this._show = value;
makeDirty(this, SHOW_INDEX);
}
}
},
position: {
get: function() {
return this._position;
},
set: function(value) {
Check_default.typeOf.object("value", value);
const position = this._position;
if (!Cartesian3_default.equals(position, value)) {
Cartesian3_default.clone(value, position);
Cartesian3_default.clone(value, this._actualPosition);
this._updateClamping();
makeDirty(this, POSITION_INDEX);
}
}
},
heightReference: {
get: function() {
return this._heightReference;
},
set: function(value) {
Check_default.typeOf.number("value", value);
const heightReference = this._heightReference;
if (value !== heightReference) {
this._heightReference = value;
this._updateClamping();
makeDirty(this, POSITION_INDEX);
}
}
},
pixelOffset: {
get: function() {
return this._pixelOffset;
},
set: function(value) {
Check_default.typeOf.object("value", value);
const pixelOffset = this._pixelOffset;
if (!Cartesian2_default.equals(pixelOffset, value)) {
Cartesian2_default.clone(value, pixelOffset);
makeDirty(this, PIXEL_OFFSET_INDEX);
}
}
},
scaleByDistance: {
get: function() {
return this._scaleByDistance;
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.object("value", value);
if (value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
}
const scaleByDistance = this._scaleByDistance;
if (!NearFarScalar_default.equals(scaleByDistance, value)) {
this._scaleByDistance = NearFarScalar_default.clone(value, scaleByDistance);
makeDirty(this, SCALE_BY_DISTANCE_INDEX);
}
}
},
translucencyByDistance: {
get: function() {
return this._translucencyByDistance;
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.object("value", value);
if (value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
}
const translucencyByDistance = this._translucencyByDistance;
if (!NearFarScalar_default.equals(translucencyByDistance, value)) {
this._translucencyByDistance = NearFarScalar_default.clone(
value,
translucencyByDistance
);
makeDirty(this, TRANSLUCENCY_BY_DISTANCE_INDEX);
}
}
},
pixelOffsetScaleByDistance: {
get: function() {
return this._pixelOffsetScaleByDistance;
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.object("value", value);
if (value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
}
const pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance;
if (!NearFarScalar_default.equals(pixelOffsetScaleByDistance, value)) {
this._pixelOffsetScaleByDistance = NearFarScalar_default.clone(
value,
pixelOffsetScaleByDistance
);
makeDirty(this, PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX);
}
}
},
eyeOffset: {
get: function() {
return this._eyeOffset;
},
set: function(value) {
Check_default.typeOf.object("value", value);
const eyeOffset = this._eyeOffset;
if (!Cartesian3_default.equals(eyeOffset, value)) {
Cartesian3_default.clone(value, eyeOffset);
makeDirty(this, EYE_OFFSET_INDEX);
}
}
},
horizontalOrigin: {
get: function() {
return this._horizontalOrigin;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (this._horizontalOrigin !== value) {
this._horizontalOrigin = value;
makeDirty(this, HORIZONTAL_ORIGIN_INDEX);
}
}
},
verticalOrigin: {
get: function() {
return this._verticalOrigin;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (this._verticalOrigin !== value) {
this._verticalOrigin = value;
makeDirty(this, VERTICAL_ORIGIN_INDEX);
}
}
},
scale: {
get: function() {
return this._scale;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (this._scale !== value) {
this._scale = value;
makeDirty(this, SCALE_INDEX);
}
}
},
color: {
get: function() {
return this._color;
},
set: function(value) {
Check_default.typeOf.object("value", value);
const color = this._color;
if (!Color_default.equals(color, value)) {
Color_default.clone(value, color);
makeDirty(this, COLOR_INDEX);
}
}
},
rotation: {
get: function() {
return this._rotation;
},
set: function(value) {
Check_default.typeOf.number("value", value);
if (this._rotation !== value) {
this._rotation = value;
makeDirty(this, ROTATION_INDEX);
}
}
},
alignedAxis: {
get: function() {
return this._alignedAxis;
},
set: function(value) {
Check_default.typeOf.object("value", value);
const alignedAxis = this._alignedAxis;
if (!Cartesian3_default.equals(alignedAxis, value)) {
Cartesian3_default.clone(value, alignedAxis);
makeDirty(this, ALIGNED_AXIS_INDEX);
}
}
},
width: {
get: function() {
return defaultValue_default(this._width, this._imageWidth);
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.number("value", value);
}
if (this._width !== value) {
this._width = value;
makeDirty(this, IMAGE_INDEX_INDEX);
}
}
},
height: {
get: function() {
return defaultValue_default(this._height, this._imageHeight);
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.number("value", value);
}
if (this._height !== value) {
this._height = value;
makeDirty(this, IMAGE_INDEX_INDEX);
}
}
},
sizeInMeters: {
get: function() {
return this._sizeInMeters;
},
set: function(value) {
Check_default.typeOf.bool("value", value);
if (this._sizeInMeters !== value) {
this._sizeInMeters = value;
makeDirty(this, COLOR_INDEX);
}
}
},
distanceDisplayCondition: {
get: function() {
return this._distanceDisplayCondition;
},
set: function(value) {
if (!DistanceDisplayCondition_default.equals(value, this._distanceDisplayCondition)) {
if (defined_default(value)) {
Check_default.typeOf.object("value", value);
if (value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
}
this._distanceDisplayCondition = DistanceDisplayCondition_default.clone(
value,
this._distanceDisplayCondition
);
makeDirty(this, DISTANCE_DISPLAY_CONDITION);
}
}
},
disableDepthTestDistance: {
get: function() {
return this._disableDepthTestDistance;
},
set: function(value) {
if (defined_default(value)) {
Check_default.typeOf.number("value", value);
if (value < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than or equal to 0.0."
);
}
}
if (this._disableDepthTestDistance !== value) {
this._disableDepthTestDistance = value;
makeDirty(this, DISABLE_DEPTH_DISTANCE);
}
}
},
id: {
get: function() {
return this._id;
},
set: function(value) {
this._id = value;
if (defined_default(this._pickId)) {
this._pickId.object.id = value;
}
}
},
pickPrimitive: {
get: function() {
return this._pickPrimitive;
},
set: function(value) {
this._pickPrimitive = value;
if (defined_default(this._pickId)) {
this._pickId.object.primitive = value;
}
}
},
pickId: {
get: function() {
return this._pickId;
}
},
image: {
get: function() {
return this._imageId;
},
set: function(value) {
if (!defined_default(value)) {
this._imageIndex = -1;
this._imageSubRegion = void 0;
this._imageId = void 0;
this._image = void 0;
this._imageIndexPromise = void 0;
makeDirty(this, IMAGE_INDEX_INDEX);
} else if (typeof value === "string") {
this.setImage(value, value);
} else if (value instanceof Resource_default) {
this.setImage(value.url, value);
} else if (defined_default(value.src)) {
this.setImage(value.src, value);
} else {
this.setImage(createGuid_default(), value);
}
}
},
ready: {
get: function() {
return this._imageIndex !== -1;
}
},
_clampedPosition: {
get: function() {
return this._actualClampedPosition;
},
set: function(value) {
this._actualClampedPosition = Cartesian3_default.clone(
value,
this._actualClampedPosition
);
makeDirty(this, POSITION_INDEX);
}
},
clusterShow: {
get: function() {
return this._clusterShow;
},
set: function(value) {
if (this._clusterShow !== value) {
this._clusterShow = value;
makeDirty(this, SHOW_INDEX);
}
}
},
outlineColor: {
get: function() {
return this._outlineColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const outlineColor = this._outlineColor;
if (!Color_default.equals(outlineColor, value)) {
Color_default.clone(value, outlineColor);
makeDirty(this, SDF_INDEX);
}
}
},
outlineWidth: {
get: function() {
return this._outlineWidth;
},
set: function(value) {
if (this._outlineWidth !== value) {
this._outlineWidth = value;
makeDirty(this, SDF_INDEX);
}
}
}
});
Billboard.prototype.getPickId = function(context) {
if (!defined_default(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);
};
var scratchCartographic4 = new Cartographic_default();
var scratchPosition5 = new Cartesian3_default();
Billboard._updateClamping = function(collection, owner) {
const scene = collection._scene;
if (!defined_default(scene) || !defined_default(scene.globe)) {
if (owner._heightReference !== HeightReference_default.NONE) {
throw new DeveloperError_default(
"Height reference is not supported without a scene and globe."
);
}
return;
}
const globe = scene.globe;
const ellipsoid = globe.ellipsoid;
const surface = globe._surface;
const mode2 = scene.frameState.mode;
const modeChanged = mode2 !== owner._mode;
owner._mode = mode2;
if ((owner._heightReference === HeightReference_default.NONE || modeChanged) && defined_default(owner._removeCallbackFunc)) {
owner._removeCallbackFunc();
owner._removeCallbackFunc = void 0;
owner._clampedPosition = void 0;
}
if (owner._heightReference === HeightReference_default.NONE || !defined_default(owner._position)) {
return;
}
const position = ellipsoid.cartesianToCartographic(owner._position);
if (!defined_default(position)) {
owner._actualClampedPosition = void 0;
return;
}
if (defined_default(owner._removeCallbackFunc)) {
owner._removeCallbackFunc();
}
function updateFunction(clampedPosition) {
if (owner._heightReference === HeightReference_default.RELATIVE_TO_GROUND) {
if (owner._mode === SceneMode_default.SCENE3D) {
const clampedCart = ellipsoid.cartesianToCartographic(
clampedPosition,
scratchCartographic4
);
clampedCart.height += position.height;
ellipsoid.cartographicToCartesian(clampedCart, clampedPosition);
} else {
clampedPosition.x += position.height;
}
}
owner._clampedPosition = Cartesian3_default.clone(
clampedPosition,
owner._clampedPosition
);
}
owner._removeCallbackFunc = surface.updateHeight(position, updateFunction);
Cartographic_default.clone(position, scratchCartographic4);
const height = globe.getHeight(position);
if (defined_default(height)) {
scratchCartographic4.height = height;
}
ellipsoid.cartographicToCartesian(scratchCartographic4, scratchPosition5);
updateFunction(scratchPosition5);
};
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_default.equals(that._imageSubRegion, imageSubRegion)) {
return;
}
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 = void 0;
that._imageIndexPromise = void 0;
makeDirty(that, IMAGE_INDEX_INDEX);
}
if (defined_default(image)) {
const index = atlas.getImageIndex(imageId);
if (defined_default(index)) {
completeImageLoad(index);
return;
}
imageIndexPromise = atlas.addImage(imageId, image);
}
if (defined_default(imageSubRegion)) {
imageIndexPromise = atlas.addSubRegion(imageId, imageSubRegion);
}
this._imageIndexPromise = imageIndexPromise;
if (!defined_default(imageIndexPromise)) {
return;
}
imageIndexPromise.then(completeImageLoad).catch(function(error) {
console.error(`Error loading image for billboard: ${error}`);
that._imageIndexPromise = void 0;
});
};
Billboard.prototype.setImage = function(id, image) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
if (this._imageId === id) {
return;
}
this._imageIndex = -1;
this._imageSubRegion = void 0;
this._imageId = id;
this._image = image;
if (defined_default(this._billboardCollection._textureAtlas)) {
this._loadImage();
}
};
Billboard.prototype.setImageSubRegion = function(id, subRegion) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(subRegion)) {
throw new DeveloperError_default("subRegion is required.");
}
if (this._imageId === id && BoundingRectangle_default.equals(this._imageSubRegion, subRegion)) {
return;
}
this._imageIndex = -1;
this._imageId = id;
this._imageSubRegion = BoundingRectangle_default.clone(subRegion);
if (defined_default(this._billboardCollection._textureAtlas)) {
this._loadImage();
}
};
Billboard.prototype._setTranslate = function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const translate = this._translate;
if (!Cartesian2_default.equals(translate, value)) {
Cartesian2_default.clone(value, translate);
makeDirty(this, PIXEL_OFFSET_INDEX);
}
};
Billboard.prototype._getActualPosition = function() {
return defined_default(this._clampedPosition) ? this._clampedPosition : this._actualPosition;
};
Billboard.prototype._setActualPosition = function(value) {
if (!defined_default(this._clampedPosition)) {
Cartesian3_default.clone(value, this._actualPosition);
}
makeDirty(this, POSITION_INDEX);
};
var tempCartesian3 = new Cartesian4_default();
Billboard._computeActualPosition = function(billboard, position, frameState, modelMatrix) {
if (defined_default(billboard._clampedPosition)) {
if (frameState.mode !== billboard._mode) {
billboard._updateClamping();
}
return billboard._clampedPosition;
} else if (frameState.mode === SceneMode_default.SCENE3D) {
return position;
}
Matrix4_default.multiplyByPoint(modelMatrix, position, tempCartesian3);
return SceneTransforms_default.computeActualWgs84Position(frameState, tempCartesian3);
};
var scratchCartesian35 = new Cartesian3_default();
Billboard._computeScreenSpacePosition = function(modelMatrix, position, eyeOffset, pixelOffset, scene, result) {
const positionWorld = Matrix4_default.multiplyByPoint(
modelMatrix,
position,
scratchCartesian35
);
const positionWC2 = SceneTransforms_default.wgs84WithEyeOffsetToWindowCoordinates(
scene,
positionWorld,
eyeOffset,
result
);
if (!defined_default(positionWC2)) {
return void 0;
}
Cartesian2_default.add(positionWC2, pixelOffset, positionWC2);
return positionWC2;
};
var scratchPixelOffset = new Cartesian2_default(0, 0);
Billboard.prototype.computeScreenSpacePosition = function(scene, result) {
const billboardCollection = this._billboardCollection;
if (!defined_default(result)) {
result = new Cartesian2_default();
}
if (!defined_default(billboardCollection)) {
throw new DeveloperError_default(
"Billboard must be in a collection. Was it removed?"
);
}
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
Cartesian2_default.clone(this._pixelOffset, scratchPixelOffset);
Cartesian2_default.add(scratchPixelOffset, this._translate, scratchPixelOffset);
let modelMatrix = billboardCollection.modelMatrix;
let position = this._position;
if (defined_default(this._clampedPosition)) {
position = this._clampedPosition;
if (scene.mode !== SceneMode_default.SCENE3D) {
const projection = scene.mapProjection;
const ellipsoid = projection.ellipsoid;
const cart = projection.unproject(position, scratchCartographic4);
position = ellipsoid.cartographicToCartesian(cart, scratchCartesian35);
modelMatrix = Matrix4_default.IDENTITY;
}
}
const windowCoordinates = Billboard._computeScreenSpacePosition(
modelMatrix,
position,
this._eyeOffset,
scratchPixelOffset,
scene,
result
);
return windowCoordinates;
};
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_default.RIGHT) {
x -= width;
} else if (billboard.horizontalOrigin === HorizontalOrigin_default.CENTER) {
x -= width * 0.5;
}
let y = screenSpacePosition.y;
if (billboard.verticalOrigin === VerticalOrigin_default.BOTTOM || billboard.verticalOrigin === VerticalOrigin_default.BASELINE) {
y -= height;
} else if (billboard.verticalOrigin === VerticalOrigin_default.CENTER) {
y -= height * 0.5;
}
if (!defined_default(result)) {
result = new BoundingRectangle_default();
}
result.x = x;
result.y = y;
result.width = width;
result.height = height;
return result;
};
Billboard.prototype.equals = function(other) {
return this === other || defined_default(other) && this._id === other._id && Cartesian3_default.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_default.equals(this._imageSubRegion, other._imageSubRegion) && Color_default.equals(this._color, other._color) && Cartesian2_default.equals(this._pixelOffset, other._pixelOffset) && Cartesian2_default.equals(this._translate, other._translate) && Cartesian3_default.equals(this._eyeOffset, other._eyeOffset) && NearFarScalar_default.equals(this._scaleByDistance, other._scaleByDistance) && NearFarScalar_default.equals(
this._translucencyByDistance,
other._translucencyByDistance
) && NearFarScalar_default.equals(
this._pixelOffsetScaleByDistance,
other._pixelOffsetScaleByDistance
) && DistanceDisplayCondition_default.equals(
this._distanceDisplayCondition,
other._distanceDisplayCondition
) && this._disableDepthTestDistance === other._disableDepthTestDistance;
};
Billboard.prototype._destroy = function() {
if (defined_default(this._customData)) {
this._billboardCollection._scene.globe._surface.removeTileCustomData(
this._customData
);
this._customData = void 0;
}
if (defined_default(this._removeCallbackFunc)) {
this._removeCallbackFunc();
this._removeCallbackFunc = void 0;
}
this.image = void 0;
this._pickId = this._pickId && this._pickId.destroy();
this._billboardCollection = void 0;
};
var Billboard_default = Billboard;
// node_modules/@cesium/engine/Source/Scene/BlendOption.js
var BlendOption = {
OPAQUE: 0,
TRANSLUCENT: 1,
OPAQUE_AND_TRANSLUCENT: 2
};
var BlendOption_default = Object.freeze(BlendOption);
// node_modules/@cesium/engine/Source/Scene/SDFSettings.js
var SDFSettings = {
FONT_SIZE: 48,
PADDING: 10,
RADIUS: 8,
CUTOFF: 0.25
};
var SDFSettings_default = Object.freeze(SDFSettings);
// node_modules/@cesium/engine/Source/Scene/TextureAtlas.js
function TextureAtlasNode(bottomLeft, topRight, childNode1, childNode2, imageIndex) {
this.bottomLeft = defaultValue_default(bottomLeft, Cartesian2_default.ZERO);
this.topRight = defaultValue_default(topRight, Cartesian2_default.ZERO);
this.childNode1 = childNode1;
this.childNode2 = childNode2;
this.imageIndex = imageIndex;
}
var defaultInitialSize = new Cartesian2_default(16, 16);
function TextureAtlas(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const borderWidthInPixels = defaultValue_default(options.borderWidthInPixels, 1);
const initialSize = defaultValue_default(options.initialSize, defaultInitialSize);
if (!defined_default(options.context)) {
throw new DeveloperError_default("context is required.");
}
if (borderWidthInPixels < 0) {
throw new DeveloperError_default(
"borderWidthInPixels must be greater than or equal to zero."
);
}
if (initialSize.x < 1 || initialSize.y < 1) {
throw new DeveloperError_default("initialSize must be greater than zero.");
}
this._context = options.context;
this._pixelFormat = defaultValue_default(options.pixelFormat, PixelFormat_default.RGBA);
this._borderWidthInPixels = borderWidthInPixels;
this._textureCoordinates = [];
this._guid = createGuid_default();
this._idHash = {};
this._indexHash = {};
this._initialSize = initialSize;
this._root = void 0;
}
Object.defineProperties(TextureAtlas.prototype, {
borderWidthInPixels: {
get: function() {
return this._borderWidthInPixels;
}
},
textureCoordinates: {
get: function() {
return this._textureCoordinates;
}
},
texture: {
get: function() {
if (!defined_default(this._texture)) {
this._texture = new Texture_default({
context: this._context,
width: this._initialSize.x,
height: this._initialSize.y,
pixelFormat: this._pixelFormat
});
}
return this._texture;
}
},
numberOfImages: {
get: function() {
return this._textureCoordinates.length;
}
},
guid: {
get: function() {
return this._guid;
}
}
});
function resizeAtlas(textureAtlas, image) {
const context = textureAtlas._context;
const numImages = textureAtlas.numberOfImages;
const scalingFactor = 2;
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;
const nodeBottomRight = new TextureAtlasNode(
new Cartesian2_default(oldAtlasWidth + borderWidthInPixels, borderWidthInPixels),
new Cartesian2_default(atlasWidth, oldAtlasHeight)
);
const nodeBottomHalf = new TextureAtlasNode(
new Cartesian2_default(),
new Cartesian2_default(atlasWidth, oldAtlasHeight),
textureAtlas._root,
nodeBottomRight
);
const nodeTopHalf = new TextureAtlasNode(
new Cartesian2_default(borderWidthInPixels, oldAtlasHeight + borderWidthInPixels),
new Cartesian2_default(atlasWidth, atlasHeight)
);
const nodeMain = new TextureAtlasNode(
new Cartesian2_default(),
new Cartesian2_default(atlasWidth, atlasHeight),
nodeBottomHalf,
nodeTopHalf
);
for (let i = 0; i < textureAtlas._textureCoordinates.length; i++) {
const texCoord = textureAtlas._textureCoordinates[i];
if (defined_default(texCoord)) {
texCoord.x *= widthRatio;
texCoord.y *= heightRatio;
texCoord.width *= widthRatio;
texCoord.height *= heightRatio;
}
}
const newTexture = new Texture_default({
context: textureAtlas._context,
width: atlasWidth,
height: atlasHeight,
pixelFormat: textureAtlas._pixelFormat
});
const framebuffer = new Framebuffer_default({
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 {
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_default({
context: textureAtlas._context,
width: initialWidth,
height: initialHeight,
pixelFormat: textureAtlas._pixelFormat
});
textureAtlas._root = new TextureAtlasNode(
new Cartesian2_default(borderWidthInPixels, borderWidthInPixels),
new Cartesian2_default(initialWidth, initialHeight)
);
}
}
function findNode(textureAtlas, node, image) {
if (!defined_default(node)) {
return void 0;
}
if (!defined_default(node.childNode1) && !defined_default(node.childNode2)) {
if (defined_default(node.imageIndex)) {
return void 0;
}
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;
if (widthDifference < 0 || heightDifference < 0) {
return void 0;
}
if (widthDifference === 0 && heightDifference === 0) {
return node;
}
if (widthDifference > heightDifference) {
node.childNode1 = new TextureAtlasNode(
new Cartesian2_default(node.bottomLeft.x, node.bottomLeft.y),
new Cartesian2_default(node.bottomLeft.x + image.width, node.topRight.y)
);
const childNode2BottomLeftX = node.bottomLeft.x + image.width + textureAtlas._borderWidthInPixels;
if (childNode2BottomLeftX < node.topRight.x) {
node.childNode2 = new TextureAtlasNode(
new Cartesian2_default(childNode2BottomLeftX, node.bottomLeft.y),
new Cartesian2_default(node.topRight.x, node.topRight.y)
);
}
} else {
node.childNode1 = new TextureAtlasNode(
new Cartesian2_default(node.bottomLeft.x, node.bottomLeft.y),
new Cartesian2_default(node.topRight.x, node.bottomLeft.y + image.height)
);
const childNode2BottomLeftY = node.bottomLeft.y + image.height + textureAtlas._borderWidthInPixels;
if (childNode2BottomLeftY < node.topRight.y) {
node.childNode2 = new TextureAtlasNode(
new Cartesian2_default(node.bottomLeft.x, childNode2BottomLeftY),
new Cartesian2_default(node.topRight.x, node.topRight.y)
);
}
}
return findNode(textureAtlas, node.childNode1, image);
}
return findNode(textureAtlas, node.childNode1, image) || findNode(textureAtlas, node.childNode2, image);
}
function addImage(textureAtlas, image, index) {
const node = findNode(textureAtlas, textureAtlas._root, image);
if (defined_default(node)) {
node.imageIndex = index;
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_default(x, y, w, h);
textureAtlas._texture.copyFrom({
source: image,
xOffset: node.bottomLeft.x,
yOffset: node.bottomLeft.y
});
} else {
resizeAtlas(textureAtlas, image);
addImage(textureAtlas, image, index);
}
textureAtlas._guid = createGuid_default();
}
function getIndex(atlas, image) {
if (!defined_default(atlas) || atlas.isDestroyed()) {
return -1;
}
const index = atlas.numberOfImages;
addImage(atlas, image, index);
return index;
}
TextureAtlas.prototype.getImageIndex = function(id) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
return this._indexHash[id];
};
TextureAtlas.prototype.addImageSync = function(id, image) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
let index = this._indexHash[id];
if (defined_default(index)) {
return index;
}
index = getIndex(this, image);
this._idHash[id] = Promise.resolve(index);
this._indexHash[id] = index;
return index;
};
TextureAtlas.prototype.addImage = function(id, image) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
let indexPromise = this._idHash[id];
if (defined_default(indexPromise)) {
return indexPromise;
}
if (typeof image === "function") {
image = image(id);
if (!defined_default(image)) {
throw new DeveloperError_default("image is required.");
}
} else if (typeof image === "string" || image instanceof Resource_default) {
const resource = Resource_default.createIfNeeded(image);
image = resource.fetchImage();
}
const that = this;
indexPromise = Promise.resolve(image).then(function(image2) {
const index = getIndex(that, image2);
that._indexHash[id] = index;
return index;
});
this._idHash[id] = indexPromise;
return indexPromise;
};
TextureAtlas.prototype.addSubRegion = function(id, subRegion) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
if (!defined_default(subRegion)) {
throw new DeveloperError_default("subRegion is required.");
}
const indexPromise = this._idHash[id];
if (!defined_default(indexPromise)) {
throw new RuntimeError_default(`image with id "${id}" not found in the atlas.`);
}
const that = this;
return Promise.resolve(indexPromise).then(function(index) {
if (index === -1) {
return -1;
}
const atlasWidth = that._texture.width;
const atlasHeight = that._texture.height;
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;
const newIndex = that._textureCoordinates.push(new BoundingRectangle_default(x, y, w, h)) - 1;
that._indexHash[id] = newIndex;
that._guid = createGuid_default();
return newIndex;
});
};
TextureAtlas.prototype.isDestroyed = function() {
return false;
};
TextureAtlas.prototype.destroy = function() {
this._texture = this._texture && this._texture.destroy();
return destroyObject_default(this);
};
var TextureAtlas_default = TextureAtlas;
// node_modules/@cesium/engine/Source/Scene/BillboardCollection.js
var SHOW_INDEX2 = Billboard_default.SHOW_INDEX;
var POSITION_INDEX2 = Billboard_default.POSITION_INDEX;
var PIXEL_OFFSET_INDEX2 = Billboard_default.PIXEL_OFFSET_INDEX;
var EYE_OFFSET_INDEX2 = Billboard_default.EYE_OFFSET_INDEX;
var HORIZONTAL_ORIGIN_INDEX2 = Billboard_default.HORIZONTAL_ORIGIN_INDEX;
var VERTICAL_ORIGIN_INDEX2 = Billboard_default.VERTICAL_ORIGIN_INDEX;
var SCALE_INDEX2 = Billboard_default.SCALE_INDEX;
var IMAGE_INDEX_INDEX2 = Billboard_default.IMAGE_INDEX_INDEX;
var COLOR_INDEX2 = Billboard_default.COLOR_INDEX;
var ROTATION_INDEX2 = Billboard_default.ROTATION_INDEX;
var ALIGNED_AXIS_INDEX2 = Billboard_default.ALIGNED_AXIS_INDEX;
var SCALE_BY_DISTANCE_INDEX2 = Billboard_default.SCALE_BY_DISTANCE_INDEX;
var TRANSLUCENCY_BY_DISTANCE_INDEX2 = Billboard_default.TRANSLUCENCY_BY_DISTANCE_INDEX;
var PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX2 = Billboard_default.PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX;
var DISTANCE_DISPLAY_CONDITION_INDEX = Billboard_default.DISTANCE_DISPLAY_CONDITION;
var DISABLE_DEPTH_DISTANCE2 = Billboard_default.DISABLE_DEPTH_DISTANCE;
var TEXTURE_COORDINATE_BOUNDS = Billboard_default.TEXTURE_COORDINATE_BOUNDS;
var SDF_INDEX2 = Billboard_default.SDF_INDEX;
var NUMBER_OF_PROPERTIES = Billboard_default.NUMBER_OF_PROPERTIES;
var attributeLocations;
var attributeLocationsBatched = {
positionHighAndScale: 0,
positionLowAndRotation: 1,
compressedAttribute0: 2,
compressedAttribute1: 3,
compressedAttribute2: 4,
eyeOffset: 5,
scaleByDistance: 6,
pixelOffsetScaleByDistance: 7,
compressedAttribute3: 8,
textureCoordinateBoundsOrLabelTranslate: 9,
a_batchId: 10,
sdf: 11
};
var attributeLocationsInstanced = {
direction: 0,
positionHighAndScale: 1,
positionLowAndRotation: 2,
compressedAttribute0: 3,
compressedAttribute1: 4,
compressedAttribute2: 5,
eyeOffset: 6,
scaleByDistance: 7,
pixelOffsetScaleByDistance: 8,
compressedAttribute3: 9,
textureCoordinateBoundsOrLabelTranslate: 10,
a_batchId: 11,
sdf: 12
};
function BillboardCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._scene = options.scene;
this._batchTable = options.batchTable;
this._textureAtlas = void 0;
this._textureAtlasGUID = void 0;
this._destroyTextureAtlas = true;
this._sp = void 0;
this._spTranslucent = void 0;
this._rsOpaque = void 0;
this._rsTranslucent = void 0;
this._vaf = void 0;
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);
this._maxSize = 0;
this._maxEyeOffset = 0;
this._maxScale = 1;
this._maxPixelOffset = 0;
this._allHorizontalCenter = true;
this._allVerticalCenter = true;
this._allSizedInMeters = true;
this._baseVolume = new BoundingSphere_default();
this._baseVolumeWC = new BoundingSphere_default();
this._baseVolume2D = new BoundingSphere_default();
this._boundingVolume = new BoundingSphere_default();
this._boundingVolumeDirty = false;
this._colorCommands = [];
this.show = defaultValue_default(options.show, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.debugShowTextureAtlas = defaultValue_default(
options.debugShowTextureAtlas,
false
);
this.blendOption = defaultValue_default(
options.blendOption,
BlendOption_default.OPAQUE_AND_TRANSLUCENT
);
this._blendOption = void 0;
this._mode = SceneMode_default.SCENE3D;
this._buffersUsage = [
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW
];
this._highlightColor = Color_default.clone(Color_default.WHITE);
const that = this;
this._uniforms = {
u_atlas: function() {
return that._textureAtlas.texture;
},
u_highlightColor: function() {
return that._highlightColor;
}
};
const scene = this._scene;
if (defined_default(scene) && defined_default(scene.terrainProviderChanged)) {
this._removeCallbackFunc = scene.terrainProviderChanged.addEventListener(
function() {
const billboards = this._billboards;
const length3 = billboards.length;
for (let i = 0; i < length3; ++i) {
if (defined_default(billboards[i])) {
billboards[i]._updateClamping();
}
}
},
this
);
}
}
Object.defineProperties(BillboardCollection.prototype, {
length: {
get: function() {
removeBillboards(this);
return this._billboards.length;
}
},
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;
}
}
},
destroyTextureAtlas: {
get: function() {
return this._destroyTextureAtlas;
},
set: function(value) {
this._destroyTextureAtlas = value;
}
}
});
function destroyBillboards(billboards) {
const length3 = billboards.length;
for (let i = 0; i < length3; ++i) {
if (billboards[i]) {
billboards[i]._destroy();
}
}
}
BillboardCollection.prototype.add = function(options) {
const billboard = new Billboard_default(options, this);
billboard._index = this._billboards.length;
this._billboards.push(billboard);
this._createVertexArray = true;
return billboard;
};
BillboardCollection.prototype.remove = function(billboard) {
if (this.contains(billboard)) {
this._billboards[billboard._index] = void 0;
this._billboardsRemoved = true;
this._createVertexArray = true;
billboard._destroy();
return true;
}
return false;
};
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 length3 = billboards.length;
for (let i = 0, j = 0; i < length3; ++i) {
const billboard = billboards[i];
if (defined_default(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];
};
BillboardCollection.prototype.contains = function(billboard) {
return defined_default(billboard) && billboard._billboardCollection === this;
};
BillboardCollection.prototype.get = function(index) {
Check_default.typeOf.number("index", index);
removeBillboards(this);
return this._billboards[index];
};
var getIndexBuffer2;
function getIndexBufferBatched(context) {
const sixteenK = 16 * 1024;
let indexBuffer = context.cache.billboardCollection_indexBufferBatched;
if (defined_default(indexBuffer)) {
return indexBuffer;
}
const length3 = sixteenK * 6 - 6;
const indices2 = new Uint16Array(length3);
for (let i = 0, j = 0; i < length3; i += 6, j += 4) {
indices2[i] = j;
indices2[i + 1] = j + 1;
indices2[i + 2] = j + 2;
indices2[i + 3] = j + 0;
indices2[i + 4] = j + 2;
indices2[i + 5] = j + 3;
}
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: indices2,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
indexBuffer.vertexArrayDestroyable = false;
context.cache.billboardCollection_indexBufferBatched = indexBuffer;
return indexBuffer;
}
function getIndexBufferInstanced(context) {
let indexBuffer = context.cache.billboardCollection_indexBufferInstanced;
if (defined_default(indexBuffer)) {
return indexBuffer;
}
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: new Uint16Array([0, 1, 2, 0, 2, 3]),
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
indexBuffer.vertexArrayDestroyable = false;
context.cache.billboardCollection_indexBufferInstanced = indexBuffer;
return indexBuffer;
}
function getVertexBufferInstanced(context) {
let vertexBuffer = context.cache.billboardCollection_vertexBufferInstanced;
if (defined_default(vertexBuffer)) {
return vertexBuffer;
}
vertexBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
usage: BufferUsage_default.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; ++k) {
const newUsage = properties[k] === 0 ? BufferUsage_default.STATIC_DRAW : BufferUsage_default.STREAM_DRAW;
usageChanged = usageChanged || buffersUsage[k] !== newUsage;
buffersUsage[k] = newUsage;
}
return usageChanged;
};
function createVAF(context, numberOfBillboards, buffersUsage, instanced, batchTable, sdf) {
const attributes = [
{
index: attributeLocations.positionHighAndScale,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX2]
},
{
index: attributeLocations.positionLowAndRotation,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX2]
},
{
index: attributeLocations.compressedAttribute0,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[PIXEL_OFFSET_INDEX2]
},
{
index: attributeLocations.compressedAttribute1,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[TRANSLUCENCY_BY_DISTANCE_INDEX2]
},
{
index: attributeLocations.compressedAttribute2,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[COLOR_INDEX2]
},
{
index: attributeLocations.eyeOffset,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[EYE_OFFSET_INDEX2]
},
{
index: attributeLocations.scaleByDistance,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[SCALE_BY_DISTANCE_INDEX2]
},
{
index: attributeLocations.pixelOffsetScaleByDistance,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX2]
},
{
index: attributeLocations.compressedAttribute3,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[DISTANCE_DISPLAY_CONDITION_INDEX]
},
{
index: attributeLocations.textureCoordinateBoundsOrLabelTranslate,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[TEXTURE_COORDINATE_BOUNDS]
}
];
if (instanced) {
attributes.push({
index: attributeLocations.direction,
componentsPerAttribute: 2,
componentDatatype: ComponentDatatype_default.FLOAT,
vertexBuffer: getVertexBufferInstanced(context)
});
}
if (defined_default(batchTable)) {
attributes.push({
index: attributeLocations.a_batchId,
componentsPerAttribute: 1,
componentDatatype: ComponentDatatype_default.FLOAT,
bufferUsage: BufferUsage_default.STATIC_DRAW
});
}
if (sdf) {
attributes.push({
index: attributeLocations.sdf,
componentsPerAttribute: 2,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[SDF_INDEX2]
});
}
const sizeInVertices = instanced ? numberOfBillboards : 4 * numberOfBillboards;
return new VertexArrayFacade_default(context, attributes, sizeInVertices, instanced);
}
var writePositionScratch = new EncodedCartesian3_default();
function writePositionScaleAndRotation(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const positionHighWriter = vafWriters[attributeLocations.positionHighAndScale];
const positionLowWriter = vafWriters[attributeLocations.positionLowAndRotation];
const position = billboard._getActualPosition();
if (billboardCollection._mode === SceneMode_default.SCENE3D) {
BoundingSphere_default.expand(
billboardCollection._baseVolume,
position,
billboardCollection._baseVolume
);
billboardCollection._boundingVolumeDirty = true;
}
EncodedCartesian3_default.fromCartesian(position, writePositionScratch);
const scale = billboard.scale;
const rotation = billboard.rotation;
if (rotation !== 0) {
billboardCollection._shaderRotation = true;
}
billboardCollection._maxScale = Math.max(
billboardCollection._maxScale,
scale
);
const high = writePositionScratch.high;
const low = writePositionScratch.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);
}
}
var scratchCartesian24 = new Cartesian2_default();
var UPPER_BOUND = 32768;
var LEFT_SHIFT16 = 65536;
var LEFT_SHIFT12 = 4096;
var LEFT_SHIFT8 = 256;
var LEFT_SHIFT7 = 128;
var LEFT_SHIFT5 = 32;
var LEFT_SHIFT3 = 8;
var LEFT_SHIFT2 = 4;
var RIGHT_SHIFT8 = 1 / 256;
var LOWER_LEFT = 0;
var LOWER_RIGHT = 2;
var UPPER_RIGHT = 3;
var UPPER_LEFT = 1;
function writeCompressedAttrib0(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.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 (billboard.color.alpha === 0) {
show = false;
}
if (verticalOrigin === VerticalOrigin_default.BASELINE) {
verticalOrigin = VerticalOrigin_default.BOTTOM;
}
billboardCollection._allHorizontalCenter = billboardCollection._allHorizontalCenter && horizontalOrigin === HorizontalOrigin_default.CENTER;
billboardCollection._allVerticalCenter = billboardCollection._allVerticalCenter && verticalOrigin === VerticalOrigin_default.CENTER;
let bottomLeftX = 0;
let bottomLeftY = 0;
let width = 0;
let height = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
bottomLeftX = imageRectangle.x;
bottomLeftY = imageRectangle.y;
width = imageRectangle.width;
height = imageRectangle.height;
}
const topRightX = bottomLeftX + width;
const topRightY = bottomLeftY + height;
let compressed0 = Math.floor(
Math_default.clamp(pixelOffsetX, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
) * LEFT_SHIFT7;
compressed0 += (horizontalOrigin + 1) * LEFT_SHIFT5;
compressed0 += (verticalOrigin + 1) * LEFT_SHIFT3;
compressed0 += (show ? 1 : 0) * LEFT_SHIFT2;
let compressed1 = Math.floor(
Math_default.clamp(pixelOffsetY, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
) * LEFT_SHIFT8;
let compressed2 = Math.floor(
Math_default.clamp(translateX, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND
) * LEFT_SHIFT8;
const tempTanslateY = (Math_default.clamp(translateY, -UPPER_BOUND, UPPER_BOUND) + UPPER_BOUND) * RIGHT_SHIFT8;
const upperTranslateY = Math.floor(tempTanslateY);
const lowerTranslateY = Math.floor(
(tempTanslateY - upperTranslateY) * LEFT_SHIFT8
);
compressed1 += upperTranslateY;
compressed2 += lowerTranslateY;
scratchCartesian24.x = bottomLeftX;
scratchCartesian24.y = bottomLeftY;
const compressedTexCoordsLL = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
scratchCartesian24.x = topRightX;
const compressedTexCoordsLR = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
scratchCartesian24.y = topRightY;
const compressedTexCoordsUR = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
scratchCartesian24.x = bottomLeftX;
const compressedTexCoordsUL = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
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(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.compressedAttribute1];
const alignedAxis = billboard.alignedAxis;
if (!Cartesian3_default.equals(alignedAxis, Cartesian3_default.ZERO)) {
billboardCollection._shaderAlignedAxis = true;
}
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const translucency = billboard.translucencyByDistance;
if (defined_default(translucency)) {
near = translucency.near;
nearValue = translucency.nearValue;
far = translucency.far;
farValue = translucency.farValue;
if (nearValue !== 1 || farValue !== 1) {
billboardCollection._shaderTranslucencyByDistance = true;
}
}
let width = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
width = imageRectangle.width;
}
const textureWidth = billboardCollection._textureAtlas.texture.width;
const imageWidth = Math.round(
defaultValue_default(billboard.width, textureWidth * width)
);
billboardCollection._maxSize = Math.max(
billboardCollection._maxSize,
imageWidth
);
let compressed0 = Math_default.clamp(imageWidth, 0, LEFT_SHIFT16);
let compressed1 = 0;
if (Math.abs(Cartesian3_default.magnitudeSquared(alignedAxis) - 1) < Math_default.EPSILON6) {
compressed1 = AttributeCompression_default.octEncodeFloat(alignedAxis);
}
nearValue = Math_default.clamp(nearValue, 0, 1);
nearValue = nearValue === 1 ? 255 : nearValue * 255 | 0;
compressed0 = compressed0 * LEFT_SHIFT8 + nearValue;
farValue = Math_default.clamp(farValue, 0, 1);
farValue = farValue === 1 ? 255 : farValue * 255 | 0;
compressed1 = compressed1 * LEFT_SHIFT8 + 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.compressedAttribute2];
const color = billboard.color;
const pickColor = !defined_default(billboardCollection._batchTable) ? billboard.getPickId(frameState.context).color : Color_default.WHITE;
const sizeInMeters = billboard.sizeInMeters ? 1 : 0;
const validAlignedAxis = Math.abs(Cartesian3_default.magnitudeSquared(billboard.alignedAxis) - 1) < Math_default.EPSILON6 ? 1 : 0;
billboardCollection._allSizedInMeters = billboardCollection._allSizedInMeters && sizeInMeters === 1;
let height = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
height = imageRectangle.height;
}
const dimensions = billboardCollection._textureAtlas.texture.dimensions;
const imageHeight = Math.round(
defaultValue_default(billboard.height, dimensions.y * height)
);
billboardCollection._maxSize = Math.max(
billboardCollection._maxSize,
imageHeight
);
let labelHorizontalOrigin = defaultValue_default(
billboard._labelHorizontalOrigin,
-2
);
labelHorizontalOrigin += 2;
const compressed3 = imageHeight * LEFT_SHIFT2 + labelHorizontalOrigin;
let red = Color_default.floatToByte(color.red);
let green = Color_default.floatToByte(color.green);
let blue = Color_default.floatToByte(color.blue);
const compressed0 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;
red = Color_default.floatToByte(pickColor.red);
green = Color_default.floatToByte(pickColor.green);
blue = Color_default.floatToByte(pickColor.blue);
const compressed1 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;
let compressed2 = Color_default.floatToByte(color.alpha) * LEFT_SHIFT16 + Color_default.floatToByte(pickColor.alpha) * LEFT_SHIFT8;
compressed2 += sizeInMeters * 2 + 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.eyeOffset];
const eyeOffset = billboard.eyeOffset;
let eyeOffsetZ = eyeOffset.z;
if (billboard._heightReference !== HeightReference_default.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];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
width = imageRectangle.width;
height = imageRectangle.height;
}
scratchCartesian24.x = width;
scratchCartesian24.y = height;
const compressedTexCoordsRange = AttributeCompression_default.compressTextureCoordinates(
scratchCartesian24
);
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);
writer(i + 1, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0);
writer(i + 2, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0);
writer(i + 3, eyeOffset.x, eyeOffset.y, eyeOffsetZ, 0);
}
}
function writeScaleByDistance(billboardCollection, frameState, textureAtlasCoordinates, vafWriters, billboard) {
let i;
const writer = vafWriters[attributeLocations.scaleByDistance];
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const scale = billboard.scaleByDistance;
if (defined_default(scale)) {
near = scale.near;
nearValue = scale.nearValue;
far = scale.far;
farValue = scale.farValue;
if (nearValue !== 1 || farValue !== 1) {
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.pixelOffsetScaleByDistance];
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const pixelOffsetScale = billboard.pixelOffsetScaleByDistance;
if (defined_default(pixelOffsetScale)) {
near = pixelOffsetScale.near;
nearValue = pixelOffsetScale.nearValue;
far = pixelOffsetScale.far;
farValue = pixelOffsetScale.farValue;
if (nearValue !== 1 || farValue !== 1) {
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.compressedAttribute3];
let near = 0;
let far = Number.MAX_VALUE;
const distanceDisplayCondition = billboard.distanceDisplayCondition;
if (defined_default(distanceDisplayCondition)) {
near = distanceDisplayCondition.near;
far = distanceDisplayCondition.far;
near *= near;
far *= far;
billboardCollection._shaderDistanceDisplayCondition = true;
}
let disableDepthTestDistance = billboard.disableDepthTestDistance;
const clampToGround = billboard.heightReference === HeightReference_default.CLAMP_TO_GROUND && frameState.context.depthTexture;
if (!defined_default(disableDepthTestDistance)) {
disableDepthTestDistance = clampToGround ? 5e3 : 0;
}
disableDepthTestDistance *= disableDepthTestDistance;
if (clampToGround || disableDepthTestDistance > 0) {
billboardCollection._shaderDisableDepthDistance = true;
if (disableDepthTestDistance === Number.POSITIVE_INFINITY) {
disableDepthTestDistance = -1;
}
}
let imageHeight;
let imageWidth;
if (!defined_default(billboard._labelDimensions)) {
let height = 0;
let width = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
height = imageRectangle.height;
width = imageRectangle.width;
}
imageHeight = Math.round(
defaultValue_default(
billboard.height,
billboardCollection._textureAtlas.texture.dimensions.y * height
)
);
const textureWidth = billboardCollection._textureAtlas.texture.width;
imageWidth = Math.round(
defaultValue_default(billboard.width, textureWidth * width)
);
} else {
imageWidth = billboard._labelDimensions.x;
imageHeight = billboard._labelDimensions.y;
}
const w = Math.floor(Math_default.clamp(imageWidth, 0, LEFT_SHIFT12));
const h = Math.floor(Math_default.clamp(imageHeight, 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_default.CLAMP_TO_GROUND) {
const scene = billboardCollection._scene;
const context = frameState.context;
const globeTranslucent = frameState.globeTranslucencyState.translucent;
const depthTestAgainstTerrain = defined_default(scene.globe) && scene.globe.depthTestAgainstTerrain;
billboardCollection._shaderClampToGround = context.depthTexture && !globeTranslucent && depthTestAgainstTerrain;
}
let i;
const writer = vafWriters[attributeLocations.textureCoordinateBoundsOrLabelTranslate];
if (ContextLimits_default.maximumVertexTextureImageUnits > 0) {
let translateX = 0;
let translateY = 0;
if (defined_default(billboard._labelTranslate)) {
translateX = billboard._labelTranslate.x;
translateY = billboard._labelTranslate.y;
}
if (billboardCollection._instanced) {
i = billboard._index;
writer(i, translateX, translateY, 0, 0);
} else {
i = billboard._index * 4;
writer(i + 0, translateX, translateY, 0, 0);
writer(i + 1, translateX, translateY, 0, 0);
writer(i + 2, translateX, translateY, 0, 0);
writer(i + 3, translateX, translateY, 0, 0);
}
return;
}
let minX = 0;
let minY = 0;
let width = 0;
let height = 0;
const index = billboard._imageIndex;
if (index !== -1) {
const imageRectangle = textureAtlasCoordinates[index];
if (!defined_default(imageRectangle)) {
throw new DeveloperError_default(`Invalid billboard image index: ${index}`);
}
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_default(billboardCollection._batchTable)) {
return;
}
const writer = vafWriters[attributeLocations.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.sdf];
const outlineColor = billboard.outlineColor;
const outlineWidth = billboard.outlineWidth;
const red = Color_default.floatToByte(outlineColor.red);
const green = Color_default.floatToByte(outlineColor.green);
const blue = Color_default.floatToByte(outlineColor.blue);
const compressed0 = red * LEFT_SHIFT16 + green * LEFT_SHIFT8 + blue;
const outlineDistance = outlineWidth / SDFSettings_default.RADIUS;
const compressed1 = Color_default.floatToByte(outlineColor.alpha) * LEFT_SHIFT16 + Color_default.floatToByte(outlineDistance) * LEFT_SHIFT8;
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(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeCompressedAttrib1(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeCompressedAttrib2(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeEyeOffset(
billboardCollection,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
writeScaleByDistance(
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(billboardCollection, billboards, length3, frameState, modelMatrix, recomputeBoundingVolume) {
let boundingVolume;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolume = billboardCollection._baseVolume;
billboardCollection._boundingVolumeDirty = true;
} else {
boundingVolume = billboardCollection._baseVolume2D;
}
const positions = [];
for (let i = 0; i < length3; ++i) {
const billboard = billboards[i];
const position = billboard.position;
const actualPosition = Billboard_default._computeActualPosition(
billboard,
position,
frameState,
modelMatrix
);
if (defined_default(actualPosition)) {
billboard._setActualPosition(actualPosition);
if (recomputeBoundingVolume) {
positions.push(actualPosition);
} else {
BoundingSphere_default.expand(boundingVolume, actualPosition, boundingVolume);
}
}
}
if (recomputeBoundingVolume) {
BoundingSphere_default.fromPoints(positions, boundingVolume);
}
}
function updateMode(billboardCollection, frameState) {
const mode2 = frameState.mode;
const billboards = billboardCollection._billboards;
const billboardsToUpdate = billboardCollection._billboardsToUpdate;
const modelMatrix = billboardCollection._modelMatrix;
if (billboardCollection._createVertexArray || billboardCollection._mode !== mode2 || mode2 !== SceneMode_default.SCENE3D && !Matrix4_default.equals(modelMatrix, billboardCollection.modelMatrix)) {
billboardCollection._mode = mode2;
Matrix4_default.clone(billboardCollection.modelMatrix, modelMatrix);
billboardCollection._createVertexArray = true;
if (mode2 === SceneMode_default.SCENE3D || mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions(
billboardCollection,
billboards,
billboards.length,
frameState,
modelMatrix,
true
);
}
} else if (mode2 === SceneMode_default.MORPHING) {
recomputeActualPositions(
billboardCollection,
billboards,
billboards.length,
frameState,
modelMatrix,
true
);
} else if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions(
billboardCollection,
billboardsToUpdate,
billboardCollection._billboardsToUpdateIndex,
frameState,
modelMatrix,
false
);
}
}
function updateBoundingVolume(collection, frameState, boundingVolume) {
let pixelScale = 1;
if (!collection._allSizedInMeters || collection._maxPixelOffset !== 0) {
pixelScale = frameState.camera.getPixelSize(
boundingVolume,
frameState.context.drawingBufferWidth,
frameState.context.drawingBufferHeight
);
}
let size = pixelScale * collection._maxScale * collection._maxSize * 2;
if (collection._allHorizontalCenter && collection._allVerticalCenter) {
size *= 0.5;
}
const offset2 = pixelScale * collection._maxPixelOffset + collection._maxEyeOffset;
boundingVolume.radius += size + offset2;
}
function createDebugCommand(billboardCollection, context) {
const fs = "uniform sampler2D billboard_texture; \nin vec2 v_textureCoordinates; \nvoid main() \n{ \n out_FragColor = texture(billboard_texture, v_textureCoordinates); \n} \n";
const drawCommand = context.createViewportQuadCommand(fs, {
uniformMap: {
billboard_texture: function() {
return billboardCollection._textureAtlas.texture;
}
}
});
drawCommand.pass = Pass_default.OVERLAY;
return drawCommand;
}
var scratchWriterArray = [];
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 = this._instanced ? attributeLocationsInstanced : attributeLocationsBatched;
getIndexBuffer2 = this._instanced ? getIndexBufferInstanced : getIndexBufferBatched;
let textureAtlas = this._textureAtlas;
if (!defined_default(textureAtlas)) {
textureAtlas = this._textureAtlas = new TextureAtlas_default({
context
});
for (let ii = 0; ii < billboardsLength; ++ii) {
billboards[ii]._loadImage();
}
}
const textureAtlasCoordinates = textureAtlas.textureCoordinates;
if (textureAtlasCoordinates.length === 0) {
return;
}
updateMode(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 createVertexArray7 = this._createVertexArray || this._textureAtlasGUID !== textureAtlasGUID;
this._textureAtlasGUID = textureAtlasGUID;
let vafWriters;
const pass = frameState.passes;
const picking = pass.pick;
if (createVertexArray7 || !picking && this.computeNewBuffersUsage()) {
this._createVertexArray = false;
for (let k = 0; k < NUMBER_OF_PROPERTIES; ++k) {
properties[k] = 0;
}
this._vaf = this._vaf && this._vaf.destroy();
if (billboardsLength > 0) {
this._vaf = createVAF(
context,
billboardsLength,
this._buffersUsage,
this._instanced,
this._batchTable,
this._sdf
);
vafWriters = this._vaf.writers;
for (let i = 0; i < billboardsLength; ++i) {
const billboard = this._billboards[i];
billboard._dirty = false;
writeBillboard(
this,
frameState,
textureAtlasCoordinates,
vafWriters,
billboard
);
}
this._vaf.commit(getIndexBuffer2(context));
}
this._billboardsToUpdateIndex = 0;
} else if (billboardsToUpdateLength > 0) {
const writers = scratchWriterArray;
writers.length = 0;
if (properties[POSITION_INDEX2] || properties[ROTATION_INDEX2] || properties[SCALE_INDEX2]) {
writers.push(writePositionScaleAndRotation);
}
if (properties[IMAGE_INDEX_INDEX2] || properties[PIXEL_OFFSET_INDEX2] || properties[HORIZONTAL_ORIGIN_INDEX2] || properties[VERTICAL_ORIGIN_INDEX2] || properties[SHOW_INDEX2]) {
writers.push(writeCompressedAttrib0);
if (this._instanced) {
writers.push(writeEyeOffset);
}
}
if (properties[IMAGE_INDEX_INDEX2] || properties[ALIGNED_AXIS_INDEX2] || properties[TRANSLUCENCY_BY_DISTANCE_INDEX2]) {
writers.push(writeCompressedAttrib1);
writers.push(writeCompressedAttrib2);
}
if (properties[IMAGE_INDEX_INDEX2] || properties[COLOR_INDEX2]) {
writers.push(writeCompressedAttrib2);
}
if (properties[EYE_OFFSET_INDEX2]) {
writers.push(writeEyeOffset);
}
if (properties[SCALE_BY_DISTANCE_INDEX2]) {
writers.push(writeScaleByDistance);
}
if (properties[PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX2]) {
writers.push(writePixelOffsetScaleByDistance);
}
if (properties[DISTANCE_DISPLAY_CONDITION_INDEX] || properties[DISABLE_DEPTH_DISTANCE2] || properties[IMAGE_INDEX_INDEX2] || properties[POSITION_INDEX2]) {
writers.push(writeCompressedAttribute3);
}
if (properties[IMAGE_INDEX_INDEX2] || properties[POSITION_INDEX2]) {
writers.push(writeTextureCoordinateBoundsOrLabelTranslate);
}
if (properties[SDF_INDEX2]) {
writers.push(writeSDF);
}
const numWriters = writers.length;
vafWriters = this._vaf.writers;
if (billboardsToUpdateLength / billboardsLength > 0.1) {
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(getIndexBuffer2(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 (billboardsToUpdateLength > billboardsLength * 1.5) {
billboardsToUpdate.length = billboardsLength;
}
if (!defined_default(this._vaf) || !defined_default(this._vaf.va)) {
return;
}
if (this._boundingVolumeDirty) {
this._boundingVolumeDirty = false;
BoundingSphere_default.transform(
this._baseVolume,
this.modelMatrix,
this._baseVolumeWC
);
}
let boundingVolume;
let modelMatrix = Matrix4_default.IDENTITY;
if (frameState.mode === SceneMode_default.SCENE3D) {
modelMatrix = this.modelMatrix;
boundingVolume = BoundingSphere_default.clone(
this._baseVolumeWC,
this._boundingVolume
);
} else {
boundingVolume = BoundingSphere_default.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_default.OPAQUE || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsOpaque = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: WebGLConstants_default.LESS
},
depthMask: true
});
} else {
this._rsOpaque = void 0;
}
const useTranslucentDepthMask = this._blendOption === BlendOption_default.TRANSLUCENT;
if (this._blendOption === BlendOption_default.TRANSLUCENT || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsTranslucent = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: useTranslucentDepthMask ? WebGLConstants_default.LEQUAL : WebGLConstants_default.LESS
},
depthMask: useTranslucentDepthMask,
blending: BlendingState_default.ALPHA_BLEND
});
} else {
this._rsTranslucent = void 0;
}
}
this._shaderDisableDepthDistance = this._shaderDisableDepthDistance || frameState.minimumDisableDepthTestDistance !== 0;
let vsSource;
let fsSource;
let vs;
let fs;
let vertDefines;
const supportVSTextureReads = ContextLimits_default.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_default;
fsSource = BillboardCollectionFS_default;
vertDefines = [];
if (defined_default(this._batchTable)) {
vertDefines.push("VECTOR_TILE");
vsSource = this._batchTable.getVertexShaderCallback(
false,
"a_batchId",
void 0
)(vsSource);
fsSource = this._batchTable.getFragmentShaderCallback(
false,
void 0
)(fsSource);
}
vs = new ShaderSource_default({
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 - SDFSettings_default.CUTOFF;
if (this._sdf) {
vs.defines.push("SDF");
}
const vectorFragDefine = defined_default(this._batchTable) ? "VECTOR_TILE" : "";
if (this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
fs = new ShaderSource_default({
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_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
fs = new ShaderSource_default({
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_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
}
if (this._blendOption === BlendOption_default.OPAQUE) {
fs = new ShaderSource_default({
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_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
}
if (this._blendOption === BlendOption_default.TRANSLUCENT) {
fs = new ShaderSource_default({
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_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations
});
}
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_default.OPAQUE;
const opaqueAndTranslucent = this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT;
const va = this._vaf.va;
const vaLength = va.length;
let uniforms = this._uniforms;
let pickId;
if (defined_default(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_default(command)) {
command = colorList[j] = new DrawCommand_default();
}
const opaqueCommand = opaque || opaqueAndTranslucent && j % 2 === 0;
command.pass = opaqueCommand || !opaqueAndTranslucent ? Pass_default.OPAQUE : Pass_default.TRANSLUCENT;
command.owner = this;
const index = opaqueAndTranslucent ? Math.floor(j / 2) : 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_default(this.debugCommand)) {
this.debugCommand = createDebugCommand(this, frameState.context);
}
commandList.push(this.debugCommand);
}
}
};
BillboardCollection.prototype.isDestroyed = function() {
return false;
};
BillboardCollection.prototype.destroy = function() {
if (defined_default(this._removeCallbackFunc)) {
this._removeCallbackFunc();
this._removeCallbackFunc = void 0;
}
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_default(this);
};
var BillboardCollection_default = BillboardCollection;
// node_modules/@cesium/engine/Source/Scene/createBillboardPointCallback.js
function createBillboardPointCallback(centerAlpha, cssColor, cssOutlineColor, cssOutlineWidth, pixelSize) {
return function() {
const canvas = document.createElement("canvas");
const length3 = pixelSize + 2 * cssOutlineWidth;
canvas.height = canvas.width = length3;
const context2D = canvas.getContext("2d");
context2D.clearRect(0, 0, length3, length3);
if (cssOutlineWidth !== 0) {
context2D.beginPath();
context2D.arc(length3 / 2, length3 / 2, length3 / 2, 0, 2 * Math.PI, true);
context2D.closePath();
context2D.fillStyle = cssOutlineColor;
context2D.fill();
if (centerAlpha < 1) {
context2D.save();
context2D.globalCompositeOperation = "destination-out";
context2D.beginPath();
context2D.arc(
length3 / 2,
length3 / 2,
pixelSize / 2,
0,
2 * Math.PI,
true
);
context2D.closePath();
context2D.fillStyle = "black";
context2D.fill();
context2D.restore();
}
}
context2D.beginPath();
context2D.arc(length3 / 2, length3 / 2, pixelSize / 2, 0, 2 * Math.PI, true);
context2D.closePath();
context2D.fillStyle = cssColor;
context2D.fill();
return canvas;
};
}
var createBillboardPointCallback_default = createBillboardPointCallback;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilePointFeature.js
function Cesium3DTilePointFeature(content, batchId, billboard, label, polyline) {
this._content = content;
this._billboard = billboard;
this._label = label;
this._polyline = polyline;
this._batchId = batchId;
this._billboardImage = void 0;
this._billboardColor = void 0;
this._billboardOutlineColor = void 0;
this._billboardOutlineWidth = void 0;
this._billboardSize = void 0;
this._pointSize = void 0;
this._color = void 0;
this._pointSize = void 0;
this._pointOutlineColor = void 0;
this._pointOutlineWidth = void 0;
this._heightOffset = void 0;
this._pickIds = new Array(3);
setBillboardImage(this);
}
var scratchCartographic5 = new Cartographic_default();
Object.defineProperties(Cesium3DTilePointFeature.prototype, {
show: {
get: function() {
return this._label.show;
},
set: function(value) {
this._label.show = value;
this._billboard.show = value;
this._polyline.show = value;
}
},
color: {
get: function() {
return this._color;
},
set: function(value) {
this._color = Color_default.clone(value, this._color);
setBillboardImage(this);
}
},
pointSize: {
get: function() {
return this._pointSize;
},
set: function(value) {
this._pointSize = value;
setBillboardImage(this);
}
},
pointOutlineColor: {
get: function() {
return this._pointOutlineColor;
},
set: function(value) {
this._pointOutlineColor = Color_default.clone(value, this._pointOutlineColor);
setBillboardImage(this);
}
},
pointOutlineWidth: {
get: function() {
return this._pointOutlineWidth;
},
set: function(value) {
this._pointOutlineWidth = value;
setBillboardImage(this);
}
},
labelColor: {
get: function() {
return this._label.fillColor;
},
set: function(value) {
this._label.fillColor = value;
this._polyline.show = this._label.show && value.alpha > 0;
}
},
labelOutlineColor: {
get: function() {
return this._label.outlineColor;
},
set: function(value) {
this._label.outlineColor = value;
}
},
labelOutlineWidth: {
get: function() {
return this._label.outlineWidth;
},
set: function(value) {
this._label.outlineWidth = value;
}
},
font: {
get: function() {
return this._label.font;
},
set: function(value) {
this._label.font = value;
}
},
labelStyle: {
get: function() {
return this._label.style;
},
set: function(value) {
this._label.style = value;
}
},
labelText: {
get: function() {
return this._label.text;
},
set: function(value) {
if (!defined_default(value)) {
value = "";
}
this._label.text = value;
}
},
backgroundColor: {
get: function() {
return this._label.backgroundColor;
},
set: function(value) {
this._label.backgroundColor = value;
}
},
backgroundPadding: {
get: function() {
return this._label.backgroundPadding;
},
set: function(value) {
this._label.backgroundPadding = value;
}
},
backgroundEnabled: {
get: function() {
return this._label.showBackground;
},
set: function(value) {
this._label.showBackground = value;
}
},
scaleByDistance: {
get: function() {
return this._label.scaleByDistance;
},
set: function(value) {
this._label.scaleByDistance = value;
this._billboard.scaleByDistance = value;
}
},
translucencyByDistance: {
get: function() {
return this._label.translucencyByDistance;
},
set: function(value) {
this._label.translucencyByDistance = value;
this._billboard.translucencyByDistance = value;
}
},
distanceDisplayCondition: {
get: function() {
return this._label.distanceDisplayCondition;
},
set: function(value) {
this._label.distanceDisplayCondition = value;
this._polyline.distanceDisplayCondition = value;
this._billboard.distanceDisplayCondition = value;
}
},
heightOffset: {
get: function() {
return this._heightOffset;
},
set: function(value) {
const offset2 = defaultValue_default(this._heightOffset, 0);
const ellipsoid = this._content.tileset.ellipsoid;
const cart = ellipsoid.cartesianToCartographic(
this._billboard.position,
scratchCartographic5
);
cart.height = cart.height - offset2 + 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;
}
},
anchorLineEnabled: {
get: function() {
return this._polyline.show;
},
set: function(value) {
this._polyline.show = value;
}
},
anchorLineColor: {
get: function() {
return this._polyline.material.uniforms.color;
},
set: function(value) {
this._polyline.material.uniforms.color = Color_default.clone(
value,
this._polyline.material.uniforms.color
);
}
},
image: {
get: function() {
return this._billboardImage;
},
set: function(value) {
const imageChanged = this._billboardImage !== value;
this._billboardImage = value;
if (imageChanged) {
setBillboardImage(this);
}
}
},
disableDepthTestDistance: {
get: function() {
return this._label.disableDepthTestDistance;
},
set: function(value) {
this._label.disableDepthTestDistance = value;
this._billboard.disableDepthTestDistance = value;
}
},
horizontalOrigin: {
get: function() {
return this._billboard.horizontalOrigin;
},
set: function(value) {
this._billboard.horizontalOrigin = value;
}
},
verticalOrigin: {
get: function() {
return this._billboard.verticalOrigin;
},
set: function(value) {
this._billboard.verticalOrigin = value;
}
},
labelHorizontalOrigin: {
get: function() {
return this._label.horizontalOrigin;
},
set: function(value) {
this._label.horizontalOrigin = value;
}
},
labelVerticalOrigin: {
get: function() {
return this._label.verticalOrigin;
},
set: function(value) {
this._label.verticalOrigin = value;
}
},
content: {
get: function() {
return this._content;
}
},
tileset: {
get: function() {
return this._content.tileset;
}
},
primitive: {
get: function() {
return this._content.tileset;
}
},
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_default.WHITE;
Cesium3DTilePointFeature.defaultPointOutlineColor = Color_default.BLACK;
Cesium3DTilePointFeature.defaultPointOutlineWidth = 0;
Cesium3DTilePointFeature.defaultPointSize = 8;
function setBillboardImage(feature) {
const b = feature._billboard;
if (defined_default(feature._billboardImage) && feature._billboardImage !== b.image) {
b.image = feature._billboardImage;
return;
}
if (defined_default(feature._billboardImage)) {
return;
}
const newColor = defaultValue_default(
feature._color,
Cesium3DTilePointFeature.defaultColor
);
const newOutlineColor = defaultValue_default(
feature._pointOutlineColor,
Cesium3DTilePointFeature.defaultPointOutlineColor
);
const newOutlineWidth = defaultValue_default(
feature._pointOutlineWidth,
Cesium3DTilePointFeature.defaultPointOutlineWidth
);
const newPointSize = defaultValue_default(
feature._pointSize,
Cesium3DTilePointFeature.defaultPointSize
);
const currentColor = feature._billboardColor;
const currentOutlineColor = feature._billboardOutlineColor;
const currentOutlineWidth = feature._billboardOutlineWidth;
const currentPointSize = feature._billboardSize;
if (Color_default.equals(newColor, currentColor) && Color_default.equals(newOutlineColor, currentOutlineColor) && newOutlineWidth === currentOutlineWidth && newPointSize === currentPointSize) {
return;
}
feature._billboardColor = Color_default.clone(newColor, feature._billboardColor);
feature._billboardOutlineColor = Color_default.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_default(
centerAlpha,
cssColor,
cssOutlineColor,
newOutlineWidth,
newPointSize
)
);
}
Cesium3DTilePointFeature.prototype.hasProperty = function(name) {
return this._content.batchTable.hasProperty(this._batchId, name);
};
Cesium3DTilePointFeature.prototype.getPropertyIds = function(results) {
return this._content.batchTable.getPropertyIds(this._batchId, results);
};
Cesium3DTilePointFeature.prototype.getProperty = function(name) {
return this._content.batchTable.getProperty(this._batchId, name);
};
Cesium3DTilePointFeature.prototype.getPropertyInherited = function(name) {
return Cesium3DTileFeature_default.getPropertyInherited(
this._content,
this._batchId,
name
);
};
Cesium3DTilePointFeature.prototype.setProperty = function(name, value) {
this._content.batchTable.setProperty(this._batchId, name, value);
this._content.featurePropertiesDirty = true;
};
Cesium3DTilePointFeature.prototype.isExactClass = function(className) {
return this._content.batchTable.isExactClass(this._batchId, className);
};
Cesium3DTilePointFeature.prototype.isClass = function(className) {
return this._content.batchTable.isClass(this._batchId, className);
};
Cesium3DTilePointFeature.prototype.getExactClassName = function() {
return this._content.batchTable.getExactClassName(this._batchId);
};
var Cesium3DTilePointFeature_default = Cesium3DTilePointFeature;
// node_modules/@cesium/engine/Source/Core/writeTextToCanvas.js
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);
}
const pixelData = ctx.getImageData(0, 0, width, height).data;
const length3 = pixelData.length;
const width4 = width * 4;
let i, j;
let ascent, descent;
for (i = 0; i < length3; ++i) {
if (pixelData[i] !== 255) {
ascent = i / width4 | 0;
break;
}
}
for (i = length3 - 1; i >= 0; --i) {
if (pixelData[i] !== 255) {
descent = i / width4 | 0;
break;
}
}
let minx = -1;
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
};
}
var imageSmoothingEnabledName;
function writeTextToCanvas(text2, options) {
if (!defined_default(text2)) {
throw new DeveloperError_default("text is required.");
}
if (text2 === "") {
return void 0;
}
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const font = defaultValue_default(options.font, "10px sans-serif");
const stroke = defaultValue_default(options.stroke, false);
const fill = defaultValue_default(options.fill, true);
const strokeWidth = defaultValue_default(options.strokeWidth, 1);
const backgroundColor = defaultValue_default(
options.backgroundColor,
Color_default.TRANSPARENT
);
const padding = defaultValue_default(options.padding, 0);
const doublePadding = padding * 2;
const canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
canvas.style.font = font;
const context2D = canvas.getContext("2d", { willReadFrequently: true });
if (!defined_default(imageSmoothingEnabledName)) {
if (defined_default(context2D.imageSmoothingEnabled)) {
imageSmoothingEnabledName = "imageSmoothingEnabled";
} else if (defined_default(context2D.mozImageSmoothingEnabled)) {
imageSmoothingEnabledName = "mozImageSmoothingEnabled";
} else if (defined_default(context2D.webkitImageSmoothingEnabled)) {
imageSmoothingEnabledName = "webkitImageSmoothingEnabled";
} else if (defined_default(context2D.msImageSmoothingEnabled)) {
imageSmoothingEnabledName = "msImageSmoothingEnabled";
}
}
context2D.font = font;
context2D.lineJoin = "round";
context2D.lineWidth = strokeWidth;
context2D[imageSmoothingEnabledName] = false;
canvas.style.visibility = "hidden";
document.body.appendChild(canvas);
const dimensions = measureText(context2D, text2, font, stroke, fill);
canvas.dimensions = dimensions;
document.body.removeChild(canvas);
canvas.style.visibility = "";
const x = -dimensions.minx;
const width = Math.ceil(dimensions.width) + x + doublePadding;
const height = dimensions.height + doublePadding;
const baseline = height - dimensions.ascent + padding;
const y = height - baseline + doublePadding;
canvas.width = width;
canvas.height = height;
context2D.font = font;
context2D.lineJoin = "round";
context2D.lineWidth = strokeWidth;
context2D[imageSmoothingEnabledName] = false;
if (backgroundColor !== Color_default.TRANSPARENT) {
context2D.fillStyle = backgroundColor.toCssColorString();
context2D.fillRect(0, 0, canvas.width, canvas.height);
}
if (stroke) {
const strokeColor = defaultValue_default(options.strokeColor, Color_default.BLACK);
context2D.strokeStyle = strokeColor.toCssColorString();
context2D.strokeText(text2, x + padding, y);
}
if (fill) {
const fillColor = defaultValue_default(options.fillColor, Color_default.WHITE);
context2D.fillStyle = fillColor.toCssColorString();
context2D.fillText(text2, x + padding, y);
}
return canvas;
}
var writeTextToCanvas_default = writeTextToCanvas;
// node_modules/@cesium/engine/Source/Scene/LabelCollection.js
var import_bitmap_sdf = __toESM(require_bitmap_sdf(), 1);
// node_modules/@cesium/engine/Source/Scene/LabelStyle.js
var LabelStyle = {
FILL: 0,
OUTLINE: 1,
FILL_AND_OUTLINE: 2
};
var LabelStyle_default = Object.freeze(LabelStyle);
// node_modules/@cesium/engine/Source/Scene/Label.js
var fontInfoCache = {};
var fontInfoCacheLength = 0;
var fontInfoCacheMaxSize = 256;
var defaultBackgroundColor = new Color_default(0.165, 0.165, 0.165, 0.8);
var defaultBackgroundPadding = new Cartesian2_default(7, 5);
var textTypes = Object.freeze({
LTR: 0,
RTL: 1,
WEAK: 2,
BRACKETS: 3
});
function rebindAllGlyphs(label) {
if (!label._rebindAllGlyphs && !label._repositionAllGlyphs) {
label._labelCollection._labelsToUpdate.push(label);
}
label._rebindAllGlyphs = true;
}
function repositionAllGlyphs(label) {
if (!label._rebindAllGlyphs && !label._repositionAllGlyphs) {
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_default(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)) {
lineHeight = void 0;
}
fontInfo = {
family: getCSSValue(div, "font-family"),
size: getCSSValue(div, "font-size").replace("px", ""),
style: getCSSValue(div, "font-style"),
weight: getCSSValue(div, "font-weight"),
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;
}
function Label(options, labelCollection) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (defined_default(options.disableDepthTestDistance) && options.disableDepthTestDistance < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than 0.0."
);
}
let translucencyByDistance = options.translucencyByDistance;
let pixelOffsetScaleByDistance = options.pixelOffsetScaleByDistance;
let scaleByDistance = options.scaleByDistance;
let distanceDisplayCondition = options.distanceDisplayCondition;
if (defined_default(translucencyByDistance)) {
if (translucencyByDistance.far <= translucencyByDistance.near) {
throw new DeveloperError_default(
"translucencyByDistance.far must be greater than translucencyByDistance.near."
);
}
translucencyByDistance = NearFarScalar_default.clone(translucencyByDistance);
}
if (defined_default(pixelOffsetScaleByDistance)) {
if (pixelOffsetScaleByDistance.far <= pixelOffsetScaleByDistance.near) {
throw new DeveloperError_default(
"pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near."
);
}
pixelOffsetScaleByDistance = NearFarScalar_default.clone(
pixelOffsetScaleByDistance
);
}
if (defined_default(scaleByDistance)) {
if (scaleByDistance.far <= scaleByDistance.near) {
throw new DeveloperError_default(
"scaleByDistance.far must be greater than scaleByDistance.near."
);
}
scaleByDistance = NearFarScalar_default.clone(scaleByDistance);
}
if (defined_default(distanceDisplayCondition)) {
if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
throw new DeveloperError_default(
"distanceDisplayCondition.far must be greater than distanceDisplayCondition.near."
);
}
distanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition
);
}
this._renderedText = void 0;
this._text = void 0;
this._show = defaultValue_default(options.show, true);
this._font = defaultValue_default(options.font, "30px sans-serif");
this._fillColor = Color_default.clone(defaultValue_default(options.fillColor, Color_default.WHITE));
this._outlineColor = Color_default.clone(
defaultValue_default(options.outlineColor, Color_default.BLACK)
);
this._outlineWidth = defaultValue_default(options.outlineWidth, 1);
this._showBackground = defaultValue_default(options.showBackground, false);
this._backgroundColor = Color_default.clone(
defaultValue_default(options.backgroundColor, defaultBackgroundColor)
);
this._backgroundPadding = Cartesian2_default.clone(
defaultValue_default(options.backgroundPadding, defaultBackgroundPadding)
);
this._style = defaultValue_default(options.style, LabelStyle_default.FILL);
this._verticalOrigin = defaultValue_default(
options.verticalOrigin,
VerticalOrigin_default.BASELINE
);
this._horizontalOrigin = defaultValue_default(
options.horizontalOrigin,
HorizontalOrigin_default.LEFT
);
this._pixelOffset = Cartesian2_default.clone(
defaultValue_default(options.pixelOffset, Cartesian2_default.ZERO)
);
this._eyeOffset = Cartesian3_default.clone(
defaultValue_default(options.eyeOffset, Cartesian3_default.ZERO)
);
this._position = Cartesian3_default.clone(
defaultValue_default(options.position, Cartesian3_default.ZERO)
);
this._scale = defaultValue_default(options.scale, 1);
this._id = options.id;
this._translucencyByDistance = translucencyByDistance;
this._pixelOffsetScaleByDistance = pixelOffsetScaleByDistance;
this._scaleByDistance = scaleByDistance;
this._heightReference = defaultValue_default(
options.heightReference,
HeightReference_default.NONE
);
this._distanceDisplayCondition = distanceDisplayCondition;
this._disableDepthTestDistance = options.disableDepthTestDistance;
this._labelCollection = labelCollection;
this._glyphs = [];
this._backgroundBillboard = void 0;
this._batchIndex = void 0;
this._rebindAllGlyphs = true;
this._repositionAllGlyphs = true;
this._actualClampedPosition = void 0;
this._removeCallbackFunc = void 0;
this._mode = void 0;
this._clusterShow = true;
this.text = defaultValue_default(options.text, "");
this._relativeSize = 1;
parseFont(this);
this._updateClamping();
}
Object.defineProperties(Label.prototype, {
show: {
get: function() {
return this._show;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
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_default(billboard)) {
billboard.show = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.show = value;
}
}
}
},
position: {
get: function() {
return this._position;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const position = this._position;
if (!Cartesian3_default.equals(position, value)) {
Cartesian3_default.clone(value, position);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const billboard = glyphs[i].billboard;
if (defined_default(billboard)) {
billboard.position = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.position = value;
}
this._updateClamping();
}
}
},
heightReference: {
get: function() {
return this._heightReference;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
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_default(billboard)) {
billboard.heightReference = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.heightReference = value;
}
repositionAllGlyphs(this);
this._updateClamping();
}
}
},
text: {
get: function() {
return this._text;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._text !== value) {
this._text = value;
const renderedValue = value.replace(/\u00ad/g, "");
this._renderedText = Label.enableRightToLeftDetection ? reverseRtl(renderedValue) : renderedValue;
rebindAllGlyphs(this);
}
}
},
font: {
get: function() {
return this._font;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._font !== value) {
this._font = value;
rebindAllGlyphs(this);
parseFont(this);
}
}
},
fillColor: {
get: function() {
return this._fillColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const fillColor = this._fillColor;
if (!Color_default.equals(fillColor, value)) {
Color_default.clone(value, fillColor);
rebindAllGlyphs(this);
}
}
},
outlineColor: {
get: function() {
return this._outlineColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const outlineColor = this._outlineColor;
if (!Color_default.equals(outlineColor, value)) {
Color_default.clone(value, outlineColor);
rebindAllGlyphs(this);
}
}
},
outlineWidth: {
get: function() {
return this._outlineWidth;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._outlineWidth !== value) {
this._outlineWidth = value;
rebindAllGlyphs(this);
}
}
},
showBackground: {
get: function() {
return this._showBackground;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._showBackground !== value) {
this._showBackground = value;
rebindAllGlyphs(this);
}
}
},
backgroundColor: {
get: function() {
return this._backgroundColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const backgroundColor = this._backgroundColor;
if (!Color_default.equals(backgroundColor, value)) {
Color_default.clone(value, backgroundColor);
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.color = backgroundColor;
}
}
}
},
backgroundPadding: {
get: function() {
return this._backgroundPadding;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const backgroundPadding = this._backgroundPadding;
if (!Cartesian2_default.equals(backgroundPadding, value)) {
Cartesian2_default.clone(value, backgroundPadding);
repositionAllGlyphs(this);
}
}
},
style: {
get: function() {
return this._style;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._style !== value) {
this._style = value;
rebindAllGlyphs(this);
}
}
},
pixelOffset: {
get: function() {
return this._pixelOffset;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const pixelOffset = this._pixelOffset;
if (!Cartesian2_default.equals(pixelOffset, value)) {
Cartesian2_default.clone(value, pixelOffset);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard.pixelOffset = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.pixelOffset = value;
}
}
}
},
translucencyByDistance: {
get: function() {
return this._translucencyByDistance;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
const translucencyByDistance = this._translucencyByDistance;
if (!NearFarScalar_default.equals(translucencyByDistance, value)) {
this._translucencyByDistance = NearFarScalar_default.clone(
value,
translucencyByDistance
);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard.translucencyByDistance = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.translucencyByDistance = value;
}
}
}
},
pixelOffsetScaleByDistance: {
get: function() {
return this._pixelOffsetScaleByDistance;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
const pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance;
if (!NearFarScalar_default.equals(pixelOffsetScaleByDistance, value)) {
this._pixelOffsetScaleByDistance = NearFarScalar_default.clone(
value,
pixelOffsetScaleByDistance
);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard.pixelOffsetScaleByDistance = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.pixelOffsetScaleByDistance = value;
}
}
}
},
scaleByDistance: {
get: function() {
return this._scaleByDistance;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
const scaleByDistance = this._scaleByDistance;
if (!NearFarScalar_default.equals(scaleByDistance, value)) {
this._scaleByDistance = NearFarScalar_default.clone(value, scaleByDistance);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard.scaleByDistance = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.scaleByDistance = value;
}
}
}
},
eyeOffset: {
get: function() {
return this._eyeOffset;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const eyeOffset = this._eyeOffset;
if (!Cartesian3_default.equals(eyeOffset, value)) {
Cartesian3_default.clone(value, eyeOffset);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard.eyeOffset = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.eyeOffset = value;
}
}
}
},
horizontalOrigin: {
get: function() {
return this._horizontalOrigin;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._horizontalOrigin !== value) {
this._horizontalOrigin = value;
repositionAllGlyphs(this);
}
}
},
verticalOrigin: {
get: function() {
return this._verticalOrigin;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
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_default(glyph.billboard)) {
glyph.billboard.verticalOrigin = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.verticalOrigin = value;
}
repositionAllGlyphs(this);
}
}
},
scale: {
get: function() {
return this._scale;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
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_default(glyph.billboard)) {
glyph.billboard.scale = value * this._relativeSize;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.scale = value * this._relativeSize;
}
repositionAllGlyphs(this);
}
}
},
totalScale: {
get: function() {
return this._scale * this._relativeSize;
}
},
distanceDisplayCondition: {
get: function() {
return this._distanceDisplayCondition;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default("far must be greater than near");
}
if (!DistanceDisplayCondition_default.equals(value, this._distanceDisplayCondition)) {
this._distanceDisplayCondition = DistanceDisplayCondition_default.clone(
value,
this._distanceDisplayCondition
);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard.distanceDisplayCondition = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.distanceDisplayCondition = value;
}
}
}
},
disableDepthTestDistance: {
get: function() {
return this._disableDepthTestDistance;
},
set: function(value) {
if (this._disableDepthTestDistance !== value) {
if (defined_default(value) && value < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than 0.0."
);
}
this._disableDepthTestDistance = value;
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard.disableDepthTestDistance = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.disableDepthTestDistance = value;
}
}
}
},
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_default(glyph.billboard)) {
glyph.billboard.id = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.id = value;
}
}
}
},
pickId: {
get: function() {
if (this._glyphs.length === 0 || !defined_default(this._glyphs[0].billboard)) {
return void 0;
}
return this._glyphs[0].billboard.pickId;
}
},
_clampedPosition: {
get: function() {
return this._actualClampedPosition;
},
set: function(value) {
this._actualClampedPosition = Cartesian3_default.clone(
value,
this._actualClampedPosition
);
const glyphs = this._glyphs;
for (let i = 0, len = glyphs.length; i < len; i++) {
const glyph = glyphs[i];
if (defined_default(glyph.billboard)) {
glyph.billboard._clampedPosition = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard._clampedPosition = value;
}
}
},
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_default(glyph.billboard)) {
glyph.billboard.clusterShow = value;
}
}
const backgroundBillboard = this._backgroundBillboard;
if (defined_default(backgroundBillboard)) {
backgroundBillboard.clusterShow = value;
}
}
}
}
});
Label.prototype._updateClamping = function() {
Billboard_default._updateClamping(this._labelCollection, this);
};
Label.prototype.computeScreenSpacePosition = function(scene, result) {
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
if (!defined_default(result)) {
result = new Cartesian2_default();
}
const labelCollection = this._labelCollection;
const modelMatrix = labelCollection.modelMatrix;
const actualPosition = defined_default(this._actualClampedPosition) ? this._actualClampedPosition : this._position;
const windowCoordinates = Billboard_default._computeScreenSpacePosition(
modelMatrix,
actualPosition,
this._eyeOffset,
this._pixelOffset,
scene,
result
);
return windowCoordinates;
};
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_default(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_default.BOTTOM || label.verticalOrigin === VerticalOrigin_default.BASELINE) {
y -= height;
} else if (label.verticalOrigin === VerticalOrigin_default.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 length3 = glyphs.length;
for (let i = 0; i < length3; ++i) {
const glyph = glyphs[i];
const billboard = glyph.billboard;
if (!defined_default(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_default.BOTTOM || label.verticalOrigin === VerticalOrigin_default.BASELINE) {
glyphY -= glyphHeight;
} else if (label.verticalOrigin === VerticalOrigin_default.CENTER) {
glyphY -= glyphHeight * 0.5;
}
if (label._verticalOrigin === VerticalOrigin_default.TOP) {
glyphY += SDFSettings_default.PADDING * scale;
} else if (label._verticalOrigin === VerticalOrigin_default.BOTTOM || label._verticalOrigin === VerticalOrigin_default.BASELINE) {
glyphY -= SDFSettings_default.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_default(result)) {
result = new BoundingRectangle_default();
}
result.x = x;
result.y = y;
result.width = width;
result.height = height;
return result;
};
Label.prototype.equals = function(other) {
return this === other || defined_default(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_default.equals(this._position, other._position) && Color_default.equals(this._fillColor, other._fillColor) && Color_default.equals(this._outlineColor, other._outlineColor) && Color_default.equals(this._backgroundColor, other._backgroundColor) && Cartesian2_default.equals(this._backgroundPadding, other._backgroundPadding) && Cartesian2_default.equals(this._pixelOffset, other._pixelOffset) && Cartesian3_default.equals(this._eyeOffset, other._eyeOffset) && NearFarScalar_default.equals(
this._translucencyByDistance,
other._translucencyByDistance
) && NearFarScalar_default.equals(
this._pixelOffsetScaleByDistance,
other._pixelOffsetScaleByDistance
) && NearFarScalar_default.equals(this._scaleByDistance, other._scaleByDistance) && DistanceDisplayCondition_default.equals(
this._distanceDisplayCondition,
other._distanceDisplayCondition
) && this._disableDepthTestDistance === other._disableDepthTestDistance && this._id === other._id;
};
Label.prototype.isDestroyed = function() {
return false;
};
Label.enableRightToLeftDetection = false;
function convertTextToTypes(text2, rtlChars2) {
const ltrChars = /[a-zA-Z0-9]/;
const bracketsChars = /[()[\]{}<>]/;
const parsedText = [];
let word = "";
let lastType = textTypes.LTR;
let currentType = "";
const textLength = text2.length;
for (let textIndex = 0; textIndex < textLength; ++textIndex) {
const character = text2.charAt(textIndex);
if (rtlChars2.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 "<";
}
}
var hebrew = "\u05D0-\u05EA";
var arabic = "\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF";
var rtlChars = new RegExp(`[${hebrew}${arabic}]`);
function reverseRtl(value) {
const texts = value.split("\n");
let result = "";
for (let i = 0; i < texts.length; i++) {
const text2 = texts[i];
const rtlDir = rtlChars.test(text2.charAt(0));
const parsedText = convertTextToTypes(text2, 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) {
if (subText.Type === textTypes.WEAK && parsedText[wordIndex - 1].Type === textTypes.BRACKETS) {
line = reverse + line;
} else if (parsedText[wordIndex - 1].Type === textTypes.RTL) {
line = reverse + line;
splicePointer = 0;
} else if (parsedText.length > wordIndex + 1) {
if (parsedText[wordIndex + 1].Type === textTypes.RTL) {
line = reverse + line;
splicePointer = 0;
} else {
line = spliceWord(line, splicePointer, subText.Word);
splicePointer += subText.Word.length;
}
} else {
line = spliceWord(line, 0, reverse);
}
}
} else if (subText.Type === textTypes.RTL) {
line = spliceWord(line, splicePointer, reverse);
} else if (subText.Type === textTypes.LTR) {
line += subText.Word;
splicePointer = line.length;
} else if (subText.Type === textTypes.WEAK || subText.Type === textTypes.BRACKETS) {
if (wordIndex > 0) {
if (parsedText[wordIndex - 1].Type === textTypes.RTL) {
if (parsedText.length > wordIndex + 1) {
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;
}
var Label_default = Label;
// node_modules/@cesium/engine/Source/Scene/LabelCollection.js
var import_grapheme_splitter = __toESM(require_grapheme_splitter(), 1);
function Glyph() {
this.textureInfo = void 0;
this.dimensions = void 0;
this.billboard = void 0;
}
function GlyphTextureInfo(labelCollection, index, dimensions) {
this.labelCollection = labelCollection;
this.index = index;
this.dimensions = dimensions;
}
var defaultLineSpacingPercent = 1.2;
var whitePixelCanvasId = "ID_WHITE_PIXEL";
var whitePixelSize = new Cartesian2_default(4, 4);
var whitePixelBoundingRegion = new BoundingRectangle_default(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);
textureAtlas.addImage(whitePixelCanvasId, canvas);
}
var writeTextToCanvasParameters = {};
function createGlyphCanvas(character, font, fillColor, outlineColor, outlineWidth, style, verticalOrigin) {
writeTextToCanvasParameters.font = font;
writeTextToCanvasParameters.fillColor = fillColor;
writeTextToCanvasParameters.strokeColor = outlineColor;
writeTextToCanvasParameters.strokeWidth = outlineWidth;
writeTextToCanvasParameters.padding = SDFSettings_default.PADDING;
if (verticalOrigin === VerticalOrigin_default.CENTER) {
writeTextToCanvasParameters.textBaseline = "middle";
} else if (verticalOrigin === VerticalOrigin_default.TOP) {
writeTextToCanvasParameters.textBaseline = "top";
} else {
writeTextToCanvasParameters.textBaseline = "bottom";
}
writeTextToCanvasParameters.fill = style === LabelStyle_default.FILL || style === LabelStyle_default.FILL_AND_OUTLINE;
writeTextToCanvasParameters.stroke = style === LabelStyle_default.OUTLINE || style === LabelStyle_default.FILL_AND_OUTLINE;
writeTextToCanvasParameters.backgroundColor = Color_default.BLACK;
return writeTextToCanvas_default(character, writeTextToCanvasParameters);
}
function unbindGlyph(labelCollection, glyph) {
glyph.textureInfo = void 0;
glyph.dimensions = void 0;
const billboard = glyph.billboard;
if (defined_default(billboard)) {
billboard.show = false;
billboard.image = void 0;
if (defined_default(billboard._removeCallbackFunc)) {
billboard._removeCallbackFunc();
billboard._removeCallbackFunc = void 0;
}
labelCollection._spareBillboards.push(billboard);
glyph.billboard = void 0;
}
}
function addGlyphToTextureAtlas(textureAtlas, id, canvas, glyphTextureInfo) {
glyphTextureInfo.index = textureAtlas.addImageSync(id, canvas);
}
var splitter = new import_grapheme_splitter.default();
function rebindAllGlyphs2(labelCollection, label) {
const text2 = label._renderedText;
const graphemes = splitter.splitGraphemes(text2);
const textLength = graphemes.length;
const glyphs = label._glyphs;
const glyphsLength = glyphs.length;
let glyph;
let glyphIndex;
let textIndex;
label._relativeSize = label._fontSize / SDFSettings_default.FONT_SIZE;
if (textLength < glyphsLength) {
for (glyphIndex = textLength; glyphIndex < glyphsLength; ++glyphIndex) {
unbindGlyph(labelCollection, glyphs[glyphIndex]);
}
}
glyphs.length = textLength;
const showBackground = label._showBackground && text2.split("\n").join("").length > 0;
let backgroundBillboard = label._backgroundBillboard;
const backgroundBillboardCollection = labelCollection._backgroundBillboardCollection;
if (!showBackground) {
if (defined_default(backgroundBillboard)) {
backgroundBillboardCollection.remove(backgroundBillboard);
label._backgroundBillboard = backgroundBillboard = void 0;
}
} else {
if (!defined_default(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_default.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;
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_default(glyphTextureInfo)) {
const glyphFont = `${label._fontStyle} ${label._fontWeight} ${SDFSettings_default.FONT_SIZE}px ${label._fontFamily}`;
const canvas = createGlyphCanvas(
character,
glyphFont,
Color_default.WHITE,
Color_default.WHITE,
0,
LabelStyle_default.FILL,
verticalOrigin
);
glyphTextureInfo = new GlyphTextureInfo(
labelCollection,
-1,
canvas.dimensions
);
glyphTextureCache[id] = glyphTextureInfo;
if (canvas.width > 0 && canvas.height > 0) {
const sdfValues = (0, import_bitmap_sdf.default)(canvas, {
cutoff: SDFSettings_default.CUTOFF,
radius: SDFSettings_default.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_default(glyph)) {
if (glyphTextureInfo.index === -1) {
unbindGlyph(labelCollection, glyph);
} else if (defined_default(glyph.textureInfo)) {
glyph.textureInfo = void 0;
}
} else {
glyph = new Glyph();
glyphs[textIndex] = glyph;
}
glyph.textureInfo = glyphTextureInfo;
glyph.dimensions = glyphTextureInfo.dimensions;
if (glyphTextureInfo.index !== -1) {
let billboard = glyph.billboard;
const spareBillboards = labelCollection._spareBillboards;
if (!defined_default(billboard)) {
if (spareBillboards.length > 0) {
billboard = spareBillboards.pop();
} else {
billboard = labelCollection._billboardCollection.add({
collection: labelCollection
});
billboard._labelDimensions = new Cartesian2_default();
billboard._labelTranslate = new Cartesian2_default();
}
glyph.billboard = billboard;
}
billboard.show = label._show;
billboard.position = label._position;
billboard.eyeOffset = label._eyeOffset;
billboard.pixelOffset = label._pixelOffset;
billboard.horizontalOrigin = HorizontalOrigin_default.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_default.FILL_AND_OUTLINE) {
billboard.color = label._fillColor;
billboard.outlineWidth = label.outlineWidth;
} else if (label.style === LabelStyle_default.FILL) {
billboard.color = label._fillColor;
billboard.outlineWidth = 0;
} else if (label.style === LabelStyle_default.OUTLINE) {
billboard.color = Color_default.TRANSPARENT;
billboard.outlineWidth = label.outlineWidth;
}
}
}
label._repositionAllGlyphs = true;
}
function calculateWidthOffset(lineWidth, horizontalOrigin, backgroundPadding) {
if (horizontalOrigin === HorizontalOrigin_default.CENTER) {
return -lineWidth / 2;
} else if (horizontalOrigin === HorizontalOrigin_default.RIGHT) {
return -(lineWidth + backgroundPadding.x);
}
return backgroundPadding.x;
}
var glyphPixelOffset = new Cartesian2_default();
var scratchBackgroundPadding = new Cartesian2_default();
function repositionAllGlyphs2(label) {
const glyphs = label._glyphs;
const text2 = 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_default.clone(
defined_default(backgroundBillboard) ? label._backgroundPadding : Cartesian2_default.ZERO,
scratchBackgroundPadding
);
backgroundPadding.x /= label._relativeSize;
backgroundPadding.y /= label._relativeSize;
for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
if (text2.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);
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_default(label._lineHeight) ? label._lineHeight : defaultLineSpacingPercent * label._fontSize) / label._relativeSize;
const otherLinesHeight = lineSpacing * (numberOfLines - 1);
let totalLineWidth = maxLineWidth;
let totalLineHeight = maxLineHeight + otherLinesHeight;
if (defined_default(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 (text2.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_default.TOP) {
glyphPixelOffset.y = dimensions.height - maxGlyphY - backgroundPadding.y;
glyphPixelOffset.y += SDFSettings_default.PADDING;
} else if (verticalOrigin === VerticalOrigin_default.CENTER) {
glyphPixelOffset.y = (otherLinesHeight + dimensions.height - maxGlyphY) / 2;
} else if (verticalOrigin === VerticalOrigin_default.BASELINE) {
glyphPixelOffset.y = otherLinesHeight;
glyphPixelOffset.y -= SDFSettings_default.PADDING;
} else {
glyphPixelOffset.y = otherLinesHeight + maxGlyphDescent + backgroundPadding.y;
glyphPixelOffset.y -= SDFSettings_default.PADDING;
}
glyphPixelOffset.y = (glyphPixelOffset.y - dimensions.descent - lineOffsetY) * scale;
if (firstCharOfLine) {
glyphPixelOffset.x -= SDFSettings_default.PADDING * scale;
firstCharOfLine = false;
}
if (defined_default(glyph.billboard)) {
glyph.billboard._setTranslate(glyphPixelOffset);
glyph.billboard._labelDimensions.x = totalLineWidth;
glyph.billboard._labelDimensions.y = totalLineHeight;
glyph.billboard._labelHorizontalOrigin = horizontalOrigin;
}
if (glyphIndex < glyphLength - 1) {
const nextGlyph = glyphs[glyphIndex + 1];
glyphPixelOffset.x += (dimensions.width - dimensions.minx + nextGlyph.dimensions.minx) * scale;
}
}
}
if (defined_default(backgroundBillboard) && text2.split("\n").join("").length > 0) {
if (horizontalOrigin === HorizontalOrigin_default.CENTER) {
widthOffset = -maxLineWidth / 2 - backgroundPadding.x;
} else if (horizontalOrigin === HorizontalOrigin_default.RIGHT) {
widthOffset = -(maxLineWidth + backgroundPadding.x * 2);
} else {
widthOffset = 0;
}
glyphPixelOffset.x = widthOffset * scale;
if (verticalOrigin === VerticalOrigin_default.TOP) {
glyphPixelOffset.y = maxLineHeight - maxGlyphY - maxGlyphDescent;
} else if (verticalOrigin === VerticalOrigin_default.CENTER) {
glyphPixelOffset.y = (maxLineHeight - maxGlyphY) / 2 - maxGlyphDescent;
} else if (verticalOrigin === VerticalOrigin_default.BASELINE) {
glyphPixelOffset.y = -backgroundPadding.y - maxGlyphDescent;
} else {
glyphPixelOffset.y = 0;
}
glyphPixelOffset.y = glyphPixelOffset.y * scale;
backgroundBillboard.width = totalLineWidth;
backgroundBillboard.height = totalLineHeight;
backgroundBillboard._setTranslate(glyphPixelOffset);
backgroundBillboard._labelTranslate = Cartesian2_default.clone(
glyphPixelOffset,
backgroundBillboard._labelTranslate
);
}
if (label.heightReference === HeightReference_default.CLAMP_TO_GROUND) {
for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
glyph = glyphs[glyphIndex];
const billboard = glyph.billboard;
if (defined_default(billboard)) {
billboard._labelTranslate = Cartesian2_default.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_default(label._backgroundBillboard)) {
labelCollection._backgroundBillboardCollection.remove(
label._backgroundBillboard
);
label._backgroundBillboard = void 0;
}
label._labelCollection = void 0;
if (defined_default(label._removeCallbackFunc)) {
label._removeCallbackFunc();
}
destroyObject_default(label);
}
function LabelCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._scene = options.scene;
this._batchTable = options.batchTable;
this._textureAtlas = void 0;
this._backgroundTextureAtlas = void 0;
this._backgroundBillboardCollection = new BillboardCollection_default({
scene: this._scene
});
this._backgroundBillboardCollection.destroyTextureAtlas = false;
this._billboardCollection = new BillboardCollection_default({
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_default.clone(Color_default.WHITE);
this.show = defaultValue_default(options.show, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.blendOption = defaultValue_default(
options.blendOption,
BlendOption_default.OPAQUE_AND_TRANSLUCENT
);
}
Object.defineProperties(LabelCollection.prototype, {
length: {
get: function() {
return this._labels.length;
}
}
});
LabelCollection.prototype.add = function(options) {
const label = new Label_default(options, this);
this._labels.push(label);
this._labelsToUpdate.push(label);
return label;
};
LabelCollection.prototype.remove = function(label) {
if (defined_default(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;
};
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;
};
LabelCollection.prototype.contains = function(label) {
return defined_default(label) && label._labelCollection === this;
};
LabelCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
return this._labels[index];
};
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_default(this._textureAtlas)) {
this._textureAtlas = new TextureAtlas_default({
context
});
billboardCollection.textureAtlas = this._textureAtlas;
}
if (!defined_default(this._backgroundTextureAtlas)) {
this._backgroundTextureAtlas = new TextureAtlas_default({
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) {
rebindAllGlyphs2(this, label);
label._rebindAllGlyphs = false;
}
if (label._repositionAllGlyphs) {
repositionAllGlyphs2(label);
label._repositionAllGlyphs = false;
}
const glyphCountDifference = label._glyphs.length - preUpdateGlyphCount;
this._totalGlyphCount += glyphCountDifference;
}
const blendOption = backgroundBillboardCollection.length > 0 ? BlendOption_default.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);
};
LabelCollection.prototype.isDestroyed = function() {
return false;
};
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_default(this);
};
var LabelCollection_default = LabelCollection;
// node_modules/@cesium/engine/Source/Shaders/PolylineVS.js
var PolylineVS_default = "in vec3 position3DHigh;\nin vec3 position3DLow;\nin vec3 position2DHigh;\nin vec3 position2DLow;\nin vec3 prevPosition3DHigh;\nin vec3 prevPosition3DLow;\nin vec3 prevPosition2DHigh;\nin vec3 prevPosition2DLow;\nin vec3 nextPosition3DHigh;\nin vec3 nextPosition3DLow;\nin vec3 nextPosition2DHigh;\nin vec3 nextPosition2DLow;\nin vec4 texCoordExpandAndBatchIndex;\n\nout vec2 v_st;\nout float v_width;\nout vec4 v_pickColor;\nout float v_polylineAngle;\n\nvoid 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\n vec2 widthAndShow = batchTable_getWidthAndShow(batchTableIndex);\n float width = widthAndShow.x + 0.5;\n float show = widthAndShow.y;\n\n if (width < 1.0)\n {\n show = 0.0;\n }\n\n vec4 pickColor = batchTable_getPickColor(batchTableIndex);\n\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\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\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\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\n float polylineAngle;\n vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, polylineAngle);\n gl_Position = czm_viewportOrthographic * positionWC * show;\n\n v_st.s = texCoord;\n v_st.t = czm_writeNonPerspective(clamp(expandDir, 0.0, 1.0), gl_Position.w);\n\n v_width = width;\n v_pickColor = pickColor;\n v_polylineAngle = polylineAngle;\n}\n";
// node_modules/@cesium/engine/Source/Core/PolylinePipeline.js
var PolylinePipeline = {};
PolylinePipeline.numberOfPoints = function(p0, p1, minDistance) {
const distance2 = Cartesian3_default.distance(p0, p1);
return Math.ceil(distance2 / 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)))
);
};
var cartoScratch2 = new Cartographic_default();
PolylinePipeline.extractHeights = function(positions, ellipsoid) {
const length3 = positions.length;
const heights = new Array(length3);
for (let i = 0; i < length3; i++) {
const p = positions[i];
heights[i] = ellipsoid.cartesianToCartographic(p, cartoScratch2).height;
}
return heights;
};
var wrapLongitudeInversMatrix = new Matrix4_default();
var wrapLongitudeOrigin = new Cartesian3_default();
var wrapLongitudeXZNormal = new Cartesian3_default();
var wrapLongitudeXZPlane = new Plane_default(Cartesian3_default.UNIT_X, 0);
var wrapLongitudeYZNormal = new Cartesian3_default();
var wrapLongitudeYZPlane = new Plane_default(Cartesian3_default.UNIT_X, 0);
var wrapLongitudeIntersection = new Cartesian3_default();
var wrapLongitudeOffset = new Cartesian3_default();
var subdivideHeightsScratchArray = [];
function subdivideHeights(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;
}
var carto1 = new Cartographic_default();
var carto2 = new Cartographic_default();
var cartesian = new Cartesian3_default();
var scaleFirst = new Cartesian3_default();
var scaleLast = new Cartesian3_default();
var ellipsoidGeodesic = new EllipsoidGeodesic_default();
var ellipsoidRhumb = new EllipsoidRhumbLine_default();
function generateCartesianArc(p0, p1, minDistance, ellipsoid, h0, h1, array, offset2) {
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(numPoints, h0, h1);
ellipsoidGeodesic.setEndPoints(start, end);
const surfaceDistanceBetweenPoints = ellipsoidGeodesic.surfaceDistance / numPoints;
let index = offset2;
start.height = h0;
let cart = ellipsoid.cartographicToCartesian(start, cartesian);
Cartesian3_default.pack(cart, array, index);
index += 3;
for (let i = 1; i < numPoints; i++) {
const carto = ellipsoidGeodesic.interpolateUsingSurfaceDistance(
i * surfaceDistanceBetweenPoints,
carto2
);
carto.height = heights[i];
cart = ellipsoid.cartographicToCartesian(carto, cartesian);
Cartesian3_default.pack(cart, array, index);
index += 3;
}
return index;
}
function generateCartesianRhumbArc(p0, p1, granularity, ellipsoid, h0, h1, array, offset2) {
const start = ellipsoid.cartesianToCartographic(p0, carto1);
const end = ellipsoid.cartesianToCartographic(p1, carto2);
const numPoints = PolylinePipeline.numberOfPointsRhumbLine(
start,
end,
granularity
);
start.height = 0;
end.height = 0;
const heights = subdivideHeights(numPoints, h0, h1);
if (!ellipsoidRhumb.ellipsoid.equals(ellipsoid)) {
ellipsoidRhumb = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
}
ellipsoidRhumb.setEndPoints(start, end);
const surfaceDistanceBetweenPoints = ellipsoidRhumb.surfaceDistance / numPoints;
let index = offset2;
start.height = h0;
let cart = ellipsoid.cartographicToCartesian(start, cartesian);
Cartesian3_default.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_default.pack(cart, array, index);
index += 3;
}
return index;
}
PolylinePipeline.wrapLongitude = function(positions, modelMatrix) {
const cartesians = [];
const segments = [];
if (defined_default(positions) && positions.length > 0) {
modelMatrix = defaultValue_default(modelMatrix, Matrix4_default.IDENTITY);
const inverseModelMatrix = Matrix4_default.inverseTransformation(
modelMatrix,
wrapLongitudeInversMatrix
);
const origin = Matrix4_default.multiplyByPoint(
inverseModelMatrix,
Cartesian3_default.ZERO,
wrapLongitudeOrigin
);
const xzNormal = Cartesian3_default.normalize(
Matrix4_default.multiplyByPointAsVector(
inverseModelMatrix,
Cartesian3_default.UNIT_Y,
wrapLongitudeXZNormal
),
wrapLongitudeXZNormal
);
const xzPlane2 = Plane_default.fromPointNormal(
origin,
xzNormal,
wrapLongitudeXZPlane
);
const yzNormal = Cartesian3_default.normalize(
Matrix4_default.multiplyByPointAsVector(
inverseModelMatrix,
Cartesian3_default.UNIT_X,
wrapLongitudeYZNormal
),
wrapLongitudeYZNormal
);
const yzPlane = Plane_default.fromPointNormal(
origin,
yzNormal,
wrapLongitudeYZPlane
);
let count = 1;
cartesians.push(Cartesian3_default.clone(positions[0]));
let prev = cartesians[0];
const length3 = positions.length;
for (let i = 1; i < length3; ++i) {
const cur = positions[i];
if (Plane_default.getPointDistance(yzPlane, prev) < 0 || Plane_default.getPointDistance(yzPlane, cur) < 0) {
const intersection = IntersectionTests_default.lineSegmentPlane(
prev,
cur,
xzPlane2,
wrapLongitudeIntersection
);
if (defined_default(intersection)) {
const offset2 = Cartesian3_default.multiplyByScalar(
xzNormal,
5e-9,
wrapLongitudeOffset
);
if (Plane_default.getPointDistance(xzPlane2, prev) < 0) {
Cartesian3_default.negate(offset2, offset2);
}
cartesians.push(
Cartesian3_default.add(intersection, offset2, new Cartesian3_default())
);
segments.push(count + 1);
Cartesian3_default.negate(offset2, offset2);
cartesians.push(
Cartesian3_default.add(intersection, offset2, new Cartesian3_default())
);
count = 1;
}
}
cartesians.push(Cartesian3_default.clone(positions[i]));
count++;
prev = cur;
}
segments.push(count);
}
return {
positions: cartesians,
lengths: segments
};
};
PolylinePipeline.generateArc = function(options) {
if (!defined_default(options)) {
options = {};
}
const positions = options.positions;
if (!defined_default(positions)) {
throw new DeveloperError_default("options.positions is required.");
}
const length3 = positions.length;
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
let height = defaultValue_default(options.height, 0);
const hasHeightArray = Array.isArray(height);
if (length3 < 1) {
return [];
} else if (length3 === 1) {
const p = ellipsoid.scaleToGeodeticSurface(positions[0], scaleFirst);
height = hasHeightArray ? height[0] : height;
if (height !== 0) {
const n = ellipsoid.geodeticSurfaceNormal(p, cartesian);
Cartesian3_default.multiplyByScalar(n, height, n);
Cartesian3_default.add(p, n, p);
}
return [p.x, p.y, p.z];
}
let minDistance = options.minDistance;
if (!defined_default(minDistance)) {
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
minDistance = Math_default.chordLength(granularity, ellipsoid.maximumRadius);
}
let numPoints = 0;
let i;
for (i = 0; i < length3 - 1; i++) {
numPoints += PolylinePipeline.numberOfPoints(
positions[i],
positions[i + 1],
minDistance
);
}
const arrayLength = (numPoints + 1) * 3;
const newPositions = new Array(arrayLength);
let offset2 = 0;
for (i = 0; i < length3 - 1; i++) {
const p0 = positions[i];
const p1 = positions[i + 1];
const h0 = hasHeightArray ? height[i] : height;
const h1 = hasHeightArray ? height[i + 1] : height;
offset2 = generateCartesianArc(
p0,
p1,
minDistance,
ellipsoid,
h0,
h1,
newPositions,
offset2
);
}
subdivideHeightsScratchArray.length = 0;
const lastPoint = positions[length3 - 1];
const carto = ellipsoid.cartesianToCartographic(lastPoint, carto1);
carto.height = hasHeightArray ? height[length3 - 1] : height;
const cart = ellipsoid.cartographicToCartesian(carto, cartesian);
Cartesian3_default.pack(cart, newPositions, arrayLength - 3);
return newPositions;
};
var scratchCartographic0 = new Cartographic_default();
var scratchCartographic1 = new Cartographic_default();
PolylinePipeline.generateRhumbArc = function(options) {
if (!defined_default(options)) {
options = {};
}
const positions = options.positions;
if (!defined_default(positions)) {
throw new DeveloperError_default("options.positions is required.");
}
const length3 = positions.length;
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
let height = defaultValue_default(options.height, 0);
const hasHeightArray = Array.isArray(height);
if (length3 < 1) {
return [];
} else if (length3 === 1) {
const p = ellipsoid.scaleToGeodeticSurface(positions[0], scaleFirst);
height = hasHeightArray ? height[0] : height;
if (height !== 0) {
const n = ellipsoid.geodeticSurfaceNormal(p, cartesian);
Cartesian3_default.multiplyByScalar(n, height, n);
Cartesian3_default.add(p, n, p);
}
return [p.x, p.y, p.z];
}
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
let numPoints = 0;
let i;
let c0 = ellipsoid.cartesianToCartographic(
positions[0],
scratchCartographic0
);
let c14;
for (i = 0; i < length3 - 1; i++) {
c14 = ellipsoid.cartesianToCartographic(
positions[i + 1],
scratchCartographic1
);
numPoints += PolylinePipeline.numberOfPointsRhumbLine(c0, c14, granularity);
c0 = Cartographic_default.clone(c14, scratchCartographic0);
}
const arrayLength = (numPoints + 1) * 3;
const newPositions = new Array(arrayLength);
let offset2 = 0;
for (i = 0; i < length3 - 1; i++) {
const p0 = positions[i];
const p1 = positions[i + 1];
const h0 = hasHeightArray ? height[i] : height;
const h1 = hasHeightArray ? height[i + 1] : height;
offset2 = generateCartesianRhumbArc(
p0,
p1,
granularity,
ellipsoid,
h0,
h1,
newPositions,
offset2
);
}
subdivideHeightsScratchArray.length = 0;
const lastPoint = positions[length3 - 1];
const carto = ellipsoid.cartesianToCartographic(lastPoint, carto1);
carto.height = hasHeightArray ? height[length3 - 1] : height;
const cart = ellipsoid.cartographicToCartesian(carto, cartesian);
Cartesian3_default.pack(cart, newPositions, arrayLength - 3);
return newPositions;
};
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_default.unpack(numberArray, i * 3);
}
return newPositions;
};
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_default.unpack(numberArray, i * 3);
}
return newPositions;
};
var PolylinePipeline_default = PolylinePipeline;
// node_modules/@cesium/engine/Source/Scene/Polyline.js
function Polyline(options, polylineCollection) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._show = defaultValue_default(options.show, true);
this._width = defaultValue_default(options.width, 1);
this._loop = defaultValue_default(options.loop, false);
this._distanceDisplayCondition = options.distanceDisplayCondition;
this._material = options.material;
if (!defined_default(this._material)) {
this._material = Material_default.fromType(Material_default.ColorType, {
color: new Color_default(1, 1, 1, 1)
});
}
let positions = options.positions;
if (!defined_default(positions)) {
positions = [];
}
this._positions = positions;
this._actualPositions = arrayRemoveDuplicates_default(
positions,
Cartesian3_default.equalsEpsilon
);
if (this._loop && this._actualPositions.length > 2) {
if (this._actualPositions === this._positions) {
this._actualPositions = positions.slice();
}
this._actualPositions.push(Cartesian3_default.clone(this._actualPositions[0]));
}
this._length = this._actualPositions.length;
this._id = options.id;
let modelMatrix;
if (defined_default(polylineCollection)) {
modelMatrix = Matrix4_default.clone(polylineCollection.modelMatrix);
}
this._modelMatrix = modelMatrix;
this._segments = PolylinePipeline_default.wrapLongitude(
this._actualPositions,
modelMatrix
);
this._actualLength = void 0;
this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES2);
this._polylineCollection = polylineCollection;
this._dirty = false;
this._pickId = void 0;
this._boundingVolume = BoundingSphere_default.fromPoints(this._actualPositions);
this._boundingVolumeWC = BoundingSphere_default.transform(
this._boundingVolume,
this._modelMatrix
);
this._boundingVolume2D = new BoundingSphere_default();
}
var POSITION_INDEX3 = Polyline.POSITION_INDEX = 0;
var SHOW_INDEX3 = Polyline.SHOW_INDEX = 1;
var WIDTH_INDEX = Polyline.WIDTH_INDEX = 2;
var MATERIAL_INDEX = Polyline.MATERIAL_INDEX = 3;
var POSITION_SIZE_INDEX = Polyline.POSITION_SIZE_INDEX = 4;
var DISTANCE_DISPLAY_CONDITION2 = Polyline.DISTANCE_DISPLAY_CONDITION = 5;
var NUMBER_OF_PROPERTIES2 = Polyline.NUMBER_OF_PROPERTIES = 6;
function makeDirty2(polyline, propertyChanged) {
++polyline._propertiesChanged[propertyChanged];
const polylineCollection = polyline._polylineCollection;
if (defined_default(polylineCollection)) {
polylineCollection._updatePolyline(polyline, propertyChanged);
polyline._dirty = true;
}
}
Object.defineProperties(Polyline.prototype, {
show: {
get: function() {
return this._show;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (value !== this._show) {
this._show = value;
makeDirty2(this, SHOW_INDEX3);
}
}
},
positions: {
get: function() {
return this._positions;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
let positions = arrayRemoveDuplicates_default(value, Cartesian3_default.equalsEpsilon);
if (this._loop && positions.length > 2) {
if (positions === value) {
positions = value.slice();
}
positions.push(Cartesian3_default.clone(positions[0]));
}
if (this._actualPositions.length !== positions.length || this._actualPositions.length !== this._length) {
makeDirty2(this, POSITION_SIZE_INDEX);
}
this._positions = value;
this._actualPositions = positions;
this._length = positions.length;
this._boundingVolume = BoundingSphere_default.fromPoints(
this._actualPositions,
this._boundingVolume
);
this._boundingVolumeWC = BoundingSphere_default.transform(
this._boundingVolume,
this._modelMatrix,
this._boundingVolumeWC
);
makeDirty2(this, POSITION_INDEX3);
this.update();
}
},
material: {
get: function() {
return this._material;
},
set: function(material) {
if (!defined_default(material)) {
throw new DeveloperError_default("material is required.");
}
if (this._material !== material) {
this._material = material;
makeDirty2(this, MATERIAL_INDEX);
}
}
},
width: {
get: function() {
return this._width;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const width = this._width;
if (value !== width) {
this._width = value;
makeDirty2(this, WIDTH_INDEX);
}
}
},
loop: {
get: function() {
return this._loop;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (value !== this._loop) {
let positions = this._actualPositions;
if (value) {
if (positions.length > 2 && !Cartesian3_default.equals(positions[0], positions[positions.length - 1])) {
if (positions.length === this._positions.length) {
this._actualPositions = positions = this._positions.slice();
}
positions.push(Cartesian3_default.clone(positions[0]));
}
} else if (positions.length > 2 && Cartesian3_default.equals(positions[0], positions[positions.length - 1])) {
if (positions.length - 1 === this._positions.length) {
this._actualPositions = this._positions;
} else {
positions.pop();
}
}
this._loop = value;
makeDirty2(this, POSITION_SIZE_INDEX);
}
}
},
id: {
get: function() {
return this._id;
},
set: function(value) {
this._id = value;
if (defined_default(this._pickId)) {
this._pickId.object.id = value;
}
}
},
pickId: {
get: function() {
return this._pickId;
}
},
isDestroyed: {
get: function() {
return !defined_default(this._polylineCollection);
}
},
distanceDisplayCondition: {
get: function() {
return this._distanceDisplayCondition;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
if (!DistanceDisplayCondition_default.equals(value, this._distanceDisplayCondition)) {
this._distanceDisplayCondition = DistanceDisplayCondition_default.clone(
value,
this._distanceDisplayCondition
);
makeDirty2(this, DISTANCE_DISPLAY_CONDITION2);
}
}
}
});
Polyline.prototype.update = function() {
let modelMatrix = Matrix4_default.IDENTITY;
if (defined_default(this._polylineCollection)) {
modelMatrix = this._polylineCollection.modelMatrix;
}
const segmentPositionsLength = this._segments.positions.length;
const segmentLengths = this._segments.lengths;
const positionsChanged = this._propertiesChanged[POSITION_INDEX3] > 0 || this._propertiesChanged[POSITION_SIZE_INDEX] > 0;
if (!Matrix4_default.equals(modelMatrix, this._modelMatrix) || positionsChanged) {
this._segments = PolylinePipeline_default.wrapLongitude(
this._actualPositions,
modelMatrix
);
this._boundingVolumeWC = BoundingSphere_default.transform(
this._boundingVolume,
modelMatrix,
this._boundingVolumeWC
);
}
this._modelMatrix = Matrix4_default.clone(modelMatrix, this._modelMatrix);
if (this._segments.positions.length !== segmentPositionsLength) {
makeDirty2(this, POSITION_SIZE_INDEX);
} else {
const length3 = segmentLengths.length;
for (let i = 0; i < length3; ++i) {
if (segmentLengths[i] !== this._segments.lengths[i]) {
makeDirty2(this, POSITION_SIZE_INDEX);
break;
}
}
}
};
Polyline.prototype.getPickId = function(context) {
if (!defined_default(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_PROPERTIES2 - 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 = void 0;
};
var Polyline_default = Polyline;
// node_modules/@cesium/engine/Source/Scene/PolylineCollection.js
var SHOW_INDEX4 = Polyline_default.SHOW_INDEX;
var WIDTH_INDEX2 = Polyline_default.WIDTH_INDEX;
var POSITION_INDEX4 = Polyline_default.POSITION_INDEX;
var MATERIAL_INDEX2 = Polyline_default.MATERIAL_INDEX;
var POSITION_SIZE_INDEX2 = Polyline_default.POSITION_SIZE_INDEX;
var DISTANCE_DISPLAY_CONDITION3 = Polyline_default.DISTANCE_DISPLAY_CONDITION;
var NUMBER_OF_PROPERTIES3 = Polyline_default.NUMBER_OF_PROPERTIES;
var attributeLocations2 = {
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
};
function PolylineCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this.show = defaultValue_default(options.show, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this._opaqueRS = void 0;
this._translucentRS = void 0;
this._colorCommands = [];
this._polylinesUpdated = false;
this._polylinesRemoved = false;
this._createVertexArray = false;
this._propertiesChanged = new Uint32Array(NUMBER_OF_PROPERTIES3);
this._polylines = [];
this._polylineBuckets = {};
this._positionBufferUsage = {
bufferUsage: BufferUsage_default.STATIC_DRAW,
frameCount: 0
};
this._mode = void 0;
this._polylinesToUpdate = [];
this._vertexArrays = [];
this._positionBuffer = void 0;
this._texCoordExpandAndBatchIndexBuffer = void 0;
this._batchTable = void 0;
this._createBatchTable = false;
this._useHighlightColor = false;
this._highlightColor = Color_default.clone(Color_default.WHITE);
const that = this;
this._uniformMap = {
u_highlightColor: function() {
return that._highlightColor;
}
};
}
Object.defineProperties(PolylineCollection.prototype, {
length: {
get: function() {
removePolylines(this);
return this._polylines.length;
}
}
});
PolylineCollection.prototype.add = function(options) {
const p = new Polyline_default(options, this);
p._index = this._polylines.length;
this._polylines.push(p);
this._createVertexArray = true;
this._createBatchTable = true;
return p;
};
PolylineCollection.prototype.remove = function(polyline) {
if (this.contains(polyline)) {
this._polylinesRemoved = true;
this._createVertexArray = true;
this._createBatchTable = true;
if (defined_default(polyline._bucket)) {
const bucket = polyline._bucket;
bucket.shaderProgram = bucket.shaderProgram && bucket.shaderProgram.destroy();
}
polyline._destroy();
return true;
}
return false;
};
PolylineCollection.prototype.removeAll = function() {
releaseShaders(this);
destroyPolylines(this);
this._polylineBuckets = {};
this._polylinesRemoved = false;
this._polylines.length = 0;
this._polylinesToUpdate.length = 0;
this._createVertexArray = true;
};
PolylineCollection.prototype.contains = function(polyline) {
return defined_default(polyline) && polyline._polylineCollection === this;
};
PolylineCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
removePolylines(this);
return this._polylines[index];
};
function createBatchTable2(collection, context) {
if (defined_default(collection._batchTable)) {
collection._batchTable.destroy();
}
const attributes = [
{
functionName: "batchTable_getWidthAndShow",
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 2
},
{
functionName: "batchTable_getPickColor",
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 4,
normalize: true
},
{
functionName: "batchTable_getCenterHigh",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
functionName: "batchTable_getCenterLowAndRadius",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4
},
{
functionName: "batchTable_getDistanceDisplayCondition",
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2
}
];
collection._batchTable = new BatchTable_default(
context,
attributes,
collection._polylines.length
);
}
var scratchUpdatePolylineEncodedCartesian = new EncodedCartesian3_default();
var scratchUpdatePolylineCartesian4 = new Cartesian4_default();
var scratchNearFarCartesian2 = new Cartesian2_default();
PolylineCollection.prototype.update = function(frameState) {
removePolylines(this);
if (this._polylines.length === 0 || !this.show) {
return;
}
updateMode2(this, frameState);
const context = frameState.context;
const projection = frameState.mapProjection;
let polyline;
let properties = this._propertiesChanged;
if (this._createBatchTable) {
if (ContextLimits_default.maximumVertexTextureImageUnits === 0) {
throw new RuntimeError_default(
"Vertex texture fetch support is required to render polylines. The maximum number of vertex texture image units must be greater than zero."
);
}
createBatchTable2(this, context);
this._createBatchTable = false;
}
if (this._createVertexArray || computeNewBuffersUsage(this)) {
createVertexArrays(this, context, projection);
} else if (this._polylinesUpdated) {
const polylinesToUpdate = this._polylinesToUpdate;
if (this._mode !== SceneMode_default.SCENE3D) {
const updateLength = polylinesToUpdate.length;
for (let i = 0; i < updateLength; ++i) {
polyline = polylinesToUpdate[i];
polyline.update();
}
}
if (properties[POSITION_SIZE_INDEX2] || properties[MATERIAL_INDEX2]) {
createVertexArrays(this, context, projection);
} else {
const length3 = polylinesToUpdate.length;
const polylineBuckets = this._polylineBuckets;
for (let ii = 0; ii < length3; ++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_INDEX4]) {
bucket.writeUpdate(
index,
polyline,
this._positionBuffer,
projection
);
}
break;
}
index += polylineBuckets[x].lengthOfPositions;
}
}
if (properties[SHOW_INDEX4] || properties[WIDTH_INDEX2]) {
this._batchTable.setBatchedAttribute(
polyline._index,
0,
new Cartesian2_default(polyline._width, polyline._show)
);
}
if (this._batchTable.attributes.length > 2) {
if (properties[POSITION_INDEX4] || properties[POSITION_SIZE_INDEX2]) {
const boundingSphere = frameState.mode === SceneMode_default.SCENE2D ? polyline._boundingVolume2D : polyline._boundingVolumeWC;
const encodedCenter = EncodedCartesian3_default.fromCartesian(
boundingSphere.center,
scratchUpdatePolylineEncodedCartesian
);
const low = Cartesian4_default.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_CONDITION3]) {
const nearFarCartesian = scratchNearFarCartesian2;
nearFarCartesian.x = 0;
nearFarCartesian.y = Number.MAX_VALUE;
const distanceDisplayCondition = polyline.distanceDisplayCondition;
if (defined_default(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_PROPERTIES3; ++k) {
properties[k] = 0;
}
let modelMatrix = Matrix4_default.IDENTITY;
if (frameState.mode === SceneMode_default.SCENE3D) {
modelMatrix = this.modelMatrix;
}
const pass = frameState.passes;
const useDepthTest = frameState.morphTime !== 0;
if (!defined_default(this._opaqueRS) || this._opaqueRS.depthTest.enabled !== useDepthTest) {
this._opaqueRS = RenderState_default.fromCache({
depthMask: useDepthTest,
depthTest: {
enabled: useDepthTest
}
});
}
if (!defined_default(this._translucentRS) || this._translucentRS.depthTest.enabled !== useDepthTest) {
this._translucentRS = RenderState_default.fromCache({
blending: BlendingState_default.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);
}
};
var boundingSphereScratch = new BoundingSphere_default();
var boundingSphereScratch2 = new BoundingSphere_default();
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 debugShowBoundingVolume2 = polylineCollection.debugShowBoundingVolume;
const batchTable = polylineCollection._batchTable;
const uniformCallback = batchTable.getUniformMapCallback();
const length3 = vertexArrays.length;
for (let m = 0; m < length3; ++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 offset2 = bucketLocator.offset;
const sp = bucketLocator.bucket.shaderProgram;
const polylines = bucketLocator.bucket.polylines;
const polylineLength = polylines.length;
let currentId2;
let currentMaterial;
let count = 0;
let command;
let uniformMap2;
for (let s = 0; s < polylineLength; ++s) {
const polyline = polylines[s];
const mId = createMaterialId(polyline._material);
if (mId !== currentId2) {
if (defined_default(currentId2) && count > 0) {
const translucent = currentMaterial.isTranslucent();
if (commandIndex >= commandsLength) {
command = new DrawCommand_default({
owner: polylineCollection
});
commands.push(command);
} else {
command = commands[commandIndex];
}
++commandIndex;
uniformMap2 = combine_default(
uniformCallback(currentMaterial._uniforms),
polylineCollection._uniformMap
);
command.boundingVolume = BoundingSphere_default.clone(
boundingSphereScratch,
command.boundingVolume
);
command.modelMatrix = modelMatrix;
command.shaderProgram = sp;
command.vertexArray = va.va;
command.renderState = translucent ? polylineCollection._translucentRS : polylineCollection._opaqueRS;
command.pass = translucent ? Pass_default.TRANSLUCENT : Pass_default.OPAQUE;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
command.pickId = "v_pickColor";
command.uniformMap = uniformMap2;
command.count = count;
command.offset = offset2;
offset2 += count;
count = 0;
cloneBoundingSphere = true;
commandList.push(command);
}
currentMaterial = polyline._material;
currentMaterial.update(context);
currentId2 = 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_default.SCENE3D) {
boundingVolume = polyline._boundingVolumeWC;
} else if (frameState.mode === SceneMode_default.COLUMBUS_VIEW) {
boundingVolume = polyline._boundingVolume2D;
} else if (frameState.mode === SceneMode_default.SCENE2D) {
if (defined_default(polyline._boundingVolume2D)) {
boundingVolume = BoundingSphere_default.clone(
polyline._boundingVolume2D,
boundingSphereScratch2
);
boundingVolume.center.x = 0;
}
} else if (defined_default(polyline._boundingVolumeWC) && defined_default(polyline._boundingVolume2D)) {
boundingVolume = BoundingSphere_default.union(
polyline._boundingVolumeWC,
polyline._boundingVolume2D,
boundingSphereScratch2
);
}
if (cloneBoundingSphere) {
cloneBoundingSphere = false;
BoundingSphere_default.clone(boundingVolume, boundingSphereScratch);
} else {
BoundingSphere_default.union(
boundingVolume,
boundingSphereScratch,
boundingSphereScratch
);
}
}
if (defined_default(currentId2) && count > 0) {
if (commandIndex >= commandsLength) {
command = new DrawCommand_default({
owner: polylineCollection
});
commands.push(command);
} else {
command = commands[commandIndex];
}
++commandIndex;
uniformMap2 = combine_default(
uniformCallback(currentMaterial._uniforms),
polylineCollection._uniformMap
);
command.boundingVolume = BoundingSphere_default.clone(
boundingSphereScratch,
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_default.TRANSLUCENT : Pass_default.OPAQUE;
command.debugShowBoundingVolume = debugShowBoundingVolume2;
command.pickId = "v_pickColor";
command.uniformMap = uniformMap2;
command.count = count;
command.offset = offset2;
cloneBoundingSphere = true;
commandList.push(command);
}
currentId2 = void 0;
}
}
commands.length = commandIndex;
}
PolylineCollection.prototype.isDestroyed = function() {
return false;
};
PolylineCollection.prototype.destroy = function() {
destroyVertexArrays(this);
releaseShaders(this);
destroyPolylines(this);
this._batchTable = this._batchTable && this._batchTable.destroy();
return destroyObject_default(this);
};
function computeNewBuffersUsage(collection) {
let usageChanged = false;
const properties = collection._propertiesChanged;
const bufferUsage = collection._positionBufferUsage;
if (properties[POSITION_INDEX4]) {
if (bufferUsage.bufferUsage !== BufferUsage_default.STREAM_DRAW) {
usageChanged = true;
bufferUsage.bufferUsage = BufferUsage_default.STREAM_DRAW;
bufferUsage.frameCount = 100;
} else {
bufferUsage.frameCount = 100;
}
} else if (bufferUsage.bufferUsage !== BufferUsage_default.STATIC_DRAW) {
if (bufferUsage.frameCount === 0) {
usageChanged = true;
bufferUsage.bufferUsage = BufferUsage_default.STATIC_DRAW;
} else {
bufferUsage.frameCount--;
}
}
return usageChanged;
}
var emptyVertexBuffer = [0, 0, 0];
function createVertexArrays(collection, context, projection) {
collection._createVertexArray = false;
releaseShaders(collection);
destroyVertexArrays(collection);
sortPolylinesIntoBuckets(collection);
const totalIndices = [[]];
let indices2 = totalIndices[0];
const batchTable = collection._batchTable;
const useHighlightColor = collection._useHighlightColor;
const vertexBufferOffset = [0];
let offset2 = 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 mode2 = 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 (mode2 === SceneMode_default.MORPHING) {
if (!defined_default(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;
offset2 = bucket.updateIndices(
totalIndices,
vertexBufferOffset,
vertexArrayBuckets,
offset2
);
}
}
const positionBufferUsage = collection._positionBufferUsage.bufferUsage;
const texCoordExpandAndBatchIndexBufferUsage = BufferUsage_default.STATIC_DRAW;
collection._positionBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: positionArray,
usage: positionBufferUsage
});
let position3DBuffer;
if (defined_default(position3DArray)) {
position3DBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: position3DArray,
usage: positionBufferUsage
});
}
collection._texCoordExpandAndBatchIndexBuffer = Buffer_default.createVertexBuffer({
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) {
indices2 = totalIndices[k];
if (indices2.length > 0) {
const indicesArray = new Uint16Array(indices2);
const indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: indicesArray,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.UNSIGNED_SHORT
});
vbo += vertexBufferOffset[k];
const positionHighOffset = 6 * (k * (positionSizeInBytes * Math_default.SIXTY_FOUR_KILOBYTES) - vbo * positionSizeInBytes);
const positionLowOffset = positionSizeInBytes + positionHighOffset;
const prevPositionHighOffset = positionSizeInBytes + positionLowOffset;
const prevPositionLowOffset = positionSizeInBytes + prevPositionHighOffset;
const nextPositionHighOffset = positionSizeInBytes + prevPositionLowOffset;
const nextPositionLowOffset = positionSizeInBytes + nextPositionHighOffset;
const vertexTexCoordExpandAndBatchIndexBufferOffset = k * (texCoordExpandAndBatchIndexSizeInBytes * Math_default.SIXTY_FOUR_KILOBYTES) - vbo * texCoordExpandAndBatchIndexSizeInBytes;
const attributes = [
{
index: attributeLocations2.position3DHigh,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: positionHighOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.position3DLow,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: positionLowOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.position2DHigh,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: positionHighOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.position2DLow,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: positionLowOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.prevPosition3DHigh,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: prevPositionHighOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.prevPosition3DLow,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: prevPositionLowOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.prevPosition2DHigh,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: prevPositionHighOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.prevPosition2DLow,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: prevPositionLowOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.nextPosition3DHigh,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: nextPositionHighOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.nextPosition3DLow,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: nextPositionLowOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.nextPosition2DHigh,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: nextPositionHighOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.nextPosition2DLow,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
offsetInBytes: nextPositionLowOffset,
strideInBytes: 6 * positionSizeInBytes
},
{
index: attributeLocations2.texCoordExpandAndBatchIndex,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
vertexBuffer: collection._texCoordExpandAndBatchIndexBuffer,
offsetInBytes: vertexTexCoordExpandAndBatchIndexBufferOffset
}
];
let bufferProperty3D;
let buffer3D;
let buffer2D;
let bufferProperty2D;
if (mode2 === SceneMode_default.SCENE3D) {
buffer3D = collection._positionBuffer;
bufferProperty3D = "vertexBuffer";
buffer2D = emptyVertexBuffer;
bufferProperty2D = "value";
} else if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.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_default({
context,
attributes,
indexBuffer
});
collection._vertexArrays.push({
va,
buckets: vertexArrayBuckets[k]
});
}
}
}
}
function replacer(key, value) {
if (value instanceof Texture_default) {
return value.id;
}
return value;
}
var scratchUniformArray2 = [];
function createMaterialId(material) {
const uniforms = Material_default._uniformList[material.type];
const length3 = uniforms.length;
scratchUniformArray2.length = 2 * length3;
let index = 0;
for (let i = 0; i < length3; ++i) {
const uniform = uniforms[i];
scratchUniformArray2[index] = uniform;
scratchUniformArray2[index + 1] = material._uniforms[uniform]();
index += 2;
}
return `${material.type}:${JSON.stringify(scratchUniformArray2, replacer)}`;
}
function sortPolylinesIntoBuckets(collection) {
const mode2 = collection._mode;
const modelMatrix = collection._modelMatrix;
const polylineBuckets = collection._polylineBuckets = {};
const polylines = collection._polylines;
const length3 = polylines.length;
for (let i = 0; i < length3; ++i) {
const p = polylines[i];
if (p._actualPositions.length > 1) {
p.update();
const material = p.material;
let value = polylineBuckets[material.type];
if (!defined_default(value)) {
value = polylineBuckets[material.type] = new PolylineBucket(
material,
mode2,
modelMatrix
);
}
value.addPolyline(p);
}
}
}
function updateMode2(collection, frameState) {
const mode2 = frameState.mode;
if (collection._mode !== mode2 || !Matrix4_default.equals(collection._modelMatrix, collection.modelMatrix)) {
collection._mode = mode2;
collection._modelMatrix = Matrix4_default.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 length3 = collection._polylines.length;
for (let i = 0; i < length3; ++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 length3 = polylines.length;
for (let i = 0; i < length3; ++i) {
if (!polylines[i].isDestroyed) {
const bucket = polylines[i]._bucket;
if (defined_default(bucket)) {
bucket.shaderProgram = bucket.shaderProgram && bucket.shaderProgram.destroy();
}
}
}
}
function destroyVertexArrays(collection) {
const length3 = collection._vertexArrays.length;
for (let t = 0; t < length3; ++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 length3 = polylines.length;
for (let i = 0; i < length3; ++i) {
if (!polylines[i].isDestroyed) {
polylines[i]._destroy();
}
}
}
function VertexArrayBucketLocator(count, offset2, bucket) {
this.count = count;
this.offset = offset2;
this.bucket = bucket;
}
function PolylineBucket(material, mode2, modelMatrix) {
this.polylines = [];
this.lengthOfPositions = 0;
this.material = material;
this.shaderProgram = void 0;
this.mode = mode2;
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_default(this.shaderProgram)) {
return;
}
const defines = ["DISTANCE_DISPLAY_CONDITION"];
if (useHighlightColor) {
defines.push("VECTOR_TILE");
}
if (this.material.shaderSource.search(/in\s+float\s+v_polylineAngle;/g) !== -1) {
defines.push("POLYLINE_DASH");
}
if (!FeatureDetection_default.isInternetExplorer()) {
defines.push("CLIP_POLYLINE");
}
const fs = new ShaderSource_default({
defines,
sources: ["in vec4 v_pickColor;\n", this.material.shaderSource, PolylineFS_default]
});
const vsSource = batchTable.getVertexShaderCallback()(PolylineVS_default);
const vs = new ShaderSource_default({
defines,
sources: [PolylineCommon_default, vsSource]
});
this.shaderProgram = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations2
});
};
function intersectsIDL(polyline) {
return Cartesian3_default.dot(Cartesian3_default.UNIT_X, polyline._boundingVolume.center) < 0 || polyline._boundingVolume.intersectPlane(Plane_default.ORIGIN_ZX_PLANE) === Intersect_default.INTERSECTING;
}
PolylineBucket.prototype.getPolylinePositionsLength = function(polyline) {
let length3;
if (this.mode === SceneMode_default.SCENE3D || !intersectsIDL(polyline)) {
length3 = polyline._actualPositions.length;
return length3 * 4 - 4;
}
let count = 0;
const segmentLengths = polyline._segments.lengths;
length3 = segmentLengths.length;
for (let i = 0; i < length3; ++i) {
count += segmentLengths[i] * 4 - 4;
}
return count;
};
var scratchWritePosition = new Cartesian3_default();
var scratchWritePrevPosition = new Cartesian3_default();
var scratchWriteNextPosition = new Cartesian3_default();
var scratchWriteVector = new Cartesian3_default();
var scratchPickColorCartesian = new Cartesian4_default();
var scratchWidthShowCartesian = new Cartesian2_default();
PolylineBucket.prototype.write = function(positionArray, texCoordExpandAndBatchIndexArray, positionIndex, colorIndex, texCoordExpandAndBatchIndexIndex, batchTable, context, projection) {
const mode2 = this.mode;
const maxLon = projection.ellipsoid.maximumRadius * Math_default.PI;
const polylines = this.polylines;
const length3 = polylines.length;
for (let i = 0; i < length3; ++i) {
const polyline = polylines[i];
const width = polyline.width;
const show = polyline.show && width > 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_default.subtract(positions[0], positions[1], position);
Cartesian3_default.add(positions[0], position, position);
}
} else {
position = positions[j - 1];
}
Cartesian3_default.clone(position, scratchWritePrevPosition);
Cartesian3_default.clone(positions[j], scratchWritePosition);
if (j === positionsLength - 1) {
if (polyline._loop) {
position = positions[1];
} else {
position = scratchWriteVector;
Cartesian3_default.subtract(
positions[positionsLength - 1],
positions[positionsLength - 2],
position
);
Cartesian3_default.add(positions[positionsLength - 1], position, position);
}
} else {
position = positions[j + 1];
}
Cartesian3_default.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 (mode2 === SceneMode_default.SCENE2D) {
scratchWritePrevPosition.z = 0;
scratchWritePosition.z = 0;
scratchWriteNextPosition.z = 0;
}
if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.MORPHING) {
if ((segmentStart || segmentEnd) && maxLon - Math.abs(scratchWritePosition.x) < 1) {
if (scratchWritePosition.x < 0 && scratchWritePrevPosition.x > 0 || scratchWritePosition.x > 0 && scratchWritePrevPosition.x < 0) {
Cartesian3_default.clone(scratchWritePosition, scratchWritePrevPosition);
}
if (scratchWritePosition.x < 0 && scratchWriteNextPosition.x > 0 || scratchWritePosition.x > 0 && scratchWriteNextPosition.x < 0) {
Cartesian3_default.clone(scratchWritePosition, scratchWriteNextPosition);
}
}
}
const startK = segmentStart ? 2 : 0;
const endK = segmentEnd ? 2 : 4;
for (let k = startK; k < endK; ++k) {
EncodedCartesian3_default.writeElements(
scratchWritePosition,
positionArray,
positionIndex
);
EncodedCartesian3_default.writeElements(
scratchWritePrevPosition,
positionArray,
positionIndex + 6
);
EncodedCartesian3_default.writeElements(
scratchWriteNextPosition,
positionArray,
positionIndex + 12
);
const direction2 = k - 2 < 0 ? -1 : 1;
texCoordExpandAndBatchIndexArray[texCoordExpandAndBatchIndexIndex] = j / (positionsLength - 1);
texCoordExpandAndBatchIndexArray[texCoordExpandAndBatchIndexIndex + 1] = 2 * (k % 2) - 1;
texCoordExpandAndBatchIndexArray[texCoordExpandAndBatchIndexIndex + 2] = direction2;
texCoordExpandAndBatchIndexArray[texCoordExpandAndBatchIndexIndex + 3] = polylineBatchIndex;
positionIndex += 6 * 3;
texCoordExpandAndBatchIndexIndex += 4;
}
}
const colorCartesian = scratchPickColorCartesian;
colorCartesian.x = Color_default.floatToByte(pickColor.red);
colorCartesian.y = Color_default.floatToByte(pickColor.green);
colorCartesian.z = Color_default.floatToByte(pickColor.blue);
colorCartesian.w = Color_default.floatToByte(pickColor.alpha);
const widthShowCartesian = scratchWidthShowCartesian;
widthShowCartesian.x = width;
widthShowCartesian.y = show ? 1 : 0;
const boundingSphere = mode2 === SceneMode_default.SCENE2D ? polyline._boundingVolume2D : polyline._boundingVolumeWC;
const encodedCenter = EncodedCartesian3_default.fromCartesian(
boundingSphere.center,
scratchUpdatePolylineEncodedCartesian
);
const high = encodedCenter.high;
const low = Cartesian4_default.fromElements(
encodedCenter.low.x,
encodedCenter.low.y,
encodedCenter.low.z,
boundingSphere.radius,
scratchUpdatePolylineCartesian4
);
const nearFarCartesian = scratchNearFarCartesian2;
nearFarCartesian.x = 0;
nearFarCartesian.y = Number.MAX_VALUE;
const distanceDisplayCondition = polyline.distanceDisplayCondition;
if (defined_default(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);
}
}
};
var morphPositionScratch = new Cartesian3_default();
var morphPrevPositionScratch = new Cartesian3_default();
var morphNextPositionScratch = new Cartesian3_default();
var morphVectorScratch = new Cartesian3_default();
PolylineBucket.prototype.writeForMorph = function(positionArray, positionIndex) {
const modelMatrix = this.modelMatrix;
const polylines = this.polylines;
const length3 = polylines.length;
for (let i = 0; i < length3; ++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_default.subtract(positions[0], positions[1], prevPosition);
Cartesian3_default.add(positions[0], prevPosition, prevPosition);
}
} else {
prevPosition = positions[j - 1];
}
prevPosition = Matrix4_default.multiplyByPoint(
modelMatrix,
prevPosition,
morphPrevPositionScratch
);
const position = Matrix4_default.multiplyByPoint(
modelMatrix,
positions[j],
morphPositionScratch
);
let nextPosition;
if (j === positionsLength - 1) {
if (polyline._loop) {
nextPosition = positions[1];
} else {
nextPosition = morphVectorScratch;
Cartesian3_default.subtract(
positions[positionsLength - 1],
positions[positionsLength - 2],
nextPosition
);
Cartesian3_default.add(
positions[positionsLength - 1],
nextPosition,
nextPosition
);
}
} else {
nextPosition = positions[j + 1];
}
nextPosition = Matrix4_default.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_default.writeElements(position, positionArray, positionIndex);
EncodedCartesian3_default.writeElements(
prevPosition,
positionArray,
positionIndex + 6
);
EncodedCartesian3_default.writeElements(
nextPosition,
positionArray,
positionIndex + 12
);
positionIndex += 6 * 3;
}
}
}
};
var scratchSegmentLengths = new Array(1);
PolylineBucket.prototype.updateIndices = function(totalIndices, vertexBufferOffset, vertexArrayBuckets, offset2) {
let vaCount = vertexArrayBuckets.length - 1;
let bucketLocator = new VertexArrayBucketLocator(0, offset2, this);
vertexArrayBuckets[vaCount].push(bucketLocator);
let count = 0;
let indices2 = totalIndices[totalIndices.length - 1];
let indicesCount = 0;
if (indices2.length > 0) {
indicesCount = indices2[indices2.length - 1] + 1;
}
const polylines = this.polylines;
const length3 = polylines.length;
for (let i = 0; i < length3; ++i) {
const polyline = polylines[i];
polyline._locatorBuckets = [];
let segments;
if (this.mode === SceneMode_default.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;
for (let k = 0; k < segmentLength; ++k) {
if (indicesCount + 4 > Math_default.SIXTY_FOUR_KILOBYTES) {
polyline._locatorBuckets.push({
locator: bucketLocator,
count: segmentIndexCount
});
segmentIndexCount = 0;
vertexBufferOffset.push(4);
indices2 = [];
totalIndices.push(indices2);
indicesCount = 0;
bucketLocator.count = count;
count = 0;
offset2 = 0;
bucketLocator = new VertexArrayBucketLocator(0, 0, this);
vertexArrayBuckets[++vaCount] = [bucketLocator];
}
indices2.push(indicesCount, indicesCount + 2, indicesCount + 1);
indices2.push(indicesCount + 1, indicesCount + 2, indicesCount + 3);
segmentIndexCount += 6;
count += 6;
offset2 += 6;
indicesCount += 4;
}
}
polyline._locatorBuckets.push({
locator: bucketLocator,
count: segmentIndexCount
});
if (indicesCount + 4 > Math_default.SIXTY_FOUR_KILOBYTES) {
vertexBufferOffset.push(0);
indices2 = [];
totalIndices.push(indices2);
indicesCount = 0;
bucketLocator.count = count;
offset2 = 0;
count = 0;
bucketLocator = new VertexArrayBucketLocator(0, 0, this);
vertexArrayBuckets[++vaCount] = [bucketLocator];
}
}
polyline._clean();
}
bucketLocator.count = count;
return offset2;
};
PolylineBucket.prototype.getPolylineStartIndex = function(polyline) {
const polylines = this.polylines;
let positionIndex = 0;
const length3 = polylines.length;
for (let i = 0; i < length3; ++i) {
const p = polylines[i];
if (p === polyline) {
break;
}
positionIndex += p._actualLength;
}
return positionIndex;
};
var scratchSegments = {
positions: void 0,
lengths: void 0
};
var scratchLengths = new Array(1);
var pscratch = new Cartesian3_default();
var scratchCartographic6 = new Cartographic_default();
PolylineBucket.prototype.getSegments = function(polyline, projection) {
let positions = polyline._actualPositions;
if (this.mode === SceneMode_default.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 length3 = positions.length;
let position;
let p = pscratch;
for (let n = 0; n < length3; ++n) {
position = positions[n];
p = Matrix4_default.multiplyByPoint(modelMatrix, position, p);
newPositions.push(
projection.project(
ellipsoid.cartesianToCartographic(p, scratchCartographic6)
)
);
}
if (newPositions.length > 0) {
polyline._boundingVolume2D = BoundingSphere_default.fromPoints(
newPositions,
polyline._boundingVolume2D
);
const center2D = polyline._boundingVolume2D.center;
polyline._boundingVolume2D.center = new Cartesian3_default(
center2D.z,
center2D.x,
center2D.y
);
}
scratchSegments.positions = newPositions;
scratchSegments.lengths = polyline._segments.lengths;
return scratchSegments;
};
var scratchPositionsArray;
PolylineBucket.prototype.writeUpdate = function(index, polyline, positionBuffer, projection) {
const mode2 = this.mode;
const maxLon = projection.ellipsoid.maximumRadius * Math_default.PI;
let positionsLength = polyline._actualLength;
if (positionsLength) {
index += this.getPolylineStartIndex(polyline);
let positionArray = scratchPositionsArray;
const positionsArrayLength = 6 * positionsLength * 3;
if (!defined_default(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_default.subtract(positions[0], positions[1], position);
Cartesian3_default.add(positions[0], position, position);
}
} else {
position = positions[i - 1];
}
Cartesian3_default.clone(position, scratchWritePrevPosition);
Cartesian3_default.clone(positions[i], scratchWritePosition);
if (i === positionsLength - 1) {
if (polyline._loop) {
position = positions[1];
} else {
position = scratchWriteVector;
Cartesian3_default.subtract(
positions[positionsLength - 1],
positions[positionsLength - 2],
position
);
Cartesian3_default.add(positions[positionsLength - 1], position, position);
}
} else {
position = positions[i + 1];
}
Cartesian3_default.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 (mode2 === SceneMode_default.SCENE2D) {
scratchWritePrevPosition.z = 0;
scratchWritePosition.z = 0;
scratchWriteNextPosition.z = 0;
}
if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.MORPHING) {
if ((segmentStart || segmentEnd) && maxLon - Math.abs(scratchWritePosition.x) < 1) {
if (scratchWritePosition.x < 0 && scratchWritePrevPosition.x > 0 || scratchWritePosition.x > 0 && scratchWritePrevPosition.x < 0) {
Cartesian3_default.clone(scratchWritePosition, scratchWritePrevPosition);
}
if (scratchWritePosition.x < 0 && scratchWriteNextPosition.x > 0 || scratchWritePosition.x > 0 && scratchWriteNextPosition.x < 0) {
Cartesian3_default.clone(scratchWritePosition, scratchWriteNextPosition);
}
}
}
const startJ = segmentStart ? 2 : 0;
const endJ = segmentEnd ? 2 : 4;
for (let j = startJ; j < endJ; ++j) {
EncodedCartesian3_default.writeElements(
scratchWritePosition,
positionArray,
positionIndex
);
EncodedCartesian3_default.writeElements(
scratchWritePrevPosition,
positionArray,
positionIndex + 6
);
EncodedCartesian3_default.writeElements(
scratchWriteNextPosition,
positionArray,
positionIndex + 12
);
positionIndex += 6 * 3;
}
}
positionBuffer.copyFromArrayView(
positionArray,
6 * 3 * Float32Array.BYTES_PER_ELEMENT * index
);
}
};
var PolylineCollection_default = PolylineCollection;
// node_modules/@cesium/engine/Source/Scene/Vector3DTilePoints.js
function Vector3DTilePoints(options) {
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_default({
batchTable: options.batchTable
});
this._labelCollection = new LabelCollection_default({
batchTable: options.batchTable
});
this._polylineCollection = new PolylineCollection_default();
this._polylineCollection._useHighlightColor = true;
this._packedBuffer = void 0;
this._ready = false;
this._promise = void 0;
this._error = void 0;
}
Object.defineProperties(Vector3DTilePoints.prototype, {
ready: {
get: function() {
return this._ready;
}
},
pointsLength: {
get: function() {
return this._billboardCollection.length;
}
},
texturesByteLength: {
get: function() {
const billboardSize = this._billboardCollection.textureAtlas.texture.sizeInBytes;
const labelSize = this._labelCollection._textureAtlas.texture.sizeInBytes;
return billboardSize + labelSize;
}
}
});
function packBuffer2(points, ellipsoid) {
const rectangle = points._rectangle;
const minimumHeight = points._minHeight;
const maximumHeight = points._maxHeight;
const packedLength = 2 + Rectangle_default.packedLength + Ellipsoid_default.packedLength;
const packedBuffer = new Float64Array(packedLength);
let offset2 = 0;
packedBuffer[offset2++] = minimumHeight;
packedBuffer[offset2++] = maximumHeight;
Rectangle_default.pack(rectangle, packedBuffer, offset2);
offset2 += Rectangle_default.packedLength;
Ellipsoid_default.pack(ellipsoid, packedBuffer, offset2);
return packedBuffer;
}
var createVerticesTaskProcessor2 = new TaskProcessor_default(
"createVectorTilePoints",
5
);
var scratchPosition6 = new Cartesian3_default();
function createPoints(points, ellipsoid) {
let positions = points._positions;
let packedBuffer = points._packedBuffer;
if (!defined_default(packedBuffer)) {
positions = points._positions = positions.slice();
points._batchIds = points._batchIds.slice();
packedBuffer = points._packedBuffer = packBuffer2(points, ellipsoid);
}
const transferrableObjects = [positions.buffer, packedBuffer.buffer];
const parameters = {
positions: positions.buffer,
packedBuffer: packedBuffer.buffer
};
const verticesPromise = createVerticesTaskProcessor2.scheduleTask(
parameters,
transferrableObjects
);
if (!defined_default(verticesPromise)) {
return;
}
return verticesPromise.then((result) => {
if (points.isDestroyed()) {
return;
}
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_default.unpack(positions, i * 3, scratchPosition6);
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_default.clone(position), Cartesian3_default.clone(position)];
}
points._positions = void 0;
points._packedBuffer = void 0;
points._ready = true;
}).catch((error) => {
if (points.isDestroyed()) {
return;
}
points._error = error;
});
}
Vector3DTilePoints.prototype.createFeatures = function(content, features) {
const billboardCollection = this._billboardCollection;
const labelCollection = this._labelCollection;
const polylineCollection = this._polylineCollection;
const batchIds = this._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const billboard = billboardCollection.get(i);
const label = labelCollection.get(i);
const polyline = polylineCollection.get(i);
features[batchId] = new Cesium3DTilePointFeature_default(
content,
batchId,
billboard,
label,
polyline
);
}
};
Vector3DTilePoints.prototype.applyDebugSettings = function(enabled, color) {
if (enabled) {
Color_default.clone(color, this._billboardCollection._highlightColor);
Color_default.clone(color, this._labelCollection._highlightColor);
Color_default.clone(color, this._polylineCollection._highlightColor);
} else {
Color_default.clone(Color_default.WHITE, this._billboardCollection._highlightColor);
Color_default.clone(Color_default.WHITE, this._labelCollection._highlightColor);
Color_default.clone(Color_default.WHITE, this._polylineCollection._highlightColor);
}
};
function clearStyle2(polygons, features) {
const batchIds = polygons._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
feature.show = true;
feature.pointSize = Cesium3DTilePointFeature_default.defaultPointSize;
feature.color = Cesium3DTilePointFeature_default.defaultColor;
feature.pointOutlineColor = Cesium3DTilePointFeature_default.defaultPointOutlineColor;
feature.pointOutlineWidth = Cesium3DTilePointFeature_default.defaultPointOutlineWidth;
feature.labelColor = Color_default.WHITE;
feature.labelOutlineColor = Color_default.WHITE;
feature.labelOutlineWidth = 1;
feature.font = "30px sans-serif";
feature.labelStyle = LabelStyle_default.FILL;
feature.labelText = void 0;
feature.backgroundColor = new Color_default(0.165, 0.165, 0.165, 0.8);
feature.backgroundPadding = new Cartesian2_default(7, 5);
feature.backgroundEnabled = false;
feature.scaleByDistance = void 0;
feature.translucencyByDistance = void 0;
feature.distanceDisplayCondition = void 0;
feature.heightOffset = 0;
feature.anchorLineEnabled = false;
feature.anchorLineColor = Color_default.WHITE;
feature.image = void 0;
feature.disableDepthTestDistance = 0;
feature.horizontalOrigin = HorizontalOrigin_default.CENTER;
feature.verticalOrigin = VerticalOrigin_default.CENTER;
feature.labelHorizontalOrigin = HorizontalOrigin_default.RIGHT;
feature.labelVerticalOrigin = VerticalOrigin_default.BASELINE;
}
}
var scratchColor7 = new Color_default();
var scratchColor22 = new Color_default();
var scratchColor32 = new Color_default();
var scratchColor42 = new Color_default();
var scratchColor52 = new Color_default();
var scratchColor62 = new Color_default();
var scratchScaleByDistance = new NearFarScalar_default();
var scratchTranslucencyByDistance = new NearFarScalar_default();
var scratchDistanceDisplayCondition = new DistanceDisplayCondition_default();
Vector3DTilePoints.prototype.applyStyle = function(style, features) {
if (!defined_default(style)) {
clearStyle2(this, features);
return;
}
const batchIds = this._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
if (defined_default(style.show)) {
feature.show = style.show.evaluate(feature);
}
if (defined_default(style.pointSize)) {
feature.pointSize = style.pointSize.evaluate(feature);
}
if (defined_default(style.color)) {
feature.color = style.color.evaluateColor(feature, scratchColor7);
}
if (defined_default(style.pointOutlineColor)) {
feature.pointOutlineColor = style.pointOutlineColor.evaluateColor(
feature,
scratchColor22
);
}
if (defined_default(style.pointOutlineWidth)) {
feature.pointOutlineWidth = style.pointOutlineWidth.evaluate(feature);
}
if (defined_default(style.labelColor)) {
feature.labelColor = style.labelColor.evaluateColor(
feature,
scratchColor32
);
}
if (defined_default(style.labelOutlineColor)) {
feature.labelOutlineColor = style.labelOutlineColor.evaluateColor(
feature,
scratchColor42
);
}
if (defined_default(style.labelOutlineWidth)) {
feature.labelOutlineWidth = style.labelOutlineWidth.evaluate(feature);
}
if (defined_default(style.font)) {
feature.font = style.font.evaluate(feature);
}
if (defined_default(style.labelStyle)) {
feature.labelStyle = style.labelStyle.evaluate(feature);
}
if (defined_default(style.labelText)) {
feature.labelText = style.labelText.evaluate(feature);
} else {
feature.labelText = void 0;
}
if (defined_default(style.backgroundColor)) {
feature.backgroundColor = style.backgroundColor.evaluateColor(
feature,
scratchColor52
);
}
if (defined_default(style.backgroundPadding)) {
feature.backgroundPadding = style.backgroundPadding.evaluate(feature);
}
if (defined_default(style.backgroundEnabled)) {
feature.backgroundEnabled = style.backgroundEnabled.evaluate(feature);
}
if (defined_default(style.scaleByDistance)) {
const scaleByDistanceCart4 = style.scaleByDistance.evaluate(feature);
if (defined_default(scaleByDistanceCart4)) {
scratchScaleByDistance.near = scaleByDistanceCart4.x;
scratchScaleByDistance.nearValue = scaleByDistanceCart4.y;
scratchScaleByDistance.far = scaleByDistanceCart4.z;
scratchScaleByDistance.farValue = scaleByDistanceCart4.w;
feature.scaleByDistance = scratchScaleByDistance;
} else {
feature.scaleByDistance = void 0;
}
} else {
feature.scaleByDistance = void 0;
}
if (defined_default(style.translucencyByDistance)) {
const translucencyByDistanceCart4 = style.translucencyByDistance.evaluate(
feature
);
if (defined_default(translucencyByDistanceCart4)) {
scratchTranslucencyByDistance.near = translucencyByDistanceCart4.x;
scratchTranslucencyByDistance.nearValue = translucencyByDistanceCart4.y;
scratchTranslucencyByDistance.far = translucencyByDistanceCart4.z;
scratchTranslucencyByDistance.farValue = translucencyByDistanceCart4.w;
feature.translucencyByDistance = scratchTranslucencyByDistance;
} else {
feature.translucencyByDistance = void 0;
}
} else {
feature.translucencyByDistance = void 0;
}
if (defined_default(style.distanceDisplayCondition)) {
const distanceDisplayConditionCart2 = style.distanceDisplayCondition.evaluate(
feature
);
if (defined_default(distanceDisplayConditionCart2)) {
scratchDistanceDisplayCondition.near = distanceDisplayConditionCart2.x;
scratchDistanceDisplayCondition.far = distanceDisplayConditionCart2.y;
feature.distanceDisplayCondition = scratchDistanceDisplayCondition;
} else {
feature.distanceDisplayCondition = void 0;
}
} else {
feature.distanceDisplayCondition = void 0;
}
if (defined_default(style.heightOffset)) {
feature.heightOffset = style.heightOffset.evaluate(feature);
}
if (defined_default(style.anchorLineEnabled)) {
feature.anchorLineEnabled = style.anchorLineEnabled.evaluate(feature);
}
if (defined_default(style.anchorLineColor)) {
feature.anchorLineColor = style.anchorLineColor.evaluateColor(
feature,
scratchColor62
);
}
if (defined_default(style.image)) {
feature.image = style.image.evaluate(feature);
} else {
feature.image = void 0;
}
if (defined_default(style.disableDepthTestDistance)) {
feature.disableDepthTestDistance = style.disableDepthTestDistance.evaluate(
feature
);
}
if (defined_default(style.horizontalOrigin)) {
feature.horizontalOrigin = style.horizontalOrigin.evaluate(feature);
}
if (defined_default(style.verticalOrigin)) {
feature.verticalOrigin = style.verticalOrigin.evaluate(feature);
}
if (defined_default(style.labelHorizontalOrigin)) {
feature.labelHorizontalOrigin = style.labelHorizontalOrigin.evaluate(
feature
);
}
if (defined_default(style.labelVerticalOrigin)) {
feature.labelVerticalOrigin = style.labelVerticalOrigin.evaluate(feature);
}
}
};
Vector3DTilePoints.prototype.update = function(frameState) {
if (!this._ready) {
if (!defined_default(this._promise)) {
this._promise = createPoints(this, frameState.mapProjection.ellipsoid);
}
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
return;
}
this._polylineCollection.update(frameState);
this._billboardCollection.update(frameState);
this._labelCollection.update(frameState);
};
Vector3DTilePoints.prototype.isDestroyed = function() {
return false;
};
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_default(this);
};
var Vector3DTilePoints_default = Vector3DTilePoints;
// node_modules/@cesium/engine/Source/Scene/Vector3DTilePolygons.js
function Vector3DTilePolygons(options) {
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 = void 0;
this._batchTableColors = void 0;
this._packedBuffer = void 0;
this._batchedPositions = void 0;
this._transferrableBatchIds = void 0;
this._vertexBatchIds = void 0;
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._minimumHeight = options.minimumHeight;
this._maximumHeight = options.maximumHeight;
this._polygonMinimumHeights = options.polygonMinimumHeights;
this._polygonMaximumHeights = options.polygonMaximumHeights;
this._center = defaultValue_default(options.center, Cartesian3_default.ZERO);
this._rectangle = options.rectangle;
this._center = void 0;
this._boundingVolume = options.boundingVolume;
this._boundingVolumes = void 0;
this._batchedIndices = void 0;
this._ready = false;
this._promise = void 0;
this._error = void 0;
this._primitive = void 0;
this.debugWireframe = false;
this.forceRebatch = false;
this.classificationType = ClassificationType_default.BOTH;
}
Object.defineProperties(Vector3DTilePolygons.prototype, {
trianglesLength: {
get: function() {
if (defined_default(this._primitive)) {
return this._primitive.trianglesLength;
}
return 0;
}
},
geometryByteLength: {
get: function() {
if (defined_default(this._primitive)) {
return this._primitive.geometryByteLength;
}
return 0;
}
},
ready: {
get: function() {
return this._ready;
}
}
});
function packBuffer3(polygons) {
const packedBuffer = new Float64Array(
3 + Cartesian3_default.packedLength + Ellipsoid_default.packedLength + Rectangle_default.packedLength
);
let offset2 = 0;
packedBuffer[offset2++] = polygons._indices.BYTES_PER_ELEMENT;
packedBuffer[offset2++] = polygons._minimumHeight;
packedBuffer[offset2++] = polygons._maximumHeight;
Cartesian3_default.pack(polygons._center, packedBuffer, offset2);
offset2 += Cartesian3_default.packedLength;
Ellipsoid_default.pack(polygons._ellipsoid, packedBuffer, offset2);
offset2 += Ellipsoid_default.packedLength;
Rectangle_default.pack(polygons._rectangle, packedBuffer, offset2);
return packedBuffer;
}
function unpackBuffer2(polygons, packedBuffer) {
let offset2 = 1;
const numBVS = packedBuffer[offset2++];
const bvs = polygons._boundingVolumes = new Array(numBVS);
for (let i = 0; i < numBVS; ++i) {
bvs[i] = OrientedBoundingBox_default.unpack(packedBuffer, offset2);
offset2 += OrientedBoundingBox_default.packedLength;
}
const numBatchedIndices = packedBuffer[offset2++];
const bis = polygons._batchedIndices = new Array(numBatchedIndices);
for (let j = 0; j < numBatchedIndices; ++j) {
const color = Color_default.unpack(packedBuffer, offset2);
offset2 += Color_default.packedLength;
const indexOffset = packedBuffer[offset2++];
const count = packedBuffer[offset2++];
const length3 = packedBuffer[offset2++];
const batchIds = new Array(length3);
for (let k = 0; k < length3; ++k) {
batchIds[k] = packedBuffer[offset2++];
}
bis[j] = new Vector3DTileBatch_default({
color,
offset: indexOffset,
count,
batchIds
});
}
}
var createVerticesTaskProcessor3 = new TaskProcessor_default(
"createVectorTilePolygons",
5
);
var scratchColor8 = new Color_default();
function createPrimitive2(polygons) {
if (defined_default(polygons._primitive)) {
return;
}
let positions = polygons._positions;
let counts = polygons._counts;
let indexCounts = polygons._indexCounts;
let indices2 = polygons._indices;
let batchIds = polygons._transferrableBatchIds;
let batchTableColors = polygons._batchTableColors;
let packedBuffer = polygons._packedBuffer;
if (!defined_default(batchTableColors)) {
positions = polygons._positions = polygons._positions.slice();
counts = polygons._counts = polygons._counts.slice();
indexCounts = polygons._indexCounts = polygons._indexCounts.slice();
indices2 = polygons._indices = polygons._indices.slice();
polygons._center = polygons._ellipsoid.cartographicToCartesian(
Rectangle_default.center(polygons._rectangle)
);
batchIds = polygons._transferrableBatchIds = new Uint32Array(
polygons._batchIds
);
batchTableColors = polygons._batchTableColors = new Uint32Array(
batchIds.length
);
const batchTable = polygons._batchTable;
const length3 = batchTableColors.length;
for (let i = 0; i < length3; ++i) {
const color = batchTable.getColor(i, scratchColor8);
batchTableColors[i] = color.toRgba();
}
packedBuffer = polygons._packedBuffer = packBuffer3(polygons);
}
const transferrableObjects = [
positions.buffer,
counts.buffer,
indexCounts.buffer,
indices2.buffer,
batchIds.buffer,
batchTableColors.buffer,
packedBuffer.buffer
];
const parameters = {
packedBuffer: packedBuffer.buffer,
positions: positions.buffer,
counts: counts.buffer,
indexCounts: indexCounts.buffer,
indices: indices2.buffer,
batchIds: batchIds.buffer,
batchTableColors: batchTableColors.buffer
};
let minimumHeights = polygons._polygonMinimumHeights;
let maximumHeights = polygons._polygonMaximumHeights;
if (defined_default(minimumHeights) && defined_default(maximumHeights)) {
minimumHeights = minimumHeights.slice();
maximumHeights = maximumHeights.slice();
transferrableObjects.push(minimumHeights.buffer, maximumHeights.buffer);
parameters.minimumHeights = minimumHeights;
parameters.maximumHeights = maximumHeights;
}
const verticesPromise = createVerticesTaskProcessor3.scheduleTask(
parameters,
transferrableObjects
);
if (!defined_default(verticesPromise)) {
return;
}
return verticesPromise.then((result) => {
if (polygons.isDestroyed()) {
return;
}
polygons._positions = void 0;
polygons._counts = void 0;
polygons._polygonMinimumHeights = void 0;
polygons._polygonMaximumHeights = void 0;
const packedBuffer2 = new Float64Array(result.packedBuffer);
const indexDatatype = packedBuffer2[0];
unpackBuffer2(polygons, packedBuffer2);
polygons._indices = IndexDatatype_default.getSizeInBytes(indexDatatype) === 2 ? new Uint16Array(result.indices) : new Uint32Array(result.indices);
polygons._indexOffsets = new Uint32Array(result.indexOffsets);
polygons._indexCounts = new Uint32Array(result.indexCounts);
polygons._batchedPositions = new Float32Array(result.positions);
polygons._vertexBatchIds = new Uint16Array(result.batchIds);
finishPrimitive2(polygons);
polygons._ready = true;
}).catch((error) => {
if (polygons.isDestroyed()) {
return;
}
polygons._error = error;
});
}
function finishPrimitive2(polygons) {
if (!defined_default(polygons._primitive)) {
polygons._primitive = new Vector3DTilePrimitive_default({
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 = void 0;
polygons._batchIds = void 0;
polygons._positions = void 0;
polygons._counts = void 0;
polygons._indices = void 0;
polygons._indexCounts = void 0;
polygons._indexOffsets = void 0;
polygons._batchTableColors = void 0;
polygons._packedBuffer = void 0;
polygons._batchedPositions = void 0;
polygons._transferrableBatchIds = void 0;
polygons._vertexBatchIds = void 0;
polygons._ellipsoid = void 0;
polygons._minimumHeight = void 0;
polygons._maximumHeight = void 0;
polygons._polygonMinimumHeights = void 0;
polygons._polygonMaximumHeights = void 0;
polygons._center = void 0;
polygons._rectangle = void 0;
polygons._boundingVolume = void 0;
polygons._boundingVolumes = void 0;
polygons._batchedIndices = void 0;
}
}
Vector3DTilePolygons.prototype.createFeatures = function(content, features) {
this._primitive.createFeatures(content, features);
};
Vector3DTilePolygons.prototype.applyDebugSettings = function(enabled, color) {
this._primitive.applyDebugSettings(enabled, color);
};
Vector3DTilePolygons.prototype.applyStyle = function(style, features) {
this._primitive.applyStyle(style, features);
};
Vector3DTilePolygons.prototype.updateCommands = function(batchId, color) {
this._primitive.updateCommands(batchId, color);
};
Vector3DTilePolygons.prototype.update = function(frameState) {
if (!this._ready) {
if (!defined_default(this._promise)) {
this._promise = createPrimitive2(this);
}
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
return;
}
this._primitive.debugWireframe = this.debugWireframe;
this._primitive.forceRebatch = this.forceRebatch;
this._primitive.classificationType = this.classificationType;
this._primitive.update(frameState);
};
Vector3DTilePolygons.prototype.isDestroyed = function() {
return false;
};
Vector3DTilePolygons.prototype.destroy = function() {
this._primitive = this._primitive && this._primitive.destroy();
return destroyObject_default(this);
};
var Vector3DTilePolygons_default = Vector3DTilePolygons;
// node_modules/@cesium/engine/Source/Shaders/Vector3DTilePolylinesVS.js
var Vector3DTilePolylinesVS_default = "in vec4 currentPosition;\nin vec4 previousPosition;\nin vec4 nextPosition;\nin vec2 expandAndWidth;\nin float a_batchId;\n\nuniform mat4 u_modifiedModelView;\n\nvoid main()\n{\n float expandDir = expandAndWidth.x;\n float width = abs(expandAndWidth.y) + 0.5;\n bool usePrev = expandAndWidth.y < 0.0;\n\n vec4 p = u_modifiedModelView * currentPosition;\n vec4 prev = u_modifiedModelView * previousPosition;\n vec4 next = u_modifiedModelView * nextPosition;\n\n float angle;\n vec4 positionWC = getPolylineWindowCoordinatesEC(p, prev, next, expandDir, width, usePrev, angle);\n gl_Position = czm_viewportOrthographic * positionWC;\n}\n";
// node_modules/@cesium/engine/Source/Scene/Vector3DTilePolylines.js
function Vector3DTilePolylines(options) {
this._positions = options.positions;
this._widths = options.widths;
this._counts = options.counts;
this._batchIds = options.batchIds;
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.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 = void 0;
this._sp = void 0;
this._rs = void 0;
this._uniformMap = void 0;
this._command = void 0;
this._transferrableBatchIds = void 0;
this._packedBuffer = void 0;
this._keepDecodedPositions = options.keepDecodedPositions;
this._decodedPositions = void 0;
this._decodedPositionOffsets = void 0;
this._currentPositions = void 0;
this._previousPositions = void 0;
this._nextPositions = void 0;
this._expandAndWidth = void 0;
this._vertexBatchIds = void 0;
this._indices = void 0;
this._constantColor = Color_default.clone(Color_default.WHITE);
this._highlightColor = this._constantColor;
this._trianglesLength = 0;
this._geometryByteLength = 0;
this._ready = false;
this._promise = void 0;
this._error = void 0;
}
Object.defineProperties(Vector3DTilePolylines.prototype, {
trianglesLength: {
get: function() {
return this._trianglesLength;
}
},
geometryByteLength: {
get: function() {
return this._geometryByteLength;
}
},
ready: {
get: function() {
return this._ready;
}
}
});
function packBuffer4(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_default.packedLength + Ellipsoid_default.packedLength + Cartesian3_default.packedLength;
const packedBuffer = new Float64Array(packedLength);
let offset2 = 0;
packedBuffer[offset2++] = minimumHeight;
packedBuffer[offset2++] = maximumHeight;
Rectangle_default.pack(rectangle, packedBuffer, offset2);
offset2 += Rectangle_default.packedLength;
Ellipsoid_default.pack(ellipsoid, packedBuffer, offset2);
offset2 += Ellipsoid_default.packedLength;
Cartesian3_default.pack(center, packedBuffer, offset2);
return packedBuffer;
}
var createVerticesTaskProcessor4 = new TaskProcessor_default(
"createVectorTilePolylines",
5
);
var attributeLocations3 = {
previousPosition: 0,
currentPosition: 1,
nextPosition: 2,
expandAndWidth: 3,
a_batchId: 4
};
function createVertexArray4(polylines, context) {
if (defined_default(polylines._va)) {
return;
}
let positions = polylines._positions;
let widths = polylines._widths;
let counts = polylines._counts;
let batchIds = polylines._transferrableBatchIds;
let packedBuffer = polylines._packedBuffer;
if (!defined_default(packedBuffer)) {
positions = polylines._positions = positions.slice();
widths = polylines._widths = widths.slice();
counts = polylines._counts = counts.slice();
batchIds = polylines._transferrableBatchIds = polylines._batchIds.slice();
packedBuffer = polylines._packedBuffer = packBuffer4(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 = createVerticesTaskProcessor4.scheduleTask(
parameters,
transferrableObjects
);
if (!defined_default(verticesPromise)) {
return;
}
return verticesPromise.then(function(result) {
if (polylines.isDestroyed()) {
return;
}
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_default.UNSIGNED_SHORT ? new Uint16Array(result.indices) : new Uint32Array(result.indices);
finishVertexArray(polylines, context);
polylines._ready = true;
}).catch((error) => {
if (polylines.isDestroyed()) {
return;
}
polylines._error = error;
});
}
function finishVertexArray(polylines, context) {
if (!defined_default(polylines._va)) {
const curPositions = polylines._currentPositions;
const prevPositions = polylines._previousPositions;
const nextPositions = polylines._nextPositions;
const expandAndWidth = polylines._expandAndWidth;
const vertexBatchIds = polylines._vertexBatchIds;
const indices2 = polylines._indices;
let byteLength = prevPositions.byteLength + curPositions.byteLength + nextPositions.byteLength;
byteLength += expandAndWidth.byteLength + vertexBatchIds.byteLength + indices2.byteLength;
polylines._trianglesLength = indices2.length / 3;
polylines._geometryByteLength = byteLength;
const prevPositionBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: prevPositions,
usage: BufferUsage_default.STATIC_DRAW
});
const curPositionBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: curPositions,
usage: BufferUsage_default.STATIC_DRAW
});
const nextPositionBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: nextPositions,
usage: BufferUsage_default.STATIC_DRAW
});
const expandAndWidthBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: expandAndWidth,
usage: BufferUsage_default.STATIC_DRAW
});
const idBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: vertexBatchIds,
usage: BufferUsage_default.STATIC_DRAW
});
const indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: indices2,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: indices2.BYTES_PER_ELEMENT === 2 ? IndexDatatype_default.UNSIGNED_SHORT : IndexDatatype_default.UNSIGNED_INT
});
const vertexAttributes = [
{
index: attributeLocations3.previousPosition,
vertexBuffer: prevPositionBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
index: attributeLocations3.currentPosition,
vertexBuffer: curPositionBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
index: attributeLocations3.nextPosition,
vertexBuffer: nextPositionBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
index: attributeLocations3.expandAndWidth,
vertexBuffer: expandAndWidthBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2
},
{
index: attributeLocations3.a_batchId,
vertexBuffer: idBuffer,
componentDatatype: ComponentDatatype_default.UNSIGNED_SHORT,
componentsPerAttribute: 1
}
];
polylines._va = new VertexArray_default({
context,
attributes: vertexAttributes,
indexBuffer
});
polylines._positions = void 0;
polylines._widths = void 0;
polylines._counts = void 0;
polylines._ellipsoid = void 0;
polylines._minimumHeight = void 0;
polylines._maximumHeight = void 0;
polylines._rectangle = void 0;
polylines._transferrableBatchIds = void 0;
polylines._packedBuffer = void 0;
polylines._currentPositions = void 0;
polylines._previousPositions = void 0;
polylines._nextPositions = void 0;
polylines._expandAndWidth = void 0;
polylines._vertexBatchIds = void 0;
polylines._indices = void 0;
}
}
var modifiedModelViewScratch3 = new Matrix4_default();
var rtcScratch3 = new Cartesian3_default();
function createUniformMap2(primitive, context) {
if (defined_default(primitive._uniformMap)) {
return;
}
primitive._uniformMap = {
u_modifiedModelView: function() {
const viewMatrix = context.uniformState.view;
Matrix4_default.clone(viewMatrix, modifiedModelViewScratch3);
Matrix4_default.multiplyByPoint(
modifiedModelViewScratch3,
primitive._center,
rtcScratch3
);
Matrix4_default.setTranslation(
modifiedModelViewScratch3,
rtcScratch3,
modifiedModelViewScratch3
);
return modifiedModelViewScratch3;
},
u_highlightColor: function() {
return primitive._highlightColor;
}
};
}
function createRenderStates4(primitive) {
if (defined_default(primitive._rs)) {
return;
}
const polygonOffset = {
enabled: true,
factor: -5,
units: -5
};
primitive._rs = RenderState_default.fromCache({
blending: BlendingState_default.ALPHA_BLEND,
depthMask: false,
depthTest: {
enabled: true
},
polygonOffset
});
}
var PolylineFS = "uniform vec4 u_highlightColor; \nvoid main()\n{\n out_FragColor = u_highlightColor;\n}\n";
function createShaders2(primitive, context) {
if (defined_default(primitive._sp)) {
return;
}
const batchTable = primitive._batchTable;
const vsSource = batchTable.getVertexShaderCallback(
false,
"a_batchId",
void 0
)(Vector3DTilePolylinesVS_default);
const fsSource = batchTable.getFragmentShaderCallback(
false,
void 0,
false
)(PolylineFS);
const vs = new ShaderSource_default({
defines: [
"VECTOR_TILE",
!FeatureDetection_default.isInternetExplorer() ? "CLIP_POLYLINE" : ""
],
sources: [PolylineCommon_default, vsSource]
});
const fs = new ShaderSource_default({
defines: ["VECTOR_TILE"],
sources: [fsSource]
});
primitive._sp = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations3
});
}
function queueCommands2(primitive, frameState) {
if (!defined_default(primitive._command)) {
const uniformMap2 = primitive._batchTable.getUniformMapCallback()(
primitive._uniformMap
);
primitive._command = new DrawCommand_default({
owner: primitive,
vertexArray: primitive._va,
renderState: primitive._rs,
shaderProgram: primitive._sp,
uniformMap: uniformMap2,
boundingVolume: primitive._boundingVolume,
pass: Pass_default.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_default(batchIds) || !defined_default(positions)) {
return void 0;
}
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 void 0;
}
const results = new Float64Array(positionsLength * 3);
for (i = 0; i < polylinesLength; ++i) {
if (batchIds[i] === batchId) {
const offset2 = offsets[i];
const count = offsets[i + 1] - offset2;
for (j = 0; j < count; ++j) {
const decodedOffset = (offset2 + j) * 3;
results[resultCounter++] = positions[decodedOffset];
results[resultCounter++] = positions[decodedOffset + 1];
results[resultCounter++] = positions[decodedOffset + 2];
}
}
}
return results;
};
Vector3DTilePolylines.prototype.getPositions = function(batchId) {
return Vector3DTilePolylines.getPolylinePositions(this, batchId);
};
Vector3DTilePolylines.prototype.createFeatures = function(content, features) {
const batchIds = this._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
features[batchId] = new Cesium3DTileFeature_default(content, batchId);
}
};
Vector3DTilePolylines.prototype.applyDebugSettings = function(enabled, color) {
this._highlightColor = enabled ? color : this._constantColor;
};
function clearStyle3(polygons, features) {
const batchIds = polygons._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
feature.show = true;
feature.color = Color_default.WHITE;
}
}
var scratchColor9 = new Color_default();
var DEFAULT_COLOR_VALUE3 = Color_default.WHITE;
var DEFAULT_SHOW_VALUE3 = true;
Vector3DTilePolylines.prototype.applyStyle = function(style, features) {
if (!defined_default(style)) {
clearStyle3(this, features);
return;
}
const batchIds = this._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
feature.color = defined_default(style.color) ? style.color.evaluateColor(feature, scratchColor9) : DEFAULT_COLOR_VALUE3;
feature.show = defined_default(style.show) ? style.show.evaluate(feature) : DEFAULT_SHOW_VALUE3;
}
};
Vector3DTilePolylines.prototype.update = function(frameState) {
const context = frameState.context;
if (!this._ready) {
if (!defined_default(this._promise)) {
this._promise = createVertexArray4(this, context);
}
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
return;
}
createUniformMap2(this, context);
createShaders2(this, context);
createRenderStates4(this);
const passes = frameState.passes;
if (passes.render || passes.pick) {
queueCommands2(this, frameState);
}
};
Vector3DTilePolylines.prototype.isDestroyed = function() {
return false;
};
Vector3DTilePolylines.prototype.destroy = function() {
this._va = this._va && this._va.destroy();
this._sp = this._sp && this._sp.destroy();
return destroyObject_default(this);
};
var Vector3DTilePolylines_default = Vector3DTilePolylines;
// node_modules/@cesium/engine/Source/Shaders/Vector3DTileClampedPolylinesVS.js
var Vector3DTileClampedPolylinesVS_default = 'in vec3 startEllipsoidNormal;\nin vec3 endEllipsoidNormal;\nin vec4 startPositionAndHeight;\nin vec4 endPositionAndHeight;\nin vec4 startFaceNormalAndVertexCorner;\nin vec4 endFaceNormalAndHalfWidth;\nin float a_batchId;\n\nuniform mat4 u_modifiedModelView;\nuniform vec2 u_minimumMaximumVectorHeights;\n\nout vec4 v_startPlaneEC;\nout vec4 v_endPlaneEC;\nout vec4 v_rightPlaneEC;\nout float v_halfWidth;\nout vec3 v_volumeUpEC;\n\nvoid main()\n{\n // vertex corner IDs\n // 3-----------7\n // /| left /|\n // / | 1 / |\n // 2-----------6 5 end\n // | / | /\n // start |/ right |/\n // 0-----------4\n //\n float isEnd = floor(startFaceNormalAndVertexCorner.w * 0.251); // 0 for front, 1 for end\n float isTop = floor(startFaceNormalAndVertexCorner.w * mix(0.51, 0.19, isEnd)); // 0 for bottom, 1 for top\n\n vec3 forward = endPositionAndHeight.xyz - startPositionAndHeight.xyz;\n vec3 right = normalize(cross(forward, startEllipsoidNormal));\n\n vec4 position = vec4(startPositionAndHeight.xyz, 1.0);\n position.xyz += forward * isEnd;\n\n v_volumeUpEC = czm_normal * normalize(cross(right, forward));\n\n // Push for volume height\n float offset;\n vec3 ellipsoidNormal = mix(startEllipsoidNormal, endEllipsoidNormal, isEnd);\n\n // offset height to create volume\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\n // move from RTC to EC\n position = u_modifiedModelView * position;\n right = czm_normal * right;\n\n // Push for width in a direction that is in the start or end plane and in a plane with right\n // N = normalEC ("right-facing" direction for push)\n // R = right\n // p = angle between N and R\n // w = distance to push along R if R == N\n // d = distance to push along N\n //\n // N R\n // { p| } * cos(p) = dot(N, R) = w / d\n // d | |w * d = w / dot(N, R)\n // { | }\n // o---------- polyline segment ---->\n //\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\n offset = 2.0 * endFaceNormalAndHalfWidth.w * max(0.0, czm_metersPerPixel(position)); // offset = widthEC\n offset = offset / dot(miterPushNormal, right);\n position.xyz += miterPushNormal * (offset * sign(0.5 - mod(startFaceNormalAndVertexCorner.w, 2.0)));\n\n gl_Position = czm_depthClamp(czm_projection * position);\n\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\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';
// node_modules/@cesium/engine/Source/Shaders/Vector3DTileClampedPolylinesFS.js
var Vector3DTileClampedPolylinesFS_default = "in vec4 v_startPlaneEC;\nin vec4 v_endPlaneEC;\nin vec4 v_rightPlaneEC;\nin float v_halfWidth;\nin vec3 v_volumeUpEC;\n\nuniform vec4 u_highlightColor;\nvoid main()\n{\n float logDepthOrDepth = czm_branchFreeTernary(czm_sceneMode == czm_sceneMode2D, gl_FragCoord.z, czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw)));\n\n // Discard for sky\n if (logDepthOrDepth == 0.0) {\n#ifdef DEBUG_SHOW_VOLUME\n out_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\n vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);\n eyeCoordinate /= eyeCoordinate.w;\n\n float halfMaxWidth = v_halfWidth * czm_metersPerPixel(eyeCoordinate);\n\n // Expand halfMaxWidth if direction to camera is almost perpendicular with the volume's up direction\n halfMaxWidth += halfMaxWidth * (1.0 - dot(-normalize(eyeCoordinate.xyz), v_volumeUpEC));\n\n // Check distance of the eye coordinate against the right-facing plane\n float widthwiseDistance = czm_planeDistance(v_rightPlaneEC, eyeCoordinate.xyz);\n\n // Check eye coordinate against the mitering planes\n float distanceFromStart = czm_planeDistance(v_startPlaneEC, eyeCoordinate.xyz);\n float distanceFromEnd = czm_planeDistance(v_endPlaneEC, eyeCoordinate.xyz);\n\n if (abs(widthwiseDistance) > halfMaxWidth || distanceFromStart < 0.0 || distanceFromEnd < 0.0) {\n#ifdef DEBUG_SHOW_VOLUME\n out_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 out_FragColor = u_highlightColor;\n\n czm_writeDepthClamp();\n}\n";
// node_modules/@cesium/engine/Source/Scene/Vector3DTileClampedPolylines.js
function Vector3DTileClampedPolylines(options) {
this._positions = options.positions;
this._widths = options.widths;
this._counts = options.counts;
this._batchIds = options.batchIds;
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._minimumHeight = options.minimumHeight;
this._maximumHeight = options.maximumHeight;
this._center = options.center;
this._rectangle = options.rectangle;
this._batchTable = options.batchTable;
this._va = void 0;
this._sp = void 0;
this._rs = void 0;
this._uniformMap = void 0;
this._command = void 0;
this._transferrableBatchIds = void 0;
this._packedBuffer = void 0;
this._minimumMaximumVectorHeights = new Cartesian2_default(
ApproximateTerrainHeights_default._defaultMinTerrainHeight,
ApproximateTerrainHeights_default._defaultMaxTerrainHeight
);
this._boundingVolume = OrientedBoundingBox_default.fromRectangle(
options.rectangle,
ApproximateTerrainHeights_default._defaultMinTerrainHeight,
ApproximateTerrainHeights_default._defaultMaxTerrainHeight,
this._ellipsoid
);
this._classificationType = options.classificationType;
this._keepDecodedPositions = options.keepDecodedPositions;
this._decodedPositions = void 0;
this._decodedPositionOffsets = void 0;
this._startEllipsoidNormals = void 0;
this._endEllipsoidNormals = void 0;
this._startPositionAndHeights = void 0;
this._startFaceNormalAndVertexCornerIds = void 0;
this._endPositionAndHeights = void 0;
this._endFaceNormalAndHalfWidths = void 0;
this._vertexBatchIds = void 0;
this._indices = void 0;
this._constantColor = Color_default.clone(Color_default.WHITE);
this._highlightColor = this._constantColor;
this._trianglesLength = 0;
this._geometryByteLength = 0;
this._ready = false;
this._promise = void 0;
this._error = void 0;
}
Object.defineProperties(Vector3DTileClampedPolylines.prototype, {
trianglesLength: {
get: function() {
return this._trianglesLength;
}
},
geometryByteLength: {
get: function() {
return this._geometryByteLength;
}
},
ready: {
get: function() {
return this._ready;
}
}
});
function updateMinimumMaximumHeights(polylines, rectangle, ellipsoid) {
const result = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
rectangle,
ellipsoid
);
const min3 = result.minimumTerrainHeight;
const max3 = result.maximumTerrainHeight;
const minimumMaximumVectorHeights = polylines._minimumMaximumVectorHeights;
minimumMaximumVectorHeights.x = min3;
minimumMaximumVectorHeights.y = max3;
const obb = polylines._boundingVolume;
const rect = polylines._rectangle;
OrientedBoundingBox_default.fromRectangle(rect, min3, max3, ellipsoid, obb);
}
function packBuffer5(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_default.packedLength + Ellipsoid_default.packedLength + Cartesian3_default.packedLength;
const packedBuffer = new Float64Array(packedLength);
let offset2 = 0;
packedBuffer[offset2++] = minimumHeight;
packedBuffer[offset2++] = maximumHeight;
Rectangle_default.pack(rectangle, packedBuffer, offset2);
offset2 += Rectangle_default.packedLength;
Ellipsoid_default.pack(ellipsoid, packedBuffer, offset2);
offset2 += Ellipsoid_default.packedLength;
Cartesian3_default.pack(center, packedBuffer, offset2);
return packedBuffer;
}
var createVerticesTaskProcessor5 = new TaskProcessor_default(
"createVectorTileClampedPolylines"
);
var attributeLocations4 = {
startEllipsoidNormal: 0,
endEllipsoidNormal: 1,
startPositionAndHeight: 2,
endPositionAndHeight: 3,
startFaceNormalAndVertexCorner: 4,
endFaceNormalAndHalfWidth: 5,
a_batchId: 6
};
function createVertexArray5(polylines, context) {
if (defined_default(polylines._va)) {
return;
}
let positions = polylines._positions;
let widths = polylines._widths;
let counts = polylines._counts;
let batchIds = polylines._transferrableBatchIds;
let packedBuffer = polylines._packedBuffer;
if (!defined_default(packedBuffer)) {
positions = polylines._positions = positions.slice();
widths = polylines._widths = widths.slice();
counts = polylines._counts = counts.slice();
batchIds = polylines._transferrableBatchIds = polylines._batchIds.slice();
packedBuffer = polylines._packedBuffer = packBuffer5(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 = createVerticesTaskProcessor5.scheduleTask(
parameters,
transferrableObjects
);
if (!defined_default(verticesPromise)) {
return;
}
return verticesPromise.then(function(result) {
if (polylines.isDestroyed()) {
return;
}
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_default.UNSIGNED_SHORT ? new Uint16Array(result.indices) : new Uint32Array(result.indices);
finishVertexArray2(polylines, context);
polylines._ready = true;
}).catch((error) => {
if (polylines.isDestroyed()) {
return;
}
polylines._error = error;
});
}
function finishVertexArray2(polylines, context) {
if (!defined_default(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 indices2 = polylines._indices;
let byteLength = startEllipsoidNormals.byteLength + endEllipsoidNormals.byteLength;
byteLength += startPositionAndHeights.byteLength + endPositionAndHeights.byteLength;
byteLength += startFaceNormalAndVertexCornerIds.byteLength + endFaceNormalAndHalfWidths.byteLength;
byteLength += batchIdAttribute.byteLength + indices2.byteLength;
polylines._trianglesLength = indices2.length / 3;
polylines._geometryByteLength = byteLength;
const startEllipsoidNormalsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: startEllipsoidNormals,
usage: BufferUsage_default.STATIC_DRAW
});
const endEllipsoidNormalsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: endEllipsoidNormals,
usage: BufferUsage_default.STATIC_DRAW
});
const startPositionAndHeightsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: startPositionAndHeights,
usage: BufferUsage_default.STATIC_DRAW
});
const endPositionAndHeightsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: endPositionAndHeights,
usage: BufferUsage_default.STATIC_DRAW
});
const startFaceNormalAndVertexCornerIdsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: startFaceNormalAndVertexCornerIds,
usage: BufferUsage_default.STATIC_DRAW
});
const endFaceNormalAndHalfWidthsBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: endFaceNormalAndHalfWidths,
usage: BufferUsage_default.STATIC_DRAW
});
const batchIdAttributeBuffer = Buffer_default.createVertexBuffer({
context,
typedArray: batchIdAttribute,
usage: BufferUsage_default.STATIC_DRAW
});
const indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: indices2,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: indices2.BYTES_PER_ELEMENT === 2 ? IndexDatatype_default.UNSIGNED_SHORT : IndexDatatype_default.UNSIGNED_INT
});
const vertexAttributes = [
{
index: attributeLocations4.startEllipsoidNormal,
vertexBuffer: startEllipsoidNormalsBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
index: attributeLocations4.endEllipsoidNormal,
vertexBuffer: endEllipsoidNormalsBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3
},
{
index: attributeLocations4.startPositionAndHeight,
vertexBuffer: startPositionAndHeightsBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4
},
{
index: attributeLocations4.endPositionAndHeight,
vertexBuffer: endPositionAndHeightsBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4
},
{
index: attributeLocations4.startFaceNormalAndVertexCorner,
vertexBuffer: startFaceNormalAndVertexCornerIdsBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4
},
{
index: attributeLocations4.endFaceNormalAndHalfWidth,
vertexBuffer: endFaceNormalAndHalfWidthsBuffer,
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 4
},
{
index: attributeLocations4.a_batchId,
vertexBuffer: batchIdAttributeBuffer,
componentDatatype: ComponentDatatype_default.UNSIGNED_SHORT,
componentsPerAttribute: 1
}
];
polylines._va = new VertexArray_default({
context,
attributes: vertexAttributes,
indexBuffer
});
polylines._positions = void 0;
polylines._widths = void 0;
polylines._counts = void 0;
polylines._ellipsoid = void 0;
polylines._minimumHeight = void 0;
polylines._maximumHeight = void 0;
polylines._rectangle = void 0;
polylines._transferrableBatchIds = void 0;
polylines._packedBuffer = void 0;
polylines._startEllipsoidNormals = void 0;
polylines._endEllipsoidNormals = void 0;
polylines._startPositionAndHeights = void 0;
polylines._startFaceNormalAndVertexCornerIds = void 0;
polylines._endPositionAndHeights = void 0;
polylines._endFaceNormalAndHalfWidths = void 0;
polylines._vertexBatchIds = void 0;
polylines._indices = void 0;
}
}
var modifiedModelViewScratch4 = new Matrix4_default();
var rtcScratch4 = new Cartesian3_default();
function createUniformMap3(primitive, context) {
if (defined_default(primitive._uniformMap)) {
return;
}
primitive._uniformMap = {
u_modifiedModelView: function() {
const viewMatrix = context.uniformState.view;
Matrix4_default.clone(viewMatrix, modifiedModelViewScratch4);
Matrix4_default.multiplyByPoint(
modifiedModelViewScratch4,
primitive._center,
rtcScratch4
);
Matrix4_default.setTranslation(
modifiedModelViewScratch4,
rtcScratch4,
modifiedModelViewScratch4
);
return modifiedModelViewScratch4;
},
u_highlightColor: function() {
return primitive._highlightColor;
},
u_minimumMaximumVectorHeights: function() {
return primitive._minimumMaximumVectorHeights;
}
};
}
function getRenderState2(mask3DTiles) {
return RenderState_default.fromCache({
cull: {
enabled: true,
face: CullFace_default.FRONT
},
blending: BlendingState_default.PRE_MULTIPLIED_ALPHA_BLEND,
depthMask: false,
stencilTest: {
enabled: mask3DTiles,
frontFunction: StencilFunction_default.EQUAL,
frontOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.KEEP
},
backFunction: StencilFunction_default.EQUAL,
backOperation: {
fail: StencilOperation_default.KEEP,
zFail: StencilOperation_default.KEEP,
zPass: StencilOperation_default.KEEP
},
reference: StencilConstants_default.CESIUM_3D_TILE_MASK,
mask: StencilConstants_default.CESIUM_3D_TILE_MASK
}
});
}
function createRenderStates5(primitive) {
if (defined_default(primitive._rs)) {
return;
}
primitive._rs = getRenderState2(false);
primitive._rs3DTiles = getRenderState2(true);
}
function createShaders3(primitive, context) {
if (defined_default(primitive._sp)) {
return;
}
const batchTable = primitive._batchTable;
const vsSource = batchTable.getVertexShaderCallback(
false,
"a_batchId",
void 0
)(Vector3DTileClampedPolylinesVS_default);
const fsSource = batchTable.getFragmentShaderCallback(
false,
void 0,
true
)(Vector3DTileClampedPolylinesFS_default);
const vs = new ShaderSource_default({
defines: [
"VECTOR_TILE",
!FeatureDetection_default.isInternetExplorer() ? "CLIP_POLYLINE" : ""
],
sources: [PolylineCommon_default, vsSource]
});
const fs = new ShaderSource_default({
defines: ["VECTOR_TILE"],
sources: [fsSource]
});
primitive._sp = ShaderProgram_default.fromCache({
context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations4
});
}
function queueCommands3(primitive, frameState) {
let command = primitive._command;
if (!defined_default(primitive._command)) {
const uniformMap2 = primitive._batchTable.getUniformMapCallback()(
primitive._uniformMap
);
command = primitive._command = new DrawCommand_default({
owner: primitive,
vertexArray: primitive._va,
renderState: primitive._rs,
shaderProgram: primitive._sp,
uniformMap: uniformMap2,
boundingVolume: primitive._boundingVolume,
pass: Pass_default.TERRAIN_CLASSIFICATION,
pickId: primitive._batchTable.getPickId()
});
const derivedTilesetCommand = DrawCommand_default.shallowClone(
command,
command.derivedCommands.tileset
);
derivedTilesetCommand.renderState = primitive._rs3DTiles;
derivedTilesetCommand.pass = Pass_default.CESIUM_3D_TILE_CLASSIFICATION;
command.derivedCommands.tileset = derivedTilesetCommand;
}
const classificationType = primitive._classificationType;
if (classificationType === ClassificationType_default.TERRAIN || classificationType === ClassificationType_default.BOTH) {
frameState.commandList.push(command);
}
if (classificationType === ClassificationType_default.CESIUM_3D_TILE || classificationType === ClassificationType_default.BOTH) {
frameState.commandList.push(command.derivedCommands.tileset);
}
}
Vector3DTileClampedPolylines.prototype.getPositions = function(batchId) {
return Vector3DTilePolylines_default.getPolylinePositions(this, batchId);
};
Vector3DTileClampedPolylines.prototype.createFeatures = function(content, features) {
const batchIds = this._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
features[batchId] = new Cesium3DTileFeature_default(content, batchId);
}
};
Vector3DTileClampedPolylines.prototype.applyDebugSettings = function(enabled, color) {
this._highlightColor = enabled ? color : this._constantColor;
};
function clearStyle4(polygons, features) {
const batchIds = polygons._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
feature.show = true;
feature.color = Color_default.WHITE;
}
}
var scratchColor10 = new Color_default();
var DEFAULT_COLOR_VALUE4 = Color_default.WHITE;
var DEFAULT_SHOW_VALUE4 = true;
Vector3DTileClampedPolylines.prototype.applyStyle = function(style, features) {
if (!defined_default(style)) {
clearStyle4(this, features);
return;
}
const batchIds = this._batchIds;
const length3 = batchIds.length;
for (let i = 0; i < length3; ++i) {
const batchId = batchIds[i];
const feature = features[batchId];
feature.color = defined_default(style.color) ? style.color.evaluateColor(feature, scratchColor10) : DEFAULT_COLOR_VALUE4;
feature.show = defined_default(style.show) ? style.show.evaluate(feature) : DEFAULT_SHOW_VALUE4;
}
};
function initialize15(polylines) {
return ApproximateTerrainHeights_default.initialize().then(function() {
updateMinimumMaximumHeights(
polylines,
polylines._rectangle,
polylines._ellipsoid
);
}).catch((error) => {
if (polylines.isDestroyed()) {
return;
}
polylines._error = error;
});
}
Vector3DTileClampedPolylines.prototype.update = function(frameState) {
const context = frameState.context;
if (!this._ready) {
if (!defined_default(this._promise)) {
this._promise = initialize15(this).then(createVertexArray5(this, context));
}
if (defined_default(this._error)) {
const error = this._error;
this._error = void 0;
throw error;
}
return;
}
createUniformMap3(this, context);
createShaders3(this, context);
createRenderStates5(this);
const passes = frameState.passes;
if (passes.render || passes.pick) {
queueCommands3(this, frameState);
}
};
Vector3DTileClampedPolylines.prototype.isDestroyed = function() {
return false;
};
Vector3DTileClampedPolylines.prototype.destroy = function() {
this._va = this._va && this._va.destroy();
this._sp = this._sp && this._sp.destroy();
return destroyObject_default(this);
};
var Vector3DTileClampedPolylines_default = Vector3DTileClampedPolylines;
// node_modules/@cesium/engine/Source/Core/decodeVectorPolylinePositions.js
var maxShort = 32767;
var scratchBVCartographic2 = new Cartographic_default();
var scratchEncodedPosition = new Cartesian3_default();
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_default.zigZagDeltaDecode(uBuffer, vBuffer, heightBuffer);
const decoded = new Float64Array(positions.length);
for (let i = 0; i < positionsLength; ++i) {
const u3 = uBuffer[i];
const v7 = vBuffer[i];
const h = heightBuffer[i];
const lon = Math_default.lerp(rectangle.west, rectangle.east, u3 / maxShort);
const lat = Math_default.lerp(rectangle.south, rectangle.north, v7 / maxShort);
const alt = Math_default.lerp(minimumHeight, maximumHeight, h / maxShort);
const cartographic2 = Cartographic_default.fromRadians(
lon,
lat,
alt,
scratchBVCartographic2
);
const decodedPosition = ellipsoid.cartographicToCartesian(
cartographic2,
scratchEncodedPosition
);
Cartesian3_default.pack(decodedPosition, decoded, i * 3);
}
return decoded;
}
var decodeVectorPolylinePositions_default = decodeVectorPolylinePositions;
// node_modules/@cesium/engine/Source/Scene/Vector3DTileContent.js
function Vector3DTileContent(tileset, tile, resource, arrayBuffer, byteOffset) {
this._tileset = tileset;
this._tile = tile;
this._resource = resource;
this._polygons = void 0;
this._polylines = void 0;
this._points = void 0;
this._metadata = void 0;
this._batchTable = void 0;
this._features = void 0;
this.featurePropertiesDirty = false;
this._group = void 0;
this._ready = false;
this._resolveContent = void 0;
this._readyPromise = new Promise((resolve2) => {
this._resolveContent = resolve2;
});
initialize16(this, arrayBuffer, byteOffset);
}
Object.defineProperties(Vector3DTileContent.prototype, {
featuresLength: {
get: function() {
return defined_default(this._batchTable) ? this._batchTable.featuresLength : 0;
}
},
pointsLength: {
get: function() {
if (defined_default(this._points)) {
return this._points.pointsLength;
}
return 0;
}
},
trianglesLength: {
get: function() {
let trianglesLength = 0;
if (defined_default(this._polygons)) {
trianglesLength += this._polygons.trianglesLength;
}
if (defined_default(this._polylines)) {
trianglesLength += this._polylines.trianglesLength;
}
return trianglesLength;
}
},
geometryByteLength: {
get: function() {
let geometryByteLength = 0;
if (defined_default(this._polygons)) {
geometryByteLength += this._polygons.geometryByteLength;
}
if (defined_default(this._polylines)) {
geometryByteLength += this._polylines.geometryByteLength;
}
return geometryByteLength;
}
},
texturesByteLength: {
get: function() {
if (defined_default(this._points)) {
return this._points.texturesByteLength;
}
return 0;
}
},
batchTableByteLength: {
get: function() {
return defined_default(this._batchTable) ? this._batchTable.batchTableByteLength : 0;
}
},
innerContents: {
get: function() {
return void 0;
}
},
ready: {
get: function() {
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Vector3DTileContent.readyPromise",
"Vector3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Vector3DTileContent.ready to return true instead."
);
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 createColorChangedCallback2(content) {
return function(batchId, color) {
if (defined_default(content._polygons)) {
content._polygons.updateCommands(batchId, color);
}
};
}
function getBatchIds2(featureTableJson, featureTableBinary) {
let polygonBatchIds;
let polylineBatchIds;
let pointBatchIds;
let i;
const numberOfPolygons = defaultValue_default(featureTableJson.POLYGONS_LENGTH, 0);
const numberOfPolylines = defaultValue_default(featureTableJson.POLYLINES_LENGTH, 0);
const numberOfPoints = defaultValue_default(featureTableJson.POINTS_LENGTH, 0);
if (numberOfPolygons > 0 && defined_default(featureTableJson.POLYGON_BATCH_IDS)) {
const polygonBatchIdsByteOffset = featureTableBinary.byteOffset + featureTableJson.POLYGON_BATCH_IDS.byteOffset;
polygonBatchIds = new Uint16Array(
featureTableBinary.buffer,
polygonBatchIdsByteOffset,
numberOfPolygons
);
}
if (numberOfPolylines > 0 && defined_default(featureTableJson.POLYLINE_BATCH_IDS)) {
const polylineBatchIdsByteOffset = featureTableBinary.byteOffset + featureTableJson.POLYLINE_BATCH_IDS.byteOffset;
polylineBatchIds = new Uint16Array(
featureTableBinary.buffer,
polylineBatchIdsByteOffset,
numberOfPolylines
);
}
if (numberOfPoints > 0 && defined_default(featureTableJson.POINT_BATCH_IDS)) {
const pointBatchIdsByteOffset = featureTableBinary.byteOffset + featureTableJson.POINT_BATCH_IDS.byteOffset;
pointBatchIds = new Uint16Array(
featureTableBinary.buffer,
pointBatchIdsByteOffset,
numberOfPoints
);
}
const atLeastOneDefined = defined_default(polygonBatchIds) || defined_default(polylineBatchIds) || defined_default(pointBatchIds);
const atLeastOneUndefined = numberOfPolygons > 0 && !defined_default(polygonBatchIds) || numberOfPolylines > 0 && !defined_default(polylineBatchIds) || numberOfPoints > 0 && !defined_default(pointBatchIds);
if (atLeastOneDefined && atLeastOneUndefined) {
throw new RuntimeError_default(
"If one group of batch ids is defined, then all batch ids must be defined"
);
}
const allUndefinedBatchIds = !defined_default(polygonBatchIds) && !defined_default(polylineBatchIds) && !defined_default(pointBatchIds);
if (allUndefinedBatchIds) {
let id = 0;
if (!defined_default(polygonBatchIds) && numberOfPolygons > 0) {
polygonBatchIds = new Uint16Array(numberOfPolygons);
for (i = 0; i < numberOfPolygons; ++i) {
polygonBatchIds[i] = id++;
}
}
if (!defined_default(polylineBatchIds) && numberOfPolylines > 0) {
polylineBatchIds = new Uint16Array(numberOfPolylines);
for (i = 0; i < numberOfPolylines; ++i) {
polylineBatchIds[i] = id++;
}
}
if (!defined_default(pointBatchIds) && numberOfPoints > 0) {
pointBatchIds = new Uint16Array(numberOfPoints);
for (i = 0; i < numberOfPoints; ++i) {
pointBatchIds[i] = id++;
}
}
}
return {
polygons: polygonBatchIds,
polylines: polylineBatchIds,
points: pointBatchIds
};
}
var sizeOfUint327 = Uint32Array.BYTES_PER_ELEMENT;
function createFloatingPolylines(options) {
return new Vector3DTilePolylines_default(options);
}
function createClampedPolylines(options) {
return new Vector3DTileClampedPolylines_default(options);
}
function initialize16(content, arrayBuffer, byteOffset) {
byteOffset = defaultValue_default(byteOffset, 0);
const uint8Array = new Uint8Array(arrayBuffer);
const view = new DataView(arrayBuffer);
byteOffset += sizeOfUint327;
const version2 = view.getUint32(byteOffset, true);
if (version2 !== 1) {
throw new RuntimeError_default(
`Only Vector tile version 1 is supported. Version ${version2} is not.`
);
}
byteOffset += sizeOfUint327;
const byteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
if (byteLength === 0) {
content._ready = true;
content._resolveContent(content);
return;
}
const featureTableJSONByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
if (featureTableJSONByteLength === 0) {
throw new RuntimeError_default(
"Feature table must have a byte length greater than zero"
);
}
const featureTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
const batchTableJSONByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
const batchTableBinaryByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
const indicesByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
const positionByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
const polylinePositionByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
const pointsPositionByteLength = view.getUint32(byteOffset, true);
byteOffset += sizeOfUint327;
const featureTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
featureTableJSONByteLength
);
byteOffset += featureTableJSONByteLength;
const featureTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
featureTableBinaryByteLength
);
byteOffset += featureTableBinaryByteLength;
let batchTableJson;
let batchTableBinary;
if (batchTableJSONByteLength > 0) {
batchTableJson = getJsonFromTypedArray_default(
uint8Array,
byteOffset,
batchTableJSONByteLength
);
byteOffset += batchTableJSONByteLength;
if (batchTableBinaryByteLength > 0) {
batchTableBinary = new Uint8Array(
arrayBuffer,
byteOffset,
batchTableBinaryByteLength
);
batchTableBinary = new Uint8Array(batchTableBinary);
byteOffset += batchTableBinaryByteLength;
}
}
const numberOfPolygons = defaultValue_default(featureTableJson.POLYGONS_LENGTH, 0);
const numberOfPolylines = defaultValue_default(featureTableJson.POLYLINES_LENGTH, 0);
const numberOfPoints = defaultValue_default(featureTableJson.POINTS_LENGTH, 0);
const totalPrimitives = numberOfPolygons + numberOfPolylines + numberOfPoints;
const batchTable = new Cesium3DTileBatchTable_default(
content,
totalPrimitives,
batchTableJson,
batchTableBinary,
createColorChangedCallback2(content)
);
content._batchTable = batchTable;
if (totalPrimitives === 0) {
return;
}
const featureTable = new Cesium3DTileFeatureTable_default(
featureTableJson,
featureTableBinary
);
const region = featureTable.getGlobalProperty("REGION");
if (!defined_default(region)) {
throw new RuntimeError_default(
"Feature table global property: REGION must be defined"
);
}
const rectangle = Rectangle_default.unpack(region);
const minHeight = region[4];
const maxHeight = region[5];
const modelMatrix = content._tile.computedTransform;
let center = featureTable.getGlobalProperty(
"RTC_CENTER",
ComponentDatatype_default.FLOAT,
3
);
if (defined_default(center)) {
center = Cartesian3_default.unpack(center);
Matrix4_default.multiplyByPoint(modelMatrix, center, center);
} else {
center = Rectangle_default.center(rectangle);
center.height = Math_default.lerp(minHeight, maxHeight, 0.5);
center = Ellipsoid_default.WGS84.cartographicToCartesian(center);
}
const batchIds = getBatchIds2(featureTableJson, featureTableBinary);
byteOffset += (4 - byteOffset % 4) % 4;
if (numberOfPolygons > 0) {
featureTable.featuresLength = numberOfPolygons;
const polygonCounts = defaultValue_default(
featureTable.getPropertyArray(
"POLYGON_COUNTS",
ComponentDatatype_default.UNSIGNED_INT,
1
),
featureTable.getPropertyArray(
"POLYGON_COUNT",
ComponentDatatype_default.UNSIGNED_INT,
1
)
);
if (!defined_default(polygonCounts)) {
throw new RuntimeError_default(
"Feature table property: POLYGON_COUNTS must be defined when POLYGONS_LENGTH is greater than 0"
);
}
const polygonIndexCounts = defaultValue_default(
featureTable.getPropertyArray(
"POLYGON_INDEX_COUNTS",
ComponentDatatype_default.UNSIGNED_INT,
1
),
featureTable.getPropertyArray(
"POLYGON_INDEX_COUNT",
ComponentDatatype_default.UNSIGNED_INT,
1
)
);
if (!defined_default(polygonIndexCounts)) {
throw new RuntimeError_default(
"Feature table property: POLYGON_INDEX_COUNTS must be defined when POLYGONS_LENGTH is greater than 0"
);
}
const numPolygonPositions = polygonCounts.reduce(function(total, count) {
return total + count * 2;
}, 0);
const numPolygonIndices = polygonIndexCounts.reduce(
function(total, count) {
return total + count;
},
0
);
const indices2 = new Uint32Array(arrayBuffer, byteOffset, numPolygonIndices);
byteOffset += indicesByteLength;
const polygonPositions = new Uint16Array(
arrayBuffer,
byteOffset,
numPolygonPositions
);
byteOffset += positionByteLength;
let polygonMinimumHeights;
let polygonMaximumHeights;
if (defined_default(featureTableJson.POLYGON_MINIMUM_HEIGHTS) && defined_default(featureTableJson.POLYGON_MAXIMUM_HEIGHTS)) {
polygonMinimumHeights = featureTable.getPropertyArray(
"POLYGON_MINIMUM_HEIGHTS",
ComponentDatatype_default.FLOAT,
1
);
polygonMaximumHeights = featureTable.getPropertyArray(
"POLYGON_MAXIMUM_HEIGHTS",
ComponentDatatype_default.FLOAT,
1
);
}
content._polygons = new Vector3DTilePolygons_default({
positions: polygonPositions,
counts: polygonCounts,
indexCounts: polygonIndexCounts,
indices: indices2,
minimumHeight: minHeight,
maximumHeight: maxHeight,
polygonMinimumHeights,
polygonMaximumHeights,
center,
rectangle,
boundingVolume: content.tile.boundingVolume.boundingVolume,
batchTable,
batchIds: batchIds.polygons,
modelMatrix
});
}
if (numberOfPolylines > 0) {
featureTable.featuresLength = numberOfPolylines;
const polylineCounts = defaultValue_default(
featureTable.getPropertyArray(
"POLYLINE_COUNTS",
ComponentDatatype_default.UNSIGNED_INT,
1
),
featureTable.getPropertyArray(
"POLYLINE_COUNT",
ComponentDatatype_default.UNSIGNED_INT,
1
)
);
if (!defined_default(polylineCounts)) {
throw new RuntimeError_default(
"Feature table property: POLYLINE_COUNTS must be defined when POLYLINES_LENGTH is greater than 0"
);
}
let widths = featureTable.getPropertyArray(
"POLYLINE_WIDTHS",
ComponentDatatype_default.UNSIGNED_SHORT,
1
);
if (!defined_default(widths)) {
widths = new Uint16Array(numberOfPolylines);
for (let i = 0; i < numberOfPolylines; ++i) {
widths[i] = 2;
}
}
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_default(examineVectorLinesFunction)) {
const decodedPositions = decodeVectorPolylinePositions_default(
new Uint16Array(polylinePositions),
rectangle,
minHeight,
maxHeight,
Ellipsoid_default.WGS84
);
examineVectorLines(
decodedPositions,
polylineCounts,
batchIds.polylines,
batchTable,
content.url,
examineVectorLinesFunction
);
}
let createPolylines = createFloatingPolylines;
if (defined_default(tileset.classificationType)) {
createPolylines = createClampedPolylines;
}
content._polylines = createPolylines({
positions: polylinePositions,
widths,
counts: polylineCounts,
batchIds: batchIds.polylines,
minimumHeight: minHeight,
maximumHeight: maxHeight,
center,
rectangle,
boundingVolume: content.tile.boundingVolume.boundingVolume,
batchTable,
classificationType: tileset.classificationType,
keepDecodedPositions: tileset.vectorKeepDecodedPositions
});
}
if (numberOfPoints > 0) {
const pointPositions = new Uint16Array(
arrayBuffer,
byteOffset,
numberOfPoints * 3
);
byteOffset += pointsPositionByteLength;
content._points = new Vector3DTilePoints_default({
positions: pointPositions,
batchIds: batchIds.points,
minimumHeight: minHeight,
maximumHeight: maxHeight,
rectangle,
batchTable
});
}
}
function createFeatures2(content) {
const featuresLength = content.featuresLength;
if (!defined_default(content._features) && featuresLength > 0) {
const features = new Array(featuresLength);
if (defined_default(content._polygons)) {
content._polygons.createFeatures(content, features);
}
if (defined_default(content._polylines)) {
content._polylines.createFeatures(content, features);
}
if (defined_default(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) {
const featuresLength = this.featuresLength;
if (!defined_default(batchId) || batchId < 0 || batchId >= featuresLength) {
throw new DeveloperError_default(
`batchId is required and between zero and featuresLength - 1 (${featuresLength - 1}).`
);
}
if (!defined_default(this._features)) {
createFeatures2(this);
}
return this._features[batchId];
};
Vector3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
if (defined_default(this._polygons)) {
this._polygons.applyDebugSettings(enabled, color);
}
if (defined_default(this._polylines)) {
this._polylines.applyDebugSettings(enabled, color);
}
if (defined_default(this._points)) {
this._points.applyDebugSettings(enabled, color);
}
};
Vector3DTileContent.prototype.applyStyle = function(style) {
if (!defined_default(this._features)) {
createFeatures2(this);
}
if (defined_default(this._polygons)) {
this._polygons.applyStyle(style, this._features);
}
if (defined_default(this._polylines)) {
this._polylines.applyStyle(style, this._features);
}
if (defined_default(this._points)) {
this._points.applyStyle(style, this._features);
}
};
Vector3DTileContent.prototype.update = function(tileset, frameState) {
let ready = true;
if (defined_default(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_default(this._polylines)) {
this._polylines.update(frameState);
ready = ready && this._polylines.ready;
}
if (defined_default(this._points)) {
this._points.update(frameState);
ready = ready && this._points.ready;
}
if (defined_default(this._batchTable) && ready) {
if (!defined_default(this._features)) {
createFeatures2(this);
}
this._batchTable.update(tileset, frameState);
this._ready = true;
this._resolveContent(this);
}
};
Vector3DTileContent.prototype.getPolylinePositions = function(batchId) {
const polylines = this._polylines;
if (!defined_default(polylines)) {
return void 0;
}
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_default(this);
};
function examineVectorLines(positions, counts, batchIds, batchTable, url2, 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], url2, batchTable);
}
}
var Vector3DTileContent_default = Vector3DTileContent;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileContentFactory.js
var Cesium3DTileContentFactory = {
b3dm: function(tileset, tile, resource, arrayBuffer, byteOffset) {
return Model3DTileContent_default.fromB3dm(
tileset,
tile,
resource,
arrayBuffer,
byteOffset
);
},
pnts: function(tileset, tile, resource, arrayBuffer, byteOffset) {
return Model3DTileContent_default.fromPnts(
tileset,
tile,
resource,
arrayBuffer,
byteOffset
);
},
i3dm: function(tileset, tile, resource, arrayBuffer, byteOffset) {
return Model3DTileContent_default.fromI3dm(
tileset,
tile,
resource,
arrayBuffer,
byteOffset
);
},
cmpt: function(tileset, tile, resource, arrayBuffer, byteOffset) {
return Composite3DTileContent_default.fromTileType(
tileset,
tile,
resource,
arrayBuffer,
byteOffset,
Cesium3DTileContentFactory
);
},
externalTileset: function(tileset, tile, resource, json) {
return Tileset3DTileContent_default.fromJson(tileset, tile, resource, json);
},
geom: function(tileset, tile, resource, arrayBuffer, byteOffset) {
return new Geometry3DTileContent_default(
tileset,
tile,
resource,
arrayBuffer,
byteOffset
);
},
vctr: function(tileset, tile, resource, arrayBuffer, byteOffset) {
return new Vector3DTileContent_default(
tileset,
tile,
resource,
arrayBuffer,
byteOffset
);
},
subt: function(tileset, tile, resource, arrayBuffer, byteOffset) {
return Implicit3DTileContent_default.fromSubtreeJson(
tileset,
tile,
resource,
void 0,
arrayBuffer,
byteOffset
);
},
subtreeJson: function(tileset, tile, resource, json) {
return Implicit3DTileContent_default.fromSubtreeJson(tileset, tile, resource, json);
},
glb: function(tileset, tile, resource, arrayBuffer, byteOffset) {
const arrayBufferByteLength = arrayBuffer.byteLength;
if (arrayBufferByteLength < 12) {
throw new RuntimeError_default("Invalid glb content");
}
const dataView = new DataView(arrayBuffer, byteOffset);
const byteLength = dataView.getUint32(8, true);
const glb = new Uint8Array(arrayBuffer, byteOffset, byteLength);
return Model3DTileContent_default.fromGltf(tileset, tile, resource, glb);
},
gltf: function(tileset, tile, resource, json) {
return Model3DTileContent_default.fromGltf(tileset, tile, resource, json);
},
geoJson: function(tileset, tile, resource, json) {
return Model3DTileContent_default.fromGeoJson(tileset, tile, resource, json);
}
};
var Cesium3DTileContentFactory_default = Cesium3DTileContentFactory;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileContentState.js
var Cesium3DTileContentState = {
UNLOADED: 0,
LOADING: 1,
PROCESSING: 2,
READY: 3,
EXPIRED: 4,
FAILED: 5
};
var Cesium3DTileContentState_default = Object.freeze(Cesium3DTileContentState);
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileContentType.js
var Cesium3DTileContentType = {
BATCHED_3D_MODEL: "b3dm",
INSTANCED_3D_MODEL: "i3dm",
COMPOSITE: "cmpt",
POINT_CLOUD: "pnts",
VECTOR: "vctr",
GEOMETRY: "geom",
GLTF: "gltf",
GLTF_BINARY: "glb",
IMPLICIT_SUBTREE: "subt",
IMPLICIT_SUBTREE_JSON: "subtreeJson",
EXTERNAL_TILESET: "externalTileset",
MULTIPLE_CONTENT: "multipleContent",
GEOJSON: "geoJson",
VOXEL_BINARY: "voxl",
VOXEL_JSON: "voxelJson"
};
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.VOXEL_BINARY:
case Cesium3DTileContentType.GLTF_BINARY:
return true;
default:
return false;
}
};
var Cesium3DTileContentType_default = Object.freeze(Cesium3DTileContentType);
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileOptimizationHint.js
var Cesium3DTileOptimizationHint = {
NOT_COMPUTED: -1,
USE_OPTIMIZATION: 1,
SKIP_OPTIMIZATION: 0
};
var Cesium3DTileOptimizationHint_default = Object.freeze(Cesium3DTileOptimizationHint);
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilePass.js
var 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
};
var passOptions = new Array(Cesium3DTilePass.NUMBER_OF_PASSES);
passOptions[Cesium3DTilePass.RENDER] = Object.freeze({
pass: Cesium3DTilePass.RENDER,
isRender: true,
requestTiles: true,
ignoreCommands: false
});
passOptions[Cesium3DTilePass.PICK] = Object.freeze({
pass: Cesium3DTilePass.PICK,
isRender: false,
requestTiles: false,
ignoreCommands: false
});
passOptions[Cesium3DTilePass.SHADOW] = Object.freeze({
pass: Cesium3DTilePass.SHADOW,
isRender: false,
requestTiles: true,
ignoreCommands: false
});
passOptions[Cesium3DTilePass.PRELOAD] = Object.freeze({
pass: Cesium3DTilePass.SHADOW,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.PRELOAD_FLIGHT] = Object.freeze({
pass: Cesium3DTilePass.PRELOAD_FLIGHT,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK] = Object.freeze({
pass: Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.MOST_DETAILED_PRELOAD] = Object.freeze({
pass: Cesium3DTilePass.MOST_DETAILED_PRELOAD,
isRender: false,
requestTiles: true,
ignoreCommands: true
});
passOptions[Cesium3DTilePass.MOST_DETAILED_PICK] = Object.freeze({
pass: Cesium3DTilePass.MOST_DETAILED_PICK,
isRender: false,
requestTiles: false,
ignoreCommands: false
});
Cesium3DTilePass.getPassOptions = function(pass) {
return passOptions[pass];
};
var Cesium3DTilePass_default = Object.freeze(Cesium3DTilePass);
// node_modules/@cesium/engine/Source/Scene/Empty3DTileContent.js
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 void 0;
}
},
ready: {
get: function() {
return true;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Empty3DTileContent.readyPromise",
"Empty3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Empty3DTileContent.ready to return true instead."
);
return Promise.resolve(this);
}
},
tileset: {
get: function() {
return this._tileset;
}
},
tile: {
get: function() {
return this._tile;
}
},
url: {
get: function() {
return void 0;
}
},
metadata: {
get: function() {
return void 0;
},
set: function(value) {
throw new DeveloperError_default(
"Empty3DTileContent cannot have content metadata"
);
}
},
batchTable: {
get: function() {
return void 0;
}
},
group: {
get: function() {
return void 0;
},
set: function(value) {
throw new DeveloperError_default("Empty3DTileContent cannot have group metadata");
}
}
});
Empty3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Empty3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
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_default(this);
};
var Empty3DTileContent_default = Empty3DTileContent;
// node_modules/@cesium/engine/Source/Scene/ContentMetadata.js
function ContentMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const content = options.content;
const metadataClass = options.class;
Check_default.typeOf.object("options.content", content);
Check_default.typeOf.object("options.class", metadataClass);
this._class = metadataClass;
this._properties = content.properties;
this._extensions = content.extensions;
this._extras = content.extras;
}
Object.defineProperties(ContentMetadata.prototype, {
class: {
get: function() {
return this._class;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
ContentMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
ContentMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
ContentMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
ContentMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
ContentMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
ContentMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
ContentMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var ContentMetadata_default = ContentMetadata;
// node_modules/@cesium/engine/Source/Scene/findContentMetadata.js
function findContentMetadata(tileset, contentHeader) {
const metadataJson = hasExtension_default(contentHeader, "3DTILES_metadata") ? contentHeader.extensions["3DTILES_metadata"] : contentHeader.metadata;
if (!defined_default(metadataJson)) {
return void 0;
}
if (!defined_default(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 void 0;
}
const classes = defaultValue_default(
tileset.schema.classes,
defaultValue_default.EMPTY_OBJECT
);
if (defined_default(metadataJson.class)) {
const contentClass = classes[metadataJson.class];
return new ContentMetadata_default({
content: metadataJson,
class: contentClass
});
}
return void 0;
}
findContentMetadata._oneTimeWarning = oneTimeWarning_default;
var findContentMetadata_default = findContentMetadata;
// node_modules/@cesium/engine/Source/Scene/findGroupMetadata.js
function findGroupMetadata(tileset, contentHeader) {
const metadataExtension = tileset.metadataExtension;
if (!defined_default(metadataExtension)) {
return void 0;
}
const groups = metadataExtension.groups;
const group = hasExtension_default(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] : void 0;
}
var findGroupMetadata_default = findGroupMetadata;
// node_modules/@cesium/engine/Source/Scene/TileMetadata.js
function TileMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const tile = options.tile;
const metadataClass = options.class;
Check_default.typeOf.object("options.tile", tile);
Check_default.typeOf.object("options.class", metadataClass);
this._class = metadataClass;
this._properties = tile.properties;
this._extensions = tile.extensions;
this._extras = tile.extras;
}
Object.defineProperties(TileMetadata.prototype, {
class: {
get: function() {
return this._class;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
TileMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
TileMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
TileMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
TileMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
TileMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
TileMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
TileMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var TileMetadata_default = TileMetadata;
// node_modules/@cesium/engine/Source/Scene/findTileMetadata.js
function findTileMetadata(tileset, tileHeader) {
const metadataJson = hasExtension_default(tileHeader, "3DTILES_metadata") ? tileHeader.extensions["3DTILES_metadata"] : tileHeader.metadata;
if (!defined_default(metadataJson)) {
return void 0;
}
if (!defined_default(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 void 0;
}
const classes = defaultValue_default(
tileset.schema.classes,
defaultValue_default.EMPTY_OBJECT
);
if (defined_default(metadataJson.class)) {
const tileClass = classes[metadataJson.class];
return new TileMetadata_default({
tile: metadataJson,
class: tileClass
});
}
return void 0;
}
findTileMetadata._oneTimeWarning = oneTimeWarning_default;
var findTileMetadata_default = findTileMetadata;
// node_modules/@cesium/engine/Source/Scene/preprocess3DTileContent.js
function preprocess3DTileContent(arrayBuffer) {
const uint8Array = new Uint8Array(arrayBuffer);
let contentType = getMagic_default(uint8Array);
if (contentType === "glTF") {
contentType = "glb";
}
if (Cesium3DTileContentType_default.isBinaryFormat(contentType)) {
return {
contentType,
binaryPayload: uint8Array
};
}
const json = getJsonContent(uint8Array);
if (defined_default(json.root)) {
return {
contentType: Cesium3DTileContentType_default.EXTERNAL_TILESET,
jsonPayload: json
};
}
if (defined_default(json.asset)) {
return {
contentType: Cesium3DTileContentType_default.GLTF,
jsonPayload: json
};
}
if (defined_default(json.tileAvailability)) {
return {
contentType: Cesium3DTileContentType_default.IMPLICIT_SUBTREE_JSON,
jsonPayload: json
};
}
if (defined_default(json.type)) {
return {
contentType: Cesium3DTileContentType_default.GEOJSON,
jsonPayload: json
};
}
if (defined_default(json.voxelTable)) {
return {
contentType: Cesium3DTileContentType_default.VOXEL_JSON,
jsonPayload: json
};
}
throw new RuntimeError_default("Invalid tile content.");
}
function getJsonContent(uint8Array) {
let json;
try {
json = getJsonFromTypedArray_default(uint8Array);
} catch (error) {
throw new RuntimeError_default("Invalid tile content.");
}
return json;
}
var preprocess3DTileContent_default = preprocess3DTileContent;
// node_modules/@cesium/engine/Source/Scene/Multiple3DTileContent.js
function Multiple3DTileContent(tileset, tile, tilesetResource, contentsJson) {
this._tileset = tileset;
this._tile = tile;
this._tilesetResource = tilesetResource;
this._contents = [];
this._contentsCreated = false;
const contentHeaders = defined_default(contentsJson.contents) ? contentsJson.contents : contentsJson.content;
this._innerContentHeaders = contentHeaders;
this._requestsInFlight = 0;
this._cancelCount = 0;
const contentCount = this._innerContentHeaders.length;
this._arrayFetchPromises = new Array(contentCount);
this._requests = new Array(contentCount);
this._ready = false;
this._resolveContent = void 0;
this._readyPromise = new Promise((resolve2) => {
this._resolveContent = resolve2;
});
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_default.getServerKey(
contentResource.getUrlComponent()
);
this._innerContentResources[i] = contentResource;
this._serverKeys[i] = serverKey;
}
}
Object.defineProperties(Multiple3DTileContent.prototype, {
featurePropertiesDirty: {
get: function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
if (contents[i].featurePropertiesDirty) {
return true;
}
}
return false;
},
set: function(value) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].featurePropertiesDirty = value;
}
}
},
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 this._contents;
}
},
ready: {
get: function() {
if (!this._contentsCreated) {
return false;
}
return this._ready;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Multiple3DTileContent.readyPromise",
"Multiple3DTileContent.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Wait for Multiple3DTileContent.ready to return true instead."
);
return this._readyPromise;
}
},
tileset: {
get: function() {
return this._tileset;
}
},
tile: {
get: function() {
return this._tile;
}
},
url: {
get: function() {
return void 0;
}
},
metadata: {
get: function() {
return void 0;
},
set: function() {
throw new DeveloperError_default("Multiple3DTileContent cannot have metadata");
}
},
batchTable: {
get: function() {
return void 0;
}
},
group: {
get: function() {
return void 0;
},
set: function() {
throw new DeveloperError_default(
"Multiple3DTileContent cannot have group metadata"
);
}
},
innerContentUrls: {
get: function() {
return this._innerContentHeaders.map(function(contentHeader) {
return contentHeader.uri;
});
}
}
});
function updatePendingRequests(multipleContents, deltaRequestCount) {
multipleContents._requestsInFlight += deltaRequestCount;
multipleContents.tileset.statistics.numberOfPendingRequests += deltaRequestCount;
}
function cancelPendingRequests(multipleContents, originalContentState) {
multipleContents._cancelCount++;
multipleContents._tile._contentState = originalContentState;
const statistics2 = multipleContents.tileset.statistics;
statistics2.numberOfPendingRequests -= multipleContents._requestsInFlight;
statistics2.numberOfAttemptedRequests += multipleContents._requestsInFlight;
multipleContents._requestsInFlight = 0;
const contentCount = multipleContents._innerContentHeaders.length;
multipleContents._arrayFetchPromises = new Array(contentCount);
}
Multiple3DTileContent.prototype.requestInnerContents = function() {
if (!canScheduleAllRequests(this._serverKeys)) {
this.tileset.statistics.numberOfAttemptedRequests += this._serverKeys.length;
return;
}
const contentHeaders = this._innerContentHeaders;
updatePendingRequests(this, contentHeaders.length);
const originalCancelCount = this._cancelCount;
for (let i = 0; i < contentHeaders.length; i++) {
this._arrayFetchPromises[i] = requestInnerContent(
this,
i,
originalCancelCount,
this._tile._contentState
);
}
return createInnerContents(this);
};
function canScheduleAllRequests(serverKeys) {
const requestCountsByServer = {};
for (let i = 0; i < serverKeys.length; i++) {
const serverKey = serverKeys[i];
if (defined_default(requestCountsByServer[serverKey])) {
requestCountsByServer[serverKey]++;
} else {
requestCountsByServer[serverKey] = 1;
}
}
for (const key in requestCountsByServer) {
if (requestCountsByServer.hasOwnProperty(key) && !RequestScheduler_default.serverHasOpenSlots(key, requestCountsByServer[key])) {
return false;
}
}
return RequestScheduler_default.heapHasOpenSlots(serverKeys.length);
}
function requestInnerContent(multipleContents, index, originalCancelCount, originalContentState) {
const contentResource = multipleContents._innerContentResources[index].clone();
const tile = multipleContents.tile;
const priorityFunction = function() {
return tile._priority;
};
const serverKey = multipleContents._serverKeys[index];
const request = new Request_default({
throttle: true,
throttleByServer: true,
type: RequestType_default.TILES3D,
priorityFunction,
serverKey
});
contentResource.request = request;
multipleContents._requests[index] = request;
const promise = contentResource.fetchArrayBuffer();
if (!defined_default(promise)) {
return;
}
return promise.then(function(arrayBuffer) {
if (originalCancelCount < multipleContents._cancelCount) {
return;
}
if (contentResource.request.cancelled || contentResource.request.state === RequestState_default.CANCELLED) {
cancelPendingRequests(multipleContents, originalContentState);
return;
}
updatePendingRequests(multipleContents, -1);
return arrayBuffer;
}).catch(function(error) {
if (originalCancelCount < multipleContents._cancelCount) {
return;
}
if (contentResource.request.cancelled || contentResource.request.state === RequestState_default.CANCELLED) {
cancelPendingRequests(multipleContents, originalContentState);
return;
}
updatePendingRequests(multipleContents, -1);
handleInnerContentFailed(multipleContents, index, error);
});
}
async function createInnerContents(multipleContents) {
const originalCancelCount = multipleContents._cancelCount;
const arrayBuffers = await Promise.all(multipleContents._arrayFetchPromises);
if (originalCancelCount < multipleContents._cancelCount) {
return;
}
const promises = arrayBuffers.map(
(arrayBuffer, i) => createInnerContent(multipleContents, arrayBuffer, i)
);
const contents = await Promise.all(promises);
multipleContents._contentsCreated = true;
multipleContents._contents = contents.filter(defined_default);
return contents;
}
async function createInnerContent(multipleContents, arrayBuffer, index) {
if (!defined_default(arrayBuffer)) {
return;
}
try {
const preprocessed = preprocess3DTileContent_default(arrayBuffer);
if (preprocessed.contentType === Cesium3DTileContentType_default.EXTERNAL_TILESET) {
throw new RuntimeError_default(
"External tilesets are disallowed inside multiple contents"
);
}
multipleContents._disableSkipLevelOfDetail = multipleContents._disableSkipLevelOfDetail || preprocessed.contentType === Cesium3DTileContentType_default.GEOMETRY || preprocessed.contentType === Cesium3DTileContentType_default.VECTOR;
const tileset = multipleContents._tileset;
const resource = multipleContents._innerContentResources[index];
const tile = multipleContents._tile;
let content;
const contentFactory = Cesium3DTileContentFactory_default[preprocessed.contentType];
if (defined_default(preprocessed.binaryPayload)) {
content = await Promise.resolve(
contentFactory(
tileset,
tile,
resource,
preprocessed.binaryPayload.buffer,
0
)
);
} else {
content = await Promise.resolve(
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_default(tileset, contentHeader);
}
const groupMetadata = findGroupMetadata_default(tileset, contentHeader);
if (defined_default(groupMetadata)) {
content.group = new Cesium3DContentGroup_default({
metadata: groupMetadata
});
}
return content;
} catch (error) {
handleInnerContentFailed(multipleContents, index, error);
}
}
function handleInnerContentFailed(multipleContents, index, error) {
const tileset = multipleContents._tileset;
const url2 = multipleContents._innerContentResources[index].url;
const message = defined_default(error.message) ? error.message : error.toString();
if (tileset.tileFailed.numberOfListeners > 0) {
tileset.tileFailed.raiseEvent({
url: url2,
message
});
} else {
console.log(`A content failed to load: ${url2}`);
console.log(`Error: ${message}`);
}
}
Multiple3DTileContent.prototype.cancelRequests = function() {
for (let i = 0; i < this._requests.length; i++) {
const request = this._requests[i];
if (defined_default(request)) {
request.cancel();
}
}
};
Multiple3DTileContent.prototype.hasProperty = function(batchId, name) {
return false;
};
Multiple3DTileContent.prototype.getFeature = function(batchId) {
return void 0;
};
Multiple3DTileContent.prototype.applyDebugSettings = function(enabled, color) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyDebugSettings(enabled, color);
}
};
Multiple3DTileContent.prototype.applyStyle = function(style) {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].applyStyle(style);
}
};
Multiple3DTileContent.prototype.update = function(tileset, frameState) {
const contents = this._contents;
const length3 = contents.length;
let ready = true;
for (let i = 0; i < length3; ++i) {
contents[i].update(tileset, frameState);
ready = ready && contents[i].ready;
}
if (!this._ready && ready) {
this._ready = true;
this._resolveContent(this);
}
};
Multiple3DTileContent.prototype.isDestroyed = function() {
return false;
};
Multiple3DTileContent.prototype.destroy = function() {
const contents = this._contents;
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
contents[i].destroy();
}
return destroyObject_default(this);
};
var Multiple3DTileContent_default = Multiple3DTileContent;
// node_modules/@cesium/engine/Source/Core/PolygonPipeline.js
var import_earcut = __toESM(require_earcut(), 1);
var scaleToGeodeticHeightN = new Cartesian3_default();
var scaleToGeodeticHeightP = new Cartesian3_default();
var PolygonPipeline = {};
PolygonPipeline.computeArea2D = function(positions) {
Check_default.defined("positions", positions);
Check_default.typeOf.number.greaterThanOrEquals(
"positions.length",
positions.length,
3
);
const length3 = positions.length;
let area = 0;
for (let i0 = length3 - 1, i1 = 0; i1 < length3; i0 = i1++) {
const v02 = positions[i0];
const v13 = positions[i1];
area += v02.x * v13.y - v13.x * v02.y;
}
return area * 0.5;
};
PolygonPipeline.computeWindingOrder2D = function(positions) {
const area = PolygonPipeline.computeArea2D(positions);
return area > 0 ? WindingOrder_default.COUNTER_CLOCKWISE : WindingOrder_default.CLOCKWISE;
};
PolygonPipeline.triangulate = function(positions, holes) {
Check_default.defined("positions", positions);
const flattenedPositions = Cartesian2_default.packArray(positions);
return (0, import_earcut.default)(flattenedPositions, holes, 2);
};
var subdivisionV0Scratch = new Cartesian3_default();
var subdivisionV1Scratch = new Cartesian3_default();
var subdivisionV2Scratch = new Cartesian3_default();
var subdivisionS0Scratch = new Cartesian3_default();
var subdivisionS1Scratch = new Cartesian3_default();
var subdivisionS2Scratch = new Cartesian3_default();
var subdivisionMidScratch = new Cartesian3_default();
var subdivisionT0Scratch = new Cartesian2_default();
var subdivisionT1Scratch = new Cartesian2_default();
var subdivisionT2Scratch = new Cartesian2_default();
var subdivisionTexcoordMidScratch = new Cartesian2_default();
PolygonPipeline.computeSubdivision = function(ellipsoid, positions, indices2, texcoords, granularity) {
granularity = defaultValue_default(granularity, Math_default.RADIANS_PER_DEGREE);
const hasTexcoords = defined_default(texcoords);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.defined("positions", positions);
Check_default.defined("indices", indices2);
Check_default.typeOf.number.greaterThanOrEquals("indices.length", indices2.length, 3);
Check_default.typeOf.number.equals("indices.length % 3", "0", indices2.length % 3, 0);
Check_default.typeOf.number.greaterThan("granularity", granularity, 0);
const triangles = indices2.slice(0);
let i;
const length3 = positions.length;
const subdividedPositions = new Array(length3 * 3);
const subdividedTexcoords = new Array(length3 * 2);
let q = 0;
let p = 0;
for (i = 0; i < length3; 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 = [];
const edges = {};
const radius = ellipsoid.maximumRadius;
const minDistance = Math_default.chordLength(granularity, radius);
const minDistanceSqrd = minDistance * minDistance;
while (triangles.length > 0) {
const i2 = triangles.pop();
const i1 = triangles.pop();
const i0 = triangles.pop();
const v02 = Cartesian3_default.fromArray(
subdividedPositions,
i0 * 3,
subdivisionV0Scratch
);
const v13 = Cartesian3_default.fromArray(
subdividedPositions,
i1 * 3,
subdivisionV1Scratch
);
const v23 = Cartesian3_default.fromArray(
subdividedPositions,
i2 * 3,
subdivisionV2Scratch
);
let t0, t1, t2;
if (hasTexcoords) {
t0 = Cartesian2_default.fromArray(
subdividedTexcoords,
i0 * 2,
subdivisionT0Scratch
);
t1 = Cartesian2_default.fromArray(
subdividedTexcoords,
i1 * 2,
subdivisionT1Scratch
);
t2 = Cartesian2_default.fromArray(
subdividedTexcoords,
i2 * 2,
subdivisionT2Scratch
);
}
const s0 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.normalize(v02, subdivisionS0Scratch),
radius,
subdivisionS0Scratch
);
const s1 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.normalize(v13, subdivisionS1Scratch),
radius,
subdivisionS1Scratch
);
const s2 = Cartesian3_default.multiplyByScalar(
Cartesian3_default.normalize(v23, subdivisionS2Scratch),
radius,
subdivisionS2Scratch
);
const g0 = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(s0, s1, subdivisionMidScratch)
);
const g1 = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(s1, s2, subdivisionMidScratch)
);
const g2 = Cartesian3_default.magnitudeSquared(
Cartesian3_default.subtract(s2, s0, subdivisionMidScratch)
);
const max3 = Math.max(g0, g1, g2);
let edge;
let mid;
let midTexcoord;
if (max3 > minDistanceSqrd) {
if (g0 === max3) {
edge = `${Math.min(i0, i1)} ${Math.max(i0, i1)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = Cartesian3_default.add(v02, v13, subdivisionMidScratch);
Cartesian3_default.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_default.add(t0, t1, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i0, i, i2);
triangles.push(i, i1, i2);
} else if (g1 === max3) {
edge = `${Math.min(i1, i2)} ${Math.max(i1, i2)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = Cartesian3_default.add(v13, v23, subdivisionMidScratch);
Cartesian3_default.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_default.add(t1, t2, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i1, i, i0);
triangles.push(i, i2, i0);
} else if (g2 === max3) {
edge = `${Math.min(i2, i0)} ${Math.max(i2, i0)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = Cartesian3_default.add(v23, v02, subdivisionMidScratch);
Cartesian3_default.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_default.add(t2, t0, subdivisionTexcoordMidScratch);
Cartesian2_default.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_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: subdividedPositions
})
},
indices: subdividedIndices,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: subdividedTexcoords
});
}
return new Geometry_default(geometryOptions);
};
var subdivisionC0Scratch = new Cartographic_default();
var subdivisionC1Scratch = new Cartographic_default();
var subdivisionC2Scratch = new Cartographic_default();
var subdivisionCartographicScratch = new Cartographic_default();
PolygonPipeline.computeRhumbLineSubdivision = function(ellipsoid, positions, indices2, texcoords, granularity) {
granularity = defaultValue_default(granularity, Math_default.RADIANS_PER_DEGREE);
const hasTexcoords = defined_default(texcoords);
Check_default.typeOf.object("ellipsoid", ellipsoid);
Check_default.defined("positions", positions);
Check_default.defined("indices", indices2);
Check_default.typeOf.number.greaterThanOrEquals("indices.length", indices2.length, 3);
Check_default.typeOf.number.equals("indices.length % 3", "0", indices2.length % 3, 0);
Check_default.typeOf.number.greaterThan("granularity", granularity, 0);
const triangles = indices2.slice(0);
let i;
const length3 = positions.length;
const subdividedPositions = new Array(length3 * 3);
const subdividedTexcoords = new Array(length3 * 2);
let q = 0;
let p = 0;
for (i = 0; i < length3; 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 = [];
const edges = {};
const radius = ellipsoid.maximumRadius;
const minDistance = Math_default.chordLength(granularity, radius);
const rhumb0 = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
const rhumb1 = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
const rhumb2 = new EllipsoidRhumbLine_default(void 0, void 0, ellipsoid);
while (triangles.length > 0) {
const i2 = triangles.pop();
const i1 = triangles.pop();
const i0 = triangles.pop();
const v02 = Cartesian3_default.fromArray(
subdividedPositions,
i0 * 3,
subdivisionV0Scratch
);
const v13 = Cartesian3_default.fromArray(
subdividedPositions,
i1 * 3,
subdivisionV1Scratch
);
const v23 = Cartesian3_default.fromArray(
subdividedPositions,
i2 * 3,
subdivisionV2Scratch
);
let t0, t1, t2;
if (hasTexcoords) {
t0 = Cartesian2_default.fromArray(
subdividedTexcoords,
i0 * 2,
subdivisionT0Scratch
);
t1 = Cartesian2_default.fromArray(
subdividedTexcoords,
i1 * 2,
subdivisionT1Scratch
);
t2 = Cartesian2_default.fromArray(
subdividedTexcoords,
i2 * 2,
subdivisionT2Scratch
);
}
const c0 = ellipsoid.cartesianToCartographic(v02, subdivisionC0Scratch);
const c14 = ellipsoid.cartesianToCartographic(v13, subdivisionC1Scratch);
const c22 = ellipsoid.cartesianToCartographic(v23, subdivisionC2Scratch);
rhumb0.setEndPoints(c0, c14);
const g0 = rhumb0.surfaceDistance;
rhumb1.setEndPoints(c14, c22);
const g1 = rhumb1.surfaceDistance;
rhumb2.setEndPoints(c22, c0);
const g2 = rhumb2.surfaceDistance;
const max3 = Math.max(g0, g1, g2);
let edge;
let mid;
let midHeight;
let midCartesian3;
let midTexcoord;
if (max3 > minDistance) {
if (g0 === max3) {
edge = `${Math.min(i0, i1)} ${Math.max(i0, i1)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = rhumb0.interpolateUsingFraction(
0.5,
subdivisionCartographicScratch
);
midHeight = (c0.height + c14.height) * 0.5;
midCartesian3 = Cartesian3_default.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_default.add(t0, t1, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i0, i, i2);
triangles.push(i, i1, i2);
} else if (g1 === max3) {
edge = `${Math.min(i1, i2)} ${Math.max(i1, i2)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = rhumb1.interpolateUsingFraction(
0.5,
subdivisionCartographicScratch
);
midHeight = (c14.height + c22.height) * 0.5;
midCartesian3 = Cartesian3_default.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_default.add(t1, t2, subdivisionTexcoordMidScratch);
Cartesian2_default.multiplyByScalar(midTexcoord, 0.5, midTexcoord);
subdividedTexcoords.push(midTexcoord.x, midTexcoord.y);
}
}
triangles.push(i1, i, i0);
triangles.push(i, i2, i0);
} else if (g2 === max3) {
edge = `${Math.min(i2, i0)} ${Math.max(i2, i0)}`;
i = edges[edge];
if (!defined_default(i)) {
mid = rhumb2.interpolateUsingFraction(
0.5,
subdivisionCartographicScratch
);
midHeight = (c22.height + c0.height) * 0.5;
midCartesian3 = Cartesian3_default.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_default.add(t2, t0, subdivisionTexcoordMidScratch);
Cartesian2_default.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_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: subdividedPositions
})
},
indices: subdividedIndices,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: subdividedTexcoords
});
}
return new Geometry_default(geometryOptions);
};
PolygonPipeline.scaleToGeodeticHeight = function(positions, height, ellipsoid, scaleToSurface4) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
let n = scaleToGeodeticHeightN;
let p = scaleToGeodeticHeightP;
height = defaultValue_default(height, 0);
scaleToSurface4 = defaultValue_default(scaleToSurface4, true);
if (defined_default(positions)) {
const length3 = positions.length;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.fromArray(positions, i, p);
if (scaleToSurface4) {
p = ellipsoid.scaleToGeodeticSurface(p, p);
}
if (height !== 0) {
n = ellipsoid.geodeticSurfaceNormal(p, n);
Cartesian3_default.multiplyByScalar(n, height, n);
Cartesian3_default.add(p, n, p);
}
positions[i] = p.x;
positions[i + 1] = p.y;
positions[i + 2] = p.z;
}
}
return positions;
};
var PolygonPipeline_default = PolygonPipeline;
// node_modules/@cesium/engine/Source/Core/RectangleGeometryLibrary.js
var cos = Math.cos;
var sin = Math.sin;
var sqrt = Math.sqrt;
var RectangleGeometryLibrary = {};
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_default(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;
}
}
};
var rotationMatrixScratch = new Matrix2_default();
var nwCartesian = new Cartesian3_default();
var centerScratch = new Cartographic_default();
var centerCartesian = new Cartesian3_default();
var proj = new GeographicProjection_default();
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_default.subtract(nwCartesian, centerCartesian, nwCartesian);
const rotationMatrix = Matrix2_default.fromRotation(rotation, rotationMatrixScratch);
nwCartesian = Matrix2_default.multiplyByVector(
rotationMatrix,
nwCartesian,
nwCartesian
);
nwCartesian = Cartesian3_default.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,
south,
east,
west,
granYCos,
granYSin,
granXCos,
granXSin,
nwCorner
};
}
RectangleGeometryLibrary.computeOptions = function(rectangle, granularity, rotation, stRotation, boundingRectangleScratch2, 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 === Math_default.PI_OVER_TWO) {
northCap = true;
}
if (south === -Math_default.PI_OVER_TWO) {
southCap = true;
}
let dx;
const dy = north - south;
if (west > east) {
dx = Math_default.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_default.northwest(rectangle, nwCornerResult);
const center = Rectangle_default.center(rectangle, centerScratch);
if (rotation !== 0 || stRotation !== 0) {
if (center.longitude < nwCorner.longitude) {
center.longitude += Math_default.TWO_PI;
}
centerCartesian = proj.project(center, centerCartesian);
}
const granYCos = granularityY;
const granXCos = granularityX;
const granYSin = 0;
const granXSin = 0;
const boundingRectangle = Rectangle_default.clone(
rectangle,
boundingRectangleScratch2
);
const computedOptions = {
granYCos,
granYSin,
granXCos,
granXSin,
nwCorner,
boundingRectangle,
width,
height,
northCap,
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;
if (north < -Math_default.PI_OVER_TWO || north > Math_default.PI_OVER_TWO || south < -Math_default.PI_OVER_TWO || south > Math_default.PI_OVER_TWO) {
throw new DeveloperError_default(
"Rotated rectangle is invalid. It crosses over either the north or south pole."
);
}
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_default.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;
};
var RectangleGeometryLibrary_default = RectangleGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/RectangleOutlineGeometry.js
var bottomBoundingSphere = new BoundingSphere_default();
var topBoundingSphere = new BoundingSphere_default();
var positionScratch6 = new Cartesian3_default();
var rectangleScratch = new Rectangle_default();
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 corners2 = 4;
if (northCap) {
widthMultiplier -= 1;
rowHeight -= 1;
size += 1;
corners2 -= 2;
}
if (southCap) {
widthMultiplier -= 1;
rowHeight -= 1;
size += 1;
corners2 -= 2;
}
size += widthMultiplier * width + 2 * rowHeight - corners2;
const positions = new Float64Array(size * 3);
let posIndex = 0;
let row = 0;
let col;
const position = positionScratch6;
if (northCap) {
RectangleGeometryLibrary_default.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_default.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_default.computePosition(
computedOptions,
ellipsoid,
false,
row,
col,
position
);
positions[posIndex++] = position.x;
positions[posIndex++] = position.y;
positions[posIndex++] = position.z;
}
row = height - 1;
if (!southCap) {
for (col = width - 2; col >= 0; col--) {
RectangleGeometryLibrary_default.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_default.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 indices2 = IndexDatatype_default.createTypedArray(
positions.length / 3,
indicesSize
);
let index = 0;
for (let i = 0; i < positions.length / 3 - 1; i++) {
indices2[index++] = i;
indices2[index++] = i + 1;
}
indices2[index++] = positions.length / 3 - 1;
indices2[index++] = 0;
const geo = new Geometry_default({
attributes: new GeometryAttributes_default(),
primitiveType: PrimitiveType_default.LINES
});
geo.attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
geo.indices = indices2;
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_default.scaleToGeodeticHeight(
geo.attributes.position.values,
maxHeight,
ellipsoid,
false
);
let length3 = topPositions.length;
const positions = new Float64Array(length3 * 2);
positions.set(topPositions);
const bottomPositions = PolygonPipeline_default.scaleToGeodeticHeight(
geo.attributes.position.values,
minHeight,
ellipsoid
);
positions.set(bottomPositions, length3);
geo.attributes.position.values = positions;
const northCap = computedOptions.northCap;
const southCap = computedOptions.southCap;
let corners2 = 4;
if (northCap) {
corners2 -= 1;
}
if (southCap) {
corners2 -= 1;
}
const indicesSize = (positions.length / 3 + corners2) * 2;
const indices2 = IndexDatatype_default.createTypedArray(
positions.length / 3,
indicesSize
);
length3 = positions.length / 6;
let index = 0;
for (let i = 0; i < length3 - 1; i++) {
indices2[index++] = i;
indices2[index++] = i + 1;
indices2[index++] = i + length3;
indices2[index++] = i + length3 + 1;
}
indices2[index++] = length3 - 1;
indices2[index++] = 0;
indices2[index++] = length3 + length3 - 1;
indices2[index++] = length3;
indices2[index++] = 0;
indices2[index++] = length3;
let bottomCorner;
if (northCap) {
bottomCorner = height - 1;
} else {
const topRightCorner = width - 1;
indices2[index++] = topRightCorner;
indices2[index++] = topRightCorner + length3;
bottomCorner = width + height - 2;
}
indices2[index++] = bottomCorner;
indices2[index++] = bottomCorner + length3;
if (!southCap) {
const bottomLeftCorner = width + bottomCorner - 1;
indices2[index++] = bottomLeftCorner;
indices2[index] = bottomLeftCorner + length3;
}
geo.indices = indices2;
return geo;
}
function RectangleOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const rectangle = options.rectangle;
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const rotation = defaultValue_default(options.rotation, 0);
if (!defined_default(rectangle)) {
throw new DeveloperError_default("rectangle is required.");
}
Rectangle_default.validate(rectangle);
if (rectangle.north < rectangle.south) {
throw new DeveloperError_default(
"options.rectangle.north must be greater than options.rectangle.south"
);
}
const height = defaultValue_default(options.height, 0);
const extrudedHeight = defaultValue_default(options.extrudedHeight, height);
this._rectangle = Rectangle_default.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";
}
RectangleOutlineGeometry.packedLength = Rectangle_default.packedLength + Ellipsoid_default.packedLength + 5;
RectangleOutlineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
Rectangle_default.pack(value._rectangle, array, startingIndex);
startingIndex += Rectangle_default.packedLength;
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
array[startingIndex++] = value._granularity;
array[startingIndex++] = value._surfaceHeight;
array[startingIndex++] = value._rotation;
array[startingIndex++] = value._extrudedHeight;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchRectangle2 = new Rectangle_default();
var scratchEllipsoid = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchOptions3 = {
rectangle: scratchRectangle2,
ellipsoid: scratchEllipsoid,
granularity: void 0,
height: void 0,
rotation: void 0,
extrudedHeight: void 0,
offsetAttribute: void 0
};
RectangleOutlineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
const rectangle = Rectangle_default.unpack(array, startingIndex, scratchRectangle2);
startingIndex += Rectangle_default.packedLength;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid);
startingIndex += Ellipsoid_default.packedLength;
const granularity = array[startingIndex++];
const height = array[startingIndex++];
const rotation = array[startingIndex++];
const extrudedHeight = array[startingIndex++];
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions3.granularity = granularity;
scratchOptions3.height = height;
scratchOptions3.rotation = rotation;
scratchOptions3.extrudedHeight = extrudedHeight;
scratchOptions3.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new RectangleOutlineGeometry(scratchOptions3);
}
result._rectangle = Rectangle_default.clone(rectangle, result._rectangle);
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._surfaceHeight = height;
result._rotation = rotation;
result._extrudedHeight = extrudedHeight;
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
var nwScratch = new Cartographic_default();
RectangleOutlineGeometry.createGeometry = function(rectangleGeometry) {
const rectangle = rectangleGeometry._rectangle;
const ellipsoid = rectangleGeometry._ellipsoid;
const computedOptions = RectangleGeometryLibrary_default.computeOptions(
rectangle,
rectangleGeometry._granularity,
rectangleGeometry._rotation,
0,
rectangleScratch,
nwScratch
);
let geometry;
let boundingSphere;
if (Math_default.equalsEpsilon(
rectangle.north,
rectangle.south,
Math_default.EPSILON10
) || Math_default.equalsEpsilon(
rectangle.east,
rectangle.west,
Math_default.EPSILON10
)) {
return void 0;
}
const surfaceHeight = rectangleGeometry._surfaceHeight;
const extrudedHeight = rectangleGeometry._extrudedHeight;
const extrude = !Math_default.equalsEpsilon(
surfaceHeight,
extrudedHeight,
0,
Math_default.EPSILON2
);
let offsetValue;
if (extrude) {
geometry = constructExtrudedRectangle(rectangleGeometry, computedOptions);
if (defined_default(rectangleGeometry._offsetAttribute)) {
const size = geometry.attributes.position.values.length / 3;
let offsetAttribute = new Uint8Array(size);
if (rectangleGeometry._offsetAttribute === GeometryOffsetAttribute_default.TOP) {
offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
} else {
offsetValue = rectangleGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
offsetAttribute = offsetAttribute.fill(offsetValue);
}
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: offsetAttribute
});
}
const topBS = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
surfaceHeight,
topBoundingSphere
);
const bottomBS = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
extrudedHeight,
bottomBoundingSphere
);
boundingSphere = BoundingSphere_default.union(topBS, bottomBS);
} else {
geometry = constructRectangle(rectangleGeometry, computedOptions);
geometry.attributes.position.values = PolygonPipeline_default.scaleToGeodeticHeight(
geometry.attributes.position.values,
surfaceHeight,
ellipsoid,
false
);
if (defined_default(rectangleGeometry._offsetAttribute)) {
const length3 = geometry.attributes.position.values.length;
offsetValue = rectangleGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
boundingSphere = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
surfaceHeight
);
}
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: PrimitiveType_default.LINES,
boundingSphere,
offsetAttribute: rectangleGeometry._offsetAttribute
});
};
var RectangleOutlineGeometry_default = RectangleOutlineGeometry;
// node_modules/@cesium/engine/Source/Scene/TileBoundingRegion.js
function TileBoundingRegion(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.rectangle", options.rectangle);
this.rectangle = Rectangle_default.clone(options.rectangle);
this.minimumHeight = defaultValue_default(options.minimumHeight, 0);
this.maximumHeight = defaultValue_default(options.maximumHeight, 0);
this.southwestCornerCartesian = new Cartesian3_default();
this.northeastCornerCartesian = new Cartesian3_default();
this.westNormal = new Cartesian3_default();
this.southNormal = new Cartesian3_default();
this.eastNormal = new Cartesian3_default();
this.northNormal = new Cartesian3_default();
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
computeBox(this, options.rectangle, ellipsoid);
this._orientedBoundingBox = void 0;
this._boundingSphere = void 0;
if (defaultValue_default(options.computeBoundingVolumes, true)) {
this.computeBoundingVolumes(ellipsoid);
}
}
Object.defineProperties(TileBoundingRegion.prototype, {
boundingVolume: {
get: function() {
return this._orientedBoundingBox;
}
},
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
TileBoundingRegion.prototype.computeBoundingVolumes = function(ellipsoid) {
this._orientedBoundingBox = OrientedBoundingBox_default.fromRectangle(
this.rectangle,
this.minimumHeight,
this.maximumHeight,
ellipsoid
);
this._boundingSphere = BoundingSphere_default.fromOrientedBoundingBox(
this._orientedBoundingBox
);
};
var cartesian3Scratch = new Cartesian3_default();
var cartesian3Scratch22 = new Cartesian3_default();
var cartesian3Scratch32 = new Cartesian3_default();
var westNormalScratch = new Cartesian3_default();
var eastWestNormalScratch = new Cartesian3_default();
var westernMidpointScratch = new Cartesian3_default();
var easternMidpointScratch = new Cartesian3_default();
var cartographicScratch2 = new Cartographic_default();
var planeScratch = new Plane_default(Cartesian3_default.UNIT_X, 0);
var rayScratch = new Ray_default();
function computeBox(tileBB, rectangle, ellipsoid) {
ellipsoid.cartographicToCartesian(
Rectangle_default.southwest(rectangle),
tileBB.southwestCornerCartesian
);
ellipsoid.cartographicToCartesian(
Rectangle_default.northeast(rectangle),
tileBB.northeastCornerCartesian
);
cartographicScratch2.longitude = rectangle.west;
cartographicScratch2.latitude = (rectangle.south + rectangle.north) * 0.5;
cartographicScratch2.height = 0;
const westernMidpointCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
westernMidpointScratch
);
const westNormal = Cartesian3_default.cross(
westernMidpointCartesian,
Cartesian3_default.UNIT_Z,
westNormalScratch
);
Cartesian3_default.normalize(westNormal, tileBB.westNormal);
cartographicScratch2.longitude = rectangle.east;
const easternMidpointCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
easternMidpointScratch
);
const eastNormal = Cartesian3_default.cross(
Cartesian3_default.UNIT_Z,
easternMidpointCartesian,
cartesian3Scratch
);
Cartesian3_default.normalize(eastNormal, tileBB.eastNormal);
let westVector = Cartesian3_default.subtract(
westernMidpointCartesian,
easternMidpointCartesian,
cartesian3Scratch
);
if (Cartesian3_default.magnitude(westVector) === 0) {
westVector = Cartesian3_default.clone(westNormal, westVector);
}
const eastWestNormal = Cartesian3_default.normalize(
westVector,
eastWestNormalScratch
);
const south = rectangle.south;
let southSurfaceNormal;
if (south > 0) {
cartographicScratch2.longitude = (rectangle.west + rectangle.east) * 0.5;
cartographicScratch2.latitude = south;
const southCenterCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
rayScratch.origin
);
Cartesian3_default.clone(eastWestNormal, rayScratch.direction);
const westPlane = Plane_default.fromPointNormal(
tileBB.southwestCornerCartesian,
tileBB.westNormal,
planeScratch
);
IntersectionTests_default.rayPlane(
rayScratch,
westPlane,
tileBB.southwestCornerCartesian
);
southSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
southCenterCartesian,
cartesian3Scratch22
);
} else {
southSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
Rectangle_default.southeast(rectangle),
cartesian3Scratch22
);
}
const southNormal = Cartesian3_default.cross(
southSurfaceNormal,
westVector,
cartesian3Scratch32
);
Cartesian3_default.normalize(southNormal, tileBB.southNormal);
const north = rectangle.north;
let northSurfaceNormal;
if (north < 0) {
cartographicScratch2.longitude = (rectangle.west + rectangle.east) * 0.5;
cartographicScratch2.latitude = north;
const northCenterCartesian = ellipsoid.cartographicToCartesian(
cartographicScratch2,
rayScratch.origin
);
Cartesian3_default.negate(eastWestNormal, rayScratch.direction);
const eastPlane = Plane_default.fromPointNormal(
tileBB.northeastCornerCartesian,
tileBB.eastNormal,
planeScratch
);
IntersectionTests_default.rayPlane(
rayScratch,
eastPlane,
tileBB.northeastCornerCartesian
);
northSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
northCenterCartesian,
cartesian3Scratch22
);
} else {
northSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic(
Rectangle_default.northwest(rectangle),
cartesian3Scratch22
);
}
const northNormal = Cartesian3_default.cross(
westVector,
northSurfaceNormal,
cartesian3Scratch32
);
Cartesian3_default.normalize(northNormal, tileBB.northNormal);
}
var southwestCornerScratch = new Cartesian3_default();
var northeastCornerScratch = new Cartesian3_default();
var negativeUnitY = new Cartesian3_default(0, -1, 0);
var negativeUnitZ = new Cartesian3_default(0, 0, -1);
var vectorScratch = new Cartesian3_default();
function distanceToCameraRegion(tileBB, frameState) {
const camera = frameState.camera;
const cameraCartesianPosition = camera.positionWC;
const cameraCartographicPosition = camera.positionCartographic;
let result = 0;
if (!Rectangle_default.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_default.SCENE3D) {
southwestCornerCartesian = frameState.mapProjection.project(
Rectangle_default.southwest(tileBB.rectangle),
southwestCornerScratch
);
southwestCornerCartesian.z = southwestCornerCartesian.y;
southwestCornerCartesian.y = southwestCornerCartesian.x;
southwestCornerCartesian.x = 0;
northeastCornerCartesian = frameState.mapProjection.project(
Rectangle_default.northeast(tileBB.rectangle),
northeastCornerScratch
);
northeastCornerCartesian.z = northeastCornerCartesian.y;
northeastCornerCartesian.y = northeastCornerCartesian.x;
northeastCornerCartesian.x = 0;
westNormal = negativeUnitY;
eastNormal = Cartesian3_default.UNIT_Y;
southNormal = negativeUnitZ;
northNormal = Cartesian3_default.UNIT_Z;
}
const vectorFromSouthwestCorner = Cartesian3_default.subtract(
cameraCartesianPosition,
southwestCornerCartesian,
vectorScratch
);
const distanceToWestPlane = Cartesian3_default.dot(
vectorFromSouthwestCorner,
westNormal
);
const distanceToSouthPlane = Cartesian3_default.dot(
vectorFromSouthwestCorner,
southNormal
);
const vectorFromNortheastCorner = Cartesian3_default.subtract(
cameraCartesianPosition,
northeastCornerCartesian,
vectorScratch
);
const distanceToEastPlane = Cartesian3_default.dot(
vectorFromNortheastCorner,
eastNormal
);
const distanceToNorthPlane = Cartesian3_default.dot(
vectorFromNortheastCorner,
northNormal
);
if (distanceToWestPlane > 0) {
result += distanceToWestPlane * distanceToWestPlane;
} else if (distanceToEastPlane > 0) {
result += distanceToEastPlane * distanceToEastPlane;
}
if (distanceToSouthPlane > 0) {
result += distanceToSouthPlane * distanceToSouthPlane;
} else if (distanceToNorthPlane > 0) {
result += distanceToNorthPlane * distanceToNorthPlane;
}
}
let cameraHeight;
let minimumHeight;
let maximumHeight;
if (frameState.mode === SceneMode_default.SCENE3D) {
cameraHeight = cameraCartographicPosition.height;
minimumHeight = tileBB.minimumHeight;
maximumHeight = tileBB.maximumHeight;
} else {
cameraHeight = cameraCartesianPosition.x;
minimumHeight = 0;
maximumHeight = 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);
}
TileBoundingRegion.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
const regionResult = distanceToCameraRegion(this, frameState);
if (frameState.mode === SceneMode_default.SCENE3D && defined_default(this._orientedBoundingBox)) {
const obbResult = Math.sqrt(
this._orientedBoundingBox.distanceSquaredTo(frameState.camera.positionWC)
);
return Math.max(regionResult, obbResult);
}
return regionResult;
};
TileBoundingRegion.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
return this._orientedBoundingBox.intersectPlane(plane);
};
TileBoundingRegion.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const modelMatrix = new Matrix4_default.clone(Matrix4_default.IDENTITY);
const geometry = new RectangleOutlineGeometry_default({
rectangle: this.rectangle,
height: this.minimumHeight,
extrudedHeight: this.maximumHeight
});
const instance = new GeometryInstance_default({
geometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
return new Primitive_default({
geometryInstances: instance,
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileBoundingRegion_default = TileBoundingRegion;
// node_modules/@cesium/engine/Source/Core/CoplanarPolygonGeometryLibrary.js
var CoplanarPolygonGeometryLibrary = {};
var scratchIntersectionPoint = new Cartesian3_default();
var scratchXAxis2 = new Cartesian3_default();
var scratchYAxis2 = new Cartesian3_default();
var scratchZAxis2 = new Cartesian3_default();
var obbScratch = new OrientedBoundingBox_default();
CoplanarPolygonGeometryLibrary.validOutline = function(positions) {
Check_default.defined("positions", positions);
const orientedBoundingBox = OrientedBoundingBox_default.fromPoints(
positions,
obbScratch
);
const halfAxes = orientedBoundingBox.halfAxes;
const xAxis = Matrix3_default.getColumn(halfAxes, 0, scratchXAxis2);
const yAxis = Matrix3_default.getColumn(halfAxes, 1, scratchYAxis2);
const zAxis = Matrix3_default.getColumn(halfAxes, 2, scratchZAxis2);
const xMag = Cartesian3_default.magnitude(xAxis);
const yMag = Cartesian3_default.magnitude(yAxis);
const zMag = Cartesian3_default.magnitude(zAxis);
return !(xMag === 0 && (yMag === 0 || zMag === 0) || yMag === 0 && zMag === 0);
};
CoplanarPolygonGeometryLibrary.computeProjectTo2DArguments = function(positions, centerResult, planeAxis1Result, planeAxis2Result) {
Check_default.defined("positions", positions);
Check_default.defined("centerResult", centerResult);
Check_default.defined("planeAxis1Result", planeAxis1Result);
Check_default.defined("planeAxis2Result", planeAxis2Result);
const orientedBoundingBox = OrientedBoundingBox_default.fromPoints(
positions,
obbScratch
);
const halfAxes = orientedBoundingBox.halfAxes;
const xAxis = Matrix3_default.getColumn(halfAxes, 0, scratchXAxis2);
const yAxis = Matrix3_default.getColumn(halfAxes, 1, scratchYAxis2);
const zAxis = Matrix3_default.getColumn(halfAxes, 2, scratchZAxis2);
const xMag = Cartesian3_default.magnitude(xAxis);
const yMag = Cartesian3_default.magnitude(yAxis);
const zMag = Cartesian3_default.magnitude(zAxis);
const min3 = Math.min(xMag, yMag, zMag);
if (xMag === 0 && (yMag === 0 || zMag === 0) || yMag === 0 && zMag === 0) {
return false;
}
let planeAxis1;
let planeAxis2;
if (min3 === yMag || min3 === zMag) {
planeAxis1 = xAxis;
}
if (min3 === xMag) {
planeAxis1 = yAxis;
} else if (min3 === zMag) {
planeAxis2 = yAxis;
}
if (min3 === xMag || min3 === yMag) {
planeAxis2 = zAxis;
}
Cartesian3_default.normalize(planeAxis1, planeAxis1Result);
Cartesian3_default.normalize(planeAxis2, planeAxis2Result);
Cartesian3_default.clone(orientedBoundingBox.center, centerResult);
return true;
};
function projectTo2D(position, center, axis1, axis2, result) {
const v7 = Cartesian3_default.subtract(position, center, scratchIntersectionPoint);
const x = Cartesian3_default.dot(axis1, v7);
const y = Cartesian3_default.dot(axis2, v7);
return Cartesian2_default.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);
};
};
var CoplanarPolygonGeometryLibrary_default = CoplanarPolygonGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/Queue.js
function Queue() {
this._array = [];
this._offset = 0;
this._length = 0;
}
Object.defineProperties(Queue.prototype, {
length: {
get: function() {
return this._length;
}
}
});
Queue.prototype.enqueue = function(item) {
this._array.push(item);
this._length++;
};
Queue.prototype.dequeue = function() {
if (this._length === 0) {
return void 0;
}
const array = this._array;
let offset2 = this._offset;
const item = array[offset2];
array[offset2] = void 0;
offset2++;
if (offset2 > 10 && offset2 * 2 > array.length) {
this._array = array.slice(offset2);
offset2 = 0;
}
this._offset = offset2;
this._length--;
return item;
};
Queue.prototype.peek = function() {
if (this._length === 0) {
return void 0;
}
return this._array[this._offset];
};
Queue.prototype.contains = function(item) {
return this._array.indexOf(item) !== -1;
};
Queue.prototype.clear = function() {
this._array.length = this._offset = this._length = 0;
};
Queue.prototype.sort = function(compareFunction) {
if (this._offset > 0) {
this._array = this._array.slice(this._offset);
this._offset = 0;
}
this._array.sort(compareFunction);
};
var Queue_default = Queue;
// node_modules/@cesium/engine/Source/Core/PolygonGeometryLibrary.js
var PolygonGeometryLibrary = {};
PolygonGeometryLibrary.computeHierarchyPackedLength = function(polygonHierarchy, CartesianX) {
let numComponents = 0;
const stack = [polygonHierarchy];
while (stack.length > 0) {
const hierarchy = stack.pop();
if (!defined_default(hierarchy)) {
continue;
}
numComponents += 2;
const positions = hierarchy.positions;
const holes = hierarchy.holes;
if (defined_default(positions) && positions.length > 0) {
numComponents += positions.length * CartesianX.packedLength;
}
if (defined_default(holes)) {
const length3 = holes.length;
for (let i = 0; i < length3; ++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_default(hierarchy)) {
continue;
}
const positions = hierarchy.positions;
const holes = hierarchy.holes;
array[startingIndex++] = defined_default(positions) ? positions.length : 0;
array[startingIndex++] = defined_default(holes) ? holes.length : 0;
if (defined_default(positions)) {
const positionsLength = positions.length;
for (let i = 0; i < positionsLength; ++i, startingIndex += CartesianX.packedLength) {
CartesianX.pack(positions[i], array, startingIndex);
}
}
if (defined_default(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) : void 0;
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,
holes,
startingIndex
};
};
var distance2DScratch = new Cartesian2_default();
function getPointAtDistance2D(p0, p1, distance2, length3) {
Cartesian2_default.subtract(p1, p0, distance2DScratch);
Cartesian2_default.multiplyByScalar(
distance2DScratch,
distance2 / length3,
distance2DScratch
);
Cartesian2_default.add(p0, distance2DScratch, distance2DScratch);
return [distance2DScratch.x, distance2DScratch.y];
}
var distanceScratch4 = new Cartesian3_default();
function getPointAtDistance(p0, p1, distance2, length3) {
Cartesian3_default.subtract(p1, p0, distanceScratch4);
Cartesian3_default.multiplyByScalar(
distanceScratch4,
distance2 / length3,
distanceScratch4
);
Cartesian3_default.add(p0, distanceScratch4, distanceScratch4);
return [distanceScratch4.x, distanceScratch4.y, distanceScratch4.z];
}
PolygonGeometryLibrary.subdivideLineCount = function(p0, p1, minDistance) {
const distance2 = Cartesian3_default.distance(p0, p1);
const n = distance2 / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
return Math.pow(2, countDivide);
};
var scratchCartographic02 = new Cartographic_default();
var scratchCartographic12 = new Cartographic_default();
var scratchCartographic22 = new Cartographic_default();
var scratchCartesian0 = new Cartesian3_default();
var scratchRhumbLine = new EllipsoidRhumbLine_default();
PolygonGeometryLibrary.subdivideRhumbLineCount = function(ellipsoid, p0, p1, minDistance) {
const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic02);
const c14 = ellipsoid.cartesianToCartographic(p1, scratchCartographic12);
const rhumb = new EllipsoidRhumbLine_default(c0, c14, ellipsoid);
const n = rhumb.surfaceDistance / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
return Math.pow(2, countDivide);
};
PolygonGeometryLibrary.subdivideTexcoordLine = function(t0, t1, p0, p1, minDistance, result) {
const subdivisions = PolygonGeometryLibrary.subdivideLineCount(
p0,
p1,
minDistance
);
const length2D = Cartesian2_default.distance(t0, t1);
const distanceBetweenCoords = length2D / subdivisions;
const texcoords = result;
texcoords.length = subdivisions * 2;
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 length3 = Cartesian3_default.distance(p0, p1);
const distanceBetweenVertices = length3 / numVertices;
if (!defined_default(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, length3);
positions[index++] = p[0];
positions[index++] = p[1];
positions[index++] = p[2];
}
return positions;
};
PolygonGeometryLibrary.subdivideTexcoordRhumbLine = function(t0, t1, ellipsoid, p0, p1, minDistance, result) {
const c0 = ellipsoid.cartesianToCartographic(p0, scratchCartographic02);
const c14 = ellipsoid.cartesianToCartographic(p1, scratchCartographic12);
scratchRhumbLine.setEndPoints(c0, c14);
const n = scratchRhumbLine.surfaceDistance / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
const subdivisions = Math.pow(2, countDivide);
const length2D = Cartesian2_default.distance(t0, t1);
const distanceBetweenCoords = length2D / subdivisions;
const texcoords = result;
texcoords.length = subdivisions * 2;
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, scratchCartographic02);
const c14 = ellipsoid.cartesianToCartographic(p1, scratchCartographic12);
const rhumb = new EllipsoidRhumbLine_default(c0, c14, ellipsoid);
const n = rhumb.surfaceDistance / minDistance;
const countDivide = Math.max(0, Math.ceil(Math_default.log2(n)));
const numVertices = Math.pow(2, countDivide);
const distanceBetweenVertices = rhumb.surfaceDistance / numVertices;
if (!defined_default(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,
scratchCartographic22
);
const p = ellipsoid.cartographicToCartesian(c, scratchCartesian0);
positions[index++] = p.x;
positions[index++] = p.y;
positions[index++] = p.z;
}
return positions;
};
var scaleToGeodeticHeightN1 = new Cartesian3_default();
var scaleToGeodeticHeightN2 = new Cartesian3_default();
var scaleToGeodeticHeightP1 = new Cartesian3_default();
var scaleToGeodeticHeightP2 = new Cartesian3_default();
PolygonGeometryLibrary.scaleToGeodeticHeightExtruded = function(geometry, maxHeight, minHeight, ellipsoid, perPositionHeight) {
ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const n1 = scaleToGeodeticHeightN1;
let n2 = scaleToGeodeticHeightN2;
const p = scaleToGeodeticHeightP1;
let p2 = scaleToGeodeticHeightP2;
if (defined_default(geometry) && defined_default(geometry.attributes) && defined_default(geometry.attributes.position)) {
const positions = geometry.attributes.position.values;
const length3 = positions.length / 2;
for (let i = 0; i < length3; i += 3) {
Cartesian3_default.fromArray(positions, i, p);
ellipsoid.geodeticSurfaceNormal(p, n1);
p2 = ellipsoid.scaleToGeodeticSurface(p, p2);
n2 = Cartesian3_default.multiplyByScalar(n1, minHeight, n2);
n2 = Cartesian3_default.add(p2, n2, n2);
positions[i + length3] = n2.x;
positions[i + 1 + length3] = n2.y;
positions[i + 2 + length3] = n2.z;
if (perPositionHeight) {
p2 = Cartesian3_default.clone(p, p2);
}
n2 = Cartesian3_default.multiplyByScalar(n1, maxHeight, n2);
n2 = Cartesian3_default.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) {
const polygons = [];
const queue = new Queue_default();
queue.enqueue(polygonHierarchy);
let i;
let j;
let length3;
while (queue.length !== 0) {
const outerNode = queue.dequeue();
let outerRing = outerNode.positions;
if (scaleToEllipsoidSurface) {
length3 = outerRing.length;
for (i = 0; i < length3; i++) {
ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
}
}
outerRing = arrayRemoveDuplicates_default(
outerRing,
Cartesian3_default.equalsEpsilon,
true
);
if (outerRing.length < 3) {
continue;
}
const numChildren = outerNode.holes ? outerNode.holes.length : 0;
for (i = 0; i < numChildren; i++) {
const hole = outerNode.holes[i];
let holePositions = hole.positions;
if (scaleToEllipsoidSurface) {
length3 = holePositions.length;
for (j = 0; j < length3; ++j) {
ellipsoid.scaleToGeodeticSurface(holePositions[j], holePositions[j]);
}
}
holePositions = arrayRemoveDuplicates_default(
holePositions,
Cartesian3_default.equalsEpsilon,
true
);
if (holePositions.length < 3) {
continue;
}
polygons.push(holePositions);
let numGrandchildren = 0;
if (defined_default(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) {
const hierarchy = [];
const polygons = [];
const queue = new Queue_default();
queue.enqueue(polygonHierarchy);
while (queue.length !== 0) {
const outerNode = queue.dequeue();
let outerRing = outerNode.positions;
const holes = outerNode.holes;
let i;
let length3;
if (scaleToEllipsoidSurface) {
length3 = outerRing.length;
for (i = 0; i < length3; i++) {
ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
}
}
if (!keepDuplicates) {
outerRing = arrayRemoveDuplicates_default(
outerRing,
Cartesian3_default.equalsEpsilon,
true
);
}
if (outerRing.length < 3) {
continue;
}
let positions2D = projectPointsTo2D(outerRing);
if (!defined_default(positions2D)) {
continue;
}
const holeIndices = [];
let originalWindingOrder = PolygonPipeline_default.computeWindingOrder2D(
positions2D
);
if (originalWindingOrder === WindingOrder_default.CLOCKWISE) {
positions2D.reverse();
outerRing = outerRing.slice().reverse();
}
let positions = outerRing.slice();
const numChildren = defined_default(holes) ? holes.length : 0;
const polygonHoles = [];
let j;
for (i = 0; i < numChildren; i++) {
const hole = holes[i];
let holePositions = hole.positions;
if (scaleToEllipsoidSurface) {
length3 = holePositions.length;
for (j = 0; j < length3; ++j) {
ellipsoid.scaleToGeodeticSurface(holePositions[j], holePositions[j]);
}
}
if (!keepDuplicates) {
holePositions = arrayRemoveDuplicates_default(
holePositions,
Cartesian3_default.equalsEpsilon,
true
);
}
if (holePositions.length < 3) {
continue;
}
const holePositions2D = projectPointsTo2D(holePositions);
if (!defined_default(holePositions2D)) {
continue;
}
originalWindingOrder = PolygonPipeline_default.computeWindingOrder2D(
holePositions2D
);
if (originalWindingOrder === WindingOrder_default.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_default(hole.holes)) {
numGrandchildren = hole.holes.length;
}
for (j = 0; j < numGrandchildren; j++) {
queue.enqueue(hole.holes[j]);
}
}
hierarchy.push({
outerRing,
holes: polygonHoles
});
polygons.push({
positions,
positions2D,
holes: holeIndices
});
}
return {
hierarchy,
polygons
};
};
var computeBoundingRectangleCartesian2 = new Cartesian2_default();
var computeBoundingRectangleCartesian3 = new Cartesian3_default();
var computeBoundingRectangleQuaternion = new Quaternion_default();
var computeBoundingRectangleMatrix3 = new Matrix3_default();
PolygonGeometryLibrary.computeBoundingRectangle = function(planeNormal, projectPointTo2D, positions, angle, result) {
const rotation = Quaternion_default.fromAxisAngle(
planeNormal,
angle,
computeBoundingRectangleQuaternion
);
const textureMatrix = Matrix3_default.fromQuaternion(
rotation,
computeBoundingRectangleMatrix3
);
let minX = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
const length3 = positions.length;
for (let i = 0; i < length3; ++i) {
const p = Cartesian3_default.clone(
positions[i],
computeBoundingRectangleCartesian3
);
Matrix3_default.multiplyByVector(textureMatrix, p, p);
const st = projectPointTo2D(p, computeBoundingRectangleCartesian2);
if (defined_default(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 indices2 = PolygonPipeline_default.triangulate(polygon.positions2D, polygon.holes);
if (indices2.length < 3) {
indices2 = [0, 1, 2];
}
const positions = polygon.positions;
const hasTexcoords = defined_default(textureCoordinates);
const texcoords = hasTexcoords ? textureCoordinates.positions : void 0;
if (perPositionHeight) {
const length3 = positions.length;
const flattenedPositions = new Array(length3 * 3);
let index = 0;
for (let i = 0; i < length3; i++) {
const p = positions[i];
flattenedPositions[index++] = p.x;
flattenedPositions[index++] = p.y;
flattenedPositions[index++] = p.z;
}
const geometryOptions = {
attributes: {
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: flattenedPositions
})
},
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: Cartesian2_default.packArray(texcoords)
});
}
const geometry = new Geometry_default(geometryOptions);
if (vertexFormat.normal) {
return GeometryPipeline_default.computeNormal(geometry);
}
return geometry;
}
if (arcType === ArcType_default.GEODESIC) {
return PolygonPipeline_default.computeSubdivision(
ellipsoid,
positions,
indices2,
texcoords,
granularity
);
} else if (arcType === ArcType_default.RHUMB) {
return PolygonPipeline_default.computeRhumbLineSubdivision(
ellipsoid,
positions,
indices2,
texcoords,
granularity
);
}
};
var computeWallTexcoordsSubdivided = [];
var computeWallIndicesSubdivided = [];
var p1Scratch2 = new Cartesian3_default();
var p2Scratch2 = new Cartesian3_default();
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 length3 = positions.length;
let index = 0;
let textureIndex = 0;
const hasTexcoords = defined_default(textureCoordinates);
const texcoords = hasTexcoords ? textureCoordinates.positions : void 0;
if (!perPositionHeight) {
const minDistance = Math_default.chordLength(
granularity,
ellipsoid.maximumRadius
);
let numVertices = 0;
if (arcType === ArcType_default.GEODESIC) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary.subdivideLineCount(
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
} else if (arcType === ArcType_default.RHUMB) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary.subdivideRhumbLineCount(
ellipsoid,
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
}
topEdgeLength = (numVertices + length3) * 3;
edgePositions = new Array(topEdgeLength * 2);
if (hasTexcoords) {
topEdgeTexcoordLength = (numVertices + length3) * 2;
edgeTexcoords = new Array(topEdgeTexcoordLength * 2);
}
for (i = 0; i < length3; i++) {
p1 = positions[i];
p2 = positions[(i + 1) % length3];
let tempPositions;
let tempTexcoords;
if (hasTexcoords) {
t1 = texcoords[i];
t2 = texcoords[(i + 1) % length3];
}
if (arcType === ArcType_default.GEODESIC) {
tempPositions = PolygonGeometryLibrary.subdivideLine(
p1,
p2,
minDistance,
computeWallIndicesSubdivided
);
if (hasTexcoords) {
tempTexcoords = PolygonGeometryLibrary.subdivideTexcoordLine(
t1,
t2,
p1,
p2,
minDistance,
computeWallTexcoordsSubdivided
);
}
} else if (arcType === ArcType_default.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 = length3 * 3 * 2;
edgePositions = new Array(topEdgeLength * 2);
if (hasTexcoords) {
topEdgeTexcoordLength = length3 * 2 * 2;
edgeTexcoords = new Array(topEdgeTexcoordLength * 2);
}
for (i = 0; i < length3; i++) {
p1 = positions[i];
p2 = positions[(i + 1) % length3];
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) % length3];
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;
}
}
}
length3 = edgePositions.length;
const indices2 = IndexDatatype_default.createTypedArray(
length3 / 3,
length3 - positions.length * 6
);
let edgeIndex = 0;
length3 /= 6;
for (i = 0; i < length3; i++) {
const UL = i;
const UR = UL + 1;
const LL = UL + length3;
const LR = LL + 1;
p1 = Cartesian3_default.fromArray(edgePositions, UL * 3, p1Scratch2);
p2 = Cartesian3_default.fromArray(edgePositions, UR * 3, p2Scratch2);
if (Cartesian3_default.equalsEpsilon(
p1,
p2,
Math_default.EPSILON10,
Math_default.EPSILON10
)) {
continue;
}
indices2[edgeIndex++] = UL;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = UR;
indices2[edgeIndex++] = UR;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = LR;
}
const geometryOptions = {
attributes: new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: edgePositions
})
}),
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES
};
if (hasTexcoords) {
geometryOptions.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: edgeTexcoords
});
}
const geometry = new Geometry_default(geometryOptions);
return geometry;
};
var PolygonGeometryLibrary_default = PolygonGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/CoplanarPolygonOutlineGeometry.js
function createGeometryFromPositions(positions) {
const length3 = positions.length;
const flatPositions2 = new Float64Array(length3 * 3);
const indices2 = IndexDatatype_default.createTypedArray(length3, length3 * 2);
let positionIndex = 0;
let index = 0;
for (let i = 0; i < length3; i++) {
const position = positions[i];
flatPositions2[positionIndex++] = position.x;
flatPositions2[positionIndex++] = position.y;
flatPositions2[positionIndex++] = position.z;
indices2[index++] = i;
indices2[index++] = (i + 1) % length3;
}
const attributes = new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: flatPositions2
})
});
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES
});
}
function CoplanarPolygonOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const polygonHierarchy = options.polygonHierarchy;
Check_default.defined("options.polygonHierarchy", polygonHierarchy);
this._polygonHierarchy = polygonHierarchy;
this._workerName = "createCoplanarPolygonOutlineGeometry";
this.packedLength = PolygonGeometryLibrary_default.computeHierarchyPackedLength(
polygonHierarchy,
Cartesian3_default
) + 1;
}
CoplanarPolygonOutlineGeometry.fromPositions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.positions", options.positions);
const newOptions2 = {
polygonHierarchy: {
positions: options.positions
}
};
return new CoplanarPolygonOutlineGeometry(newOptions2);
};
CoplanarPolygonOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
startingIndex = PolygonGeometryLibrary_default.packPolygonHierarchy(
value._polygonHierarchy,
array,
startingIndex,
Cartesian3_default
);
array[startingIndex] = value.packedLength;
return array;
};
var scratchOptions4 = {
polygonHierarchy: {}
};
CoplanarPolygonOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const polygonHierarchy = PolygonGeometryLibrary_default.unpackPolygonHierarchy(
array,
startingIndex,
Cartesian3_default
);
startingIndex = polygonHierarchy.startingIndex;
delete polygonHierarchy.startingIndex;
const packedLength = array[startingIndex];
if (!defined_default(result)) {
result = new CoplanarPolygonOutlineGeometry(scratchOptions4);
}
result._polygonHierarchy = polygonHierarchy;
result.packedLength = packedLength;
return result;
};
CoplanarPolygonOutlineGeometry.createGeometry = function(polygonGeometry) {
const polygonHierarchy = polygonGeometry._polygonHierarchy;
let outerPositions = polygonHierarchy.positions;
outerPositions = arrayRemoveDuplicates_default(
outerPositions,
Cartesian3_default.equalsEpsilon,
true
);
if (outerPositions.length < 3) {
return;
}
const isValid = CoplanarPolygonGeometryLibrary_default.validOutline(outerPositions);
if (!isValid) {
return void 0;
}
const polygons = PolygonGeometryLibrary_default.polygonOutlinesFromHierarchy(
polygonHierarchy,
false
);
if (polygons.length === 0) {
return void 0;
}
const geometries = [];
for (let i = 0; i < polygons.length; i++) {
const geometryInstance = new GeometryInstance_default({
geometry: createGeometryFromPositions(polygons[i])
});
geometries.push(geometryInstance);
}
const geometry = GeometryPipeline_default.combineInstances(geometries)[0];
const boundingSphere = BoundingSphere_default.fromPoints(polygonHierarchy.positions);
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: geometry.primitiveType,
boundingSphere
});
};
var CoplanarPolygonOutlineGeometry_default = CoplanarPolygonOutlineGeometry;
// node_modules/@cesium/engine/Source/Scene/TileBoundingS2Cell.js
var centerCartographicScratch = new Cartographic_default();
function TileBoundingS2Cell(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.string("options.token", options.token);
const s2Cell = S2Cell_default.fromToken(options.token);
const minimumHeight = defaultValue_default(options.minimumHeight, 0);
const maximumHeight = defaultValue_default(options.maximumHeight, 0);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this.s2Cell = s2Cell;
this.minimumHeight = minimumHeight;
this.maximumHeight = maximumHeight;
this.ellipsoid = ellipsoid;
const boundingPlanes = computeBoundingPlanes(
s2Cell,
minimumHeight,
maximumHeight,
ellipsoid
);
this._boundingPlanes = boundingPlanes;
const vertices = computeVertices(boundingPlanes);
this._vertices = vertices;
this._edgeNormals = new Array(6);
this._edgeNormals[0] = computeEdgeNormals(
boundingPlanes[0],
vertices.slice(0, 4)
);
let i;
for (i = 0; i < 4; i++) {
this._edgeNormals[0][i] = Cartesian3_default.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++) {
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 = ellipsoid.cartesianToCartographic(
center,
centerCartographicScratch
);
centerCartographicScratch.height = (maximumHeight + minimumHeight) / 2;
this.center = ellipsoid.cartographicToCartesian(
centerCartographicScratch,
center
);
this._boundingSphere = BoundingSphere_default.fromPoints(vertices);
}
var centerGeodeticNormalScratch = new Cartesian3_default();
var topCartographicScratch = new Cartographic_default();
var topScratch = new Cartesian3_default();
var vertexCartographicScratch = new Cartographic_default();
var vertexScratch = new Cartesian3_default();
var vertexGeodeticNormalScratch = new Cartesian3_default();
var sideNormalScratch = new Cartesian3_default();
var sideScratch = new Cartesian3_default();
function computeBoundingPlanes(s2Cell, minimumHeight, maximumHeight, ellipsoid) {
const planes = new Array(6);
const centerPoint = s2Cell.getCenter();
const centerSurfaceNormal = ellipsoid.geodeticSurfaceNormal(
centerPoint,
centerGeodeticNormalScratch
);
const topCartographic = ellipsoid.cartesianToCartographic(
centerPoint,
topCartographicScratch
);
topCartographic.height = maximumHeight;
const top = ellipsoid.cartographicToCartesian(topCartographic, topScratch);
const topPlane = Plane_default.fromPointNormal(top, centerSurfaceNormal);
planes[0] = topPlane;
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 distance2 = Plane_default.getPointDistance(
topPlane,
ellipsoid.cartographicToCartesian(vertexCartographic, vertexScratch)
);
if (distance2 < maxDistance) {
maxDistance = distance2;
}
}
const bottomPlane = Plane_default.clone(topPlane);
bottomPlane.normal = Cartesian3_default.negate(
bottomPlane.normal,
bottomPlane.normal
);
bottomPlane.distance = bottomPlane.distance * -1 + maxDistance;
planes[1] = bottomPlane;
for (i = 0; i < 4; i++) {
vertex = vertices[i];
const adjacentVertex = vertices[(i + 1) % 4];
const geodeticNormal = ellipsoid.geodeticSurfaceNormal(
vertex,
vertexGeodeticNormalScratch
);
const side = Cartesian3_default.subtract(adjacentVertex, vertex, sideScratch);
let sideNormal = Cartesian3_default.cross(side, geodeticNormal, sideNormalScratch);
sideNormal = Cartesian3_default.normalize(sideNormal, sideNormal);
planes[2 + i] = Plane_default.fromPointNormal(vertex, sideNormal);
}
return planes;
}
var n0Scratch = new Cartesian3_default();
var n1Scratch = new Cartesian3_default();
var n2Scratch = new Cartesian3_default();
var x0Scratch = new Cartesian3_default();
var x1Scratch = new Cartesian3_default();
var x2Scratch = new Cartesian3_default();
var t0Scratch = new Cartesian3_default();
var t1Scratch = new Cartesian3_default();
var t2Scratch = new Cartesian3_default();
var f0Scratch = new Cartesian3_default();
var f1Scratch = new Cartesian3_default();
var f2Scratch = new Cartesian3_default();
var sScratch2 = new Cartesian3_default();
var matrixScratch = new Matrix3_default();
function computeIntersection(p0, p1, p2) {
n0Scratch = p0.normal;
n1Scratch = p1.normal;
n2Scratch = p2.normal;
x0Scratch = Cartesian3_default.multiplyByScalar(p0.normal, -p0.distance, x0Scratch);
x1Scratch = Cartesian3_default.multiplyByScalar(p1.normal, -p1.distance, x1Scratch);
x2Scratch = Cartesian3_default.multiplyByScalar(p2.normal, -p2.distance, x2Scratch);
f0Scratch = Cartesian3_default.multiplyByScalar(
Cartesian3_default.cross(n1Scratch, n2Scratch, t0Scratch),
Cartesian3_default.dot(x0Scratch, n0Scratch),
f0Scratch
);
f1Scratch = Cartesian3_default.multiplyByScalar(
Cartesian3_default.cross(n2Scratch, n0Scratch, t1Scratch),
Cartesian3_default.dot(x1Scratch, n1Scratch),
f1Scratch
);
f2Scratch = Cartesian3_default.multiplyByScalar(
Cartesian3_default.cross(n0Scratch, n1Scratch, t2Scratch),
Cartesian3_default.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_default.determinant(matrixScratch);
sScratch2 = Cartesian3_default.add(f0Scratch, f1Scratch, sScratch2);
sScratch2 = Cartesian3_default.add(sScratch2, f2Scratch, sScratch2);
return new Cartesian3_default(
sScratch2.x / determinant,
sScratch2.y / determinant,
sScratch2.z / determinant
);
}
function computeVertices(boundingPlanes) {
const vertices = new Array(8);
for (let i = 0; i < 4; i++) {
vertices[i] = computeIntersection(
boundingPlanes[0],
boundingPlanes[2 + (i + 3) % 4],
boundingPlanes[2 + i % 4]
);
vertices[i + 4] = computeIntersection(
boundingPlanes[1],
boundingPlanes[2 + (i + 3) % 4],
boundingPlanes[2 + i % 4]
);
}
return vertices;
}
var edgeScratch = new Cartesian3_default();
var edgeNormalScratch = new Cartesian3_default();
function computeEdgeNormals(plane, vertices) {
const edgeNormals = [];
for (let i = 0; i < 4; i++) {
edgeScratch = Cartesian3_default.subtract(
vertices[(i + 1) % 4],
vertices[i],
edgeScratch
);
edgeNormalScratch = Cartesian3_default.cross(
plane.normal,
edgeScratch,
edgeNormalScratch
);
edgeNormalScratch = Cartesian3_default.normalize(
edgeNormalScratch,
edgeNormalScratch
);
edgeNormals[i] = Cartesian3_default.clone(edgeNormalScratch);
}
return edgeNormals;
}
Object.defineProperties(TileBoundingS2Cell.prototype, {
boundingVolume: {
get: function() {
return this;
}
},
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
var facePointScratch = new Cartesian3_default();
TileBoundingS2Cell.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
const point = frameState.camera.positionWC;
const selectedPlaneIndices = [];
const vertices = [];
let edgeNormals;
if (Plane_default.getPointDistance(this._boundingPlanes[0], point) > 0) {
selectedPlaneIndices.push(0);
vertices.push(this._planeVertices[0]);
edgeNormals = this._edgeNormals[0];
} else if (Plane_default.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_default.getPointDistance(this._boundingPlanes[sidePlaneIndex], point) > 0) {
selectedPlaneIndices.push(sidePlaneIndex);
vertices.push(this._planeVertices[sidePlaneIndex]);
edgeNormals = this._edgeNormals[sidePlaneIndex];
}
}
if (selectedPlaneIndices.length === 0) {
return 0;
}
let facePoint;
let selectedPlane;
if (selectedPlaneIndices.length === 1) {
selectedPlane = this._boundingPlanes[selectedPlaneIndices[0]];
facePoint = closestPointPolygon(
Plane_default.projectPointOntoPlane(selectedPlane, point, facePointScratch),
vertices[0],
selectedPlane,
edgeNormals
);
return Cartesian3_default.distance(facePoint, point);
} else if (selectedPlaneIndices.length === 2) {
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_default.distance(facePoint, point);
}
let minimumDistance = Number.MAX_VALUE;
let distance2;
for (i = 0; i < 2; i++) {
selectedPlane = this._boundingPlanes[selectedPlaneIndices[i]];
facePoint = closestPointPolygon(
Plane_default.projectPointOntoPlane(selectedPlane, point, facePointScratch),
vertices[i],
selectedPlane,
this._edgeNormals[selectedPlaneIndices[i]]
);
distance2 = Cartesian3_default.distanceSquared(facePoint, point);
if (distance2 < minimumDistance) {
minimumDistance = distance2;
}
}
return Math.sqrt(minimumDistance);
} else if (selectedPlaneIndices.length > 3) {
facePoint = closestPointPolygon(
Plane_default.projectPointOntoPlane(
this._boundingPlanes[1],
point,
facePointScratch
),
this._planeVertices[1],
this._boundingPlanes[1],
this._edgeNormals[1]
);
return Cartesian3_default.distance(facePoint, point);
}
const skip = selectedPlaneIndices[1] === 2 && selectedPlaneIndices[2] === 5 ? 0 : 1;
if (selectedPlaneIndices[0] === 0) {
return Cartesian3_default.distance(
point,
this._vertices[(selectedPlaneIndices[1] - 2 + skip) % 4]
);
}
return Cartesian3_default.distance(
point,
this._vertices[4 + (selectedPlaneIndices[1] - 2 + skip) % 4]
);
};
var dScratch2 = new Cartesian3_default();
var pL0Scratch = new Cartesian3_default();
function closestPointLineSegment(p, l0, l1) {
const d = Cartesian3_default.subtract(l1, l0, dScratch2);
const pL0 = Cartesian3_default.subtract(p, l0, pL0Scratch);
let t = Cartesian3_default.dot(d, pL0);
if (t <= 0) {
return l0;
}
const dMag = Cartesian3_default.dot(d, d);
if (t >= dMag) {
return l1;
}
t = t / dMag;
return new Cartesian3_default(
(1 - t) * l0.x + t * l1.x,
(1 - t) * l0.y + t * l1.y,
(1 - t) * l0.z + t * l1.z
);
}
var edgePlaneScratch = new Plane_default(Cartesian3_default.UNIT_X, 0);
function closestPointPolygon(p, vertices, plane, edgeNormals) {
let minDistance = Number.MAX_VALUE;
let distance2;
let closestPoint;
let closestPointOnEdge;
for (let i = 0; i < vertices.length; i++) {
const edgePlane = Plane_default.fromPointNormal(
vertices[i],
edgeNormals[i],
edgePlaneScratch
);
const edgePlaneDistance = Plane_default.getPointDistance(edgePlane, p);
if (edgePlaneDistance < 0) {
continue;
}
closestPointOnEdge = closestPointLineSegment(
p,
vertices[i],
vertices[(i + 1) % 4]
);
distance2 = Cartesian3_default.distance(p, closestPointOnEdge);
if (distance2 < minDistance) {
minDistance = distance2;
closestPoint = closestPointOnEdge;
}
}
if (!defined_default(closestPoint)) {
return p;
}
return closestPoint;
}
TileBoundingS2Cell.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
let plusCount = 0;
let negCount = 0;
for (let i = 0; i < this._vertices.length; i++) {
const distanceToPlane = Cartesian3_default.dot(plane.normal, this._vertices[i]) + plane.distance;
if (distanceToPlane < 0) {
negCount++;
} else {
plusCount++;
}
}
if (plusCount === this._vertices.length) {
return Intersect_default.INSIDE;
} else if (negCount === this._vertices.length) {
return Intersect_default.OUTSIDE;
}
return Intersect_default.INTERSECTING;
};
TileBoundingS2Cell.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const modelMatrix = new Matrix4_default.clone(Matrix4_default.IDENTITY);
const topPlanePolygon = new CoplanarPolygonOutlineGeometry_default({
polygonHierarchy: {
positions: this._planeVertices[0]
}
});
const topPlaneGeometry = CoplanarPolygonOutlineGeometry_default.createGeometry(
topPlanePolygon
);
const topPlaneInstance = new GeometryInstance_default({
geometry: topPlaneGeometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
const bottomPlanePolygon = new CoplanarPolygonOutlineGeometry_default({
polygonHierarchy: {
positions: this._planeVertices[1]
}
});
const bottomPlaneGeometry = CoplanarPolygonOutlineGeometry_default.createGeometry(
bottomPlanePolygon
);
const bottomPlaneInstance = new GeometryInstance_default({
geometry: bottomPlaneGeometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
const sideInstances = [];
for (let i = 0; i < 4; i++) {
const sidePlanePolygon = new CoplanarPolygonOutlineGeometry_default({
polygonHierarchy: {
positions: this._planeVertices[2 + i]
}
});
const sidePlaneGeometry = CoplanarPolygonOutlineGeometry_default.createGeometry(
sidePlanePolygon
);
sideInstances[i] = new GeometryInstance_default({
geometry: sidePlaneGeometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
}
return new Primitive_default({
geometryInstances: [
sideInstances[0],
sideInstances[1],
sideInstances[2],
sideInstances[3],
bottomPlaneInstance,
topPlaneInstance
],
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileBoundingS2Cell_default = TileBoundingS2Cell;
// node_modules/@cesium/engine/Source/Core/EllipsoidOutlineGeometry.js
var defaultRadii = new Cartesian3_default(1, 1, 1);
var cos2 = Math.cos;
var sin2 = Math.sin;
function EllipsoidOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const radii = defaultValue_default(options.radii, defaultRadii);
const innerRadii = defaultValue_default(options.innerRadii, radii);
const minimumClock = defaultValue_default(options.minimumClock, 0);
const maximumClock = defaultValue_default(options.maximumClock, Math_default.TWO_PI);
const minimumCone = defaultValue_default(options.minimumCone, 0);
const maximumCone = defaultValue_default(options.maximumCone, Math_default.PI);
const stackPartitions = Math.round(defaultValue_default(options.stackPartitions, 10));
const slicePartitions = Math.round(defaultValue_default(options.slicePartitions, 8));
const subdivisions = Math.round(defaultValue_default(options.subdivisions, 128));
if (stackPartitions < 1) {
throw new DeveloperError_default("options.stackPartitions cannot be less than 1");
}
if (slicePartitions < 0) {
throw new DeveloperError_default("options.slicePartitions cannot be less than 0");
}
if (subdivisions < 0) {
throw new DeveloperError_default(
"options.subdivisions must be greater than or equal to zero."
);
}
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
this._radii = Cartesian3_default.clone(radii);
this._innerRadii = Cartesian3_default.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";
}
EllipsoidOutlineGeometry.packedLength = 2 * Cartesian3_default.packedLength + 8;
EllipsoidOutlineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._radii, array, startingIndex);
startingIndex += Cartesian3_default.packedLength;
Cartesian3_default.pack(value._innerRadii, array, startingIndex);
startingIndex += Cartesian3_default.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_default(value._offsetAttribute, -1);
return array;
};
var scratchRadii = new Cartesian3_default();
var scratchInnerRadii = new Cartesian3_default();
var scratchOptions5 = {
radii: scratchRadii,
innerRadii: scratchInnerRadii,
minimumClock: void 0,
maximumClock: void 0,
minimumCone: void 0,
maximumCone: void 0,
stackPartitions: void 0,
slicePartitions: void 0,
subdivisions: void 0,
offsetAttribute: void 0
};
EllipsoidOutlineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
const radii = Cartesian3_default.unpack(array, startingIndex, scratchRadii);
startingIndex += Cartesian3_default.packedLength;
const innerRadii = Cartesian3_default.unpack(array, startingIndex, scratchInnerRadii);
startingIndex += Cartesian3_default.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_default(result)) {
scratchOptions5.minimumClock = minimumClock;
scratchOptions5.maximumClock = maximumClock;
scratchOptions5.minimumCone = minimumCone;
scratchOptions5.maximumCone = maximumCone;
scratchOptions5.stackPartitions = stackPartitions;
scratchOptions5.slicePartitions = slicePartitions;
scratchOptions5.subdivisions = subdivisions;
scratchOptions5.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new EllipsoidOutlineGeometry(scratchOptions5);
}
result._radii = Cartesian3_default.clone(radii, result._radii);
result._innerRadii = Cartesian3_default.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 ? void 0 : offsetAttribute;
return result;
};
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_default.fromCartesian3(radii);
let slicePartitions = ellipsoidGeometry._slicePartitions + 1;
let stackPartitions = ellipsoidGeometry._stackPartitions + 1;
slicePartitions = Math.round(
slicePartitions * Math.abs(maximumClock - minimumClock) / Math_default.TWO_PI
);
stackPartitions = Math.round(
stackPartitions * Math.abs(maximumCone - minimumCone) / Math_default.PI
);
if (slicePartitions < 2) {
slicePartitions = 2;
}
if (stackPartitions < 2) {
stackPartitions = 2;
}
let extraIndices = 0;
let vertexMultiplier = 1;
const hasInnerSurface = innerRadii.x !== radii.x || innerRadii.y !== radii.y || innerRadii.z !== radii.z;
let isTopOpen = false;
let isBotOpen = false;
if (hasInnerSurface) {
vertexMultiplier = 2;
if (minimumCone > 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);
const numIndices = 2 * (vertexCount + extraIndices - (slicePartitions + stackPartitions) * vertexMultiplier);
const indices2 = IndexDatatype_default.createTypedArray(vertexCount, numIndices);
let i;
let j;
let theta;
let phi;
let index = 0;
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] = sin2(phi);
cosPhi[i] = cos2(phi);
}
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] = sin2(theta);
cosTheta[i] = cos2(theta);
}
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];
}
}
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];
}
}
}
sinPhi.length = subdivisions;
cosPhi.length = subdivisions;
for (i = 0; i < subdivisions; i++) {
phi = minimumCone + i * (maximumCone - minimumCone) / (subdivisions - 1);
sinPhi[i] = sin2(phi);
cosPhi[i] = cos2(phi);
}
sinTheta.length = slicePartitions;
cosTheta.length = slicePartitions;
for (i = 0; i < slicePartitions; i++) {
theta = minimumClock + i * (maximumClock - minimumClock) / (slicePartitions - 1);
sinTheta[i] = sin2(theta);
cosTheta[i] = cos2(theta);
}
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];
}
}
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];
}
}
}
index = 0;
for (i = 0; i < stackPartitions * vertexMultiplier; i++) {
const topOffset = i * subdivisions;
for (j = 0; j < subdivisions - 1; j++) {
indices2[index++] = topOffset + j;
indices2[index++] = topOffset + j + 1;
}
}
let offset2 = stackPartitions * subdivisions * vertexMultiplier;
for (i = 0; i < slicePartitions; i++) {
for (j = 0; j < subdivisions - 1; j++) {
indices2[index++] = offset2 + i + j * slicePartitions;
indices2[index++] = offset2 + i + (j + 1) * slicePartitions;
}
}
if (hasInnerSurface) {
offset2 = stackPartitions * subdivisions * vertexMultiplier + slicePartitions * subdivisions;
for (i = 0; i < slicePartitions; i++) {
for (j = 0; j < subdivisions - 1; j++) {
indices2[index++] = offset2 + i + j * slicePartitions;
indices2[index++] = offset2 + i + (j + 1) * slicePartitions;
}
}
}
if (hasInnerSurface) {
let outerOffset = stackPartitions * subdivisions * vertexMultiplier;
let innerOffset = outerOffset + subdivisions * slicePartitions;
if (isTopOpen) {
for (i = 0; i < slicePartitions; i++) {
indices2[index++] = outerOffset + i;
indices2[index++] = innerOffset + i;
}
}
if (isBotOpen) {
outerOffset += subdivisions * slicePartitions - slicePartitions;
innerOffset += subdivisions * slicePartitions - slicePartitions;
for (i = 0; i < slicePartitions; i++) {
indices2[index++] = outerOffset + i;
indices2[index++] = innerOffset + i;
}
}
}
const attributes = new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
})
});
if (defined_default(ellipsoidGeometry._offsetAttribute)) {
const length3 = positions.length;
const offsetValue = ellipsoidGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES,
boundingSphere: BoundingSphere_default.fromEllipsoid(ellipsoid),
offsetAttribute: ellipsoidGeometry._offsetAttribute
});
};
var EllipsoidOutlineGeometry_default = EllipsoidOutlineGeometry;
// node_modules/@cesium/engine/Source/Core/SphereOutlineGeometry.js
function SphereOutlineGeometry(options) {
const radius = defaultValue_default(options.radius, 1);
const radii = new Cartesian3_default(radius, radius, radius);
const ellipsoidOptions = {
radii,
stackPartitions: options.stackPartitions,
slicePartitions: options.slicePartitions,
subdivisions: options.subdivisions
};
this._ellipsoidGeometry = new EllipsoidOutlineGeometry_default(ellipsoidOptions);
this._workerName = "createSphereOutlineGeometry";
}
SphereOutlineGeometry.packedLength = EllipsoidOutlineGeometry_default.packedLength;
SphereOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
return EllipsoidOutlineGeometry_default.pack(
value._ellipsoidGeometry,
array,
startingIndex
);
};
var scratchEllipsoidGeometry = new EllipsoidOutlineGeometry_default();
var scratchOptions6 = {
radius: void 0,
radii: new Cartesian3_default(),
stackPartitions: void 0,
slicePartitions: void 0,
subdivisions: void 0
};
SphereOutlineGeometry.unpack = function(array, startingIndex, result) {
const ellipsoidGeometry = EllipsoidOutlineGeometry_default.unpack(
array,
startingIndex,
scratchEllipsoidGeometry
);
scratchOptions6.stackPartitions = ellipsoidGeometry._stackPartitions;
scratchOptions6.slicePartitions = ellipsoidGeometry._slicePartitions;
scratchOptions6.subdivisions = ellipsoidGeometry._subdivisions;
if (!defined_default(result)) {
scratchOptions6.radius = ellipsoidGeometry._radii.x;
return new SphereOutlineGeometry(scratchOptions6);
}
Cartesian3_default.clone(ellipsoidGeometry._radii, scratchOptions6.radii);
result._ellipsoidGeometry = new EllipsoidOutlineGeometry_default(scratchOptions6);
return result;
};
SphereOutlineGeometry.createGeometry = function(sphereGeometry) {
return EllipsoidOutlineGeometry_default.createGeometry(
sphereGeometry._ellipsoidGeometry
);
};
var SphereOutlineGeometry_default = SphereOutlineGeometry;
// node_modules/@cesium/engine/Source/Scene/TileBoundingSphere.js
function TileBoundingSphere(center, radius) {
if (radius === 0) {
radius = Math_default.EPSILON7;
}
this._boundingSphere = new BoundingSphere_default(center, radius);
}
Object.defineProperties(TileBoundingSphere.prototype, {
center: {
get: function() {
return this._boundingSphere.center;
}
},
radius: {
get: function() {
return this._boundingSphere.radius;
}
},
boundingVolume: {
get: function() {
return this._boundingSphere;
}
},
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
TileBoundingSphere.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
const boundingSphere = this._boundingSphere;
return Math.max(
0,
Cartesian3_default.distance(boundingSphere.center, frameState.camera.positionWC) - boundingSphere.radius
);
};
TileBoundingSphere.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
return BoundingSphere_default.intersectPlane(this._boundingSphere, plane);
};
TileBoundingSphere.prototype.update = function(center, radius) {
Cartesian3_default.clone(center, this._boundingSphere.center);
this._boundingSphere.radius = radius;
};
TileBoundingSphere.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const geometry = new SphereOutlineGeometry_default({
radius: this.radius
});
const modelMatrix = Matrix4_default.fromTranslation(
this.center,
new Matrix4_default.clone(Matrix4_default.IDENTITY)
);
const instance = new GeometryInstance_default({
geometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
return new Primitive_default({
geometryInstances: instance,
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileBoundingSphere_default = TileBoundingSphere;
// node_modules/@cesium/engine/Source/Scene/TileOrientedBoundingBox.js
var scratchU = new Cartesian3_default();
var scratchV = new Cartesian3_default();
var scratchW2 = new Cartesian3_default();
var scratchCartesian8 = new Cartesian3_default();
function computeMissingVector(a3, b, result) {
result = Cartesian3_default.cross(a3, b, result);
const magnitude = Cartesian3_default.magnitude(result);
return Cartesian3_default.multiplyByScalar(
result,
Math_default.EPSILON7 / magnitude,
result
);
}
function findOrthogonalVector(a3, result) {
const temp = Cartesian3_default.normalize(a3, scratchCartesian8);
const b = Cartesian3_default.equalsEpsilon(
temp,
Cartesian3_default.UNIT_X,
Math_default.EPSILON6
) ? Cartesian3_default.UNIT_Y : Cartesian3_default.UNIT_X;
return computeMissingVector(a3, b, result);
}
function checkHalfAxes(halfAxes) {
let u3 = Matrix3_default.getColumn(halfAxes, 0, scratchU);
let v7 = Matrix3_default.getColumn(halfAxes, 1, scratchV);
let w = Matrix3_default.getColumn(halfAxes, 2, scratchW2);
const uZero = Cartesian3_default.equals(u3, Cartesian3_default.ZERO);
const vZero = Cartesian3_default.equals(v7, Cartesian3_default.ZERO);
const wZero = Cartesian3_default.equals(w, Cartesian3_default.ZERO);
if (!uZero && !vZero && !wZero) {
return halfAxes;
}
if (uZero && vZero && wZero) {
halfAxes[0] = Math_default.EPSILON7;
halfAxes[4] = Math_default.EPSILON7;
halfAxes[8] = Math_default.EPSILON7;
return halfAxes;
}
if (uZero && !vZero && !wZero) {
u3 = computeMissingVector(v7, w, u3);
} else if (!uZero && vZero && !wZero) {
v7 = computeMissingVector(u3, w, v7);
} else if (!uZero && !vZero && wZero) {
w = computeMissingVector(v7, u3, w);
} else if (!uZero) {
v7 = findOrthogonalVector(u3, v7);
w = computeMissingVector(v7, u3, w);
} else if (!vZero) {
u3 = findOrthogonalVector(v7, u3);
w = computeMissingVector(v7, u3, w);
} else if (!wZero) {
u3 = findOrthogonalVector(w, u3);
v7 = computeMissingVector(w, u3, v7);
}
Matrix3_default.setColumn(halfAxes, 0, u3, halfAxes);
Matrix3_default.setColumn(halfAxes, 1, v7, halfAxes);
Matrix3_default.setColumn(halfAxes, 2, w, halfAxes);
return halfAxes;
}
function TileOrientedBoundingBox(center, halfAxes) {
halfAxes = checkHalfAxes(halfAxes);
this._orientedBoundingBox = new OrientedBoundingBox_default(center, halfAxes);
this._boundingSphere = BoundingSphere_default.fromOrientedBoundingBox(
this._orientedBoundingBox
);
}
Object.defineProperties(TileOrientedBoundingBox.prototype, {
boundingVolume: {
get: function() {
return this._orientedBoundingBox;
}
},
boundingSphere: {
get: function() {
return this._boundingSphere;
}
}
});
TileOrientedBoundingBox.prototype.distanceToCamera = function(frameState) {
Check_default.defined("frameState", frameState);
return Math.sqrt(
this._orientedBoundingBox.distanceSquaredTo(frameState.camera.positionWC)
);
};
TileOrientedBoundingBox.prototype.intersectPlane = function(plane) {
Check_default.defined("plane", plane);
return this._orientedBoundingBox.intersectPlane(plane);
};
TileOrientedBoundingBox.prototype.update = function(center, halfAxes) {
Cartesian3_default.clone(center, this._orientedBoundingBox.center);
halfAxes = checkHalfAxes(halfAxes);
Matrix3_default.clone(halfAxes, this._orientedBoundingBox.halfAxes);
BoundingSphere_default.fromOrientedBoundingBox(
this._orientedBoundingBox,
this._boundingSphere
);
};
TileOrientedBoundingBox.prototype.createDebugVolume = function(color) {
Check_default.defined("color", color);
const geometry = new BoxOutlineGeometry_default({
minimum: new Cartesian3_default(-1, -1, -1),
maximum: new Cartesian3_default(1, 1, 1)
});
const modelMatrix = Matrix4_default.fromRotationTranslation(
this.boundingVolume.halfAxes,
this.boundingVolume.center
);
const instance = new GeometryInstance_default({
geometry,
id: "outline",
modelMatrix,
attributes: {
color: ColorGeometryInstanceAttribute_default.fromColor(color)
}
});
return new Primitive_default({
geometryInstances: instance,
appearance: new PerInstanceColorAppearance_default({
translucent: false,
flat: true
}),
asynchronous: false
});
};
var TileOrientedBoundingBox_default = TileOrientedBoundingBox;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTile.js
function Cesium3DTile(tileset, baseResource2, header, parent) {
this._tileset = tileset;
this._header = header;
const hasContentsArray = defined_default(header.contents);
const hasMultipleContents = hasContentsArray && header.contents.length > 1 || hasExtension_default(header, "3DTILES_multiple_contents");
const contentHeader = hasContentsArray && !hasMultipleContents ? header.contents[0] : header.content;
this._contentHeader = contentHeader;
this.transform = defined_default(header.transform) ? Matrix4_default.unpack(header.transform) : Matrix4_default.clone(Matrix4_default.IDENTITY);
const parentTransform = defined_default(parent) ? parent.computedTransform : tileset.modelMatrix;
const computedTransform = Matrix4_default.multiply(
parentTransform,
this.transform,
new Matrix4_default()
);
const parentInitialTransform = defined_default(parent) ? parent._initialTransform : Matrix4_default.IDENTITY;
this._initialTransform = Matrix4_default.multiply(
parentInitialTransform,
this.transform,
new Matrix4_default()
);
this.computedTransform = computedTransform;
this._boundingVolume = this.createBoundingVolume(
header.boundingVolume,
computedTransform
);
this._boundingVolume2D = void 0;
let contentBoundingVolume;
if (defined_default(contentHeader) && defined_default(contentHeader.boundingVolume)) {
contentBoundingVolume = this.createBoundingVolume(
contentHeader.boundingVolume,
computedTransform
);
}
this._contentBoundingVolume = contentBoundingVolume;
this._contentBoundingVolume2D = void 0;
let viewerRequestVolume;
if (defined_default(header.viewerRequestVolume)) {
viewerRequestVolume = this.createBoundingVolume(
header.viewerRequestVolume,
computedTransform
);
}
this._viewerRequestVolume = viewerRequestVolume;
this.geometricError = header.geometricError;
this._geometricError = header.geometricError;
if (!defined_default(this._geometricError)) {
this._geometricError = defined_default(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_default(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_default.REPLACE : Cesium3DTileRefine_default.ADD;
} else if (defined_default(parent)) {
refine = parent.refine;
} else {
refine = Cesium3DTileRefine_default.REPLACE;
}
this.refine = refine;
this.children = [];
this.parent = parent;
let content;
let hasEmptyContent = false;
let contentState;
let contentResource;
let serverKey;
baseResource2 = Resource_default.createIfNeeded(baseResource2);
if (hasMultipleContents) {
contentState = Cesium3DTileContentState_default.UNLOADED;
contentResource = baseResource2.clone();
} else if (defined_default(contentHeader)) {
let contentHeaderUri = contentHeader.uri;
if (defined_default(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_default(tileset, this);
hasEmptyContent = true;
contentState = Cesium3DTileContentState_default.READY;
} else {
contentState = Cesium3DTileContentState_default.UNLOADED;
contentResource = baseResource2.getDerivedResource({
url: contentHeaderUri
});
serverKey = RequestScheduler_default.getServerKey(
contentResource.getUrlComponent()
);
}
} else {
content = new Empty3DTileContent_default(tileset, this);
hasEmptyContent = true;
contentState = Cesium3DTileContentState_default.READY;
}
this._content = content;
this._contentResource = contentResource;
this._contentState = contentState;
this._expiredContent = void 0;
this._serverKey = serverKey;
this.hasEmptyContent = hasEmptyContent;
this.hasTilesetContent = false;
this.hasImplicitContent = false;
this.hasImplicitContentMetadata = false;
this.hasMultipleContents = hasMultipleContents;
this.metadata = findTileMetadata_default(tileset, header);
this.cacheNode = void 0;
const expire = header.expire;
let expireDuration;
let expireDate;
if (defined_default(expire)) {
expireDuration = expire.duration;
if (defined_default(expire.date)) {
expireDate = JulianDate_default.fromIso8601(expire.date);
}
}
this.expireDuration = expireDuration;
this.expireDate = expireDate;
this.lastStyleTime = 0;
this._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.NOT_COMPUTED;
this.clippingPlanesDirty = false;
this.priorityDeferred = false;
this.implicitTileset = void 0;
this.implicitCoordinates = void 0;
this.implicitSubtree = void 0;
this._distanceToCamera = 0;
this._centerZDepth = 0;
this._screenSpaceError = 0;
this._screenSpaceErrorProgressiveResolution = 0;
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 = void 0;
this._ancestorWithContentAvailable = void 0;
this._refines = false;
this._shouldSelect = false;
this._isClipped = true;
this._clippingPlanesState = 0;
this._debugBoundingVolume = void 0;
this._debugContentBoundingVolume = void 0;
this._debugViewerRequestVolume = void 0;
this._debugColor = Color_default.fromRandom({ alpha: 1 });
this._debugColorizeTiles = false;
this._priority = 0;
this._priorityHolder = this;
this._priorityProgressiveResolution = false;
this._priorityProgressiveResolutionScreenSpaceErrorLeaf = false;
this._priorityReverseScreenSpaceError = 0;
this._foveatedFactor = 0;
this._wasMinPriorityChild = false;
this._loadTimestamp = new JulianDate_default();
this._commandsLength = 0;
this._color = void 0;
this._colorDirty = false;
this._request = void 0;
}
Cesium3DTile._deprecationWarning = deprecationWarning_default;
Object.defineProperties(Cesium3DTile.prototype, {
tileset: {
get: function() {
return this._tileset;
}
},
content: {
get: function() {
return this._content;
}
},
boundingVolume: {
get: function() {
return this._boundingVolume;
}
},
contentBoundingVolume: {
get: function() {
return defaultValue_default(this._contentBoundingVolume, this._boundingVolume);
}
},
boundingSphere: {
get: function() {
return this._boundingVolume.boundingSphere;
}
},
isVisible: {
get: function() {
return this._visible && this._inRequestVolume;
}
},
extras: {
get: function() {
return this._header.extras;
}
},
color: {
get: function() {
if (!defined_default(this._color)) {
this._color = new Color_default();
}
return Color_default.clone(this._color);
},
set: function(value) {
this._color = Color_default.clone(value, this._color);
this._colorDirty = true;
}
},
hasRenderableContent: {
get: function() {
return !this.hasEmptyContent && !this.hasTilesetContent && !this.hasImplicitContent;
}
},
contentAvailable: {
get: function() {
return this.contentReady && this.hasRenderableContent || defined_default(this._expiredContent) && !this.contentFailed;
}
},
contentReady: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.READY;
}
},
contentUnloaded: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.UNLOADED;
}
},
hasUnloadedRenderableContent: {
get: function() {
return this.hasRenderableContent && this.contentUnloaded;
}
},
contentExpired: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.EXPIRED;
}
},
contentFailed: {
get: function() {
return this._contentState === Cesium3DTileContentState_default.FAILED;
}
},
commandsLength: {
get: function() {
return this._commandsLength;
}
}
});
var scratchCartesian9 = new Cartesian3_default();
function isPriorityDeferred(tile, frameState) {
const { tileset, boundingSphere } = tile;
const { radius, center } = boundingSphere;
const { camera } = frameState;
const scaledCameraDirection = Cartesian3_default.multiplyByScalar(
camera.directionWC,
tile._centerZDepth,
scratchCartesian9
);
const closestPointOnLine = Cartesian3_default.add(
camera.positionWC,
scaledCameraDirection,
scratchCartesian9
);
const toLine = Cartesian3_default.subtract(
closestPointOnLine,
center,
scratchCartesian9
);
const distanceToCenterLine = Cartesian3_default.magnitude(toLine);
const notTouchingSphere = distanceToCenterLine > radius;
if (notTouchingSphere) {
const toLineNormalized = Cartesian3_default.normalize(toLine, scratchCartesian9);
const scaledToLine = Cartesian3_default.multiplyByScalar(
toLineNormalized,
radius,
scratchCartesian9
);
const closestOnSphere = Cartesian3_default.add(
center,
scaledToLine,
scratchCartesian9
);
const toClosestOnSphere = Cartesian3_default.subtract(
closestOnSphere,
camera.positionWC,
scratchCartesian9
);
const toClosestOnSphereNormalize = Cartesian3_default.normalize(
toClosestOnSphere,
scratchCartesian9
);
tile._foveatedFactor = 1 - Math.abs(Cartesian3_default.dot(camera.directionWC, toClosestOnSphereNormalize));
} else {
tile._foveatedFactor = 0;
}
const replace = tile.refine === Cesium3DTileRefine_default.REPLACE;
const skipLevelOfDetail = tileset.isSkippingLevelOfDetail;
if (replace && !skipLevelOfDetail || !tileset.foveatedScreenSpaceError || tileset.foveatedConeSize === 1 || tile._priorityProgressiveResolution && replace && skipLevelOfDetail || tileset._pass === Cesium3DTilePass_default.PRELOAD_FLIGHT || tileset._pass === Cesium3DTilePass_default.PRELOAD) {
return false;
}
const maximumFovatedFactor = 1 - Math.cos(camera.frustum.fov * 0.5);
const foveatedConeFactor = tileset.foveatedConeSize * maximumFovatedFactor;
if (tile._foveatedFactor <= foveatedConeFactor) {
return false;
}
const range = maximumFovatedFactor - foveatedConeFactor;
const normalizedFoveatedFactor = Math_default.clamp(
(tile._foveatedFactor - foveatedConeFactor) / range,
0,
1
);
const sseRelaxation = tileset.foveatedInterpolationCallback(
tileset.foveatedMinimumScreenSpaceErrorRelaxation,
tileset.maximumScreenSpaceError,
normalizedFoveatedFactor
);
const sse = tile._screenSpaceError === 0 && defined_default(tile.parent) ? tile.parent._screenSpaceError * 0.5 : tile._screenSpaceError;
return tileset.maximumScreenSpaceError - sseRelaxation <= sse;
}
var scratchJulianDate = new JulianDate_default();
Cesium3DTile.prototype.getScreenSpaceError = function(frameState, useParentGeometricError, progressiveResolutionHeightFraction) {
const tileset = this._tileset;
const heightFraction = defaultValue_default(progressiveResolutionHeightFraction, 1);
const parentGeometricError = defined_default(this.parent) ? this.parent.geometricError : tileset._scaledGeometricError;
const geometricError = useParentGeometricError ? parentGeometricError : this.geometricError;
if (geometricError === 0) {
return 0;
}
const { camera, context } = frameState;
let frustum = camera.frustum;
const width = context.drawingBufferWidth;
const height = context.drawingBufferHeight * heightFraction;
let error;
if (frameState.mode === SceneMode_default.SCENE2D || frustum instanceof OrthographicFrustum_default) {
const offCenterFrustum = frustum.offCenterFrustum;
if (defined_default(offCenterFrustum)) {
frustum = offCenterFrustum;
}
const pixelSize = Math.max(frustum.top - frustum.bottom, frustum.right - frustum.left) / Math.max(width, height);
error = geometricError / pixelSize;
} else {
const distance2 = Math.max(this._distanceToCamera, Math_default.EPSILON7);
const sseDenominator = frustum.sseDenominator;
error = geometricError * height / (distance2 * sseDenominator);
if (tileset.dynamicScreenSpaceError) {
const density = tileset._dynamicScreenSpaceErrorComputedDensity;
const factor2 = tileset.dynamicScreenSpaceErrorFactor;
const dynamicError = Math_default.fog(distance2, density) * factor2;
error -= dynamicError;
}
}
error /= frameState.pixelRatio;
return error;
};
function isPriorityProgressiveResolution(tileset, tile) {
if (tileset.progressiveResolutionHeightFraction <= 0 || tileset.progressiveResolutionHeightFraction > 0.5) {
return false;
}
let isProgressiveResolutionTile = tile._screenSpaceErrorProgressiveResolution > tileset._maximumScreenSpaceError;
tile._priorityProgressiveResolutionScreenSpaceErrorLeaf = false;
const parent = tile.parent;
const maximumScreenSpaceError = tileset._maximumScreenSpaceError;
const tilePasses = tile._screenSpaceErrorProgressiveResolution <= maximumScreenSpaceError;
const parentFails = defined_default(parent) && parent._screenSpaceErrorProgressiveResolution > maximumScreenSpaceError;
if (tilePasses && parentFails) {
tile._priorityProgressiveResolutionScreenSpaceErrorLeaf = true;
isProgressiveResolutionTile = true;
}
return isProgressiveResolutionTile;
}
function getPriorityReverseScreenSpaceError(tileset, tile) {
const parent = tile.parent;
const useParentScreenSpaceError = defined_default(parent) && (!tileset.isSkippingLevelOfDetail || tile._screenSpaceError === 0 || parent.hasTilesetContent || parent.hasImplicitContent);
const screenSpaceError2 = useParentScreenSpaceError ? parent._screenSpaceError : tile._screenSpaceError;
return tileset.root._screenSpaceError - screenSpaceError2;
}
Cesium3DTile.prototype.updateVisibility = function(frameState) {
const { parent, tileset } = this;
if (this._updatedVisibilityFrame === tileset._updatedVisibilityFrame) {
return;
}
const parentTransform = defined_default(parent) ? parent.computedTransform : tileset.modelMatrix;
const parentVisibilityPlaneMask = defined_default(parent) ? parent._visibilityPlaneMask : CullingVolume_default.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
);
this._visible = this._visibilityPlaneMask !== CullingVolume_default.MASK_OUTSIDE;
this._inRequestVolume = this.insideViewerRequestVolume(frameState);
this._priorityReverseScreenSpaceError = getPriorityReverseScreenSpaceError(
tileset,
this
);
this._priorityProgressiveResolution = isPriorityProgressiveResolution(
tileset,
this
);
this.priorityDeferred = isPriorityDeferred(this, frameState);
this._updatedVisibilityFrame = tileset._updatedVisibilityFrame;
};
Cesium3DTile.prototype.updateExpiration = function() {
if (defined_default(this.expireDate) && this.contentReady && !this.hasEmptyContent && !this.hasMultipleContents) {
const now2 = JulianDate_default.now(scratchJulianDate);
if (JulianDate_default.lessThan(this.expireDate, now2)) {
this._contentState = Cesium3DTileContentState_default.EXPIRED;
this._expiredContent = this._content;
}
}
};
function updateExpireDate(tile) {
if (!defined_default(tile.expireDuration)) {
return;
}
const expireDurationDate = JulianDate_default.now(scratchJulianDate);
JulianDate_default.addSeconds(
expireDurationDate,
tile.expireDuration,
expireDurationDate
);
if (defined_default(tile.expireDate)) {
if (JulianDate_default.lessThan(tile.expireDate, expireDurationDate)) {
JulianDate_default.clone(expireDurationDate, tile.expireDate);
}
} else {
tile.expireDate = JulianDate_default.clone(expireDurationDate);
}
}
function createPriorityFunction(tile) {
return function() {
return tile._priority;
};
}
Cesium3DTile.prototype.requestContent = function() {
if (this.hasEmptyContent) {
return;
}
if (this.hasMultipleContents) {
return requestMultipleContents(this);
}
return requestSingleContent(this);
};
function requestMultipleContents(tile) {
let multipleContents = tile._content;
const tileset = tile._tileset;
if (!defined_default(multipleContents)) {
const contentsJson = hasExtension_default(tile._header, "3DTILES_multiple_contents") ? tile._header.extensions["3DTILES_multiple_contents"] : tile._header;
multipleContents = new Multiple3DTileContent_default(
tileset,
tile,
tile._contentResource.clone(),
contentsJson
);
tile._content = multipleContents;
}
const promise = multipleContents.requestInnerContents();
if (!defined_default(promise)) {
return;
}
tile._contentState = Cesium3DTileContentState_default.LOADING;
return promise.then((content) => {
if (tile.isDestroyed()) {
return;
}
if (!defined_default(content)) {
return;
}
tile._contentState = Cesium3DTileContentState_default.PROCESSING;
return multipleContents;
}).catch((error) => {
if (tile.isDestroyed()) {
return;
}
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
});
}
async function processArrayBuffer(tile, tileset, request, expired, requestPromise) {
const previousState = tile._contentState;
tile._contentState = Cesium3DTileContentState_default.LOADING;
++tileset.statistics.numberOfPendingRequests;
let arrayBuffer;
try {
arrayBuffer = await requestPromise;
} catch (error) {
--tileset.statistics.numberOfPendingRequests;
if (tile.isDestroyed()) {
return;
}
if (request.cancelled || request.state === RequestState_default.CANCELLED) {
tile._contentState = previousState;
++tileset.statistics.numberOfAttemptedRequests;
return;
}
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
if (tile.isDestroyed()) {
--tileset.statistics.numberOfPendingRequests;
return;
}
if (request.cancelled || request.state === RequestState_default.CANCELLED) {
tile._contentState = previousState;
--tileset.statistics.numberOfPendingRequests;
++tileset.statistics.numberOfAttemptedRequests;
return;
}
try {
const content = await makeContent(tile, arrayBuffer);
--tileset.statistics.numberOfPendingRequests;
if (tile.isDestroyed()) {
return;
}
if (expired) {
tile.expireDate = void 0;
}
tile._content = content;
tile._contentState = Cesium3DTileContentState_default.PROCESSING;
return content;
} catch (error) {
--tileset.statistics.numberOfPendingRequests;
if (tile.isDestroyed()) {
return;
}
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
}
function requestSingleContent(tile) {
const resource = tile._contentResource.clone();
const expired = tile.contentExpired;
if (expired) {
resource.setQueryParameters({
expired: tile.expireDate.toString()
});
}
const request = new Request_default({
throttle: true,
throttleByServer: true,
type: RequestType_default.TILES3D,
priorityFunction: createPriorityFunction(tile),
serverKey: tile._serverKey
});
tile._request = request;
resource.request = request;
const tileset = tile._tileset;
const promise = resource.fetchArrayBuffer();
if (!defined_default(promise)) {
++tileset.statistics.numberOfAttemptedRequests;
return;
}
return processArrayBuffer(tile, tileset, request, expired, promise);
}
async function makeContent(tile, arrayBuffer) {
const preprocessed = preprocess3DTileContent_default(arrayBuffer);
const tileset = tile._tileset;
tileset._disableSkipLevelOfDetail = tileset._disableSkipLevelOfDetail || preprocessed.contentType === Cesium3DTileContentType_default.GEOMETRY || preprocessed.contentType === Cesium3DTileContentType_default.VECTOR;
if (preprocessed.contentType === Cesium3DTileContentType_default.IMPLICIT_SUBTREE || preprocessed.contentType === Cesium3DTileContentType_default.IMPLICIT_SUBTREE_JSON) {
tile.hasImplicitContent = true;
}
if (preprocessed.contentType === Cesium3DTileContentType_default.EXTERNAL_TILESET) {
tile.hasTilesetContent = true;
}
let content;
const contentFactory = Cesium3DTileContentFactory_default[preprocessed.contentType];
if (tile.isDestroyed()) {
return;
}
if (defined_default(preprocessed.binaryPayload)) {
content = await Promise.resolve(
contentFactory(
tileset,
tile,
tile._contentResource,
preprocessed.binaryPayload.buffer,
0
)
);
} else {
content = await Promise.resolve(
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_default(tileset, contentHeader);
}
const groupMetadata = findGroupMetadata_default(tileset, contentHeader);
if (defined_default(groupMetadata)) {
content.group = new Cesium3DContentGroup_default({
metadata: groupMetadata
});
}
return content;
}
Cesium3DTile.prototype.cancelRequests = function() {
if (this.hasMultipleContents) {
this._content.cancelRequests();
} else {
this._request.cancel();
}
};
Cesium3DTile.prototype.unloadContent = function() {
if (!this.hasRenderableContent) {
return;
}
this._content = this._content && this._content.destroy();
this._contentState = Cesium3DTileContentState_default.UNLOADED;
this.lastStyleTime = 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();
};
var scratchProjectedBoundingSphere = new BoundingSphere_default();
function getBoundingVolume(tile, frameState) {
if (frameState.mode !== SceneMode_default.SCENE3D && !defined_default(tile._boundingVolume2D)) {
const boundingSphere = tile._boundingVolume.boundingSphere;
const sphere = BoundingSphere_default.projectTo2D(
boundingSphere,
frameState.mapProjection,
scratchProjectedBoundingSphere
);
tile._boundingVolume2D = new TileBoundingSphere_default(
sphere.center,
sphere.radius
);
}
return frameState.mode !== SceneMode_default.SCENE3D ? tile._boundingVolume2D : tile._boundingVolume;
}
function getContentBoundingVolume2(tile, frameState) {
if (frameState.mode !== SceneMode_default.SCENE3D && !defined_default(tile._contentBoundingVolume2D)) {
const boundingSphere = tile._contentBoundingVolume.boundingSphere;
const sphere = BoundingSphere_default.projectTo2D(
boundingSphere,
frameState.mapProjection,
scratchProjectedBoundingSphere
);
tile._contentBoundingVolume2D = new TileBoundingSphere_default(
sphere.center,
sphere.radius
);
}
return frameState.mode !== SceneMode_default.SCENE3D ? tile._contentBoundingVolume2D : tile._contentBoundingVolume;
}
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_default(clippingPlanes) && clippingPlanes.enabled) {
const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
boundingVolume,
tileset.clippingPlanesOriginMatrix
);
this._isClipped = intersection !== Intersect_default.INSIDE;
if (intersection === Intersect_default.OUTSIDE) {
return CullingVolume_default.MASK_OUTSIDE;
}
}
return cullingVolume.computeVisibilityWithPlaneMask(
boundingVolume,
parentVisibilityPlaneMask
);
};
Cesium3DTile.prototype.contentVisibility = function(frameState) {
if (!defined_default(this._contentBoundingVolume)) {
return Intersect_default.INSIDE;
}
if (this._visibilityPlaneMask === CullingVolume_default.MASK_INSIDE) {
return Intersect_default.INSIDE;
}
const cullingVolume = frameState.cullingVolume;
const boundingVolume = getContentBoundingVolume2(this, frameState);
const tileset = this._tileset;
const clippingPlanes = tileset.clippingPlanes;
if (defined_default(clippingPlanes) && clippingPlanes.enabled) {
const intersection = clippingPlanes.computeIntersectionWithBoundingVolume(
boundingVolume,
tileset.clippingPlanesOriginMatrix
);
this._isClipped = intersection !== Intersect_default.INSIDE;
if (intersection === Intersect_default.OUTSIDE) {
return Intersect_default.OUTSIDE;
}
}
return cullingVolume.computeVisibility(boundingVolume);
};
Cesium3DTile.prototype.distanceToTile = function(frameState) {
const boundingVolume = getBoundingVolume(this, frameState);
return boundingVolume.distanceToCamera(frameState);
};
var scratchToTileCenter = new Cartesian3_default();
Cesium3DTile.prototype.distanceToTileCenter = function(frameState) {
const tileBoundingVolume = getBoundingVolume(this, frameState);
const boundingVolume = tileBoundingVolume.boundingVolume;
const toCenter = Cartesian3_default.subtract(
boundingVolume.center,
frameState.camera.positionWC,
scratchToTileCenter
);
return Cartesian3_default.dot(frameState.camera.directionWC, toCenter);
};
Cesium3DTile.prototype.insideViewerRequestVolume = function(frameState) {
const viewerRequestVolume = this._viewerRequestVolume;
return !defined_default(viewerRequestVolume) || viewerRequestVolume.distanceToCamera(frameState) === 0;
};
var scratchMatrix2 = new Matrix3_default();
var scratchScale3 = new Cartesian3_default();
var scratchHalfAxes2 = new Matrix3_default();
var scratchCenter4 = new Cartesian3_default();
var scratchRectangle3 = new Rectangle_default();
var scratchOrientedBoundingBox = new OrientedBoundingBox_default();
var scratchTransform = new Matrix4_default();
function createBox(box, transform3, result) {
let center = Cartesian3_default.fromElements(box[0], box[1], box[2], scratchCenter4);
let halfAxes = Matrix3_default.fromArray(box, 3, scratchHalfAxes2);
center = Matrix4_default.multiplyByPoint(transform3, center, center);
const rotationScale = Matrix4_default.getMatrix3(transform3, scratchMatrix2);
halfAxes = Matrix3_default.multiply(rotationScale, halfAxes, halfAxes);
if (defined_default(result)) {
result.update(center, halfAxes);
return result;
}
return new TileOrientedBoundingBox_default(center, halfAxes);
}
function createBoxFromTransformedRegion(region, transform3, initialTransform, result) {
const rectangle = Rectangle_default.unpack(region, 0, scratchRectangle3);
const minimumHeight = region[4];
const maximumHeight = region[5];
const orientedBoundingBox = OrientedBoundingBox_default.fromRectangle(
rectangle,
minimumHeight,
maximumHeight,
Ellipsoid_default.WGS84,
scratchOrientedBoundingBox
);
let center = orientedBoundingBox.center;
let halfAxes = orientedBoundingBox.halfAxes;
transform3 = Matrix4_default.multiplyTransformation(
transform3,
Matrix4_default.inverseTransformation(initialTransform, scratchTransform),
scratchTransform
);
center = Matrix4_default.multiplyByPoint(transform3, center, center);
const rotationScale = Matrix4_default.getMatrix3(transform3, scratchMatrix2);
halfAxes = Matrix3_default.multiply(rotationScale, halfAxes, halfAxes);
if (defined_default(result) && result instanceof TileOrientedBoundingBox_default) {
result.update(center, halfAxes);
return result;
}
return new TileOrientedBoundingBox_default(center, halfAxes);
}
function createRegion(region, transform3, initialTransform, result) {
if (!Matrix4_default.equalsEpsilon(transform3, initialTransform, Math_default.EPSILON8)) {
return createBoxFromTransformedRegion(
region,
transform3,
initialTransform,
result
);
}
if (defined_default(result)) {
return result;
}
const rectangleRegion = Rectangle_default.unpack(region, 0, scratchRectangle3);
return new TileBoundingRegion_default({
rectangle: rectangleRegion,
minimumHeight: region[4],
maximumHeight: region[5]
});
}
function createSphere(sphere, transform3, result) {
let center = Cartesian3_default.fromElements(
sphere[0],
sphere[1],
sphere[2],
scratchCenter4
);
let radius = sphere[3];
center = Matrix4_default.multiplyByPoint(transform3, center, center);
const scale = Matrix4_default.getScale(transform3, scratchScale3);
const uniformScale = Cartesian3_default.maximumComponent(scale);
radius *= uniformScale;
if (defined_default(result)) {
result.update(center, radius);
return result;
}
return new TileBoundingSphere_default(center, radius);
}
Cesium3DTile.prototype.createBoundingVolume = function(boundingVolumeHeader, transform3, result) {
if (!defined_default(boundingVolumeHeader)) {
throw new RuntimeError_default("boundingVolume must be defined");
}
if (hasExtension_default(boundingVolumeHeader, "3DTILES_bounding_volume_S2")) {
return new TileBoundingS2Cell_default(
boundingVolumeHeader.extensions["3DTILES_bounding_volume_S2"]
);
}
const { box, region, sphere } = boundingVolumeHeader;
if (defined_default(box)) {
return createBox(box, transform3, result);
}
if (defined_default(region)) {
return createRegion(region, transform3, this._initialTransform, result);
}
if (defined_default(sphere)) {
return createSphere(sphere, transform3, result);
}
throw new RuntimeError_default(
"boundingVolume must contain a sphere, region, or box"
);
};
Cesium3DTile.prototype.updateTransform = function(parentTransform) {
parentTransform = defaultValue_default(parentTransform, Matrix4_default.IDENTITY);
const computedTransform = Matrix4_default.multiplyTransformation(
parentTransform,
this.transform,
scratchTransform
);
const transformChanged = !Matrix4_default.equals(
computedTransform,
this.computedTransform
);
if (!transformChanged) {
return;
}
Matrix4_default.clone(computedTransform, this.computedTransform);
const header = this._header;
const contentHeader = this._contentHeader;
this._boundingVolume = this.createBoundingVolume(
header.boundingVolume,
this.computedTransform,
this._boundingVolume
);
if (defined_default(this._contentBoundingVolume)) {
this._contentBoundingVolume = this.createBoundingVolume(
contentHeader.boundingVolume,
this.computedTransform,
this._contentBoundingVolume
);
}
if (defined_default(this._viewerRequestVolume)) {
this._viewerRequestVolume = this.createBoundingVolume(
header.viewerRequestVolume,
this.computedTransform,
this._viewerRequestVolume
);
}
this.updateGeometricErrorScale();
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_default.getScale(this.computedTransform, scratchScale3);
const uniformScale = Cartesian3_default.maximumComponent(scale);
this.geometricError = this._geometricError * uniformScale;
if (!defined_default(this.parent)) {
const tileset = this._tileset;
tileset._scaledGeometricError = tileset._geometricError * uniformScale;
}
};
function applyDebugSettings(tile, tileset, frameState, passOptions2) {
if (!passOptions2.isRender) {
return;
}
const hasContentBoundingVolume = defined_default(tile._contentHeader) && defined_default(tile._contentHeader.boundingVolume);
const showVolume = tileset.debugShowBoundingVolume || tileset.debugShowContentBoundingVolume && !hasContentBoundingVolume;
if (showVolume) {
let color;
if (!tile._finalResolution) {
color = Color_default.YELLOW;
} else if (!tile.hasRenderableContent) {
color = Color_default.DARKGRAY;
} else {
color = Color_default.WHITE;
}
if (!defined_default(tile._debugBoundingVolume)) {
tile._debugBoundingVolume = tile._boundingVolume.createDebugVolume(color);
}
tile._debugBoundingVolume.update(frameState);
const attributes = tile._debugBoundingVolume.getGeometryInstanceAttributes(
"outline"
);
attributes.color = ColorGeometryInstanceAttribute_default.toValue(
color,
attributes.color
);
} else if (!showVolume && defined_default(tile._debugBoundingVolume)) {
tile._debugBoundingVolume = tile._debugBoundingVolume.destroy();
}
if (tileset.debugShowContentBoundingVolume && hasContentBoundingVolume) {
if (!defined_default(tile._debugContentBoundingVolume)) {
tile._debugContentBoundingVolume = tile._contentBoundingVolume.createDebugVolume(
Color_default.BLUE
);
}
tile._debugContentBoundingVolume.update(frameState);
} else if (!tileset.debugShowContentBoundingVolume && defined_default(tile._debugContentBoundingVolume)) {
tile._debugContentBoundingVolume = tile._debugContentBoundingVolume.destroy();
}
if (tileset.debugShowViewerRequestVolume && defined_default(tile._viewerRequestVolume)) {
if (!defined_default(tile._debugViewerRequestVolume)) {
tile._debugViewerRequestVolume = tile._viewerRequestVolume.createDebugVolume(
Color_default.YELLOW
);
}
tile._debugViewerRequestVolume.update(frameState);
} else if (!tileset.debugShowViewerRequestVolume && defined_default(tile._debugViewerRequestVolume)) {
tile._debugViewerRequestVolume = tile._debugViewerRequestVolume.destroy();
}
const debugColorizeTilesOn = tileset.debugColorizeTiles && !tile._debugColorizeTiles || defined_default(tileset._heatmap.tilePropertyName);
const debugColorizeTilesOff = !tileset.debugColorizeTiles && tile._debugColorizeTiles;
if (debugColorizeTilesOn) {
tileset._heatmap.colorize(tile, frameState);
tile._debugColorizeTiles = true;
tile.color = tile._debugColor;
} else if (debugColorizeTilesOff) {
tile._debugColorizeTiles = false;
tile.color = Color_default.WHITE;
}
if (tile._colorDirty) {
tile._colorDirty = false;
tile._content.applyDebugSettings(true, tile._color);
}
if (debugColorizeTilesOff) {
tileset.makeStyleDirty();
}
}
function updateContent(tile, tileset, frameState) {
const expiredContent = tile._expiredContent;
if (!tile.hasMultipleContents && defined_default(expiredContent)) {
if (!tile.contentReady) {
try {
expiredContent.update(tileset, frameState);
} catch (error) {
}
return;
}
tile._expiredContent.destroy();
tile._expiredContent = void 0;
}
if (!defined_default(tile.content)) {
return;
}
try {
tile.content.update(tileset, frameState);
} catch (error) {
tile._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
}
function updateClippingPlanes2(tile, tileset) {
const clippingPlanes = tileset.clippingPlanes;
let currentClippingPlanesState = 0;
if (defined_default(clippingPlanes) && tile._isClipped && clippingPlanes.enabled) {
currentClippingPlanesState = clippingPlanes.clippingPlanesState;
}
if (currentClippingPlanesState !== tile._clippingPlanesState) {
tile._clippingPlanesState = currentClippingPlanesState;
tile.clippingPlanesDirty = true;
}
}
Cesium3DTile.prototype.update = function(tileset, frameState, passOptions2) {
const { commandList } = frameState;
const commandStart = commandList.length;
updateClippingPlanes2(this, tileset);
applyDebugSettings(this, tileset, frameState, passOptions2);
updateContent(this, tileset, frameState);
const commandEnd = commandList.length;
this._commandsLength = commandEnd - commandStart;
for (let i = commandStart; i < commandEnd; ++i) {
const command = commandList[i];
const translucent = command.pass === Pass_default.TRANSLUCENT;
command.depthForTranslucentClassification = translucent;
}
this.clippingPlanesDirty = false;
};
var scratchCommandList = [];
Cesium3DTile.prototype.process = function(tileset, frameState) {
if (!this.contentExpired && !this.contentReady && this._content.ready) {
updateExpireDate(this);
this._selectedFrame = 0;
this.lastStyleTime = 0;
JulianDate_default.now(this._loadTimestamp);
this._contentState = Cesium3DTileContentState_default.READY;
if (!this.hasTilesetContent && !this.hasImplicitContent) {
tileset._statistics.incrementLoadCounts(this.content);
++tileset._statistics.numberOfTilesWithContentReady;
++tileset._statistics.numberOfLoadedTilesTotal;
tileset._cache.add(this);
}
}
const savedCommandList = frameState.commandList;
frameState.commandList = scratchCommandList;
try {
this._content.update(tileset, frameState);
} catch (error) {
this._contentState = Cesium3DTileContentState_default.FAILED;
throw error;
}
scratchCommandList.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(
Math_default.normalize(value, minimum, maximum) - Math_default.EPSILON7,
0
);
}
Cesium3DTile.prototype.updatePriority = function() {
const tileset = this.tileset;
const preferLeaves = tileset.preferLeaves;
const minimumPriority = tileset._minimumPriority;
const maximumPriority = tileset._maximumPriority;
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);
let depthDigits = priorityNormalizeAndClamp(
this._depth,
minimumPriority.depth,
maximumPriority.depth
);
depthDigits = preferLeaves ? 1 - depthDigits : depthDigits;
const useDistance = !tileset.isSkippingLevelOfDetail && this.refine === Cesium3DTileRefine_default.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_default.PRELOAD_FLIGHT ? 0 : preloadFlightScale;
this._priority = depthDigits + preferredSortingDigits + preloadProgressiveResolutionDigits + foveatedDigits + foveatedDeferDigits + preloadFlightDigits;
};
Cesium3DTile.prototype.isDestroyed = function() {
return false;
};
Cesium3DTile.prototype.destroy = function() {
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_default(this);
};
var Cesium3DTile_default = Cesium3DTile;
// node_modules/@cesium/engine/Source/Scene/GroupMetadata.js
function GroupMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const id = options.id;
const group = options.group;
const metadataClass = options.class;
Check_default.typeOf.object("options.group", group);
Check_default.typeOf.object("options.class", metadataClass);
const properties = defined_default(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, {
class: {
get: function() {
return this._class;
}
},
id: {
get: function() {
return this._id;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
GroupMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
GroupMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
GroupMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
GroupMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
GroupMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
GroupMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
GroupMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var GroupMetadata_default = GroupMetadata;
// node_modules/@cesium/engine/Source/Scene/TilesetMetadata.js
function TilesetMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const tileset = options.tileset;
const metadataClass = options.class;
Check_default.typeOf.object("options.tileset", tileset);
Check_default.typeOf.object("options.class", metadataClass);
const properties = defined_default(tileset.properties) ? tileset.properties : {};
this._class = metadataClass;
this._properties = properties;
this._extras = tileset.extras;
this._extensions = tileset.extensions;
}
Object.defineProperties(TilesetMetadata.prototype, {
class: {
get: function() {
return this._class;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
TilesetMetadata.prototype.hasProperty = function(propertyId) {
return MetadataEntity_default.hasProperty(propertyId, this._properties, this._class);
};
TilesetMetadata.prototype.hasPropertyBySemantic = function(semantic) {
return MetadataEntity_default.hasPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
TilesetMetadata.prototype.getPropertyIds = function(results) {
return MetadataEntity_default.getPropertyIds(this._properties, this._class, results);
};
TilesetMetadata.prototype.getProperty = function(propertyId) {
return MetadataEntity_default.getProperty(propertyId, this._properties, this._class);
};
TilesetMetadata.prototype.setProperty = function(propertyId, value) {
return MetadataEntity_default.setProperty(
propertyId,
value,
this._properties,
this._class
);
};
TilesetMetadata.prototype.getPropertyBySemantic = function(semantic) {
return MetadataEntity_default.getPropertyBySemantic(
semantic,
this._properties,
this._class
);
};
TilesetMetadata.prototype.setPropertyBySemantic = function(semantic, value) {
return MetadataEntity_default.setPropertyBySemantic(
semantic,
value,
this._properties,
this._class
);
};
var TilesetMetadata_default = TilesetMetadata;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetMetadata.js
function Cesium3DTilesetMetadata(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const metadataJson = options.metadataJson;
const schema = options.schema;
Check_default.typeOf.object("options.metadataJson", metadataJson);
Check_default.typeOf.object("options.schema", schema);
const metadata = defaultValue_default(metadataJson.metadata, metadataJson.tileset);
let tileset;
if (defined_default(metadata)) {
tileset = new TilesetMetadata_default({
tileset: metadata,
class: schema.classes[metadata.class]
});
}
let groupIds = [];
const groups = [];
const groupsJson = metadataJson.groups;
if (Array.isArray(groupsJson)) {
const length3 = groupsJson.length;
for (let i = 0; i < length3; i++) {
const group = groupsJson[i];
groups.push(
new GroupMetadata_default({
group,
class: schema.classes[group.class]
})
);
}
} else if (defined_default(groupsJson)) {
groupIds = Object.keys(groupsJson).sort();
const length3 = groupIds.length;
for (let i = 0; i < length3; i++) {
const groupId = groupIds[i];
if (groupsJson.hasOwnProperty(groupId)) {
const group = groupsJson[groupId];
groups.push(
new GroupMetadata_default({
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: {
get: function() {
return this._schema;
}
},
groups: {
get: function() {
return this._groups;
}
},
groupIds: {
get: function() {
return this._groupIds;
}
},
tileset: {
get: function() {
return this._tileset;
}
},
statistics: {
get: function() {
return this._statistics;
}
},
extras: {
get: function() {
return this._extras;
}
},
extensions: {
get: function() {
return this._extensions;
}
}
});
var Cesium3DTilesetMetadata_default = Cesium3DTilesetMetadata;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileOptimizations.js
var Cesium3DTileOptimizations = {};
var scratchAxis = new Cartesian3_default();
Cesium3DTileOptimizations.checkChildrenWithinParent = function(tile) {
Check_default.typeOf.object("tile", tile);
const children = tile.children;
const length3 = children.length;
const boundingVolume = tile.boundingVolume;
if (boundingVolume instanceof TileOrientedBoundingBox_default || boundingVolume instanceof TileBoundingRegion_default) {
const orientedBoundingBox = boundingVolume._orientedBoundingBox;
tile._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.USE_OPTIMIZATION;
for (let i = 0; i < length3; ++i) {
const child = children[i];
const childBoundingVolume = child.boundingVolume;
if (!(childBoundingVolume instanceof TileOrientedBoundingBox_default || childBoundingVolume instanceof TileBoundingRegion_default)) {
tile._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.SKIP_OPTIMIZATION;
break;
}
const childOrientedBoundingBox = childBoundingVolume._orientedBoundingBox;
const axis = Cartesian3_default.subtract(
childOrientedBoundingBox.center,
orientedBoundingBox.center,
scratchAxis
);
const axisLength = Cartesian3_default.magnitude(axis);
Cartesian3_default.divideByScalar(axis, axisLength, axis);
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);
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 (proj1 <= proj2 + axisLength) {
tile._optimChildrenWithinParent = Cesium3DTileOptimizationHint_default.SKIP_OPTIMIZATION;
break;
}
}
}
return tile._optimChildrenWithinParent === Cesium3DTileOptimizationHint_default.USE_OPTIMIZATION;
};
var Cesium3DTileOptimizations_default = Cesium3DTileOptimizations;
// node_modules/@cesium/engine/Source/Core/DoublyLinkedList.js
function DoublyLinkedList() {
this.head = void 0;
this.tail = void 0;
this._length = 0;
}
Object.defineProperties(DoublyLinkedList.prototype, {
length: {
get: function() {
return this._length;
}
}
});
function DoublyLinkedListNode(item, previous, next) {
this.item = item;
this.previous = previous;
this.next = next;
}
DoublyLinkedList.prototype.add = function(item) {
const node = new DoublyLinkedListNode(item, this.tail, void 0);
if (defined_default(this.tail)) {
this.tail.next = node;
this.tail = node;
} else {
this.head = node;
this.tail = node;
}
++this._length;
return node;
};
function remove(list, node) {
if (defined_default(node.previous) && defined_default(node.next)) {
node.previous.next = node.next;
node.next.previous = node.previous;
} else if (defined_default(node.previous)) {
node.previous.next = void 0;
list.tail = node.previous;
} else if (defined_default(node.next)) {
node.next.previous = void 0;
list.head = node.next;
} else {
list.head = void 0;
list.tail = void 0;
}
node.next = void 0;
node.previous = void 0;
}
DoublyLinkedList.prototype.remove = function(node) {
if (!defined_default(node)) {
return;
}
remove(this, node);
--this._length;
};
DoublyLinkedList.prototype.splice = function(node, nextNode) {
if (node === nextNode) {
return;
}
remove(this, nextNode);
const oldNodeNext = node.next;
node.next = nextNode;
if (this.tail === node) {
this.tail = nextNode;
} else {
oldNodeNext.previous = nextNode;
}
nextNode.next = oldNodeNext;
nextNode.previous = node;
};
var DoublyLinkedList_default = DoublyLinkedList;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetCache.js
function Cesium3DTilesetCache() {
this._list = new DoublyLinkedList_default();
this._sentinel = this._list.add();
this._trimTiles = false;
}
Cesium3DTilesetCache.prototype.reset = function() {
this._list.splice(this._list.tail, this._sentinel);
};
Cesium3DTilesetCache.prototype.touch = function(tile) {
const node = tile.cacheNode;
if (defined_default(node)) {
this._list.splice(this._sentinel, node);
}
};
Cesium3DTilesetCache.prototype.add = function(tile) {
if (!defined_default(tile.cacheNode)) {
tile.cacheNode = this._list.add(tile);
}
};
Cesium3DTilesetCache.prototype.unloadTile = function(tileset, tile, unloadCallback) {
const node = tile.cacheNode;
if (!defined_default(node)) {
return;
}
this._list.remove(node);
tile.cacheNode = void 0;
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;
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;
};
var Cesium3DTilesetCache_default = Cesium3DTilesetCache;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetHeatmap.js
function Cesium3DTilesetHeatmap(tilePropertyName) {
this.tilePropertyName = tilePropertyName;
this._minimum = Number.MAX_VALUE;
this._maximum = -Number.MAX_VALUE;
this._previousMinimum = Number.MAX_VALUE;
this._previousMaximum = -Number.MAX_VALUE;
this._referenceMinimum = {};
this._referenceMaximum = {};
}
function getHeatmapValue(tileValue, tilePropertyName) {
let value;
if (tilePropertyName === "_loadTimestamp") {
value = JulianDate_default.toDate(tileValue).getTime();
} else {
value = tileValue;
}
return value;
}
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_default(tilePropertyName)) {
const heatmapValue = getHeatmapValue(
tile[tilePropertyName],
tilePropertyName
);
if (!defined_default(heatmapValue)) {
heatmap.tilePropertyName = void 0;
return heatmapValue;
}
heatmap._maximum = Math.max(heatmapValue, heatmap._maximum);
heatmap._minimum = Math.min(heatmapValue, heatmap._minimum);
return heatmapValue;
}
}
var heatmapColors = [
new Color_default(0.1, 0.1, 0.1, 1),
new Color_default(0.153, 0.278, 0.878, 1),
new Color_default(0.827, 0.231, 0.49, 1),
new Color_default(0.827, 0.188, 0.22, 1),
new Color_default(1, 0.592, 0.259, 1),
new Color_default(1, 0.843, 0, 1)
];
Cesium3DTilesetHeatmap.prototype.colorize = function(tile, frameState) {
const tilePropertyName = this.tilePropertyName;
if (!defined_default(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;
}
const shiftedMax = maximum - minimum + Math_default.EPSILON7;
const shiftedValue = Math_default.clamp(
heatmapValue - minimum,
0,
shiftedMax
);
const zeroToOne = shiftedValue / shiftedMax;
const lastIndex = heatmapColors.length - 1;
const colorPosition = zeroToOne * lastIndex;
const colorPositionFloor = Math.floor(colorPosition);
const colorPositionCeil = Math.ceil(colorPosition);
const t = colorPosition - colorPositionFloor;
const colorZero = heatmapColors[colorPositionFloor];
const colorOne = heatmapColors[colorPositionCeil];
const finalColor = Color_default.clone(Color_default.WHITE);
finalColor.red = Math_default.lerp(colorZero.red, colorOne.red, t);
finalColor.green = Math_default.lerp(colorZero.green, colorOne.green, t);
finalColor.blue = Math_default.lerp(colorZero.blue, colorOne.blue, t);
tile._debugColor = finalColor;
};
Cesium3DTilesetHeatmap.prototype.resetMinimumMaximum = function() {
const tilePropertyName = this.tilePropertyName;
if (defined_default(tilePropertyName)) {
const referenceMinimum = this._referenceMinimum[tilePropertyName];
const referenceMaximum = this._referenceMaximum[tilePropertyName];
const useReference = defined_default(referenceMinimum) && defined_default(referenceMaximum);
this._previousMinimum = useReference ? referenceMinimum : this._minimum;
this._previousMaximum = useReference ? referenceMaximum : this._maximum;
this._minimum = Number.MAX_VALUE;
this._maximum = -Number.MAX_VALUE;
}
};
var Cesium3DTilesetHeatmap_default = Cesium3DTilesetHeatmap;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetStatistics.js
function Cesium3DTilesetStatistics() {
this.selected = 0;
this.visited = 0;
this.numberOfCommands = 0;
this.numberOfAttemptedRequests = 0;
this.numberOfPendingRequests = 0;
this.numberOfTilesProcessing = 0;
this.numberOfTilesWithContentReady = 0;
this.numberOfTilesTotal = 0;
this.numberOfLoadedTilesTotal = 0;
this.numberOfFeaturesSelected = 0;
this.numberOfFeaturesLoaded = 0;
this.numberOfPointsSelected = 0;
this.numberOfPointsLoaded = 0;
this.numberOfTrianglesSelected = 0;
this.numberOfTilesStyled = 0;
this.numberOfFeaturesStyled = 0;
this.numberOfTilesCulledWithChildrenUnion = 0;
this.geometryByteLength = 0;
this.texturesByteLength = 0;
this.batchTableByteLength = 0;
}
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(statistics2, content, decrement, load5) {
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 (load5) {
statistics2.numberOfFeaturesLoaded += decrement ? -featuresLength : featuresLength;
statistics2.numberOfPointsLoaded += decrement ? -pointsLength : pointsLength;
statistics2.geometryByteLength += decrement ? -geometryByteLength : geometryByteLength;
statistics2.texturesByteLength += decrement ? -texturesByteLength : texturesByteLength;
statistics2.batchTableByteLength += decrement ? -batchTableByteLength : batchTableByteLength;
} else {
statistics2.numberOfFeaturesSelected += decrement ? -featuresLength : featuresLength;
statistics2.numberOfPointsSelected += decrement ? -pointsLength : pointsLength;
statistics2.numberOfTrianglesSelected += decrement ? -trianglesLength : trianglesLength;
}
if (defined_default(contents)) {
const length3 = contents.length;
for (let i = 0; i < length3; ++i) {
updatePointAndFeatureCounts(statistics2, contents[i], decrement, load5);
}
}
}
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(statistics2, result) {
result.selected = statistics2.selected;
result.visited = statistics2.visited;
result.numberOfCommands = statistics2.numberOfCommands;
result.selected = statistics2.selected;
result.numberOfAttemptedRequests = statistics2.numberOfAttemptedRequests;
result.numberOfPendingRequests = statistics2.numberOfPendingRequests;
result.numberOfTilesProcessing = statistics2.numberOfTilesProcessing;
result.numberOfTilesWithContentReady = statistics2.numberOfTilesWithContentReady;
result.numberOfTilesTotal = statistics2.numberOfTilesTotal;
result.numberOfFeaturesSelected = statistics2.numberOfFeaturesSelected;
result.numberOfFeaturesLoaded = statistics2.numberOfFeaturesLoaded;
result.numberOfPointsSelected = statistics2.numberOfPointsSelected;
result.numberOfPointsLoaded = statistics2.numberOfPointsLoaded;
result.numberOfTrianglesSelected = statistics2.numberOfTrianglesSelected;
result.numberOfTilesStyled = statistics2.numberOfTilesStyled;
result.numberOfFeaturesStyled = statistics2.numberOfFeaturesStyled;
result.numberOfTilesCulledWithChildrenUnion = statistics2.numberOfTilesCulledWithChildrenUnion;
result.geometryByteLength = statistics2.geometryByteLength;
result.texturesByteLength = statistics2.texturesByteLength;
result.batchTableByteLength = statistics2.batchTableByteLength;
};
var Cesium3DTilesetStatistics_default = Cesium3DTilesetStatistics;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileStyleEngine.js
function Cesium3DTileStyleEngine() {
this._style = void 0;
this._styleDirty = false;
this._lastStyleTime = 0;
}
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 (!defined_default(tileset.root)) {
return;
}
if (defined_default(this._style) && !this._style._ready) {
return;
}
const styleDirty = this._styleDirty;
if (styleDirty) {
++this._lastStyleTime;
}
const lastStyleTime = this._lastStyleTime;
const statistics2 = tileset._statistics;
const tiles = styleDirty ? tileset._selectedTiles : tileset._selectedTilesToStyle;
const length3 = tiles.length;
for (let i = 0; i < length3; ++i) {
const tile = tiles[i];
if (tile.lastStyleTime !== lastStyleTime) {
const content = tile.content;
tile.lastStyleTime = lastStyleTime;
content.applyStyle(this._style);
statistics2.numberOfFeaturesStyled += content.featuresLength;
++statistics2.numberOfTilesStyled;
}
}
};
var Cesium3DTileStyleEngine_default = Cesium3DTileStyleEngine;
// node_modules/@cesium/engine/Source/Scene/ImplicitTileset.js
function ImplicitTileset(baseResource2, tileJson, metadataSchema) {
const implicitTiling = hasExtension_default(tileJson, "3DTILES_implicit_tiling") ? tileJson.extensions["3DTILES_implicit_tiling"] : tileJson.implicitTiling;
Check_default.typeOf.object("implicitTiling", implicitTiling);
this.baseResource = baseResource2;
this.geometricError = tileJson.geometricError;
this.metadataSchema = metadataSchema;
const boundingVolume = tileJson.boundingVolume;
if (!defined_default(boundingVolume.box) && !defined_default(boundingVolume.region) && !hasExtension_default(boundingVolume, "3DTILES_bounding_volume_S2") && !hasExtension_default(boundingVolume, "3DTILES_bounding_volume_cylinder")) {
throw new RuntimeError_default(
"Only box, region, 3DTILES_bounding_volume_S2, and 3DTILES_bounding_volume_cylinder are supported for implicit tiling"
);
}
this.boundingVolume = boundingVolume;
this.refine = tileJson.refine;
this.subtreeUriTemplate = new Resource_default({ url: implicitTiling.subtrees.uri });
this.contentUriTemplates = [];
this.contentHeaders = [];
const contentHeaders = gatherContentHeaders(tileJson);
for (let i = 0; i < contentHeaders.length; i++) {
const contentHeader = contentHeaders[i];
this.contentHeaders.push(clone_default(contentHeader, true));
const contentResource = new Resource_default({ url: contentHeader.uri });
this.contentUriTemplates.push(contentResource);
}
this.contentCount = this.contentHeaders.length;
this.tileHeader = makeTileHeaderTemplate(tileJson);
this.subdivisionScheme = ImplicitSubdivisionScheme_default[implicitTiling.subdivisionScheme];
this.branchingFactor = ImplicitSubdivisionScheme_default.getBranchingFactor(
this.subdivisionScheme
);
this.subtreeLevels = implicitTiling.subtreeLevels;
if (defined_default(implicitTiling.availableLevels)) {
this.availableLevels = implicitTiling.availableLevels;
} else {
this.availableLevels = implicitTiling.maximumLevel + 1;
}
}
function gatherContentHeaders(tileJson) {
if (hasExtension_default(tileJson, "3DTILES_multiple_contents")) {
const extension = tileJson.extensions["3DTILES_multiple_contents"];
return defined_default(extension.contents) ? extension.contents : extension.content;
}
if (defined_default(tileJson.contents)) {
return tileJson.contents;
}
if (defined_default(tileJson.content)) {
return [tileJson.content];
}
return [];
}
function makeTileHeaderTemplate(tileJson) {
const template = clone_default(tileJson, true);
if (defined_default(template.extensions)) {
delete template.extensions["3DTILES_implicit_tiling"];
delete template.extensions["3DTILES_multiple_contents"];
if (Object.keys(template.extensions).length === 0) {
delete template.extensions;
}
}
delete template.implicitTiling;
delete template.contents;
delete template.content;
return template;
}
var ImplicitTileset_default = ImplicitTileset;
// node_modules/@cesium/engine/Source/Core/MortonOrder.js
var MortonOrder = {};
function insertOneSpacing(v7) {
v7 = (v7 ^ v7 << 8) & 16711935;
v7 = (v7 ^ v7 << 4) & 252645135;
v7 = (v7 ^ v7 << 2) & 858993459;
v7 = (v7 ^ v7 << 1) & 1431655765;
return v7;
}
function insertTwoSpacing(v7) {
v7 = (v7 ^ v7 << 16) & 50331903;
v7 = (v7 ^ v7 << 8) & 50393103;
v7 = (v7 ^ v7 << 4) & 51130563;
v7 = (v7 ^ v7 << 2) & 153391689;
return v7;
}
function removeOneSpacing(v7) {
v7 &= 1431655765;
v7 = (v7 ^ v7 >> 1) & 858993459;
v7 = (v7 ^ v7 >> 2) & 252645135;
v7 = (v7 ^ v7 >> 4) & 16711935;
v7 = (v7 ^ v7 >> 8) & 65535;
return v7;
}
function removeTwoSpacing(v7) {
v7 &= 153391689;
v7 = (v7 ^ v7 >> 2) & 51130563;
v7 = (v7 ^ v7 >> 4) & 50393103;
v7 = (v7 ^ v7 >> 8) & 4278190335;
v7 = (v7 ^ v7 >> 16) & 1023;
return v7;
}
MortonOrder.encode2D = function(x, y) {
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
if (x < 0 || x > 65535 || y < 0 || y > 65535) {
throw new DeveloperError_default("inputs must be 16-bit unsigned integers");
}
return (insertOneSpacing(x) | insertOneSpacing(y) << 1) >>> 0;
};
MortonOrder.decode2D = function(mortonIndex, result) {
Check_default.typeOf.number("mortonIndex", mortonIndex);
if (mortonIndex < 0 || mortonIndex > 4294967295) {
throw new DeveloperError_default("input must be a 32-bit unsigned integer");
}
if (!defined_default(result)) {
result = new Array(2);
}
result[0] = removeOneSpacing(mortonIndex);
result[1] = removeOneSpacing(mortonIndex >> 1);
return result;
};
MortonOrder.encode3D = function(x, y, z) {
Check_default.typeOf.number("x", x);
Check_default.typeOf.number("y", y);
Check_default.typeOf.number("z", z);
if (x < 0 || x > 1023 || y < 0 || y > 1023 || z < 0 || z > 1023) {
throw new DeveloperError_default("inputs must be 10-bit unsigned integers");
}
return insertTwoSpacing(x) | insertTwoSpacing(y) << 1 | insertTwoSpacing(z) << 2;
};
MortonOrder.decode3D = function(mortonIndex, result) {
Check_default.typeOf.number("mortonIndex", mortonIndex);
if (mortonIndex < 0 || mortonIndex > 1073741823) {
throw new DeveloperError_default("input must be a 30-bit unsigned integer");
}
if (!defined_default(result)) {
result = new Array(3);
}
result[0] = removeTwoSpacing(mortonIndex);
result[1] = removeTwoSpacing(mortonIndex >> 1);
result[2] = removeTwoSpacing(mortonIndex >> 2);
return result;
};
var MortonOrder_default = MortonOrder;
// node_modules/@cesium/engine/Source/Scene/ImplicitTileCoordinates.js
function ImplicitTileCoordinates(options) {
Check_default.typeOf.string("options.subdivisionScheme", options.subdivisionScheme);
Check_default.typeOf.number("options.subtreeLevels", options.subtreeLevels);
Check_default.typeOf.number("options.level", options.level);
Check_default.typeOf.number("options.x", options.x);
Check_default.typeOf.number("options.y", options.y);
if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
Check_default.typeOf.number("options.z", options.z);
}
if (options.level < 0) {
throw new DeveloperError_default("level must be non-negative");
}
if (options.x < 0) {
throw new DeveloperError_default("x must be non-negative");
}
if (options.y < 0) {
throw new DeveloperError_default("y must be non-negative");
}
if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
if (options.z < 0) {
throw new DeveloperError_default("z must be non-negative");
}
}
const dimensionAtLevel = 1 << options.level;
if (options.x >= dimensionAtLevel) {
throw new DeveloperError_default("x is out of range");
}
if (options.y >= dimensionAtLevel) {
throw new DeveloperError_default("y is out of range");
}
if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
if (options.z >= dimensionAtLevel) {
throw new DeveloperError_default("z is out of range");
}
}
this.subdivisionScheme = options.subdivisionScheme;
this.subtreeLevels = options.subtreeLevels;
this.level = options.level;
this.x = options.x;
this.y = options.y;
this.z = void 0;
if (options.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
this.z = options.z;
}
}
Object.defineProperties(ImplicitTileCoordinates.prototype, {
childIndex: {
get: function() {
let childIndex = 0;
childIndex |= this.x & 1;
childIndex |= (this.y & 1) << 1;
if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
childIndex |= (this.z & 1) << 2;
}
return childIndex;
}
},
mortonIndex: {
get: function() {
if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
return MortonOrder_default.encode3D(this.x, this.y, this.z);
}
return MortonOrder_default.encode2D(this.x, this.y);
}
},
tileIndex: {
get: function() {
const levelOffset = this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE ? ((1 << 3 * this.level) - 1) / 7 : ((1 << 2 * this.level) - 1) / 3;
const mortonIndex = this.mortonIndex;
return levelOffset + mortonIndex;
}
}
});
function checkMatchingSubtreeShape(a3, b) {
if (a3.subdivisionScheme !== b.subdivisionScheme) {
throw new DeveloperError_default("coordinates must have same subdivisionScheme");
}
if (a3.subtreeLevels !== b.subtreeLevels) {
throw new DeveloperError_default("coordinates must have same subtreeLevels");
}
}
ImplicitTileCoordinates.prototype.getDescendantCoordinates = function(offsetCoordinates) {
Check_default.typeOf.object("offsetCoordinates", offsetCoordinates);
checkMatchingSubtreeShape(this, offsetCoordinates);
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_default.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
});
}
return new ImplicitTileCoordinates({
subdivisionScheme: this.subdivisionScheme,
subtreeLevels: this.subtreeLevels,
level: descendantLevel,
x: descendantX,
y: descendantY
});
};
ImplicitTileCoordinates.prototype.getAncestorCoordinates = function(offsetLevels) {
Check_default.typeOf.number("offsetLevels", offsetLevels);
if (offsetLevels < 0) {
throw new DeveloperError_default("offsetLevels must be non-negative");
}
if (offsetLevels > this.level) {
throw new DeveloperError_default("ancestor cannot be above the tileset root");
}
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_default.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
});
}
return new ImplicitTileCoordinates({
subdivisionScheme: this.subdivisionScheme,
subtreeLevels: this.subtreeLevels,
level: ancestorLevel,
x: ancestorX,
y: ancestorY
});
};
ImplicitTileCoordinates.prototype.getOffsetCoordinates = function(descendantCoordinates) {
Check_default.typeOf.object("descendantCoordinates", descendantCoordinates);
if (!this.isEqual(descendantCoordinates) && !this.isAncestor(descendantCoordinates)) {
throw new DeveloperError_default("this is not an ancestor of descendant");
}
checkMatchingSubtreeShape(this, descendantCoordinates);
const offsetLevel = descendantCoordinates.level - this.level;
const dimensionAtOffsetLevel = 1 << offsetLevel;
const offsetX = descendantCoordinates.x % dimensionAtOffsetLevel;
const offsetY = descendantCoordinates.y % dimensionAtOffsetLevel;
if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
const offsetZ = descendantCoordinates.z % dimensionAtOffsetLevel;
return new ImplicitTileCoordinates({
subdivisionScheme: this.subdivisionScheme,
subtreeLevels: this.subtreeLevels,
level: offsetLevel,
x: offsetX,
y: offsetY,
z: offsetZ
});
}
return new ImplicitTileCoordinates({
subdivisionScheme: this.subdivisionScheme,
subtreeLevels: this.subtreeLevels,
level: offsetLevel,
x: offsetX,
y: offsetY
});
};
ImplicitTileCoordinates.prototype.getChildCoordinates = function(childIndex) {
Check_default.typeOf.number("childIndex", childIndex);
const branchingFactor = ImplicitSubdivisionScheme_default.getBranchingFactor(
this.subdivisionScheme
);
if (childIndex < 0 || branchingFactor <= childIndex) {
throw new DeveloperError_default(
`childIndex must be at least 0 and less than ${branchingFactor}`
);
}
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_default.OCTREE) {
const z = 2 * this.z + Math.floor(childIndex / 4) % 2;
return new ImplicitTileCoordinates({
subdivisionScheme: this.subdivisionScheme,
subtreeLevels: this.subtreeLevels,
level,
x,
y,
z
});
}
return new ImplicitTileCoordinates({
subdivisionScheme: this.subdivisionScheme,
subtreeLevels: this.subtreeLevels,
level,
x,
y
});
};
ImplicitTileCoordinates.prototype.getSubtreeCoordinates = function() {
return this.getAncestorCoordinates(this.level % this.subtreeLevels);
};
ImplicitTileCoordinates.prototype.getParentSubtreeCoordinates = function() {
return this.getAncestorCoordinates(
this.level % this.subtreeLevels + this.subtreeLevels
);
};
ImplicitTileCoordinates.prototype.isAncestor = function(descendantCoordinates) {
Check_default.typeOf.object("descendantCoordinates", descendantCoordinates);
checkMatchingSubtreeShape(this, descendantCoordinates);
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_default.OCTREE) {
const ancestorZ = descendantCoordinates.z >> levelDifference;
const isAncestorZ = this.z === ancestorZ;
return isAncestorX && isAncestorY && isAncestorZ;
}
return isAncestorX && isAncestorY;
};
ImplicitTileCoordinates.prototype.isEqual = function(otherCoordinates) {
Check_default.typeOf.object("otherCoordinates", otherCoordinates);
return this.subdivisionScheme === otherCoordinates.subdivisionScheme && this.subtreeLevels === otherCoordinates.subtreeLevels && this.level === otherCoordinates.level && this.x === otherCoordinates.x && this.y === otherCoordinates.y && (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE ? this.z === otherCoordinates.z : true);
};
ImplicitTileCoordinates.prototype.isImplicitTilesetRoot = function() {
return this.level === 0;
};
ImplicitTileCoordinates.prototype.isSubtreeRoot = function() {
return this.level % this.subtreeLevels === 0;
};
ImplicitTileCoordinates.prototype.isBottomOfSubtree = function() {
return this.level % this.subtreeLevels === this.subtreeLevels - 1;
};
ImplicitTileCoordinates.prototype.getTemplateValues = function() {
const values = {
level: this.level,
x: this.x,
y: this.y
};
if (this.subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
values.z = this.z;
}
return values;
};
var scratchCoordinatesArray = [0, 0, 0];
ImplicitTileCoordinates.fromMortonIndex = function(subdivisionScheme, subtreeLevels, level, mortonIndex) {
let coordinatesArray;
if (subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
coordinatesArray = MortonOrder_default.decode3D(
mortonIndex,
scratchCoordinatesArray
);
return new ImplicitTileCoordinates({
subdivisionScheme,
subtreeLevels,
level,
x: coordinatesArray[0],
y: coordinatesArray[1],
z: coordinatesArray[2]
});
}
coordinatesArray = MortonOrder_default.decode2D(mortonIndex, scratchCoordinatesArray);
return new ImplicitTileCoordinates({
subdivisionScheme,
subtreeLevels,
level,
x: coordinatesArray[0],
y: coordinatesArray[1]
});
};
ImplicitTileCoordinates.fromTileIndex = function(subdivisionScheme, subtreeLevels, tileIndex) {
let level;
let levelOffset;
let mortonIndex;
if (subdivisionScheme === ImplicitSubdivisionScheme_default.OCTREE) {
level = Math.floor(Math_default.log2(7 * tileIndex + 1) / 3);
levelOffset = ((1 << 3 * level) - 1) / 7;
mortonIndex = tileIndex - levelOffset;
} else {
level = Math.floor(Math_default.log2(3 * tileIndex + 1) / 2);
levelOffset = ((1 << 2 * level) - 1) / 3;
mortonIndex = tileIndex - levelOffset;
}
return ImplicitTileCoordinates.fromMortonIndex(
subdivisionScheme,
subtreeLevels,
level,
mortonIndex
);
};
var ImplicitTileCoordinates_default = ImplicitTileCoordinates;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetTraversal.js
function Cesium3DTilesetTraversal() {
}
Cesium3DTilesetTraversal.selectTiles = function(tileset, frameState) {
DeveloperError_default.throwInstantiationError();
};
Cesium3DTilesetTraversal.sortChildrenByDistanceToCamera = function(a3, b) {
if (b._distanceToCamera === 0 && a3._distanceToCamera === 0) {
return b._centerZDepth - a3._centerZDepth;
}
return b._distanceToCamera - a3._distanceToCamera;
};
Cesium3DTilesetTraversal.canTraverse = function(tile) {
if (tile.children.length === 0) {
return false;
}
if (tile.hasTilesetContent || tile.hasImplicitContent) {
return !tile.contentExpired;
}
return tile._screenSpaceError > tile.tileset._maximumScreenSpaceError;
};
Cesium3DTilesetTraversal.selectTile = function(tile, frameState) {
if (tile.contentVisibility(frameState) === Intersect_default.OUTSIDE) {
return;
}
const { content, tileset } = tile;
if (content.featurePropertiesDirty) {
content.featurePropertiesDirty = false;
tile.lastStyleTime = 0;
tileset._selectedTilesToStyle.push(tile);
} else if (tile._selectedFrame < frameState.frameNumber - 1) {
tileset._selectedTilesToStyle.push(tile);
}
tile._selectedFrame = frameState.frameNumber;
tileset._selectedTiles.push(tile);
};
Cesium3DTilesetTraversal.visitTile = function(tile, frameState) {
++tile.tileset._statistics.visited;
tile._visitedFrame = frameState.frameNumber;
};
Cesium3DTilesetTraversal.touchTile = function(tile, frameState) {
if (tile._touchedFrame === frameState.frameNumber) {
return;
}
tile.tileset._cache.touch(tile);
tile._touchedFrame = frameState.frameNumber;
};
Cesium3DTilesetTraversal.loadTile = function(tile, frameState) {
const { tileset } = tile;
if (tile._requestedFrame === frameState.frameNumber || !tile.hasUnloadedRenderableContent && !tile.contentExpired) {
return;
}
if (!isOnScreenLongEnough(tile, frameState)) {
return;
}
const cameraHasNotStoppedMovingLongEnough = frameState.camera.timeSinceMoved < tileset.foveatedTimeDelay;
if (tile.priorityDeferred && cameraHasNotStoppedMovingLongEnough) {
return;
}
tile._requestedFrame = frameState.frameNumber;
tileset._requestedTiles.push(tile);
};
function isOnScreenLongEnough(tile, frameState) {
const { tileset } = tile;
if (!tileset._cullRequestsWhileMoving) {
return true;
}
const {
positionWCDeltaMagnitude,
positionWCDeltaMagnitudeLastFrame
} = frameState.camera;
const deltaMagnitude = positionWCDeltaMagnitude !== 0 ? positionWCDeltaMagnitude : positionWCDeltaMagnitudeLastFrame;
const diameter = Math.max(tile.boundingSphere.radius * 2, 1);
const movementRatio = tileset.cullRequestsWhileMovingMultiplier * deltaMagnitude / diameter;
return movementRatio < 1;
}
Cesium3DTilesetTraversal.updateTile = function(tile, frameState) {
updateTileVisibility(tile, frameState);
tile.updateExpiration();
tile._wasMinPriorityChild = false;
tile._priorityHolder = tile;
updateMinimumMaximumPriority(tile);
tile._shouldSelect = false;
tile._finalResolution = true;
};
function updateTileVisibility(tile, frameState) {
tile.updateVisibility(frameState);
if (!tile.isVisible) {
return;
}
const hasChildren = tile.children.length > 0;
if ((tile.hasTilesetContent || tile.hasImplicitContent) && hasChildren) {
const child = tile.children[0];
updateTileVisibility(child, frameState);
tile._visible = child._visible;
return;
}
if (meetsScreenSpaceErrorEarly(tile, frameState)) {
tile._visible = false;
return;
}
const replace = tile.refine === Cesium3DTileRefine_default.REPLACE;
const useOptimization = tile._optimChildrenWithinParent === Cesium3DTileOptimizationHint_default.USE_OPTIMIZATION;
if (replace && useOptimization && hasChildren) {
if (!anyChildrenVisible(tile, frameState)) {
++tile.tileset._statistics.numberOfTilesCulledWithChildrenUnion;
tile._visible = false;
return;
}
}
}
function meetsScreenSpaceErrorEarly(tile, frameState) {
const { parent, tileset } = tile;
if (!defined_default(parent) || parent.hasTilesetContent || parent.hasImplicitContent || parent.refine !== Cesium3DTileRefine_default.ADD) {
return false;
}
return tile.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError;
}
function anyChildrenVisible(tile, frameState) {
let anyVisible = false;
const children = tile.children;
for (let i = 0; i < children.length; ++i) {
const child = children[i];
child.updateVisibility(frameState);
anyVisible = anyVisible || child.isVisible;
}
return anyVisible;
}
function updateMinimumMaximumPriority(tile) {
const minimumPriority = tile.tileset._minimumPriority;
const maximumPriority = tile.tileset._maximumPriority;
const priorityHolder = tile._priorityHolder;
maximumPriority.distance = Math.max(
priorityHolder._distanceToCamera,
maximumPriority.distance
);
minimumPriority.distance = Math.min(
priorityHolder._distanceToCamera,
minimumPriority.distance
);
maximumPriority.depth = Math.max(tile._depth, maximumPriority.depth);
minimumPriority.depth = Math.min(tile._depth, minimumPriority.depth);
maximumPriority.foveatedFactor = Math.max(
priorityHolder._foveatedFactor,
maximumPriority.foveatedFactor
);
minimumPriority.foveatedFactor = Math.min(
priorityHolder._foveatedFactor,
minimumPriority.foveatedFactor
);
maximumPriority.reverseScreenSpaceError = Math.max(
tile._priorityReverseScreenSpaceError,
maximumPriority.reverseScreenSpaceError
);
minimumPriority.reverseScreenSpaceError = Math.min(
tile._priorityReverseScreenSpaceError,
minimumPriority.reverseScreenSpaceError
);
}
var Cesium3DTilesetTraversal_default = Cesium3DTilesetTraversal;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetMostDetailedTraversal.js
function Cesium3DTilesetMostDetailedTraversal() {
}
var traversal = {
stack: new ManagedArray_default(),
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 (!root.isVisible) {
return ready;
}
const { touchTile, visitTile: visitTile3 } = Cesium3DTilesetTraversal_default;
const stack = traversal.stack;
stack.push(root);
while (stack.length > 0) {
traversal.stackMaximumLength = Math.max(
traversal.stackMaximumLength,
stack.length
);
const tile = stack.pop();
const add2 = tile.refine === Cesium3DTileRefine_default.ADD;
const replace = tile.refine === Cesium3DTileRefine_default.REPLACE;
const traverse = canTraverse(tile);
if (traverse) {
updateAndPushChildren(tile, stack, frameState);
}
if (add2 || replace && !traverse) {
loadTile(tileset, tile);
touchTile(tile, frameState);
selectDesiredTile(tile, frameState);
if (tile.hasRenderableContent && !tile.contentAvailable) {
ready = false;
}
}
visitTile3(tile, frameState);
}
traversal.stack.trim(traversal.stackMaximumLength);
return ready;
};
function canTraverse(tile) {
if (tile.children.length === 0) {
return false;
}
if (tile.hasTilesetContent || tile.hasImplicitContent) {
return !tile.contentExpired;
}
if (tile.hasEmptyContent) {
return true;
}
return true;
}
function updateAndPushChildren(tile, stack, frameState) {
const { children } = tile;
for (let i = 0; i < children.length; ++i) {
const child = children[i];
child.updateVisibility(frameState);
if (child.isVisible) {
stack.push(child);
}
}
}
function loadTile(tileset, tile) {
if (tile.hasUnloadedRenderableContent || tile.contentExpired) {
tile._priority = 0;
tileset._requestedTiles.push(tile);
}
}
function selectDesiredTile(tile, frameState) {
if (tile.contentAvailable && tile.contentVisibility(frameState) !== Intersect_default.OUTSIDE) {
tile.tileset._selectedTiles.push(tile);
}
}
var Cesium3DTilesetMostDetailedTraversal_default = Cesium3DTilesetMostDetailedTraversal;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetBaseTraversal.js
function Cesium3DTilesetBaseTraversal() {
}
var traversal2 = {
stack: new ManagedArray_default(),
stackMaximumLength: 0
};
var emptyTraversal = {
stack: new ManagedArray_default(),
stackMaximumLength: 0
};
Cesium3DTilesetBaseTraversal.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;
Cesium3DTilesetTraversal_default.updateTile(root, frameState);
if (!root.isVisible) {
return;
}
if (root.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError) {
return;
}
executeTraversal(root, frameState);
traversal2.stack.trim(traversal2.stackMaximumLength);
emptyTraversal.stack.trim(emptyTraversal.stackMaximumLength);
const requestedTiles = tileset._requestedTiles;
for (let i = 0; i < requestedTiles.length; ++i) {
requestedTiles[i].updatePriority();
}
};
function selectDesiredTile2(tile, frameState) {
if (tile.contentAvailable) {
Cesium3DTilesetTraversal_default.selectTile(tile, frameState);
}
}
function updateAndPushChildren2(tile, stack, frameState) {
const replace = tile.refine === Cesium3DTileRefine_default.REPLACE;
const { tileset, children } = tile;
const { updateTile, loadTile: loadTile2, touchTile } = Cesium3DTilesetTraversal_default;
for (let i = 0; i < children.length; ++i) {
updateTile(children[i], frameState);
}
children.sort(Cesium3DTilesetTraversal_default.sortChildrenByDistanceToCamera);
const checkRefines = replace && tile.hasRenderableContent;
let refines = true;
let anyChildrenVisible2 = false;
let minIndex = -1;
let minimumPriority = Number.MAX_VALUE;
for (let i = 0; i < children.length; ++i) {
const child = children[i];
if (child.isVisible) {
stack.push(child);
if (child._foveatedFactor < minimumPriority) {
minIndex = i;
minimumPriority = child._foveatedFactor;
}
anyChildrenVisible2 = true;
} else if (checkRefines || tileset.loadSiblings) {
if (child._foveatedFactor < minimumPriority) {
minIndex = i;
minimumPriority = child._foveatedFactor;
}
loadTile2(child, frameState);
touchTile(child, frameState);
}
if (checkRefines) {
let childRefines;
if (!child._inRequestVolume) {
childRefines = false;
} else if (!child.hasRenderableContent) {
childRefines = executeEmptyTraversal(child, frameState);
} else {
childRefines = child.contentAvailable;
}
refines = refines && childRefines;
}
}
if (!anyChildrenVisible2) {
refines = false;
}
if (minIndex !== -1 && replace) {
const minPriorityChild = children[minIndex];
minPriorityChild._wasMinPriorityChild = true;
const priorityHolder = (tile._wasMinPriorityChild || tile === tileset.root) && minimumPriority <= tile._priorityHolder._foveatedFactor ? tile._priorityHolder : tile;
priorityHolder._foveatedFactor = Math.min(
minPriorityChild._foveatedFactor,
priorityHolder._foveatedFactor
);
priorityHolder._distanceToCamera = Math.min(
minPriorityChild._distanceToCamera,
priorityHolder._distanceToCamera
);
for (let i = 0; i < children.length; ++i) {
children[i]._priorityHolder = priorityHolder;
}
}
return refines;
}
function executeTraversal(root, frameState) {
const { tileset } = root;
const {
canTraverse: canTraverse2,
loadTile: loadTile2,
visitTile: visitTile3,
touchTile
} = Cesium3DTilesetTraversal_default;
const stack = traversal2.stack;
stack.push(root);
while (stack.length > 0) {
traversal2.stackMaximumLength = Math.max(
traversal2.stackMaximumLength,
stack.length
);
const tile = stack.pop();
const parent = tile.parent;
const parentRefines = !defined_default(parent) || parent._refines;
tile._refines = canTraverse2(tile) ? updateAndPushChildren2(tile, stack, frameState) && parentRefines : false;
const stoppedRefining = !tile._refines && parentRefines;
if (!tile.hasRenderableContent) {
tileset._emptyTiles.push(tile);
loadTile2(tile, frameState);
if (stoppedRefining) {
selectDesiredTile2(tile, frameState);
}
} else if (tile.refine === Cesium3DTileRefine_default.ADD) {
selectDesiredTile2(tile, frameState);
loadTile2(tile, frameState);
} else if (tile.refine === Cesium3DTileRefine_default.REPLACE) {
loadTile2(tile, frameState);
if (stoppedRefining) {
selectDesiredTile2(tile, frameState);
}
}
visitTile3(tile, frameState);
touchTile(tile, frameState);
}
}
function executeEmptyTraversal(root, frameState) {
const {
canTraverse: canTraverse2,
updateTile,
loadTile: loadTile2,
touchTile
} = Cesium3DTilesetTraversal_default;
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;
const traverse = !tile.hasRenderableContent && canTraverse2(tile);
const emptyLeaf = !tile.hasRenderableContent && tile.children.length === 0;
if (!traverse && !tile.contentAvailable && !emptyLeaf) {
allDescendantsLoaded = false;
}
updateTile(tile, frameState);
if (!tile.isVisible) {
loadTile2(tile, frameState);
touchTile(tile, frameState);
}
if (traverse) {
for (let i = 0; i < childrenLength; ++i) {
const child = children[i];
stack.push(child);
}
}
}
return allDescendantsLoaded;
}
var Cesium3DTilesetBaseTraversal_default = Cesium3DTilesetBaseTraversal;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTilesetSkipTraversal.js
function Cesium3DTilesetSkipTraversal() {
}
var traversal3 = {
stack: new ManagedArray_default(),
stackMaximumLength: 0
};
var descendantTraversal = {
stack: new ManagedArray_default(),
stackMaximumLength: 0
};
var selectionTraversal = {
stack: new ManagedArray_default(),
stackMaximumLength: 0,
ancestorStack: new ManagedArray_default(),
ancestorStackMaximumLength: 0
};
var descendantSelectionDepth = 2;
Cesium3DTilesetSkipTraversal.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;
Cesium3DTilesetTraversal_default.updateTile(root, frameState);
if (!root.isVisible) {
return;
}
if (root.getScreenSpaceError(frameState, true) <= tileset._maximumScreenSpaceError) {
return;
}
executeTraversal2(root, frameState);
traverseAndSelect(root, frameState);
traversal3.stack.trim(traversal3.stackMaximumLength);
descendantTraversal.stack.trim(descendantTraversal.stackMaximumLength);
selectionTraversal.stack.trim(selectionTraversal.stackMaximumLength);
selectionTraversal.ancestorStack.trim(
selectionTraversal.ancestorStackMaximumLength
);
const requestedTiles = tileset._requestedTiles;
for (let i = 0; i < requestedTiles.length; ++i) {
requestedTiles[i].updatePriority();
}
};
function selectDescendants(root, frameState) {
const { updateTile, touchTile, selectTile } = Cesium3DTilesetTraversal_default;
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;
for (let i = 0; i < children.length; ++i) {
const child = children[i];
if (child.isVisible) {
if (child.contentAvailable) {
updateTile(child, frameState);
touchTile(child, frameState);
selectTile(child, frameState);
} else if (child._depth - root._depth < descendantSelectionDepth) {
stack.push(child);
}
}
}
}
}
function selectDesiredTile3(tile, frameState) {
const loadedTile = tile.contentAvailable ? tile : tile._ancestorWithContentAvailable;
if (defined_default(loadedTile)) {
loadedTile._shouldSelect = true;
} else {
selectDescendants(tile, frameState);
}
}
function updateTileAncestorContentLinks(tile, frameState) {
tile._ancestorWithContent = void 0;
tile._ancestorWithContentAvailable = void 0;
const { parent } = tile;
if (!defined_default(parent)) {
return;
}
const parentHasContent = !parent.hasUnloadedRenderableContent || parent._requestedFrame === frameState.frameNumber;
tile._ancestorWithContent = parentHasContent ? parent : parent._ancestorWithContent;
tile._ancestorWithContentAvailable = parent.contentAvailable ? parent : parent._ancestorWithContentAvailable;
}
function reachedSkippingThreshold(tileset, tile) {
const ancestor = tile._ancestorWithContent;
return !tileset.immediatelyLoadDesiredLevelOfDetail && (tile._priorityProgressiveResolutionScreenSpaceErrorLeaf || defined_default(ancestor) && tile._screenSpaceError < ancestor._screenSpaceError / tileset.skipScreenSpaceErrorFactor && tile._depth > ancestor._depth + tileset.skipLevels);
}
function updateAndPushChildren3(tile, stack, frameState) {
const { tileset, children } = tile;
const { updateTile, loadTile: loadTile2, touchTile } = Cesium3DTilesetTraversal_default;
for (let i = 0; i < children.length; ++i) {
updateTile(children[i], frameState);
}
children.sort(Cesium3DTilesetTraversal_default.sortChildrenByDistanceToCamera);
let anyChildrenVisible2 = false;
for (let i = 0; i < children.length; ++i) {
const child = children[i];
if (child.isVisible) {
stack.push(child);
anyChildrenVisible2 = true;
} else if (tileset.loadSiblings) {
loadTile2(child, frameState);
touchTile(child, frameState);
}
}
return anyChildrenVisible2;
}
function inBaseTraversal(tile, baseScreenSpaceError) {
const { tileset } = tile;
if (tileset.immediatelyLoadDesiredLevelOfDetail) {
return false;
}
if (!defined_default(tile._ancestorWithContent)) {
return true;
}
if (tile._screenSpaceError === 0) {
return tile.parent._screenSpaceError > baseScreenSpaceError;
}
return tile._screenSpaceError > baseScreenSpaceError;
}
function executeTraversal2(root, frameState) {
const { tileset } = root;
const baseScreenSpaceError = tileset.immediatelyLoadDesiredLevelOfDetail ? Number.MAX_VALUE : Math.max(tileset.baseScreenSpaceError, tileset.maximumScreenSpaceError);
const {
canTraverse: canTraverse2,
loadTile: loadTile2,
visitTile: visitTile3,
touchTile
} = Cesium3DTilesetTraversal_default;
const stack = traversal3.stack;
stack.push(root);
while (stack.length > 0) {
traversal3.stackMaximumLength = Math.max(
traversal3.stackMaximumLength,
stack.length
);
const tile = stack.pop();
updateTileAncestorContentLinks(tile, frameState);
const parent = tile.parent;
const parentRefines = !defined_default(parent) || parent._refines;
tile._refines = canTraverse2(tile) ? updateAndPushChildren3(tile, stack, frameState) && parentRefines : false;
const stoppedRefining = !tile._refines && parentRefines;
if (!tile.hasRenderableContent) {
tileset._emptyTiles.push(tile);
loadTile2(tile, frameState);
if (stoppedRefining) {
selectDesiredTile3(tile, frameState);
}
} else if (tile.refine === Cesium3DTileRefine_default.ADD) {
selectDesiredTile3(tile, frameState);
loadTile2(tile, frameState);
} else if (tile.refine === Cesium3DTileRefine_default.REPLACE) {
if (inBaseTraversal(tile, baseScreenSpaceError)) {
loadTile2(tile, frameState);
if (stoppedRefining) {
selectDesiredTile3(tile, frameState);
}
} else if (stoppedRefining) {
selectDesiredTile3(tile, frameState);
loadTile2(tile, frameState);
} else if (reachedSkippingThreshold(tileset, tile)) {
loadTile2(tile, frameState);
}
}
visitTile3(tile, frameState);
touchTile(tile, frameState);
}
}
function traverseAndSelect(root, frameState) {
const { selectTile, canTraverse: canTraverse2 } = Cesium3DTilesetTraversal_default;
const { stack, ancestorStack } = selectionTraversal;
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(waitingTile, frameState);
continue;
}
}
const tile = stack.pop();
if (!defined_default(tile)) {
continue;
}
const traverse = canTraverse2(tile);
if (tile._shouldSelect) {
if (tile.refine === Cesium3DTileRefine_default.ADD) {
selectTile(tile, frameState);
} else {
tile._selectionDepth = ancestorStack.length;
if (tile._selectionDepth > 0) {
tile.tileset.hasMixedContent = true;
}
lastAncestor = tile;
if (!traverse) {
selectTile(tile, frameState);
continue;
}
ancestorStack.push(tile);
tile._stackLength = stack.length;
}
}
if (traverse) {
const children = tile.children;
for (let i = 0; i < children.length; ++i) {
const child = children[i];
if (child.isVisible) {
stack.push(child);
}
}
}
}
}
var Cesium3DTilesetSkipTraversal_default = Cesium3DTilesetSkipTraversal;
// node_modules/@cesium/engine/Source/Scene/Cesium3DTileset.js
function Cesium3DTileset(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._url = void 0;
this._basePath = void 0;
this._root = void 0;
this._resource = void 0;
this._asset = void 0;
this._properties = void 0;
this._geometricError = void 0;
this._scaledGeometricError = void 0;
this._extensionsUsed = void 0;
this._extensions = void 0;
this._modelUpAxis = void 0;
this._modelForwardAxis = void 0;
this._cache = new Cesium3DTilesetCache_default();
this._processingQueue = [];
this._selectedTiles = [];
this._emptyTiles = [];
this._requestedTiles = [];
this._selectedTilesToStyle = [];
this._loadTimestamp = void 0;
this._timeSinceLoad = 0;
this._updatedVisibilityFrame = 0;
this._updatedModelMatrixFrame = 0;
this._modelMatrixChanged = false;
this._previousModelMatrix = void 0;
this._extras = void 0;
this._credits = void 0;
this._showCreditsOnScreen = defaultValue_default(options.showCreditsOnScreen, false);
this._cullWithChildrenBounds = defaultValue_default(
options.cullWithChildrenBounds,
true
);
this._allTilesAdditive = true;
this._hasMixedContent = false;
this._stencilClearCommand = void 0;
this._backfaceCommands = new ManagedArray_default();
this._maximumScreenSpaceError = defaultValue_default(
options.maximumScreenSpaceError,
16
);
this._maximumMemoryUsage = defaultValue_default(options.maximumMemoryUsage, 512);
this._styleEngine = new Cesium3DTileStyleEngine_default();
this._styleApplied = false;
this._modelMatrix = defined_default(options.modelMatrix) ? Matrix4_default.clone(options.modelMatrix) : Matrix4_default.clone(Matrix4_default.IDENTITY);
this._statistics = new Cesium3DTilesetStatistics_default();
this._statisticsLast = new Cesium3DTilesetStatistics_default();
this._statisticsPerPass = new Array(Cesium3DTilePass_default.NUMBER_OF_PASSES);
for (let i = 0; i < Cesium3DTilePass_default.NUMBER_OF_PASSES; ++i) {
this._statisticsPerPass[i] = new Cesium3DTilesetStatistics_default();
}
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_default(
options.debugHeatmapTilePropertyName
);
this.cullRequestsWhileMoving = defaultValue_default(
options.cullRequestsWhileMoving,
true
);
this._cullRequestsWhileMoving = false;
this.cullRequestsWhileMovingMultiplier = defaultValue_default(
options.cullRequestsWhileMovingMultiplier,
60
);
this.progressiveResolutionHeightFraction = Math_default.clamp(
defaultValue_default(options.progressiveResolutionHeightFraction, 0.3),
0,
0.5
);
this.preferLeaves = defaultValue_default(options.preferLeaves, false);
this._tilesLoaded = false;
this._initialTilesLoaded = false;
this._tileDebugLabels = void 0;
this._classificationType = options.classificationType;
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._initialClippingPlanesOriginMatrix = Matrix4_default.IDENTITY;
this._clippingPlanesOriginMatrix = void 0;
this._clippingPlanesOriginMatrixDirty = true;
this._vectorClassificationOnly = defaultValue_default(
options.vectorClassificationOnly,
false
);
this._vectorKeepDecodedPositions = defaultValue_default(
options.vectorKeepDecodedPositions,
false
);
this.preloadWhenHidden = defaultValue_default(options.preloadWhenHidden, false);
this.preloadFlightDestinations = defaultValue_default(
options.preloadFlightDestinations,
true
);
this._pass = void 0;
this.dynamicScreenSpaceError = defaultValue_default(
options.dynamicScreenSpaceError,
false
);
this.foveatedScreenSpaceError = defaultValue_default(
options.foveatedScreenSpaceError,
true
);
this._foveatedConeSize = defaultValue_default(options.foveatedConeSize, 0.1);
this._foveatedMinimumScreenSpaceErrorRelaxation = defaultValue_default(
options.foveatedMinimumScreenSpaceErrorRelaxation,
0
);
this.foveatedInterpolationCallback = defaultValue_default(
options.foveatedInterpolationCallback,
Math_default.lerp
);
this.foveatedTimeDelay = defaultValue_default(options.foveatedTimeDelay, 0.2);
this.dynamicScreenSpaceErrorDensity = 278e-5;
this.dynamicScreenSpaceErrorFactor = 4;
this.dynamicScreenSpaceErrorHeightFalloff = 0.25;
this._dynamicScreenSpaceErrorComputedDensity = 0;
this.shadows = defaultValue_default(options.shadows, ShadowMode_default.ENABLED);
this.show = defaultValue_default(options.show, true);
this.colorBlendMode = Cesium3DTileColorBlendMode_default.HIGHLIGHT;
this.colorBlendAmount = 0.5;
this._pointCloudShading = new PointCloudShading_default(options.pointCloudShading);
this._pointCloudEyeDomeLighting = new PointCloudEyeDomeLighting_default2();
this.loadProgress = new Event_default();
this.allTilesLoaded = new Event_default();
this.initialTilesLoaded = new Event_default();
this.tileLoad = new Event_default();
this.tileUnload = new Event_default();
this.tileFailed = new Event_default();
this.tileVisible = new Event_default();
this.skipLevelOfDetail = defaultValue_default(options.skipLevelOfDetail, false);
this._disableSkipLevelOfDetail = false;
this.baseScreenSpaceError = defaultValue_default(options.baseScreenSpaceError, 1024);
this.skipScreenSpaceErrorFactor = defaultValue_default(
options.skipScreenSpaceErrorFactor,
16
);
this.skipLevels = defaultValue_default(options.skipLevels, 1);
this.immediatelyLoadDesiredLevelOfDetail = defaultValue_default(
options.immediatelyLoadDesiredLevelOfDetail,
false
);
this.loadSiblings = defaultValue_default(options.loadSiblings, false);
this._clippingPlanes = void 0;
this.clippingPlanes = options.clippingPlanes;
if (defined_default(options.imageBasedLighting)) {
this._imageBasedLighting = options.imageBasedLighting;
this._shouldDestroyImageBasedLighting = false;
} else {
this._imageBasedLighting = new ImageBasedLighting_default();
this._shouldDestroyImageBasedLighting = true;
}
this.lightColor = options.lightColor;
this.backFaceCulling = defaultValue_default(options.backFaceCulling, true);
this._enableShowOutline = defaultValue_default(options.enableShowOutline, true);
this.showOutline = defaultValue_default(options.showOutline, true);
this.outlineColor = defaultValue_default(options.outlineColor, Color_default.BLACK);
this.splitDirection = defaultValue_default(
options.splitDirection,
SplitDirection_default.NONE
);
this._projectTo2D = defaultValue_default(options.projectTo2D, false);
this.debugFreezeFrame = defaultValue_default(options.debugFreezeFrame, false);
this.debugColorizeTiles = defaultValue_default(options.debugColorizeTiles, false);
this._enableDebugWireframe = defaultValue_default(
options.enableDebugWireframe,
false
);
this.debugWireframe = defaultValue_default(options.debugWireframe, false);
if (this.debugWireframe === true && this._enableDebugWireframe === false) {
oneTimeWarning_default(
"tileset-debug-wireframe-ignored",
"enableDebugWireframe must be set to true in the Cesium3DTileset constructor, otherwise debugWireframe will be ignored."
);
}
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.debugShowContentBoundingVolume = defaultValue_default(
options.debugShowContentBoundingVolume,
false
);
this.debugShowViewerRequestVolume = defaultValue_default(
options.debugShowViewerRequestVolume,
false
);
this._tileDebugLabels = void 0;
this.debugPickedTileLabelOnly = false;
this.debugPickedTile = void 0;
this.debugPickPosition = void 0;
this.debugShowGeometricError = defaultValue_default(
options.debugShowGeometricError,
false
);
this.debugShowRenderingStatistics = defaultValue_default(
options.debugShowRenderingStatistics,
false
);
this.debugShowMemoryUsage = defaultValue_default(options.debugShowMemoryUsage, false);
this.debugShowUrl = defaultValue_default(options.debugShowUrl, false);
this.examineVectorLinesFunction = void 0;
this._metadataExtension = void 0;
this._customShader = options.customShader;
let featureIdLabel = defaultValue_default(options.featureIdLabel, "featureId_0");
if (typeof featureIdLabel === "number") {
featureIdLabel = `featureId_${featureIdLabel}`;
}
this._featureIdLabel = featureIdLabel;
let instanceFeatureIdLabel = defaultValue_default(
options.instanceFeatureIdLabel,
"instanceFeatureId_0"
);
if (typeof instanceFeatureIdLabel === "number") {
instanceFeatureIdLabel = `instanceFeatureId_${instanceFeatureIdLabel}`;
}
this._instanceFeatureIdLabel = instanceFeatureIdLabel;
if (defined_default(options.url)) {
deprecationWarning_default(
"Cesium3DTileset options.url",
"Cesium3DTileset constructor parameter options.url was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Cesium3DTileset.fromUrl instead."
);
const that = this;
let resource;
this._readyPromise = Promise.resolve(options.url).then(function(url2) {
let basePath;
resource = Resource_default.createIfNeeded(url2);
that._resource = resource;
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;
}
return processMetadataExtension(resource, tilesetJson).then(
(metadata) => {
that._metadataExtension = metadata;
return tilesetJson;
}
);
}).then(function(tilesetJson) {
if (that.isDestroyed()) {
return;
}
that._geometricError = tilesetJson.geometricError;
that._scaledGeometricError = tilesetJson.geometricError;
that._root = that.loadTileset(resource, tilesetJson);
const gltfUpAxis = defined_default(tilesetJson.asset.gltfUpAxis) ? Axis_default.fromName(tilesetJson.asset.gltfUpAxis) : Axis_default.Y;
const modelUpAxis = defaultValue_default(options.modelUpAxis, gltfUpAxis);
const modelForwardAxis = defaultValue_default(options.modelForwardAxis, Axis_default.X);
const asset = tilesetJson.asset;
that._asset = asset;
that._properties = tilesetJson.properties;
that._extensionsUsed = tilesetJson.extensionsUsed;
that._extensions = tilesetJson.extensions;
that._modelUpAxis = modelUpAxis;
that._modelForwardAxis = modelForwardAxis;
that._extras = tilesetJson.extras;
const extras = asset.extras;
if (defined_default(extras) && defined_default(extras.cesium) && defined_default(extras.cesium.credits)) {
const extraCredits = extras.cesium.credits;
let credits = that._credits;
if (!defined_default(credits)) {
credits = [];
that._credits = credits;
}
for (let i = 0; i < extraCredits.length; ++i) {
const credit = extraCredits[i];
credits.push(new Credit_default(credit.html, that._showCreditsOnScreen));
}
}
const boundingVolume = that._root.createBoundingVolume(
tilesetJson.root.boundingVolume,
Matrix4_default.IDENTITY
);
const clippingPlanesOrigin = boundingVolume.boundingSphere.center;
const originCartographic = that._ellipsoid.cartesianToCartographic(
clippingPlanesOrigin
);
if (defined_default(originCartographic) && originCartographic.height > ApproximateTerrainHeights_default._defaultMinTerrainHeight) {
that._initialClippingPlanesOriginMatrix = Transforms_default.eastNorthUpToFixedFrame(
clippingPlanesOrigin
);
}
that._clippingPlanesOriginMatrix = Matrix4_default.clone(
that._initialClippingPlanesOriginMatrix
);
return that;
});
}
}
Object.defineProperties(Cesium3DTileset.prototype, {
isCesium3DTileset: {
get: function() {
return true;
}
},
asset: {
get: function() {
return this._asset;
}
},
extensions: {
get: function() {
return this._extensions;
}
},
clippingPlanes: {
get: function() {
return this._clippingPlanes;
},
set: function(value) {
ClippingPlaneCollection_default.setOwner(value, this, "_clippingPlanes");
}
},
properties: {
get: function() {
return this._properties;
}
},
ready: {
get: function() {
deprecationWarning_default(
"Cesium3DTileset.ready",
"Cesium3DTileset.ready was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Cesium3DTileset.fromUrl instead."
);
return defined_default(this._root);
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"Cesium3DTileset.readyPromise",
"Cesium3DTileset.readyPromise was deprecated in CesiumJS 1.104. It will be removed in 1.107. Use Cesium3DTileset.fromUrl instead."
);
return this._readyPromise;
}
},
tilesLoaded: {
get: function() {
return this._tilesLoaded;
}
},
resource: {
get: function() {
return this._resource;
}
},
basePath: {
get: function() {
deprecationWarning_default(
"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;
}
},
style: {
get: function() {
return this._styleEngine.style;
},
set: function(value) {
this._styleEngine.style = value;
}
},
customShader: {
get: function() {
return this._customShader;
},
set: function(value) {
this._customShader = value;
}
},
hasMixedContent: {
get: function() {
return this._hasMixedContent;
},
set: function(value) {
Check_default.typeOf.bool("value", value);
this._hasMixedContent = value;
}
},
isSkippingLevelOfDetail: {
get: function() {
return this.skipLevelOfDetail && !defined_default(this._classificationType) && !this._disableSkipLevelOfDetail && !this._allTilesAdditive;
}
},
metadataExtension: {
get: function() {
return this._metadataExtension;
}
},
metadata: {
get: function() {
if (defined_default(this._metadataExtension)) {
return this._metadataExtension.tileset;
}
return void 0;
}
},
schema: {
get: function() {
if (defined_default(this._metadataExtension)) {
return this._metadataExtension.schema;
}
return void 0;
}
},
maximumScreenSpaceError: {
get: function() {
return this._maximumScreenSpaceError;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals(
"maximumScreenSpaceError",
value,
0
);
this._maximumScreenSpaceError = value;
}
},
maximumMemoryUsage: {
get: function() {
return this._maximumMemoryUsage;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("value", value, 0);
this._maximumMemoryUsage = value;
}
},
pointCloudShading: {
get: function() {
return this._pointCloudShading;
},
set: function(value) {
Check_default.defined("pointCloudShading", value);
this._pointCloudShading = value;
}
},
root: {
get: function() {
return this._root;
}
},
boundingSphere: {
get: function() {
this._root.updateTransform(this._modelMatrix);
return this._root.boundingSphere;
}
},
modelMatrix: {
get: function() {
return this._modelMatrix;
},
set: function(value) {
this._modelMatrix = Matrix4_default.clone(value, this._modelMatrix);
}
},
timeSinceLoad: {
get: function() {
return this._timeSinceLoad;
}
},
totalMemoryUsageInBytes: {
get: function() {
const statistics2 = this._statistics;
return statistics2.texturesByteLength + statistics2.geometryByteLength + statistics2.batchTableByteLength;
}
},
clippingPlanesOriginMatrix: {
get: function() {
if (!defined_default(this._clippingPlanesOriginMatrix)) {
return Matrix4_default.IDENTITY;
}
if (this._clippingPlanesOriginMatrixDirty) {
Matrix4_default.multiply(
this.root.computedTransform,
this._initialClippingPlanesOriginMatrix,
this._clippingPlanesOriginMatrix
);
this._clippingPlanesOriginMatrixDirty = false;
}
return this._clippingPlanesOriginMatrix;
}
},
styleEngine: {
get: function() {
return this._styleEngine;
}
},
statistics: {
get: function() {
return this._statistics;
}
},
classificationType: {
get: function() {
return this._classificationType;
}
},
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
foveatedConeSize: {
get: function() {
return this._foveatedConeSize;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals("foveatedConeSize", value, 0);
Check_default.typeOf.number.lessThanOrEquals("foveatedConeSize", value, 1);
this._foveatedConeSize = value;
}
},
foveatedMinimumScreenSpaceErrorRelaxation: {
get: function() {
return this._foveatedMinimumScreenSpaceErrorRelaxation;
},
set: function(value) {
Check_default.typeOf.number.greaterThanOrEquals(
"foveatedMinimumScreenSpaceErrorRelaxation",
value,
0
);
Check_default.typeOf.number.lessThanOrEquals(
"foveatedMinimumScreenSpaceErrorRelaxation",
value,
this.maximumScreenSpaceError
);
this._foveatedMinimumScreenSpaceErrorRelaxation = value;
}
},
extras: {
get: function() {
return this._extras;
}
},
imageBasedLighting: {
get: function() {
return this._imageBasedLighting;
},
set: function(value) {
Check_default.typeOf.object("imageBasedLighting", this._imageBasedLighting);
if (value !== this._imageBasedLighting) {
if (this._shouldDestroyImageBasedLighting && !this._imageBasedLighting.isDestroyed()) {
this._imageBasedLighting.destroy();
}
this._imageBasedLighting = value;
this._shouldDestroyImageBasedLighting = false;
}
}
},
vectorClassificationOnly: {
get: function() {
return this._vectorClassificationOnly;
}
},
vectorKeepDecodedPositions: {
get: function() {
return this._vectorKeepDecodedPositions;
}
},
showCreditsOnScreen: {
get: function() {
return this._showCreditsOnScreen;
},
set: function(value) {
this._showCreditsOnScreen = value;
}
},
featureIdLabel: {
get: function() {
return this._featureIdLabel;
},
set: function(value) {
if (typeof value === "number") {
value = `featureId_${value}`;
}
Check_default.typeOf.string("value", value);
this._featureIdLabel = value;
}
},
instanceFeatureIdLabel: {
get: function() {
return this._instanceFeatureIdLabel;
},
set: function(value) {
if (typeof value === "number") {
value = `instanceFeatureId_${value}`;
}
Check_default.typeOf.string("value", value);
this._instanceFeatureIdLabel = value;
}
}
});
Cesium3DTileset.fromIonAssetId = async function(assetId, options) {
Check_default.defined("assetId", assetId);
const resource = await IonResource_default.fromAssetId(assetId);
return Cesium3DTileset.fromUrl(resource, options);
};
Cesium3DTileset.fromUrl = async function(url2, options) {
Check_default.defined("url", url2);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const resource = Resource_default.createIfNeeded(url2);
let basePath;
if (resource.extension === "json") {
basePath = resource.getBaseUri(true);
} else if (resource.isDataUri) {
basePath = "";
}
const tilesetJson = await Cesium3DTileset.loadJson(resource);
const metadataExtension = await processMetadataExtension(
resource,
tilesetJson
);
const tileset = new Cesium3DTileset(options);
tileset._resource = resource;
tileset._url = resource.url;
tileset._basePath = basePath;
tileset._metadataExtension = metadataExtension;
tileset._geometricError = tilesetJson.geometricError;
tileset._scaledGeometricError = tilesetJson.geometricError;
const asset = tilesetJson.asset;
tileset._asset = asset;
tileset._extras = tilesetJson.extras;
let credits = resource.credits;
if (!defined_default(credits)) {
credits = [];
}
const assetExtras = asset.extras;
if (defined_default(assetExtras) && defined_default(assetExtras.cesium) && defined_default(assetExtras.cesium.credits)) {
const extraCredits = assetExtras.cesium.credits;
for (let i = 0; i < extraCredits.length; ++i) {
const credit = extraCredits[i];
credits.push(new Credit_default(credit.html, tileset._showCreditsOnScreen));
}
}
tileset._credits = credits;
const gltfUpAxis = defined_default(tilesetJson.asset.gltfUpAxis) ? Axis_default.fromName(tilesetJson.asset.gltfUpAxis) : Axis_default.Y;
const modelUpAxis = defaultValue_default(options.modelUpAxis, gltfUpAxis);
const modelForwardAxis = defaultValue_default(options.modelForwardAxis, Axis_default.X);
tileset._properties = tilesetJson.properties;
tileset._extensionsUsed = tilesetJson.extensionsUsed;
tileset._extensions = tilesetJson.extensions;
tileset._modelUpAxis = modelUpAxis;
tileset._modelForwardAxis = modelForwardAxis;
tileset._root = tileset.loadTileset(resource, tilesetJson);
const boundingVolume = tileset._root.createBoundingVolume(
tilesetJson.root.boundingVolume,
Matrix4_default.IDENTITY
);
const clippingPlanesOrigin = boundingVolume.boundingSphere.center;
const originCartographic = tileset._ellipsoid.cartesianToCartographic(
clippingPlanesOrigin
);
if (defined_default(originCartographic) && originCartographic.height > ApproximateTerrainHeights_default._defaultMinTerrainHeight) {
tileset._initialClippingPlanesOriginMatrix = Transforms_default.eastNorthUpToFixedFrame(
clippingPlanesOrigin
);
}
tileset._clippingPlanesOriginMatrix = Matrix4_default.clone(
tileset._initialClippingPlanesOriginMatrix
);
tileset._readyPromise = Promise.resolve(tileset);
tileset._ready = true;
return tileset;
};
Cesium3DTileset.loadJson = function(tilesetUrl) {
const resource = Resource_default.createIfNeeded(tilesetUrl);
return resource.fetchJson();
};
Cesium3DTileset.prototype.makeStyleDirty = function() {
this._styleEngine.makeDirty();
};
Cesium3DTileset.prototype.loadTileset = function(resource, tilesetJson, parentTile) {
const asset = tilesetJson.asset;
if (!defined_default(asset)) {
throw new RuntimeError_default("Tileset must have an asset property.");
}
if (asset.version !== "0.0" && asset.version !== "1.0" && asset.version !== "1.1") {
throw new RuntimeError_default(
"The tileset must be 3D Tiles version 0.0, 1.0, or 1.1"
);
}
if (defined_default(tilesetJson.extensionsRequired)) {
Cesium3DTileset.checkSupportedExtensions(tilesetJson.extensionsRequired);
}
const statistics2 = this._statistics;
const tilesetVersion = asset.tilesetVersion;
if (defined_default(tilesetVersion)) {
this._basePath += `?v=${tilesetVersion}`;
resource = resource.clone();
resource.setQueryParameters({ v: tilesetVersion });
}
const rootTile = makeTile2(this, resource, tilesetJson.root, parentTile);
if (defined_default(parentTile)) {
parentTile.children.push(rootTile);
rootTile._depth = parentTile._depth + 1;
}
const stack = [];
stack.push(rootTile);
while (stack.length > 0) {
const tile = stack.pop();
++statistics2.numberOfTilesTotal;
this._allTilesAdditive = this._allTilesAdditive && tile.refine === Cesium3DTileRefine_default.ADD;
const children = tile._header.children;
if (defined_default(children)) {
for (let i = 0; i < children.length; ++i) {
const childHeader = children[i];
const childTile = makeTile2(this, resource, childHeader, tile);
tile.children.push(childTile);
childTile._depth = tile._depth + 1;
stack.push(childTile);
}
}
if (this._cullWithChildrenBounds) {
Cesium3DTileOptimizations_default.checkChildrenWithinParent(tile);
}
}
return rootTile;
};
function makeTile2(tileset, baseResource2, tileHeader, parentTile) {
const hasImplicitTiling = defined_default(tileHeader.implicitTiling) || hasExtension_default(tileHeader, "3DTILES_implicit_tiling");
if (!hasImplicitTiling) {
return new Cesium3DTile_default(tileset, baseResource2, tileHeader, parentTile);
}
const metadataSchema = tileset.schema;
const implicitTileset = new ImplicitTileset_default(
baseResource2,
tileHeader,
metadataSchema
);
const rootCoordinates = new ImplicitTileCoordinates_default({
subdivisionScheme: implicitTileset.subdivisionScheme,
subtreeLevels: implicitTileset.subtreeLevels,
level: 0,
x: 0,
y: 0,
z: 0
});
const contentUri = implicitTileset.subtreeUriTemplate.getDerivedResource({
templateValues: rootCoordinates.getTemplateValues()
}).url;
const deepCopy = true;
const tileJson = clone_default(tileHeader, deepCopy);
tileJson.contents = [
{
uri: contentUri
}
];
delete tileJson.content;
delete tileJson.extensions;
const tile = new Cesium3DTile_default(tileset, baseResource2, tileJson, parentTile);
tile.implicitTileset = implicitTileset;
tile.implicitCoordinates = rootCoordinates;
return tile;
}
async function processMetadataExtension(resource, tilesetJson) {
const metadataJson = hasExtension_default(tilesetJson, "3DTILES_metadata") ? tilesetJson.extensions["3DTILES_metadata"] : tilesetJson;
let schemaLoader;
if (defined_default(metadataJson.schemaUri)) {
resource = resource.getDerivedResource({
url: metadataJson.schemaUri
});
schemaLoader = ResourceCache_default.getSchemaLoader({
resource
});
} else if (defined_default(metadataJson.schema)) {
schemaLoader = ResourceCache_default.getSchemaLoader({
schema: metadataJson.schema
});
} else {
return;
}
await schemaLoader.load();
const metadataExtension = new Cesium3DTilesetMetadata_default({
schema: schemaLoader.schema,
metadataJson
});
ResourceCache_default.unload(schemaLoader);
return metadataExtension;
}
var scratchPositionNormal = new Cartesian3_default();
var scratchCartographic7 = new Cartographic_default();
var scratchMatrix4 = new Matrix4_default();
var scratchCenter5 = new Cartesian3_default();
var scratchPosition7 = new Cartesian3_default();
var scratchDirection = new Cartesian3_default();
function updateDynamicScreenSpaceError(tileset, frameState) {
let up;
let direction2;
let height;
let minimumHeight;
let maximumHeight;
const camera = frameState.camera;
const root = tileset._root;
const tileBoundingVolume = root.contentBoundingVolume;
if (tileBoundingVolume instanceof TileBoundingRegion_default) {
up = Cartesian3_default.normalize(camera.positionWC, scratchPositionNormal);
direction2 = camera.directionWC;
height = camera.positionCartographic.height;
minimumHeight = tileBoundingVolume.minimumHeight;
maximumHeight = tileBoundingVolume.maximumHeight;
} else {
const transformLocal = Matrix4_default.inverseTransformation(
root.computedTransform,
scratchMatrix4
);
const ellipsoid = frameState.mapProjection.ellipsoid;
const boundingVolume = tileBoundingVolume.boundingVolume;
const centerLocal = Matrix4_default.multiplyByPoint(
transformLocal,
boundingVolume.center,
scratchCenter5
);
if (Cartesian3_default.magnitude(centerLocal) > ellipsoid.minimumRadius) {
const centerCartographic = Cartographic_default.fromCartesian(
centerLocal,
ellipsoid,
scratchCartographic7
);
up = Cartesian3_default.normalize(camera.positionWC, scratchPositionNormal);
direction2 = camera.directionWC;
height = camera.positionCartographic.height;
minimumHeight = 0;
maximumHeight = centerCartographic.height * 2;
} else {
const positionLocal = Matrix4_default.multiplyByPoint(
transformLocal,
camera.positionWC,
scratchPosition7
);
up = Cartesian3_default.UNIT_Z;
direction2 = Matrix4_default.multiplyByPointAsVector(
transformLocal,
camera.directionWC,
scratchDirection
);
direction2 = Cartesian3_default.normalize(direction2, direction2);
height = positionLocal.z;
if (tileBoundingVolume instanceof TileOrientedBoundingBox_default) {
const boxHeight = root._header.boundingVolume.box[11];
minimumHeight = centerLocal.z - boxHeight;
maximumHeight = centerLocal.z + boxHeight;
} else if (tileBoundingVolume instanceof TileBoundingSphere_default) {
const radius = boundingVolume.radius;
minimumHeight = centerLocal.z - radius;
maximumHeight = centerLocal.z + radius;
}
}
}
const heightFalloff = tileset.dynamicScreenSpaceErrorHeightFalloff;
const heightClose = minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;
const heightFar = maximumHeight;
const t = Math_default.clamp(
(height - heightClose) / (heightFar - heightClose),
0,
1
);
let horizonFactor = 1 - Math.abs(Cartesian3_default.dot(direction2, up));
horizonFactor = horizonFactor * (1 - t);
tileset._dynamicScreenSpaceErrorComputedDensity = tileset.dynamicScreenSpaceErrorDensity * horizonFactor;
}
function requestContent(tileset, tile) {
if (tile.hasEmptyContent) {
return;
}
const { statistics: statistics2 } = tileset;
const contentExpired = tile.contentExpired;
const promise = tile.requestContent();
if (!defined_default(promise)) {
return;
}
promise.then((content) => {
if (!defined_default(content) || tile.isDestroyed() || tileset.isDestroyed()) {
return;
}
tileset._processingQueue.push(tile);
++statistics2.numberOfTilesProcessing;
}).catch((error) => {
handleTileFailure(error, tileset, tile);
});
if (contentExpired) {
if (tile.hasTilesetContent || tile.hasImplicitContent) {
destroySubtree(tileset, tile);
} else {
statistics2.decrementLoadCounts(tile.content);
--statistics2.numberOfTilesWithContentReady;
}
}
tileset._requestedTilesInFlight.push(tile);
}
function sortRequestByPriority(a3, b) {
return a3._priority - b._priority;
}
Cesium3DTileset.prototype.postPassesUpdate = function(frameState) {
if (!defined_default(this._root)) {
return;
}
cancelOutOfViewRequests(this, frameState);
raiseLoadProgressEvent(this, frameState);
this._cache.unloadTiles(this, unloadTile);
if (this._styleApplied) {
this._styleEngine.resetDirty();
}
this._styleApplied = false;
};
Cesium3DTileset.prototype.prePassesUpdate = function(frameState) {
if (!defined_default(this._root)) {
return;
}
processTiles(this, frameState);
const clippingPlanes = this._clippingPlanes;
this._clippingPlanesOriginMatrixDirty = true;
if (defined_default(clippingPlanes) && clippingPlanes.enabled) {
clippingPlanes.update(frameState);
}
if (!defined_default(this._loadTimestamp)) {
this._loadTimestamp = JulianDate_default.clone(frameState.time);
}
this._timeSinceLoad = Math.max(
JulianDate_default.secondsDifference(frameState.time, this._loadTimestamp) * 1e3,
0
);
if (this.dynamicScreenSpaceError) {
updateDynamicScreenSpaceError(this, frameState);
}
if (frameState.newFrame) {
this._cache.reset();
}
};
function cancelOutOfViewRequests(tileset, frameState) {
const requestedTilesInFlight = tileset._requestedTilesInFlight;
let removeCount = 0;
for (let i = 0; i < requestedTilesInFlight.length; ++i) {
const tile = requestedTilesInFlight[i];
const outOfView = frameState.frameNumber - tile._touchedFrame >= 1;
if (tile._contentState !== Cesium3DTileContentState_default.LOADING) {
++removeCount;
continue;
} else if (outOfView) {
tile.cancelRequests();
++removeCount;
continue;
}
if (removeCount > 0) {
requestedTilesInFlight[i - removeCount] = tile;
}
}
requestedTilesInFlight.length -= removeCount;
}
function requestTiles(tileset) {
const requestedTiles = tileset._requestedTiles;
requestedTiles.sort(sortRequestByPriority);
for (let i = 0; i < requestedTiles.length; ++i) {
requestContent(tileset, requestedTiles[i]);
}
}
function handleTileFailure(error, tileset, tile) {
if (tileset.isDestroyed()) {
return;
}
let url2;
if (!tile.isDestroyed()) {
url2 = tile._contentResource.url;
}
const message = defined_default(error.message) ? error.message : error.toString();
if (tileset.tileFailed.numberOfListeners > 0) {
tileset.tileFailed.raiseEvent({
url: url2,
message
});
} else {
console.log(`A 3D tile failed to load: ${url2}`);
console.log(`Error: ${message}`);
}
}
function filterProcessingQueue(tileset) {
const tiles = tileset._processingQueue;
let removeCount = 0;
for (let i = 0; i < tiles.length; ++i) {
const tile = tiles[i];
if (tile.isDestroyed() || tile._contentState !== Cesium3DTileContentState_default.PROCESSING) {
++removeCount;
continue;
}
if (removeCount > 0) {
tiles[i - removeCount] = tile;
}
}
tiles.length -= removeCount;
}
function processTiles(tileset, frameState) {
filterProcessingQueue(tileset);
const tiles = tileset._processingQueue;
const statistics2 = tileset._statistics;
let tile;
for (let i = 0; i < tiles.length; ++i) {
tile = tiles[i];
try {
tile.process(tileset, frameState);
if (tile.contentReady) {
--statistics2.numberOfTilesProcessing;
tileset.tileLoad.raiseEvent(tile);
}
} catch (error) {
--statistics2.numberOfTilesProcessing;
handleTileFailure(error, tileset, tile);
}
}
}
var scratchCartesian10 = new Cartesian3_default();
var stringOptions = {
maximumFractionDigits: 3
};
function formatMemoryString(memorySizeInBytes) {
const memoryInMegabytes = memorySizeInBytes / 1048576;
if (memoryInMegabytes < 1) {
return memoryInMegabytes.toLocaleString(void 0, stringOptions);
}
return Math.round(memoryInMegabytes).toLocaleString();
}
function computeTileLabelPosition(tile) {
const { halfAxes, radius, center } = tile.boundingVolume.boundingVolume;
let position = Cartesian3_default.clone(center, scratchCartesian10);
if (defined_default(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_default(radius)) {
let normal2 = Cartesian3_default.normalize(center, scratchCartesian10);
normal2 = Cartesian3_default.multiplyByScalar(
normal2,
0.75 * radius,
scratchCartesian10
);
position = Cartesian3_default.add(normal2, center, scratchCartesian10);
}
return position;
}
function addTileDebugLabel(tile, tileset, position) {
let labelString = "";
let attributes = 0;
if (tileset.debugShowGeometricError) {
labelString += `
Geometric error: ${tile.geometricError}`;
attributes++;
}
if (tileset.debugShowRenderingStatistics) {
labelString += `
Commands: ${tile.commandsLength}`;
attributes++;
const numberOfPoints = tile.content.pointsLength;
if (numberOfPoints > 0) {
labelString += `
Points: ${tile.content.pointsLength}`;
attributes++;
}
const numberOfTriangles = tile.content.trianglesLength;
if (numberOfTriangles > 0) {
labelString += `
Triangles: ${tile.content.trianglesLength}`;
attributes++;
}
labelString += `
Features: ${tile.content.featuresLength}`;
attributes++;
}
if (tileset.debugShowMemoryUsage) {
labelString += `
Texture Memory: ${formatMemoryString(
tile.content.texturesByteLength
)}`;
labelString += `
Geometry Memory: ${formatMemoryString(
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 += `
- ${urls[i]}`;
}
attributes += urls.length;
} else {
labelString += `
Url: ${tile._contentHeader.uri}`;
attributes++;
}
}
const newLabel = {
text: labelString.substring(1),
position,
font: `${19 - attributes}px sans-serif`,
showBackground: true,
disableDepthTestDistance: Number.POSITIVE_INFINITY
};
return tileset._tileDebugLabels.add(newLabel);
}
function updateTileDebugLabels(tileset, frameState) {
const selectedTiles = tileset._selectedTiles;
const selectedLength = selectedTiles.length;
const emptyTiles = tileset._emptyTiles;
const emptyLength = emptyTiles.length;
tileset._tileDebugLabels.removeAll();
if (tileset.debugPickedTileLabelOnly) {
if (defined_default(tileset.debugPickedTile)) {
const position = defined_default(tileset.debugPickPosition) ? tileset.debugPickPosition : computeTileLabelPosition(tileset.debugPickedTile);
const label = addTileDebugLabel(
tileset.debugPickedTile,
tileset,
position
);
label.pixelOffset = new Cartesian2_default(15, -15);
}
} else {
for (let i = 0; i < selectedLength; ++i) {
const tile = selectedTiles[i];
addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
}
for (let i = 0; i < emptyLength; ++i) {
const tile = emptyTiles[i];
if (tile.hasTilesetContent || tile.hasImplicitContent) {
addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
}
}
}
tileset._tileDebugLabels.update(frameState);
}
function updateTiles(tileset, frameState, passOptions2) {
tileset._styleEngine.applyStyle(tileset);
tileset._styleApplied = true;
const { commandList, context } = frameState;
const numberOfInitialCommands = commandList.length;
const selectedTiles = tileset._selectedTiles;
const bivariateVisibilityTest = tileset.isSkippingLevelOfDetail && tileset._hasMixedContent && context.stencilBuffer && selectedTiles.length > 0;
tileset._backfaceCommands.length = 0;
if (bivariateVisibilityTest) {
if (!defined_default(tileset._stencilClearCommand)) {
tileset._stencilClearCommand = new ClearCommand_default({
stencil: 0,
pass: Pass_default.CESIUM_3D_TILE,
renderState: RenderState_default.fromCache({
stencilMask: StencilConstants_default.SKIP_LOD_MASK
})
});
}
commandList.push(tileset._stencilClearCommand);
}
const { statistics: statistics2, tileVisible } = tileset;
const isRender = passOptions2.isRender;
const lengthBeforeUpdate = commandList.length;
for (let i = 0; i < selectedTiles.length; ++i) {
const tile = selectedTiles[i];
if (isRender) {
tileVisible.raiseEvent(tile);
}
tile.update(tileset, frameState, passOptions2);
statistics2.incrementSelectionCounts(tile.content);
++statistics2.selected;
}
const emptyTiles = tileset._emptyTiles;
for (let i = 0; i < emptyTiles.length; ++i) {
const tile = emptyTiles[i];
tile.update(tileset, frameState, passOptions2);
}
let addedCommandsLength = commandList.length - lengthBeforeUpdate;
tileset._backfaceCommands.trim();
if (bivariateVisibilityTest) {
const backfaceCommands = tileset._backfaceCommands.values;
const backfaceCommandsLength = backfaceCommands.length;
commandList.length += backfaceCommandsLength;
for (let i = addedCommandsLength - 1; i >= 0; --i) {
commandList[lengthBeforeUpdate + backfaceCommandsLength + i] = commandList[lengthBeforeUpdate + i];
}
for (let i = 0; i < backfaceCommandsLength; ++i) {
commandList[lengthBeforeUpdate + i] = backfaceCommands[i];
}
}
addedCommandsLength = commandList.length - numberOfInitialCommands;
statistics2.numberOfCommands = addedCommandsLength;
if (!isRender) {
return;
}
if (tileset.pointCloudShading.attenuation && tileset.pointCloudShading.eyeDomeLighting && addedCommandsLength > 0) {
tileset._pointCloudEyeDomeLighting.update(
frameState,
numberOfInitialCommands,
tileset.pointCloudShading,
tileset.boundingSphere
);
}
if (tileset.debugShowGeometricError || tileset.debugShowRenderingStatistics || tileset.debugShowMemoryUsage || tileset.debugShowUrl) {
if (!defined_default(tileset._tileDebugLabels)) {
tileset._tileDebugLabels = new LabelCollection_default();
}
updateTileDebugLabels(tileset, frameState);
} else {
tileset._tileDebugLabels = tileset._tileDebugLabels && tileset._tileDebugLabels.destroy();
}
}
var scratchStack2 = [];
function destroySubtree(tileset, tile) {
const root = tile;
const stack = scratchStack2;
stack.push(tile);
while (stack.length > 0) {
tile = stack.pop();
const children = tile.children;
for (let i = 0; i < children.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();
}
Cesium3DTileset.prototype.trimLoadedTiles = function() {
this._cache.trim();
};
function raiseLoadProgressEvent(tileset, frameState) {
const statistics2 = tileset._statistics;
const statisticsLast = tileset._statisticsLast;
const numberOfPendingRequests = statistics2.numberOfPendingRequests;
const numberOfTilesProcessing = statistics2.numberOfTilesProcessing;
const lastNumberOfPendingRequest = statisticsLast.numberOfPendingRequests;
const lastNumberOfTilesProcessing = statisticsLast.numberOfTilesProcessing;
Cesium3DTilesetStatistics_default.clone(statistics2, statisticsLast);
const progressChanged = numberOfPendingRequests !== lastNumberOfPendingRequest || numberOfTilesProcessing !== lastNumberOfTilesProcessing;
if (progressChanged) {
frameState.afterRender.push(function() {
tileset.loadProgress.raiseEvent(
numberOfPendingRequests,
numberOfTilesProcessing
);
return true;
});
}
tileset._tilesLoaded = statistics2.numberOfPendingRequests === 0 && statistics2.numberOfTilesProcessing === 0 && statistics2.numberOfAttemptedRequests === 0;
if (progressChanged && tileset._tilesLoaded) {
frameState.afterRender.push(function() {
tileset.allTilesLoaded.raiseEvent();
return true;
});
if (!tileset._initialTilesLoaded) {
tileset._initialTilesLoaded = true;
frameState.afterRender.push(function() {
tileset.initialTilesLoaded.raiseEvent();
return true;
});
}
}
}
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_default(tileset._previousModelMatrix)) {
return;
}
tileset._updatedModelMatrixFrame = frameState.frameNumber;
tileset._modelMatrixChanged = !Matrix4_default.equals(
tileset.modelMatrix,
tileset._previousModelMatrix
);
if (tileset._modelMatrixChanged) {
tileset._previousModelMatrix = Matrix4_default.clone(
tileset.modelMatrix,
tileset._previousModelMatrix
);
}
}
function update3(tileset, frameState, passStatistics, passOptions2) {
if (frameState.mode === SceneMode_default.MORPHING) {
return false;
}
if (!defined_default(tileset._root)) {
return false;
}
const statistics2 = tileset._statistics;
statistics2.clear();
++tileset._updatedVisibilityFrame;
resetMinimumMaximum(tileset);
detectModelMatrixChanged(tileset, frameState);
tileset._cullRequestsWhileMoving = tileset.cullRequestsWhileMoving && !tileset._modelMatrixChanged;
const ready = tileset.getTraversal(passOptions2).selectTiles(tileset, frameState);
if (passOptions2.requestTiles) {
requestTiles(tileset);
}
updateTiles(tileset, frameState, passOptions2);
Cesium3DTilesetStatistics_default.clone(statistics2, passStatistics);
if (passOptions2.isRender) {
const credits = tileset._credits;
if (defined_default(credits) && statistics2.selected !== 0) {
for (let i = 0; i < credits.length; ++i) {
const credit = credits[i];
credit.showOnScreen = tileset._showCreditsOnScreen;
frameState.creditDisplay.addCreditToNextFrame(credit);
}
}
}
return ready;
}
Cesium3DTileset.prototype.getTraversal = function(passOptions2) {
const { pass } = passOptions2;
if (pass === Cesium3DTilePass_default.MOST_DETAILED_PRELOAD || pass === Cesium3DTilePass_default.MOST_DETAILED_PICK) {
return Cesium3DTilesetMostDetailedTraversal_default;
}
return this.isSkippingLevelOfDetail ? Cesium3DTilesetSkipTraversal_default : Cesium3DTilesetBaseTraversal_default;
};
Cesium3DTileset.prototype.update = function(frameState) {
this.updateForPass(frameState, frameState.tilesetPassState);
};
Cesium3DTileset.prototype.updateForPass = function(frameState, tilesetPassState) {
Check_default.typeOf.object("frameState", frameState);
Check_default.typeOf.object("tilesetPassState", tilesetPassState);
const pass = tilesetPassState.pass;
if (pass === Cesium3DTilePass_default.PRELOAD && (!this.preloadWhenHidden || this.show) || pass === Cesium3DTilePass_default.PRELOAD_FLIGHT && (!this.preloadFlightDestinations || !this.show && !this.preloadWhenHidden) || pass === Cesium3DTilePass_default.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 passOptions2 = Cesium3DTilePass_default.getPassOptions(pass);
const ignoreCommands = passOptions2.ignoreCommands;
const commandList = defaultValue_default(
tilesetPassState.commandList,
originalCommandList
);
const commandStart = commandList.length;
frameState.commandList = commandList;
frameState.camera = defaultValue_default(tilesetPassState.camera, originalCamera);
frameState.cullingVolume = defaultValue_default(
tilesetPassState.cullingVolume,
originalCullingVolume
);
const passStatistics = this._statisticsPerPass[pass];
if (this.show || ignoreCommands) {
this._pass = pass;
tilesetPassState.ready = update3(
this,
frameState,
passStatistics,
passOptions2
);
}
if (ignoreCommands) {
commandList.length = commandStart;
}
frameState.commandList = originalCommandList;
frameState.camera = originalCamera;
frameState.cullingVolume = originalCullingVolume;
};
Cesium3DTileset.prototype.hasExtension = function(extensionName) {
if (!defined_default(this._extensionsUsed)) {
return false;
}
return this._extensionsUsed.indexOf(extensionName) > -1;
};
Cesium3DTileset.prototype.isDestroyed = function() {
return false;
};
Cesium3DTileset.prototype.destroy = function() {
this._tileDebugLabels = this._tileDebugLabels && this._tileDebugLabels.destroy();
this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();
if (defined_default(this._root)) {
const stack = scratchStack2;
stack.push(this._root);
while (stack.length > 0) {
const tile = stack.pop();
tile.destroy();
const children = tile.children;
for (let i = 0; i < children.length; ++i) {
stack.push(children[i]);
}
}
}
this._root = void 0;
if (this._shouldDestroyImageBasedLighting && !this._imageBasedLighting.isDestroyed()) {
this._imageBasedLighting.destroy();
}
this._imageBasedLighting = void 0;
return destroyObject_default(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
};
Cesium3DTileset.checkSupportedExtensions = function(extensionsRequired) {
for (let i = 0; i < extensionsRequired.length; i++) {
if (!Cesium3DTileset.supportedExtensions[extensionsRequired[i]]) {
throw new RuntimeError_default(
`Unsupported 3D Tiles Extension: ${extensionsRequired[i]}`
);
}
}
};
var Cesium3DTileset_default = Cesium3DTileset;
// node_modules/@cesium/engine/Source/DataSources/Cesium3DTilesetVisualizer.js
var modelMatrixScratch2 = new Matrix4_default();
function Cesium3DTilesetVisualizer(scene, entityCollection) {
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
if (!defined_default(entityCollection)) {
throw new DeveloperError_default("entityCollection is required.");
}
entityCollection.collectionChanged.addEventListener(
Cesium3DTilesetVisualizer.prototype._onCollectionChanged,
this
);
this._scene = scene;
this._primitives = scene.primitives;
this._entityCollection = entityCollection;
this._tilesetHash = {};
this._entitiesToVisualize = new AssociativeArray_default();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
Cesium3DTilesetVisualizer.prototype.update = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
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;
const tilesetData = tilesetHash[entity.id];
const show = entity.isShowing && entity.isAvailable(time) && Property_default.getValueOrDefault(tilesetGraphics._show, time, true);
let modelMatrix;
if (show) {
modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch2);
resource = Resource_default.createIfNeeded(
Property_default.getValueOrUndefined(tilesetGraphics._uri, time)
);
}
if (!show) {
if (defined_default(tilesetData)) {
tilesetData.tilesetPrimitive.show = false;
}
continue;
}
const tileset = defined_default(tilesetData) ? tilesetData.tilesetPrimitive : void 0;
if (!defined_default(tilesetData) || resource.url !== tilesetData.url) {
if (defined_default(tileset)) {
primitives.removeAndDestroy(tileset);
}
delete tilesetHash[entity.id];
createTileset(resource, tilesetHash, entity, primitives);
}
if (!defined_default(tileset)) {
continue;
}
tileset.show = true;
if (defined_default(modelMatrix)) {
tileset.modelMatrix = modelMatrix;
}
tileset.maximumScreenSpaceError = Property_default.getValueOrDefault(
tilesetGraphics.maximumScreenSpaceError,
time,
tileset.maximumScreenSpaceError
);
}
return true;
};
Cesium3DTilesetVisualizer.prototype.isDestroyed = function() {
return false;
};
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_default(this);
};
Cesium3DTilesetVisualizer.prototype.getBoundingSphere = function(entity, result) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const tilesetData = this._tilesetHash[entity.id];
if (!defined_default(tilesetData) || tilesetData.loadFail) {
return BoundingSphereState_default.FAILED;
}
const primitive = tilesetData.tilesetPrimitive;
if (!defined_default(primitive)) {
return BoundingSphereState_default.PENDING;
}
if (!primitive.show) {
return BoundingSphereState_default.FAILED;
}
BoundingSphere_default.clone(primitive.boundingSphere, result);
return BoundingSphereState_default.DONE;
};
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_default(entity._tileset)) {
entities.set(entity.id, entity);
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined_default(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_default(tilesetData)) {
if (defined_default(tilesetData.tilesetPrimitive)) {
primitives.removeAndDestroy(tilesetData.tilesetPrimitive);
}
delete tilesetHash[entity.id];
}
}
async function createTileset(resource, tilesetHash, entity, primitives) {
tilesetHash[entity.id] = {
url: resource.url,
loadFail: false
};
try {
const tileset = await Cesium3DTileset_default.fromUrl(resource);
tileset.id = entity;
primitives.add(tileset);
if (!defined_default(tilesetHash[entity.id])) {
return;
}
tilesetHash[entity.id].tilesetPrimitive = tileset;
} catch (error) {
console.error(error);
tilesetHash[entity.id].loadFail = true;
}
}
var Cesium3DTilesetVisualizer_default = Cesium3DTilesetVisualizer;
// node_modules/@cesium/engine/Source/DataSources/CheckerboardMaterialProperty.js
var defaultEvenColor = Color_default.WHITE;
var defaultOddColor = Color_default.BLACK;
var defaultRepeat2 = new Cartesian2_default(2, 2);
function CheckerboardMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._evenColor = void 0;
this._evenColorSubscription = void 0;
this._oddColor = void 0;
this._oddColorSubscription = void 0;
this._repeat = void 0;
this._repeatSubscription = void 0;
this.evenColor = options.evenColor;
this.oddColor = options.oddColor;
this.repeat = options.repeat;
}
Object.defineProperties(CheckerboardMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._evenColor) && Property_default.isConstant(this._oddColor) && Property_default.isConstant(this._repeat);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
evenColor: createPropertyDescriptor_default("evenColor"),
oddColor: createPropertyDescriptor_default("oddColor"),
repeat: createPropertyDescriptor_default("repeat")
});
CheckerboardMaterialProperty.prototype.getType = function(time) {
return "Checkerboard";
};
CheckerboardMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.lightColor = Property_default.getValueOrClonedDefault(
this._evenColor,
time,
defaultEvenColor,
result.lightColor
);
result.darkColor = Property_default.getValueOrClonedDefault(
this._oddColor,
time,
defaultOddColor,
result.darkColor
);
result.repeat = Property_default.getValueOrDefault(this._repeat, time, defaultRepeat2);
return result;
};
CheckerboardMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof CheckerboardMaterialProperty && Property_default.equals(this._evenColor, other._evenColor) && Property_default.equals(this._oddColor, other._oddColor) && Property_default.equals(this._repeat, other._repeat);
};
var CheckerboardMaterialProperty_default = CheckerboardMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/EntityCollection.js
var entityOptionsScratch = {
id: void 0
};
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;
}
}
}
function EntityCollection(owner) {
this._owner = owner;
this._entities = new AssociativeArray_default();
this._addedEntities = new AssociativeArray_default();
this._removedEntities = new AssociativeArray_default();
this._changedEntities = new AssociativeArray_default();
this._suspendCount = 0;
this._collectionChanged = new Event_default();
this._id = createGuid_default();
this._show = true;
this._firing = false;
this._refire = false;
}
EntityCollection.prototype.suspendEvents = function() {
this._suspendCount++;
};
EntityCollection.prototype.resumeEvents = function() {
if (this._suspendCount === 0) {
throw new DeveloperError_default(
"resumeEvents can not be called before suspendEvents."
);
}
this._suspendCount--;
fireChangedEvent(this);
};
Object.defineProperties(EntityCollection.prototype, {
collectionChanged: {
get: function() {
return this._collectionChanged;
}
},
id: {
get: function() {
return this._id;
}
},
values: {
get: function() {
return this._entities.values;
}
},
show: {
get: function() {
return this._show;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (value === this._show) {
return;
}
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();
}
},
owner: {
get: function() {
return this._owner;
}
}
});
EntityCollection.prototype.computeAvailability = function() {
let startTime = Iso8601_default.MAXIMUM_VALUE;
let stopTime = Iso8601_default.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_default(availability)) {
const start = availability.start;
const stop2 = availability.stop;
if (JulianDate_default.lessThan(start, startTime) && !start.equals(Iso8601_default.MINIMUM_VALUE)) {
startTime = start;
}
if (JulianDate_default.greaterThan(stop2, stopTime) && !stop2.equals(Iso8601_default.MAXIMUM_VALUE)) {
stopTime = stop2;
}
}
}
if (Iso8601_default.MAXIMUM_VALUE.equals(startTime)) {
startTime = Iso8601_default.MINIMUM_VALUE;
}
if (Iso8601_default.MINIMUM_VALUE.equals(stopTime)) {
stopTime = Iso8601_default.MAXIMUM_VALUE;
}
return new TimeInterval_default({
start: startTime,
stop: stopTime
});
};
EntityCollection.prototype.add = function(entity) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required.");
}
if (!(entity instanceof Entity_default)) {
entity = new Entity_default(entity);
}
const id = entity.id;
const entities = this._entities;
if (entities.contains(id)) {
throw new RuntimeError_default(
`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;
};
EntityCollection.prototype.remove = function(entity) {
if (!defined_default(entity)) {
return false;
}
return this.removeById(entity.id);
};
EntityCollection.prototype.contains = function(entity) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required");
}
return this._entities.get(entity.id) === entity;
};
EntityCollection.prototype.removeById = function(id) {
if (!defined_default(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;
};
EntityCollection.prototype.removeAll = function() {
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_default(addedItem)) {
existingItem.definitionChanged.removeEventListener(
EntityCollection.prototype._onEntityDefinitionChanged,
this
);
removed.set(existingItemId, existingItem);
}
}
entities.removeAll();
addedEntities.removeAll();
this._changedEntities.removeAll();
fireChangedEvent(this);
};
EntityCollection.prototype.getById = function(id) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
return this._entities.get(id);
};
EntityCollection.prototype.getOrCreateEntity = function(id) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required.");
}
let entity = this._entities.get(id);
if (!defined_default(entity)) {
entityOptionsScratch.id = id;
entity = new Entity_default(entityOptionsScratch);
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);
};
var EntityCollection_default = EntityCollection;
// node_modules/@cesium/engine/Source/DataSources/CompositeEntityCollection.js
var entityOptionsScratch2 = {
id: void 0
};
var 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]] = void 0;
}
entity._name = void 0;
entity._availability = void 0;
}
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] = void 0;
}
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_default(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
);
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_default(compositeEntity)) {
compositeEntity = composite.getById(entity.id);
if (!defined_default(compositeEntity)) {
entityOptionsScratch2.id = entity.id;
compositeEntity = new Entity_default(entityOptionsScratch2);
} 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();
}
function CompositeEntityCollection(collections, owner) {
this._owner = owner;
this._composite = new EntityCollection_default(this);
this._suspendCount = 0;
this._collections = defined_default(collections) ? collections.slice() : [];
this._collectionsCopy = [];
this._id = createGuid_default();
this._eventHash = {};
recomposite(this);
this._shouldRecomposite = false;
}
Object.defineProperties(CompositeEntityCollection.prototype, {
collectionChanged: {
get: function() {
return this._composite._collectionChanged;
}
},
id: {
get: function() {
return this._id;
}
},
values: {
get: function() {
return this._composite.values;
}
},
owner: {
get: function() {
return this._owner;
}
}
});
CompositeEntityCollection.prototype.addCollection = function(collection, index) {
const hasIndex = defined_default(index);
if (!defined_default(collection)) {
throw new DeveloperError_default("collection is required.");
}
if (hasIndex) {
if (index < 0) {
throw new DeveloperError_default("index must be greater than or equal to zero.");
} else if (index > this._collections.length) {
throw new DeveloperError_default(
"index must be less than or equal to the number of collections."
);
}
}
if (!hasIndex) {
index = this._collections.length;
this._collections.push(collection);
} else {
this._collections.splice(index, 0, collection);
}
recomposite(this);
};
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;
};
CompositeEntityCollection.prototype.removeAllCollections = function() {
this._collections.length = 0;
recomposite(this);
};
CompositeEntityCollection.prototype.containsCollection = function(collection) {
return this._collections.indexOf(collection) !== -1;
};
CompositeEntityCollection.prototype.contains = function(entity) {
return this._composite.contains(entity);
};
CompositeEntityCollection.prototype.indexOfCollection = function(collection) {
return this._collections.indexOf(collection);
};
CompositeEntityCollection.prototype.getCollection = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.", "index");
}
return this._collections[index];
};
CompositeEntityCollection.prototype.getCollectionsLength = function() {
return this._collections.length;
};
function getCollectionIndex(collections, collection) {
if (!defined_default(collection)) {
throw new DeveloperError_default("collection is required.");
}
const index = collections.indexOf(collection);
if (index === -1) {
throw new DeveloperError_default("collection is not in this composite.");
}
return index;
}
function swapCollections(composite, i, j) {
const arr = composite._collections;
i = Math_default.clamp(i, 0, arr.length - 1);
j = Math_default.clamp(j, 0, arr.length - 1);
if (i === j) {
return;
}
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
recomposite(composite);
}
CompositeEntityCollection.prototype.raiseCollection = function(collection) {
const index = getCollectionIndex(this._collections, collection);
swapCollections(this, index, index + 1);
};
CompositeEntityCollection.prototype.lowerCollection = function(collection) {
const index = getCollectionIndex(this._collections, collection);
swapCollections(this, index, index - 1);
};
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);
};
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);
};
CompositeEntityCollection.prototype.suspendEvents = function() {
this._suspendCount++;
this._composite.suspendEvents();
};
CompositeEntityCollection.prototype.resumeEvents = function() {
if (this._suspendCount === 0) {
throw new DeveloperError_default(
"resumeEvents can not be called before suspendEvents."
);
}
this._suspendCount--;
if (this._shouldRecomposite && this._suspendCount === 0) {
recomposite(this);
this._shouldRecomposite = false;
}
this._composite.resumeEvents();
};
CompositeEntityCollection.prototype.computeAvailability = function() {
return this._composite.computeAvailability();
};
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;
for (q = collectionsLength - 1; q >= 0; q--) {
entity = collections[q].getById(removedId);
if (defined_default(entity)) {
if (!defined_default(compositeEntity)) {
compositeEntity = composite.getById(removedId);
clean(compositeEntity);
}
compositeEntity.merge(entity);
}
}
if (!defined_default(compositeEntity)) {
composite.removeById(removedId);
}
compositeEntity = void 0;
}
const addedLength = added.length;
for (i = 0; i < addedLength; i++) {
const addedEntity = added[i];
subscribeToEntity(this, eventHash, collectionId, addedEntity);
const addedId = addedEntity.id;
for (q = collectionsLength - 1; q >= 0; q--) {
entity = collections[q].getById(addedId);
if (defined_default(entity)) {
if (!defined_default(compositeEntity)) {
compositeEntity = composite.getById(addedId);
if (!defined_default(compositeEntity)) {
entityOptionsScratch2.id = addedId;
compositeEntity = new Entity_default(entityOptionsScratch2);
composite.add(compositeEntity);
} else {
clean(compositeEntity);
}
}
compositeEntity.merge(entity);
}
}
compositeEntity = void 0;
}
composite.resumeEvents();
};
CompositeEntityCollection.prototype._onDefinitionChanged = function(entity, propertyName, newValue, oldValue2) {
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_default(compositeProperty);
let firstTime = true;
for (let q = collectionsLength - 1; q >= 0; q--) {
const innerEntity = collections[q].getById(entity.id);
if (defined_default(innerEntity)) {
const property = innerEntity[propertyName];
if (defined_default(property)) {
if (firstTime) {
firstTime = false;
if (defined_default(property.merge) && defined_default(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;
};
var CompositeEntityCollection_default = CompositeEntityCollection;
// node_modules/@cesium/engine/Source/Core/EventHelper.js
function EventHelper() {
this._removalFunctions = [];
}
EventHelper.prototype.add = function(event, listener, scope) {
if (!defined_default(event)) {
throw new DeveloperError_default("event is required");
}
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);
};
};
EventHelper.prototype.removeAll = function() {
const removalFunctions = this._removalFunctions;
for (let i = 0, len = removalFunctions.length; i < len; ++i) {
removalFunctions[i]();
}
removalFunctions.length = 0;
};
var EventHelper_default = EventHelper;
// node_modules/@cesium/engine/Source/Core/TimeIntervalCollection.js
function compareIntervalStartTimes(left, right) {
return JulianDate_default.compare(left.start, right.start);
}
function TimeIntervalCollection(intervals) {
this._intervals = [];
this._changedEvent = new Event_default();
if (defined_default(intervals)) {
const length3 = intervals.length;
for (let i = 0; i < length3; i++) {
this.addInterval(intervals[i]);
}
}
}
Object.defineProperties(TimeIntervalCollection.prototype, {
changedEvent: {
get: function() {
return this._changedEvent;
}
},
start: {
get: function() {
const intervals = this._intervals;
return intervals.length === 0 ? void 0 : intervals[0].start;
}
},
isStartIncluded: {
get: function() {
const intervals = this._intervals;
return intervals.length === 0 ? false : intervals[0].isStartIncluded;
}
},
stop: {
get: function() {
const intervals = this._intervals;
const length3 = intervals.length;
return length3 === 0 ? void 0 : intervals[length3 - 1].stop;
}
},
isStopIncluded: {
get: function() {
const intervals = this._intervals;
const length3 = intervals.length;
return length3 === 0 ? false : intervals[length3 - 1].isStopIncluded;
}
},
length: {
get: function() {
return this._intervals.length;
}
},
isEmpty: {
get: function() {
return this._intervals.length === 0;
}
}
});
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 length3 = intervals.length;
if (length3 !== rightIntervals.length) {
return false;
}
for (let i = 0; i < length3; i++) {
if (!TimeInterval_default.equals(intervals[i], rightIntervals[i], dataComparer)) {
return false;
}
}
return true;
};
TimeIntervalCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
return this._intervals[index];
};
TimeIntervalCollection.prototype.removeAll = function() {
if (this._intervals.length > 0) {
this._intervals.length = 0;
this._changedEvent.raiseEvent(this);
}
};
TimeIntervalCollection.prototype.findIntervalContainingDate = function(date) {
const index = this.indexOf(date);
return index >= 0 ? this._intervals[index] : void 0;
};
TimeIntervalCollection.prototype.findDataForIntervalContainingDate = function(date) {
const index = this.indexOf(date);
return index >= 0 ? this._intervals[index].data : void 0;
};
TimeIntervalCollection.prototype.contains = function(julianDate) {
return this.indexOf(julianDate) >= 0;
};
var indexOfScratch = new TimeInterval_default();
TimeIntervalCollection.prototype.indexOf = function(date) {
if (!defined_default(date)) {
throw new DeveloperError_default("date is required");
}
const intervals = this._intervals;
indexOfScratch.start = date;
indexOfScratch.stop = date;
let index = binarySearch_default(
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_default.contains(intervals[index - 1], date)) {
return index - 1;
}
return ~index;
};
TimeIntervalCollection.prototype.findInterval = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const start = options.start;
const stop2 = 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_default(start) || interval.start.equals(start)) && (!defined_default(stop2) || interval.stop.equals(stop2)) && (!defined_default(isStartIncluded) || interval.isStartIncluded === isStartIncluded) && (!defined_default(isStopIncluded) || interval.isStopIncluded === isStopIncluded)) {
return intervals[i];
}
}
return void 0;
};
TimeIntervalCollection.prototype.addInterval = function(interval, dataComparer) {
if (!defined_default(interval)) {
throw new DeveloperError_default("interval is required");
}
if (interval.isEmpty) {
return;
}
const intervals = this._intervals;
if (intervals.length === 0 || JulianDate_default.greaterThan(interval.start, intervals[intervals.length - 1].stop)) {
intervals.push(interval);
this._changedEvent.raiseEvent(this);
return;
}
let index = binarySearch_default(intervals, interval, compareIntervalStartTimes);
if (index < 0) {
index = ~index;
} else {
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) {
comparison = JulianDate_default.compare(intervals[index - 1].stop, interval.start);
if (comparison > 0 || comparison === 0 && (intervals[index - 1].isStopIncluded || interval.isStartIncluded)) {
if (defined_default(dataComparer) ? dataComparer(intervals[index - 1].data, interval.data) : intervals[index - 1].data === interval.data) {
if (JulianDate_default.greaterThan(interval.stop, intervals[index - 1].stop)) {
interval = new TimeInterval_default({
start: intervals[index - 1].start,
stop: interval.stop,
isStartIncluded: intervals[index - 1].isStartIncluded,
isStopIncluded: interval.isStopIncluded,
data: interval.data
});
} else {
interval = new TimeInterval_default({
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 {
comparison = JulianDate_default.compare(
intervals[index - 1].stop,
interval.stop
);
if (comparison > 0 || comparison === 0 && intervals[index - 1].isStopIncluded && !interval.isStopIncluded) {
intervals.splice(
index,
0,
new TimeInterval_default({
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_default({
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) {
comparison = JulianDate_default.compare(interval.stop, intervals[index].start);
if (comparison > 0 || comparison === 0 && (interval.isStopIncluded || intervals[index].isStartIncluded)) {
if (defined_default(dataComparer) ? dataComparer(intervals[index].data, interval.data) : intervals[index].data === interval.data) {
interval = new TimeInterval_default({
start: interval.start,
stop: JulianDate_default.greaterThan(intervals[index].stop, interval.stop) ? intervals[index].stop : interval.stop,
isStartIncluded: interval.isStartIncluded,
isStopIncluded: JulianDate_default.greaterThan(
intervals[index].stop,
interval.stop
) ? intervals[index].isStopIncluded : interval.isStopIncluded,
data: interval.data
});
intervals.splice(index, 1);
} else {
intervals[index] = new TimeInterval_default({
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 {
break;
}
}
} else {
break;
}
}
intervals.splice(index, 0, interval);
this._changedEvent.raiseEvent(this);
};
TimeIntervalCollection.prototype.removeInterval = function(interval) {
if (!defined_default(interval)) {
throw new DeveloperError_default("interval is required");
}
if (interval.isEmpty) {
return false;
}
const intervals = this._intervals;
let index = binarySearch_default(intervals, interval, compareIntervalStartTimes);
if (index < 0) {
index = ~index;
}
let result = false;
if (index > 0 && (JulianDate_default.greaterThan(intervals[index - 1].stop, interval.start) || intervals[index - 1].stop.equals(interval.start) && intervals[index - 1].isStopIncluded && interval.isStartIncluded)) {
result = true;
if (JulianDate_default.greaterThan(intervals[index - 1].stop, interval.stop) || intervals[index - 1].isStopIncluded && !interval.isStopIncluded && intervals[index - 1].stop.equals(interval.stop)) {
intervals.splice(
index,
0,
new TimeInterval_default({
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_default({
start: intervals[index - 1].start,
stop: interval.start,
isStartIncluded: intervals[index - 1].isStartIncluded,
isStopIncluded: !interval.isStartIncluded,
data: intervals[index - 1].data
});
}
if (index < intervals.length && !interval.isStartIncluded && intervals[index].isStartIncluded && interval.start.equals(intervals[index].start)) {
result = true;
intervals.splice(
index,
0,
new TimeInterval_default({
start: intervals[index].start,
stop: intervals[index].start,
isStartIncluded: true,
isStopIncluded: true,
data: intervals[index].data
})
);
++index;
}
while (index < intervals.length && JulianDate_default.greaterThan(interval.stop, intervals[index].stop)) {
result = true;
intervals.splice(index, 1);
}
if (index < intervals.length && interval.stop.equals(intervals[index].stop)) {
result = true;
if (!interval.isStopIncluded && intervals[index].isStopIncluded) {
if (index + 1 < intervals.length && intervals[index + 1].start.equals(interval.stop) && intervals[index].data === intervals[index + 1].data) {
intervals.splice(index, 1);
intervals[index] = new TimeInterval_default({
start: intervals[index].start,
stop: intervals[index].stop,
isStartIncluded: true,
isStopIncluded: intervals[index].isStopIncluded,
data: intervals[index].data
});
} else {
intervals[index] = new TimeInterval_default({
start: interval.stop,
stop: interval.stop,
isStartIncluded: true,
isStopIncluded: true,
data: intervals[index].data
});
}
} else {
intervals.splice(index, 1);
}
}
if (index < intervals.length && (JulianDate_default.greaterThan(interval.stop, intervals[index].start) || interval.stop.equals(intervals[index].start) && interval.isStopIncluded && intervals[index].isStartIncluded)) {
result = true;
intervals[index] = new TimeInterval_default({
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;
};
TimeIntervalCollection.prototype.intersect = function(other, dataComparer, mergeCallback) {
if (!defined_default(other)) {
throw new DeveloperError_default("other is required.");
}
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_default.lessThan(leftInterval.stop, rightInterval.start)) {
++left;
} else if (JulianDate_default.lessThan(rightInterval.stop, leftInterval.start)) {
++right;
} else {
if (defined_default(mergeCallback) || defined_default(dataComparer) && dataComparer(leftInterval.data, rightInterval.data) || !defined_default(dataComparer) && rightInterval.data === leftInterval.data) {
const intersection = TimeInterval_default.intersect(
leftInterval,
rightInterval,
new TimeInterval_default(),
mergeCallback
);
if (!intersection.isEmpty) {
result.addInterval(intersection, dataComparer);
}
}
if (JulianDate_default.lessThan(leftInterval.stop, rightInterval.stop) || leftInterval.stop.equals(rightInterval.stop) && !leftInterval.isStopIncluded && rightInterval.isStopIncluded) {
++left;
} else {
++right;
}
}
}
return result;
};
TimeIntervalCollection.fromJulianDateArray = function(options, result) {
if (!defined_default(options)) {
throw new DeveloperError_default("options is required.");
}
if (!defined_default(options.julianDates)) {
throw new DeveloperError_default("options.iso8601Array is required.");
}
if (!defined_default(result)) {
result = new TimeIntervalCollection();
}
const julianDates = options.julianDates;
const length3 = julianDates.length;
const dataCallback = options.dataCallback;
const isStartIncluded = defaultValue_default(options.isStartIncluded, true);
const isStopIncluded = defaultValue_default(options.isStopIncluded, true);
const leadingInterval = defaultValue_default(options.leadingInterval, false);
const trailingInterval = defaultValue_default(options.trailingInterval, false);
let interval;
let startIndex = 0;
if (leadingInterval) {
++startIndex;
interval = new TimeInterval_default({
start: Iso8601_default.MINIMUM_VALUE,
stop: julianDates[0],
isStartIncluded: true,
isStopIncluded: !isStartIncluded
});
interval.data = defined_default(dataCallback) ? dataCallback(interval, result.length) : result.length;
result.addInterval(interval);
}
for (let i = 0; i < length3 - 1; ++i) {
let startDate = julianDates[i];
const endDate = julianDates[i + 1];
interval = new TimeInterval_default({
start: startDate,
stop: endDate,
isStartIncluded: result.length === startIndex ? isStartIncluded : true,
isStopIncluded: i === length3 - 2 ? isStopIncluded : false
});
interval.data = defined_default(dataCallback) ? dataCallback(interval, result.length) : result.length;
result.addInterval(interval);
startDate = endDate;
}
if (trailingInterval) {
interval = new TimeInterval_default({
start: julianDates[length3 - 1],
stop: Iso8601_default.MAXIMUM_VALUE,
isStartIncluded: !isStopIncluded,
isStopIncluded: true
});
interval.data = defined_default(dataCallback) ? dataCallback(interval, result.length) : result.length;
result.addInterval(interval);
}
return result;
};
var scratchGregorianDate = new GregorianDate_default();
var monthLengths = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function addToDate(julianDate, duration, result) {
if (!defined_default(result)) {
result = new JulianDate_default();
}
JulianDate_default.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 >= 1e3) {
second += Math.floor(millisecond / 1e3);
millisecond = millisecond % 1e3;
}
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;
}
monthLengths[2] = isLeapYear_default(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_default(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_default.fromGregorianDate(scratchGregorianDate, result);
}
var scratchJulianDate2 = new JulianDate_default();
var durationRegex = /P(?:([\d.,]+)Y)?(?:([\d.,]+)M)?(?:([\d.,]+)W)?(?:([\d.,]+)D)?(?:T(?:([\d.,]+)H)?(?:([\d.,]+)M)?(?:([\d.,]+)S)?)?/;
function parseDuration(iso8601, result) {
if (!defined_default(iso8601) || iso8601.length === 0) {
return false;
}
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_default(matches)) {
return false;
}
if (defined_default(matches[1])) {
result.year = Number(matches[1].replace(",", "."));
}
if (defined_default(matches[2])) {
result.month = Number(matches[2].replace(",", "."));
}
if (defined_default(matches[3])) {
result.day = Number(matches[3].replace(",", ".")) * 7;
}
if (defined_default(matches[4])) {
result.day += Number(matches[4].replace(",", "."));
}
if (defined_default(matches[5])) {
result.hour = Number(matches[5].replace(",", "."));
}
if (defined_default(matches[6])) {
result.minute = Number(matches[6].replace(",", "."));
}
if (defined_default(matches[7])) {
const seconds = Number(matches[7].replace(",", "."));
result.second = Math.floor(seconds);
result.millisecond = seconds % 1 * 1e3;
}
} else {
if (iso8601[iso8601.length - 1] !== "Z") {
iso8601 += "Z";
}
JulianDate_default.toGregorianDate(
JulianDate_default.fromIso8601(iso8601, scratchJulianDate2),
result
);
}
return result.year || result.month || result.day || result.hour || result.minute || result.second || result.millisecond;
}
var scratchDuration = new GregorianDate_default();
TimeIntervalCollection.fromIso8601 = function(options, result) {
if (!defined_default(options)) {
throw new DeveloperError_default("options is required.");
}
if (!defined_default(options.iso8601)) {
throw new DeveloperError_default("options.iso8601 is required.");
}
const dates = options.iso8601.split("/");
const start = JulianDate_default.fromIso8601(dates[0]);
const stop2 = JulianDate_default.fromIso8601(dates[1]);
const julianDates = [];
if (!parseDuration(dates[2], scratchDuration)) {
julianDates.push(start, stop2);
} else {
let date = JulianDate_default.clone(start);
julianDates.push(date);
while (JulianDate_default.compare(date, stop2) < 0) {
date = addToDate(date, scratchDuration);
const afterStop = JulianDate_default.compare(stop2, date) <= 0;
if (afterStop) {
JulianDate_default.clone(stop2, date);
}
julianDates.push(date);
}
}
return TimeIntervalCollection.fromJulianDateArray(
{
julianDates,
isStartIncluded: options.isStartIncluded,
isStopIncluded: options.isStopIncluded,
leadingInterval: options.leadingInterval,
trailingInterval: options.trailingInterval,
dataCallback: options.dataCallback
},
result
);
};
TimeIntervalCollection.fromIso8601DateArray = function(options, result) {
if (!defined_default(options)) {
throw new DeveloperError_default("options is required.");
}
if (!defined_default(options.iso8601Dates)) {
throw new DeveloperError_default("options.iso8601Dates is required.");
}
return TimeIntervalCollection.fromJulianDateArray(
{
julianDates: options.iso8601Dates.map(function(date) {
return JulianDate_default.fromIso8601(date);
}),
isStartIncluded: options.isStartIncluded,
isStopIncluded: options.isStopIncluded,
leadingInterval: options.leadingInterval,
trailingInterval: options.trailingInterval,
dataCallback: options.dataCallback
},
result
);
};
TimeIntervalCollection.fromIso8601DurationArray = function(options, result) {
if (!defined_default(options)) {
throw new DeveloperError_default("options is required.");
}
if (!defined_default(options.epoch)) {
throw new DeveloperError_default("options.epoch is required.");
}
if (!defined_default(options.iso8601Durations)) {
throw new DeveloperError_default("options.iso8601Durations is required.");
}
const epoch2 = options.epoch;
const iso8601Durations = options.iso8601Durations;
const relativeToPrevious = defaultValue_default(options.relativeToPrevious, false);
const julianDates = [];
let date, previousDate;
const length3 = iso8601Durations.length;
for (let i = 0; i < length3; ++i) {
if (parseDuration(iso8601Durations[i], scratchDuration) || i === 0) {
if (relativeToPrevious && defined_default(previousDate)) {
date = addToDate(previousDate, scratchDuration);
} else {
date = addToDate(epoch2, scratchDuration);
}
julianDates.push(date);
previousDate = date;
}
}
return TimeIntervalCollection.fromJulianDateArray(
{
julianDates,
isStartIncluded: options.isStartIncluded,
isStopIncluded: options.isStopIncluded,
leadingInterval: options.leadingInterval,
trailingInterval: options.trailingInterval,
dataCallback: options.dataCallback
},
result
);
};
var TimeIntervalCollection_default = TimeIntervalCollection;
// node_modules/@cesium/engine/Source/DataSources/CompositeProperty.js
function subscribeAll(property, eventHelper, definitionChanged, intervals) {
function callback() {
definitionChanged.raiseEvent(property);
}
const items = [];
eventHelper.removeAll();
const length3 = intervals.length;
for (let i = 0; i < length3; i++) {
const interval = intervals.get(i);
if (defined_default(interval.data) && items.indexOf(interval.data) === -1) {
eventHelper.add(interval.data.definitionChanged, callback);
}
}
}
function CompositeProperty() {
this._eventHelper = new EventHelper_default();
this._definitionChanged = new Event_default();
this._intervals = new TimeIntervalCollection_default();
this._intervals.changedEvent.addEventListener(
CompositeProperty.prototype._intervalsChanged,
this
);
}
Object.defineProperties(CompositeProperty.prototype, {
isConstant: {
get: function() {
return this._intervals.isEmpty;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
intervals: {
get: function() {
return this._intervals;
}
}
});
CompositeProperty.prototype.getValue = function(time, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required");
}
const innerProperty = this._intervals.findDataForIntervalContainingDate(time);
if (defined_default(innerProperty)) {
return innerProperty.getValue(time, result);
}
return void 0;
};
CompositeProperty.prototype.equals = function(other) {
return this === other || other instanceof CompositeProperty && this._intervals.equals(other._intervals, Property_default.equals);
};
CompositeProperty.prototype._intervalsChanged = function() {
subscribeAll(
this,
this._eventHelper,
this._definitionChanged,
this._intervals
);
this._definitionChanged.raiseEvent(this);
};
var CompositeProperty_default = CompositeProperty;
// node_modules/@cesium/engine/Source/DataSources/CompositeMaterialProperty.js
function CompositeMaterialProperty() {
this._definitionChanged = new Event_default();
this._composite = new CompositeProperty_default();
this._composite.definitionChanged.addEventListener(
CompositeMaterialProperty.prototype._raiseDefinitionChanged,
this
);
}
Object.defineProperties(CompositeMaterialProperty.prototype, {
isConstant: {
get: function() {
return this._composite.isConstant;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
intervals: {
get: function() {
return this._composite._intervals;
}
}
});
CompositeMaterialProperty.prototype.getType = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required");
}
const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
time
);
if (defined_default(innerProperty)) {
return innerProperty.getType(time);
}
return void 0;
};
CompositeMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required");
}
const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
time
);
if (defined_default(innerProperty)) {
return innerProperty.getValue(time, result);
}
return void 0;
};
CompositeMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof CompositeMaterialProperty && this._composite.equals(other._composite, Property_default.equals);
};
CompositeMaterialProperty.prototype._raiseDefinitionChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var CompositeMaterialProperty_default = CompositeMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/CompositePositionProperty.js
function CompositePositionProperty(referenceFrame) {
this._referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
this._definitionChanged = new Event_default();
this._composite = new CompositeProperty_default();
this._composite.definitionChanged.addEventListener(
CompositePositionProperty.prototype._raiseDefinitionChanged,
this
);
}
Object.defineProperties(CompositePositionProperty.prototype, {
isConstant: {
get: function() {
return this._composite.isConstant;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
intervals: {
get: function() {
return this._composite.intervals;
}
},
referenceFrame: {
get: function() {
return this._referenceFrame;
},
set: function(value) {
this._referenceFrame = value;
}
}
});
CompositePositionProperty.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
CompositePositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!defined_default(referenceFrame)) {
throw new DeveloperError_default("referenceFrame is required.");
}
const innerProperty = this._composite._intervals.findDataForIntervalContainingDate(
time
);
if (defined_default(innerProperty)) {
return innerProperty.getValueInReferenceFrame(time, referenceFrame, result);
}
return void 0;
};
CompositePositionProperty.prototype.equals = function(other) {
return this === other || other instanceof CompositePositionProperty && this._referenceFrame === other._referenceFrame && this._composite.equals(other._composite, Property_default.equals);
};
CompositePositionProperty.prototype._raiseDefinitionChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var CompositePositionProperty_default = CompositePositionProperty;
// node_modules/@cesium/engine/Source/Core/CornerType.js
var CornerType = {
ROUNDED: 0,
MITERED: 1,
BEVELED: 2
};
var CornerType_default = Object.freeze(CornerType);
// node_modules/@cesium/engine/Source/Core/PolylineVolumeGeometryLibrary.js
var scratch2Array = [new Cartesian3_default(), new Cartesian3_default()];
var scratchCartesian13 = new Cartesian3_default();
var scratchCartesian25 = new Cartesian3_default();
var scratchCartesian36 = new Cartesian3_default();
var scratchCartesian43 = new Cartesian3_default();
var scratchCartesian52 = new Cartesian3_default();
var scratchCartesian62 = new Cartesian3_default();
var scratchCartesian72 = new Cartesian3_default();
var scratchCartesian82 = new Cartesian3_default();
var scratchCartesian92 = new Cartesian3_default();
var scratch1 = new Cartesian3_default();
var scratch2 = new Cartesian3_default();
var PolylineVolumeGeometryLibrary = {};
var cartographic = new Cartographic_default();
function scaleToSurface(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 subdivideHeights2(points, h0, h1, granularity) {
const p0 = points[0];
const p1 = points[1];
const angleBetween = Cartesian3_default.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;
}
var nextScratch = new Cartesian3_default();
var prevScratch = new Cartesian3_default();
function computeRotationAngle(start, end, position, ellipsoid) {
const tangentPlane = new EllipsoidTangentPlane_default(position, ellipsoid);
const next = tangentPlane.projectPointOntoPlane(
Cartesian3_default.add(position, start, nextScratch),
nextScratch
);
const prev = tangentPlane.projectPointOntoPlane(
Cartesian3_default.add(position, end, prevScratch),
prevScratch
);
const angle = Cartesian2_default.angleBetween(next, prev);
return prev.x * next.y - prev.y * next.x >= 0 ? -angle : angle;
}
var negativeX = new Cartesian3_default(-1, 0, 0);
var transform = new Matrix4_default();
var translation2 = new Matrix4_default();
var rotationZ = new Matrix3_default();
var scaleMatrix = Matrix3_default.IDENTITY.clone();
var westScratch = new Cartesian3_default();
var finalPosScratch = new Cartesian4_default();
var heightCartesian = new Cartesian3_default();
function addPosition(center, left, shape, finalPositions, ellipsoid, height, xScalar, repeat) {
let west = westScratch;
let finalPosition = finalPosScratch;
transform = Transforms_default.eastNorthUpToFixedFrame(center, ellipsoid, transform);
west = Matrix4_default.multiplyByPointAsVector(transform, negativeX, west);
west = Cartesian3_default.normalize(west, west);
const angle = computeRotationAngle(west, left, center, ellipsoid);
rotationZ = Matrix3_default.fromRotationZ(angle, rotationZ);
heightCartesian.z = height;
transform = Matrix4_default.multiplyTransformation(
transform,
Matrix4_default.fromRotationTranslation(rotationZ, heightCartesian, translation2),
transform
);
const scale = scaleMatrix;
scale[0] = xScalar;
for (let j = 0; j < repeat; j++) {
for (let i = 0; i < shape.length; i += 3) {
finalPosition = Cartesian3_default.fromArray(shape, i, finalPosition);
finalPosition = Matrix3_default.multiplyByVector(
scale,
finalPosition,
finalPosition
);
finalPosition = Matrix4_default.multiplyByPoint(
transform,
finalPosition,
finalPosition
);
finalPositions.push(finalPosition.x, finalPosition.y, finalPosition.z);
}
}
return finalPositions;
}
var centerScratch2 = new Cartesian3_default();
function addPositions(centers, left, shape, finalPositions, ellipsoid, heights, xScalar) {
for (let i = 0; i < centers.length; i += 3) {
const center = Cartesian3_default.fromArray(centers, i, centerScratch2);
finalPositions = addPosition(
center,
left,
shape,
finalPositions,
ellipsoid,
heights[i / 3],
xScalar,
1
);
}
return finalPositions;
}
function convertShapeTo3DDuplicate(shape2D, boundingRectangle) {
const length3 = shape2D.length;
const shape = new Array(length3 * 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;
shape[index++] = point.y - yOffset;
for (let i = 1; i < length3; i++) {
point = shape2D[i];
const x = point.x - xOffset;
const z = point.y - yOffset;
shape[index++] = x;
shape[index++] = 0;
shape[index++] = z;
shape[index++] = x;
shape[index++] = 0;
shape[index++] = z;
}
point = shape2D[0];
shape[index++] = point.x - xOffset;
shape[index++] = 0;
shape[index++] = point.y - yOffset;
return shape;
}
function convertShapeTo3D(shape2D, boundingRectangle) {
const length3 = shape2D.length;
const shape = new Array(length3 * 3);
let index = 0;
const xOffset = boundingRectangle.x + boundingRectangle.width / 2;
const yOffset = boundingRectangle.y + boundingRectangle.height / 2;
for (let i = 0; i < length3; i++) {
shape[index++] = shape2D[i].x - xOffset;
shape[index++] = 0;
shape[index++] = shape2D[i].y - yOffset;
}
return shape;
}
var quaterion = new Quaternion_default();
var startPointScratch = new Cartesian3_default();
var rotMatrix = new Matrix3_default();
function computeRoundCorner(pivot, startPoint, endPoint, cornerType, leftIsOutside, ellipsoid, finalPositions, shape, height, duplicatePoints) {
const angle = Cartesian3_default.angleBetween(
Cartesian3_default.subtract(startPoint, pivot, scratch1),
Cartesian3_default.subtract(endPoint, pivot, scratch2)
);
const granularity = cornerType === CornerType_default.BEVELED ? 0 : Math.ceil(angle / Math_default.toRadians(5));
let m;
if (leftIsOutside) {
m = Matrix3_default.fromQuaternion(
Quaternion_default.fromAxisAngle(
Cartesian3_default.negate(pivot, scratch1),
angle / (granularity + 1),
quaterion
),
rotMatrix
);
} else {
m = Matrix3_default.fromQuaternion(
Quaternion_default.fromAxisAngle(pivot, angle / (granularity + 1), quaterion),
rotMatrix
);
}
let left;
let surfacePoint;
startPoint = Cartesian3_default.clone(startPoint, startPointScratch);
if (granularity > 0) {
const repeat = duplicatePoints ? 2 : 1;
for (let i = 0; i < granularity; i++) {
startPoint = Matrix3_default.multiplyByVector(m, startPoint, startPoint);
left = Cartesian3_default.subtract(startPoint, pivot, scratch1);
left = Cartesian3_default.normalize(left, left);
if (!leftIsOutside) {
left = Cartesian3_default.negate(left, left);
}
surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2);
finalPositions = addPosition(
surfacePoint,
left,
shape,
finalPositions,
ellipsoid,
height,
1,
repeat
);
}
} else {
left = Cartesian3_default.subtract(startPoint, pivot, scratch1);
left = Cartesian3_default.normalize(left, left);
if (!leftIsOutside) {
left = Cartesian3_default.negate(left, left);
}
surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2);
finalPositions = addPosition(
surfacePoint,
left,
shape,
finalPositions,
ellipsoid,
height,
1,
1
);
endPoint = Cartesian3_default.clone(endPoint, startPointScratch);
left = Cartesian3_default.subtract(endPoint, pivot, scratch1);
left = Cartesian3_default.normalize(left, left);
if (!leftIsOutside) {
left = Cartesian3_default.negate(left, left);
}
surfacePoint = ellipsoid.scaleToGeodeticSurface(endPoint, scratch2);
finalPositions = addPosition(
surfacePoint,
left,
shape,
finalPositions,
ellipsoid,
height,
1,
1
);
}
return finalPositions;
}
PolylineVolumeGeometryLibrary.removeDuplicatesFromShape = function(shapePositions) {
const length3 = shapePositions.length;
const cleanedPositions = [];
for (let i0 = length3 - 1, i1 = 0; i1 < length3; i0 = i1++) {
const v02 = shapePositions[i0];
const v13 = shapePositions[i1];
if (!Cartesian2_default.equals(v02, v13)) {
cleanedPositions.push(v13);
}
}
return cleanedPositions;
};
PolylineVolumeGeometryLibrary.angleIsGreaterThanPi = function(forward, backward, position, ellipsoid) {
const tangentPlane = new EllipsoidTangentPlane_default(position, ellipsoid);
const next = tangentPlane.projectPointOntoPlane(
Cartesian3_default.add(position, forward, nextScratch),
nextScratch
);
const prev = tangentPlane.projectPointOntoPlane(
Cartesian3_default.add(position, backward, prevScratch),
prevScratch
);
return prev.x * next.y - prev.y * next.x >= 0;
};
var scratchForwardProjection = new Cartesian3_default();
var scratchBackwardProjection = new Cartesian3_default();
PolylineVolumeGeometryLibrary.computePositions = function(positions, shape2D, boundingRectangle, geometry, duplicatePoints) {
const ellipsoid = geometry._ellipsoid;
const heights = scaleToSurface(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) : void 0;
const heightOffset = boundingRectangle.height / 2;
const width = boundingRectangle.width / 2;
let length3 = positions.length;
let finalPositions = [];
let ends = duplicatePoints ? [] : void 0;
let forward = scratchCartesian13;
let backward = scratchCartesian25;
let cornerDirection = scratchCartesian36;
let surfaceNormal = scratchCartesian43;
let pivot = scratchCartesian52;
let start = scratchCartesian62;
let end = scratchCartesian72;
let left = scratchCartesian82;
let previousPosition = scratchCartesian92;
let position = positions[0];
let nextPosition = positions[1];
surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);
forward = Cartesian3_default.subtract(nextPosition, position, forward);
forward = Cartesian3_default.normalize(forward, forward);
left = Cartesian3_default.cross(surfaceNormal, forward, left);
left = Cartesian3_default.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_default.clone(position, previousPosition);
position = nextPosition;
backward = Cartesian3_default.negate(forward, backward);
let subdividedHeights;
let subdividedPositions;
for (let i = 1; i < length3 - 1; i++) {
const repeat = duplicatePoints ? 2 : 1;
nextPosition = positions[i + 1];
if (position.equals(nextPosition)) {
oneTimeWarning_default(
"Positions are too close and are considered equivalent with rounding error."
);
continue;
}
forward = Cartesian3_default.subtract(nextPosition, position, forward);
forward = Cartesian3_default.normalize(forward, forward);
cornerDirection = Cartesian3_default.add(forward, backward, cornerDirection);
cornerDirection = Cartesian3_default.normalize(cornerDirection, cornerDirection);
surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);
const forwardProjection = Cartesian3_default.multiplyByScalar(
surfaceNormal,
Cartesian3_default.dot(forward, surfaceNormal),
scratchForwardProjection
);
Cartesian3_default.subtract(forward, forwardProjection, forwardProjection);
Cartesian3_default.normalize(forwardProjection, forwardProjection);
const backwardProjection = Cartesian3_default.multiplyByScalar(
surfaceNormal,
Cartesian3_default.dot(backward, surfaceNormal),
scratchBackwardProjection
);
Cartesian3_default.subtract(backward, backwardProjection, backwardProjection);
Cartesian3_default.normalize(backwardProjection, backwardProjection);
const doCorner = !Math_default.equalsEpsilon(
Math.abs(Cartesian3_default.dot(forwardProjection, backwardProjection)),
1,
Math_default.EPSILON7
);
if (doCorner) {
cornerDirection = Cartesian3_default.cross(
cornerDirection,
surfaceNormal,
cornerDirection
);
cornerDirection = Cartesian3_default.cross(
surfaceNormal,
cornerDirection,
cornerDirection
);
cornerDirection = Cartesian3_default.normalize(cornerDirection, cornerDirection);
const scalar = 1 / Math.max(
0.25,
Cartesian3_default.magnitude(
Cartesian3_default.cross(cornerDirection, backward, scratch1)
)
);
const leftIsOutside = PolylineVolumeGeometryLibrary.angleIsGreaterThanPi(
forward,
backward,
position,
ellipsoid
);
if (leftIsOutside) {
pivot = Cartesian3_default.add(
position,
Cartesian3_default.multiplyByScalar(
cornerDirection,
scalar * width,
cornerDirection
),
pivot
);
start = Cartesian3_default.add(
pivot,
Cartesian3_default.multiplyByScalar(left, width, start),
start
);
scratch2Array[0] = Cartesian3_default.clone(previousPosition, scratch2Array[0]);
scratch2Array[1] = Cartesian3_default.clone(start, scratch2Array[1]);
subdividedHeights = subdivideHeights2(
scratch2Array,
h0 + heightOffset,
h1 + heightOffset,
granularity
);
subdividedPositions = PolylinePipeline_default.generateArc({
positions: scratch2Array,
granularity,
ellipsoid
});
finalPositions = addPositions(
subdividedPositions,
left,
shapeForSides,
finalPositions,
ellipsoid,
subdividedHeights,
1
);
left = Cartesian3_default.cross(surfaceNormal, forward, left);
left = Cartesian3_default.normalize(left, left);
end = Cartesian3_default.add(
pivot,
Cartesian3_default.multiplyByScalar(left, width, end),
end
);
if (cornerType === CornerType_default.ROUNDED || cornerType === CornerType_default.BEVELED) {
computeRoundCorner(
pivot,
start,
end,
cornerType,
leftIsOutside,
ellipsoid,
finalPositions,
shapeForSides,
h1 + heightOffset,
duplicatePoints
);
} else {
cornerDirection = Cartesian3_default.negate(cornerDirection, cornerDirection);
finalPositions = addPosition(
position,
cornerDirection,
shapeForSides,
finalPositions,
ellipsoid,
h1 + heightOffset,
scalar,
repeat
);
}
previousPosition = Cartesian3_default.clone(end, previousPosition);
} else {
pivot = Cartesian3_default.add(
position,
Cartesian3_default.multiplyByScalar(
cornerDirection,
scalar * width,
cornerDirection
),
pivot
);
start = Cartesian3_default.add(
pivot,
Cartesian3_default.multiplyByScalar(left, -width, start),
start
);
scratch2Array[0] = Cartesian3_default.clone(previousPosition, scratch2Array[0]);
scratch2Array[1] = Cartesian3_default.clone(start, scratch2Array[1]);
subdividedHeights = subdivideHeights2(
scratch2Array,
h0 + heightOffset,
h1 + heightOffset,
granularity
);
subdividedPositions = PolylinePipeline_default.generateArc({
positions: scratch2Array,
granularity,
ellipsoid
});
finalPositions = addPositions(
subdividedPositions,
left,
shapeForSides,
finalPositions,
ellipsoid,
subdividedHeights,
1
);
left = Cartesian3_default.cross(surfaceNormal, forward, left);
left = Cartesian3_default.normalize(left, left);
end = Cartesian3_default.add(
pivot,
Cartesian3_default.multiplyByScalar(left, -width, end),
end
);
if (cornerType === CornerType_default.ROUNDED || cornerType === CornerType_default.BEVELED) {
computeRoundCorner(
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_default.clone(end, previousPosition);
}
backward = Cartesian3_default.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_default.clone(previousPosition, scratch2Array[0]);
scratch2Array[1] = Cartesian3_default.clone(position, scratch2Array[1]);
subdividedHeights = subdivideHeights2(
scratch2Array,
h0 + heightOffset,
h1 + heightOffset,
granularity
);
subdividedPositions = PolylinePipeline_default.generateArc({
positions: scratch2Array,
granularity,
ellipsoid
});
finalPositions = addPositions(
subdividedPositions,
left,
shapeForSides,
finalPositions,
ellipsoid,
subdividedHeights,
1
);
if (duplicatePoints) {
ends = addPosition(
position,
left,
shapeForEnds,
ends,
ellipsoid,
h1 + heightOffset,
1,
1
);
}
length3 = finalPositions.length;
const posLength = duplicatePoints ? length3 + ends.length : length3;
const combinedPositions = new Float64Array(posLength);
combinedPositions.set(finalPositions);
if (duplicatePoints) {
combinedPositions.set(ends, length3);
}
return combinedPositions;
};
var PolylineVolumeGeometryLibrary_default = PolylineVolumeGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/CorridorGeometryLibrary.js
var CorridorGeometryLibrary = {};
var scratch12 = new Cartesian3_default();
var scratch22 = new Cartesian3_default();
var scratch3 = new Cartesian3_default();
var scratch4 = new Cartesian3_default();
var scaleArray2 = [new Cartesian3_default(), new Cartesian3_default()];
var cartesian1 = new Cartesian3_default();
var cartesian2 = new Cartesian3_default();
var cartesian3 = new Cartesian3_default();
var cartesian4 = new Cartesian3_default();
var cartesian5 = new Cartesian3_default();
var cartesian6 = new Cartesian3_default();
var cartesian7 = new Cartesian3_default();
var cartesian8 = new Cartesian3_default();
var cartesian9 = new Cartesian3_default();
var cartesian10 = new Cartesian3_default();
var quaterion2 = new Quaternion_default();
var rotMatrix2 = new Matrix3_default();
function computeRoundCorner2(cornerPoint, startPoint, endPoint, cornerType, leftIsOutside) {
const angle = Cartesian3_default.angleBetween(
Cartesian3_default.subtract(startPoint, cornerPoint, scratch12),
Cartesian3_default.subtract(endPoint, cornerPoint, scratch22)
);
const granularity = cornerType === CornerType_default.BEVELED ? 1 : Math.ceil(angle / Math_default.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_default.fromQuaternion(
Quaternion_default.fromAxisAngle(
Cartesian3_default.negate(cornerPoint, scratch12),
angle / granularity,
quaterion2
),
rotMatrix2
);
} else {
m = Matrix3_default.fromQuaternion(
Quaternion_default.fromAxisAngle(cornerPoint, angle / granularity, quaterion2),
rotMatrix2
);
}
let index = 0;
startPoint = Cartesian3_default.clone(startPoint, scratch12);
for (let i = 0; i < granularity; i++) {
startPoint = Matrix3_default.multiplyByVector(m, startPoint, startPoint);
array[index++] = startPoint.x;
array[index++] = startPoint.y;
array[index++] = startPoint.z;
}
return array;
}
function addEndCaps(calculatedPositions) {
let cornerPoint = cartesian1;
let startPoint = cartesian2;
let endPoint = cartesian3;
let leftEdge = calculatedPositions[1];
startPoint = Cartesian3_default.fromArray(
calculatedPositions[1],
leftEdge.length - 3,
startPoint
);
endPoint = Cartesian3_default.fromArray(calculatedPositions[0], 0, endPoint);
cornerPoint = Cartesian3_default.midpoint(startPoint, endPoint, cornerPoint);
const firstEndCap = computeRoundCorner2(
cornerPoint,
startPoint,
endPoint,
CornerType_default.ROUNDED,
false
);
const length3 = calculatedPositions.length - 1;
const rightEdge = calculatedPositions[length3 - 1];
leftEdge = calculatedPositions[length3];
startPoint = Cartesian3_default.fromArray(
rightEdge,
rightEdge.length - 3,
startPoint
);
endPoint = Cartesian3_default.fromArray(leftEdge, 0, endPoint);
cornerPoint = Cartesian3_default.midpoint(startPoint, endPoint, cornerPoint);
const lastEndCap = computeRoundCorner2(
cornerPoint,
startPoint,
endPoint,
CornerType_default.ROUNDED,
false
);
return [firstEndCap, lastEndCap];
}
function computeMiteredCorner(position, leftCornerDirection, lastPoint, leftIsOutside) {
let cornerPoint = scratch12;
if (leftIsOutside) {
cornerPoint = Cartesian3_default.add(position, leftCornerDirection, cornerPoint);
} else {
leftCornerDirection = Cartesian3_default.negate(
leftCornerDirection,
leftCornerDirection
);
cornerPoint = Cartesian3_default.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_default.multiplyByScalar(left, scalar, scratch12);
const scaledRight = Cartesian3_default.negate(scaledLeft, scratch22);
let rightIndex = 0;
let leftIndex = positions.length - 1;
for (let i = 0; i < positions.length; i += 3) {
const pos = Cartesian3_default.fromArray(positions, i, scratch3);
const rightPos = Cartesian3_default.add(pos, scaledRight, scratch4);
rightPositions[rightIndex++] = rightPos.x;
rightPositions[rightIndex++] = rightPos.y;
rightPositions[rightIndex++] = rightPos.z;
const leftPos = Cartesian3_default.add(pos, scaledLeft, scratch4);
leftPositions[leftIndex--] = leftPos.z;
leftPositions[leftIndex--] = leftPos.y;
leftPositions[leftIndex--] = leftPos.x;
}
calculatedPositions.push(rightPositions, leftPositions);
return calculatedPositions;
}
CorridorGeometryLibrary.addAttribute = function(attribute, value, front, back) {
const x = value.x;
const y = value.y;
const z = value.z;
if (defined_default(front)) {
attribute[front] = x;
attribute[front + 1] = y;
attribute[front + 2] = z;
}
if (defined_default(back)) {
attribute[back] = z;
attribute[back - 1] = y;
attribute[back - 2] = x;
}
};
var scratchForwardProjection2 = new Cartesian3_default();
var scratchBackwardProjection2 = new Cartesian3_default();
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 normal2 = cartesian1;
let forward = cartesian2;
let backward = cartesian3;
let left = cartesian4;
let cornerDirection = cartesian5;
let startPoint = cartesian6;
let previousPos = cartesian7;
let rightPos = cartesian8;
let leftPos = cartesian9;
let center = cartesian10;
let calculatedPositions = [];
const calculatedLefts = saveAttributes ? [] : void 0;
const calculatedNormals = saveAttributes ? [] : void 0;
let position = positions[0];
let nextPosition = positions[1];
forward = Cartesian3_default.normalize(
Cartesian3_default.subtract(nextPosition, position, forward),
forward
);
normal2 = ellipsoid.geodeticSurfaceNormal(position, normal2);
left = Cartesian3_default.normalize(Cartesian3_default.cross(normal2, forward, left), left);
if (saveAttributes) {
calculatedLefts.push(left.x, left.y, left.z);
calculatedNormals.push(normal2.x, normal2.y, normal2.z);
}
previousPos = Cartesian3_default.clone(position, previousPos);
position = nextPosition;
backward = Cartesian3_default.negate(forward, backward);
let subdividedPositions;
const corners2 = [];
let i;
const length3 = positions.length;
for (i = 1; i < length3 - 1; i++) {
normal2 = ellipsoid.geodeticSurfaceNormal(position, normal2);
nextPosition = positions[i + 1];
forward = Cartesian3_default.normalize(
Cartesian3_default.subtract(nextPosition, position, forward),
forward
);
cornerDirection = Cartesian3_default.normalize(
Cartesian3_default.add(forward, backward, cornerDirection),
cornerDirection
);
const forwardProjection = Cartesian3_default.multiplyByScalar(
normal2,
Cartesian3_default.dot(forward, normal2),
scratchForwardProjection2
);
Cartesian3_default.subtract(forward, forwardProjection, forwardProjection);
Cartesian3_default.normalize(forwardProjection, forwardProjection);
const backwardProjection = Cartesian3_default.multiplyByScalar(
normal2,
Cartesian3_default.dot(backward, normal2),
scratchBackwardProjection2
);
Cartesian3_default.subtract(backward, backwardProjection, backwardProjection);
Cartesian3_default.normalize(backwardProjection, backwardProjection);
const doCorner = !Math_default.equalsEpsilon(
Math.abs(Cartesian3_default.dot(forwardProjection, backwardProjection)),
1,
Math_default.EPSILON7
);
if (doCorner) {
cornerDirection = Cartesian3_default.cross(
cornerDirection,
normal2,
cornerDirection
);
cornerDirection = Cartesian3_default.cross(
normal2,
cornerDirection,
cornerDirection
);
cornerDirection = Cartesian3_default.normalize(cornerDirection, cornerDirection);
const scalar = width / Math.max(
0.25,
Cartesian3_default.magnitude(
Cartesian3_default.cross(cornerDirection, backward, scratch12)
)
);
const leftIsOutside = PolylineVolumeGeometryLibrary_default.angleIsGreaterThanPi(
forward,
backward,
position,
ellipsoid
);
cornerDirection = Cartesian3_default.multiplyByScalar(
cornerDirection,
scalar,
cornerDirection
);
if (leftIsOutside) {
rightPos = Cartesian3_default.add(position, cornerDirection, rightPos);
center = Cartesian3_default.add(
rightPos,
Cartesian3_default.multiplyByScalar(left, width, center),
center
);
leftPos = Cartesian3_default.add(
rightPos,
Cartesian3_default.multiplyByScalar(left, width * 2, leftPos),
leftPos
);
scaleArray2[0] = Cartesian3_default.clone(previousPos, scaleArray2[0]);
scaleArray2[1] = Cartesian3_default.clone(center, scaleArray2[1]);
subdividedPositions = PolylinePipeline_default.generateArc({
positions: scaleArray2,
granularity,
ellipsoid
});
calculatedPositions = addShiftedPositions(
subdividedPositions,
left,
width,
calculatedPositions
);
if (saveAttributes) {
calculatedLefts.push(left.x, left.y, left.z);
calculatedNormals.push(normal2.x, normal2.y, normal2.z);
}
startPoint = Cartesian3_default.clone(leftPos, startPoint);
left = Cartesian3_default.normalize(
Cartesian3_default.cross(normal2, forward, left),
left
);
leftPos = Cartesian3_default.add(
rightPos,
Cartesian3_default.multiplyByScalar(left, width * 2, leftPos),
leftPos
);
previousPos = Cartesian3_default.add(
rightPos,
Cartesian3_default.multiplyByScalar(left, width, previousPos),
previousPos
);
if (cornerType === CornerType_default.ROUNDED || cornerType === CornerType_default.BEVELED) {
corners2.push({
leftPositions: computeRoundCorner2(
rightPos,
startPoint,
leftPos,
cornerType,
leftIsOutside
)
});
} else {
corners2.push({
leftPositions: computeMiteredCorner(
position,
Cartesian3_default.negate(cornerDirection, cornerDirection),
leftPos,
leftIsOutside
)
});
}
} else {
leftPos = Cartesian3_default.add(position, cornerDirection, leftPos);
center = Cartesian3_default.add(
leftPos,
Cartesian3_default.negate(
Cartesian3_default.multiplyByScalar(left, width, center),
center
),
center
);
rightPos = Cartesian3_default.add(
leftPos,
Cartesian3_default.negate(
Cartesian3_default.multiplyByScalar(left, width * 2, rightPos),
rightPos
),
rightPos
);
scaleArray2[0] = Cartesian3_default.clone(previousPos, scaleArray2[0]);
scaleArray2[1] = Cartesian3_default.clone(center, scaleArray2[1]);
subdividedPositions = PolylinePipeline_default.generateArc({
positions: scaleArray2,
granularity,
ellipsoid
});
calculatedPositions = addShiftedPositions(
subdividedPositions,
left,
width,
calculatedPositions
);
if (saveAttributes) {
calculatedLefts.push(left.x, left.y, left.z);
calculatedNormals.push(normal2.x, normal2.y, normal2.z);
}
startPoint = Cartesian3_default.clone(rightPos, startPoint);
left = Cartesian3_default.normalize(
Cartesian3_default.cross(normal2, forward, left),
left
);
rightPos = Cartesian3_default.add(
leftPos,
Cartesian3_default.negate(
Cartesian3_default.multiplyByScalar(left, width * 2, rightPos),
rightPos
),
rightPos
);
previousPos = Cartesian3_default.add(
leftPos,
Cartesian3_default.negate(
Cartesian3_default.multiplyByScalar(left, width, previousPos),
previousPos
),
previousPos
);
if (cornerType === CornerType_default.ROUNDED || cornerType === CornerType_default.BEVELED) {
corners2.push({
rightPositions: computeRoundCorner2(
leftPos,
startPoint,
rightPos,
cornerType,
leftIsOutside
)
});
} else {
corners2.push({
rightPositions: computeMiteredCorner(
position,
cornerDirection,
rightPos,
leftIsOutside
)
});
}
}
backward = Cartesian3_default.negate(forward, backward);
}
position = nextPosition;
}
normal2 = ellipsoid.geodeticSurfaceNormal(position, normal2);
scaleArray2[0] = Cartesian3_default.clone(previousPos, scaleArray2[0]);
scaleArray2[1] = Cartesian3_default.clone(position, scaleArray2[1]);
subdividedPositions = PolylinePipeline_default.generateArc({
positions: scaleArray2,
granularity,
ellipsoid
});
calculatedPositions = addShiftedPositions(
subdividedPositions,
left,
width,
calculatedPositions
);
if (saveAttributes) {
calculatedLefts.push(left.x, left.y, left.z);
calculatedNormals.push(normal2.x, normal2.y, normal2.z);
}
let endPositions;
if (cornerType === CornerType_default.ROUNDED) {
endPositions = addEndCaps(calculatedPositions);
}
return {
positions: calculatedPositions,
corners: corners2,
lefts: calculatedLefts,
normals: calculatedNormals,
endPositions
};
};
var CorridorGeometryLibrary_default = CorridorGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/CorridorGeometry.js
var cartesian12 = new Cartesian3_default();
var cartesian22 = new Cartesian3_default();
var cartesian32 = new Cartesian3_default();
var cartesian42 = new Cartesian3_default();
var cartesian52 = new Cartesian3_default();
var cartesian62 = new Cartesian3_default();
var scratch13 = new Cartesian3_default();
var scratch23 = new Cartesian3_default();
function scaleToSurface2(positions, ellipsoid) {
for (let i = 0; i < positions.length; i++) {
positions[i] = ellipsoid.scaleToGeodeticSurface(positions[i], positions[i]);
}
return positions;
}
function addNormals(attr, normal2, left, front, back, vertexFormat) {
const normals = attr.normals;
const tangents = attr.tangents;
const bitangents = attr.bitangents;
const forward = Cartesian3_default.normalize(
Cartesian3_default.cross(left, normal2, scratch13),
scratch13
);
if (vertexFormat.normal) {
CorridorGeometryLibrary_default.addAttribute(normals, normal2, front, back);
}
if (vertexFormat.tangent) {
CorridorGeometryLibrary_default.addAttribute(tangents, forward, front, back);
}
if (vertexFormat.bitangent) {
CorridorGeometryLibrary_default.addAttribute(bitangents, left, front, back);
}
}
function combine2(computedPositions, vertexFormat, ellipsoid) {
const positions = computedPositions.positions;
const corners2 = computedPositions.corners;
const endPositions = computedPositions.endPositions;
const computedLefts = computedPositions.lefts;
const computedNormals = computedPositions.normals;
const attributes = new GeometryAttributes_default();
let corner;
let leftCount = 0;
let rightCount = 0;
let i;
let indicesLength = 0;
let length3;
for (i = 0; i < positions.length; i += 2) {
length3 = positions[i].length - 3;
leftCount += length3;
indicesLength += length3 * 2;
rightCount += positions[i + 1].length - 3;
}
leftCount += 3;
rightCount += 3;
for (i = 0; i < corners2.length; i++) {
corner = corners2[i];
const leftSide = corners2[i].leftPositions;
if (defined_default(leftSide)) {
length3 = leftSide.length;
leftCount += length3;
indicesLength += length3;
} else {
length3 = corners2[i].rightPositions.length;
rightCount += length3;
indicesLength += length3;
}
}
const addEndPositions = defined_default(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) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(size) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(size) : void 0;
const attr = {
normals,
tangents,
bitangents
};
let front = 0;
let back = size - 1;
let UL, LL, UR, LR;
let normal2 = cartesian12;
let left = cartesian22;
let rightPos, leftPos;
const halfLength = endPositionLength / 2;
const indices2 = IndexDatatype_default.createTypedArray(size / 3, indicesLength);
let index = 0;
if (addEndPositions) {
leftPos = cartesian32;
rightPos = cartesian42;
const firstEndPositions = endPositions[0];
normal2 = Cartesian3_default.fromArray(computedNormals, 0, normal2);
left = Cartesian3_default.fromArray(computedLefts, 0, left);
for (i = 0; i < halfLength; i++) {
leftPos = Cartesian3_default.fromArray(
firstEndPositions,
(halfLength - 1 - i) * 3,
leftPos
);
rightPos = Cartesian3_default.fromArray(
firstEndPositions,
(halfLength + i) * 3,
rightPos
);
CorridorGeometryLibrary_default.addAttribute(finalPositions, rightPos, front);
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
leftPos,
void 0,
back
);
addNormals(attr, normal2, left, front, back, vertexFormat);
LL = front / 3;
LR = LL + 1;
UL = (back - 2) / 3;
UR = UL - 1;
indices2[index++] = UL;
indices2[index++] = LL;
indices2[index++] = UR;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
}
let posIndex = 0;
let compIndex = 0;
let rightEdge = positions[posIndex++];
let leftEdge = positions[posIndex++];
finalPositions.set(rightEdge, front);
finalPositions.set(leftEdge, back - leftEdge.length + 1);
left = Cartesian3_default.fromArray(computedLefts, compIndex, left);
let rightNormal;
let leftNormal;
length3 = leftEdge.length - 3;
for (i = 0; i < length3; i += 3) {
rightNormal = ellipsoid.geodeticSurfaceNormal(
Cartesian3_default.fromArray(rightEdge, i, scratch13),
scratch13
);
leftNormal = ellipsoid.geodeticSurfaceNormal(
Cartesian3_default.fromArray(leftEdge, length3 - i, scratch23),
scratch23
);
normal2 = Cartesian3_default.normalize(
Cartesian3_default.add(rightNormal, leftNormal, normal2),
normal2
);
addNormals(attr, normal2, left, front, back, vertexFormat);
LL = front / 3;
LR = LL + 1;
UL = (back - 2) / 3;
UR = UL - 1;
indices2[index++] = UL;
indices2[index++] = LL;
indices2[index++] = UR;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
rightNormal = ellipsoid.geodeticSurfaceNormal(
Cartesian3_default.fromArray(rightEdge, length3, scratch13),
scratch13
);
leftNormal = ellipsoid.geodeticSurfaceNormal(
Cartesian3_default.fromArray(leftEdge, length3, scratch23),
scratch23
);
normal2 = Cartesian3_default.normalize(
Cartesian3_default.add(rightNormal, leftNormal, normal2),
normal2
);
compIndex += 3;
for (i = 0; i < corners2.length; i++) {
let j;
corner = corners2[i];
const l = corner.leftPositions;
const r = corner.rightPositions;
let pivot;
let start;
let outsidePoint = cartesian62;
let previousPoint = cartesian32;
let nextPoint = cartesian42;
normal2 = Cartesian3_default.fromArray(computedNormals, compIndex, normal2);
if (defined_default(l)) {
addNormals(attr, normal2, left, void 0, back, vertexFormat);
back -= 3;
pivot = LR;
start = UR;
for (j = 0; j < l.length / 3; j++) {
outsidePoint = Cartesian3_default.fromArray(l, j * 3, outsidePoint);
indices2[index++] = pivot;
indices2[index++] = start - j - 1;
indices2[index++] = start - j;
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
outsidePoint,
void 0,
back
);
previousPoint = Cartesian3_default.fromArray(
finalPositions,
(start - j - 1) * 3,
previousPoint
);
nextPoint = Cartesian3_default.fromArray(finalPositions, pivot * 3, nextPoint);
left = Cartesian3_default.normalize(
Cartesian3_default.subtract(previousPoint, nextPoint, left),
left
);
addNormals(attr, normal2, left, void 0, back, vertexFormat);
back -= 3;
}
outsidePoint = Cartesian3_default.fromArray(
finalPositions,
pivot * 3,
outsidePoint
);
previousPoint = Cartesian3_default.subtract(
Cartesian3_default.fromArray(finalPositions, start * 3, previousPoint),
outsidePoint,
previousPoint
);
nextPoint = Cartesian3_default.subtract(
Cartesian3_default.fromArray(finalPositions, (start - j) * 3, nextPoint),
outsidePoint,
nextPoint
);
left = Cartesian3_default.normalize(
Cartesian3_default.add(previousPoint, nextPoint, left),
left
);
addNormals(attr, normal2, left, front, void 0, vertexFormat);
front += 3;
} else {
addNormals(attr, normal2, left, front, void 0, vertexFormat);
front += 3;
pivot = UR;
start = LR;
for (j = 0; j < r.length / 3; j++) {
outsidePoint = Cartesian3_default.fromArray(r, j * 3, outsidePoint);
indices2[index++] = pivot;
indices2[index++] = start + j;
indices2[index++] = start + j + 1;
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
outsidePoint,
front
);
previousPoint = Cartesian3_default.fromArray(
finalPositions,
pivot * 3,
previousPoint
);
nextPoint = Cartesian3_default.fromArray(
finalPositions,
(start + j) * 3,
nextPoint
);
left = Cartesian3_default.normalize(
Cartesian3_default.subtract(previousPoint, nextPoint, left),
left
);
addNormals(attr, normal2, left, front, void 0, vertexFormat);
front += 3;
}
outsidePoint = Cartesian3_default.fromArray(
finalPositions,
pivot * 3,
outsidePoint
);
previousPoint = Cartesian3_default.subtract(
Cartesian3_default.fromArray(finalPositions, (start + j) * 3, previousPoint),
outsidePoint,
previousPoint
);
nextPoint = Cartesian3_default.subtract(
Cartesian3_default.fromArray(finalPositions, start * 3, nextPoint),
outsidePoint,
nextPoint
);
left = Cartesian3_default.normalize(
Cartesian3_default.negate(Cartesian3_default.add(nextPoint, previousPoint, left), left),
left
);
addNormals(attr, normal2, left, void 0, back, vertexFormat);
back -= 3;
}
rightEdge = positions[posIndex++];
leftEdge = positions[posIndex++];
rightEdge.splice(0, 3);
leftEdge.splice(leftEdge.length - 3, 3);
finalPositions.set(rightEdge, front);
finalPositions.set(leftEdge, back - leftEdge.length + 1);
length3 = leftEdge.length - 3;
compIndex += 3;
left = Cartesian3_default.fromArray(computedLefts, compIndex, left);
for (j = 0; j < leftEdge.length; j += 3) {
rightNormal = ellipsoid.geodeticSurfaceNormal(
Cartesian3_default.fromArray(rightEdge, j, scratch13),
scratch13
);
leftNormal = ellipsoid.geodeticSurfaceNormal(
Cartesian3_default.fromArray(leftEdge, length3 - j, scratch23),
scratch23
);
normal2 = Cartesian3_default.normalize(
Cartesian3_default.add(rightNormal, leftNormal, normal2),
normal2
);
addNormals(attr, normal2, left, front, back, vertexFormat);
LR = front / 3;
LL = LR - 1;
UR = (back - 2) / 3;
UL = UR + 1;
indices2[index++] = UL;
indices2[index++] = LL;
indices2[index++] = UR;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
front -= 3;
back += 3;
}
normal2 = Cartesian3_default.fromArray(
computedNormals,
computedNormals.length - 3,
normal2
);
addNormals(attr, normal2, left, front, back, vertexFormat);
if (addEndPositions) {
front += 3;
back -= 3;
leftPos = cartesian32;
rightPos = cartesian42;
const lastEndPositions = endPositions[1];
for (i = 0; i < halfLength; i++) {
leftPos = Cartesian3_default.fromArray(
lastEndPositions,
(endPositionLength - i - 1) * 3,
leftPos
);
rightPos = Cartesian3_default.fromArray(lastEndPositions, i * 3, rightPos);
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
leftPos,
void 0,
back
);
CorridorGeometryLibrary_default.addAttribute(finalPositions, rightPos, front);
addNormals(attr, normal2, left, front, back, vertexFormat);
LR = front / 3;
LL = LR - 1;
UR = (back - 2) / 3;
UL = UR + 1;
indices2[index++] = UL;
indices2[index++] = LL;
indices2[index++] = UR;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
}
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.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 a3;
const halfEndPos = endPositionLength / 2;
for (i = halfEndPos + 1; i < endPositionLength + 1; i++) {
a3 = Math_default.PI_OVER_TWO + theta * i;
st[stIndex++] = rightSt * (1 + Math.cos(a3));
st[stIndex++] = 0.5 * (1 + Math.sin(a3));
}
for (i = 1; i < rightCount - endPositionLength + 1; i++) {
st[stIndex++] = i * rightSt;
st[stIndex++] = 0;
}
for (i = endPositionLength; i > halfEndPos; i--) {
a3 = Math_default.PI_OVER_TWO - i * theta;
st[stIndex++] = 1 - rightSt * (1 + Math.cos(a3));
st[stIndex++] = 0.5 * (1 + Math.sin(a3));
}
for (i = halfEndPos; i > 0; i--) {
a3 = Math_default.PI_OVER_TWO - theta * i;
st[stIndex++] = 1 - leftSt * (1 + Math.cos(a3));
st[stIndex++] = 0.5 * (1 + Math.sin(a3));
}
for (i = leftCount - endPositionLength; i > 0; i--) {
st[stIndex++] = i * leftSt;
st[stIndex++] = 1;
}
for (i = 1; i < halfEndPos + 1; i++) {
a3 = Math_default.PI_OVER_TWO + theta * i;
st[stIndex++] = leftSt * (1 + Math.cos(a3));
st[stIndex++] = 0.5 * (1 + Math.sin(a3));
}
} else {
leftCount /= 3;
rightCount /= 3;
leftSt = 1 / (leftCount - 1);
rightSt = 1 / (rightCount - 1);
for (i = 0; i < rightCount; i++) {
st[stIndex++] = i * rightSt;
st[stIndex++] = 0;
}
for (i = leftCount; i > 0; i--) {
st[stIndex++] = (i - 1) * leftSt;
st[stIndex++] = 1;
}
}
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: st
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: attr.normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: attr.tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: attr.bitangents
});
}
return {
attributes,
indices: indices2
};
}
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) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(threeSize * 6) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(threeSize * 6) : void 0;
let topPosition = cartesian12;
let bottomPosition = cartesian22;
let previousPosition = cartesian32;
let normal2 = cartesian42;
let tangent = cartesian52;
let bitangent = cartesian62;
let attrIndex = sixSize;
for (i = 0; i < threeSize; i += 3) {
const attrIndexOffset = attrIndex + sixSize;
topPosition = Cartesian3_default.fromArray(positions, i, topPosition);
bottomPosition = Cartesian3_default.fromArray(
positions,
i + threeSize,
bottomPosition
);
previousPosition = Cartesian3_default.fromArray(
positions,
(i + 3) % threeSize,
previousPosition
);
bottomPosition = Cartesian3_default.subtract(
bottomPosition,
topPosition,
bottomPosition
);
previousPosition = Cartesian3_default.subtract(
previousPosition,
topPosition,
previousPosition
);
normal2 = Cartesian3_default.normalize(
Cartesian3_default.cross(bottomPosition, previousPosition, normal2),
normal2
);
if (vertexFormat.normal) {
CorridorGeometryLibrary_default.addAttribute(normals, normal2, attrIndexOffset);
CorridorGeometryLibrary_default.addAttribute(
normals,
normal2,
attrIndexOffset + 3
);
CorridorGeometryLibrary_default.addAttribute(normals, normal2, attrIndex);
CorridorGeometryLibrary_default.addAttribute(normals, normal2, attrIndex + 3);
}
if (vertexFormat.tangent || vertexFormat.bitangent) {
bitangent = Cartesian3_default.fromArray(topNormals, i, bitangent);
if (vertexFormat.bitangent) {
CorridorGeometryLibrary_default.addAttribute(
bitangents,
bitangent,
attrIndexOffset
);
CorridorGeometryLibrary_default.addAttribute(
bitangents,
bitangent,
attrIndexOffset + 3
);
CorridorGeometryLibrary_default.addAttribute(
bitangents,
bitangent,
attrIndex
);
CorridorGeometryLibrary_default.addAttribute(
bitangents,
bitangent,
attrIndex + 3
);
}
if (vertexFormat.tangent) {
tangent = Cartesian3_default.normalize(
Cartesian3_default.cross(bitangent, normal2, tangent),
tangent
);
CorridorGeometryLibrary_default.addAttribute(
tangents,
tangent,
attrIndexOffset
);
CorridorGeometryLibrary_default.addAttribute(
tangents,
tangent,
attrIndexOffset + 3
);
CorridorGeometryLibrary_default.addAttribute(tangents, tangent, attrIndex);
CorridorGeometryLibrary_default.addAttribute(
tangents,
tangent,
attrIndex + 3
);
}
}
attrIndex += 6;
}
if (vertexFormat.normal) {
normals.set(topNormals);
for (i = 0; i < threeSize; i += 3) {
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 = void 0;
}
if (vertexFormat.bitangent) {
bitangents.set(topBitangents);
bitangents.set(topBitangents, threeSize);
attributes.bitangent.values = bitangents;
} else {
attributes.bitangent = void 0;
}
if (vertexFormat.tangent) {
const topTangents = attributes.tangent.values;
tangents.set(topTangents);
tangents.set(topTangents, threeSize);
attributes.tangent.values = tangents;
}
}
if (vertexFormat.st) {
const topSt = attributes.st.values;
const st = new Float32Array(twoSize * 6);
st.set(topSt);
st.set(topSt, twoSize);
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(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(params, vertexFormat) {
const topVertexFormat = new VertexFormat_default({
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_default.computePositions(params);
const attr = combine2(computedPositions, topVertexFormat, ellipsoid);
const height = params.height;
const extrudedHeight = params.extrudedHeight;
let attributes = attr.attributes;
const indices2 = attr.indices;
let positions = attributes.position.values;
let length3 = positions.length;
const newPositions = new Float64Array(length3 * 6);
let extrudedPositions = new Float64Array(length3);
extrudedPositions.set(positions);
let wallPositions = new Float64Array(length3 * 4);
positions = PolygonPipeline_default.scaleToGeodeticHeight(
positions,
height,
ellipsoid
);
wallPositions = addWallPositions(positions, 0, wallPositions);
extrudedPositions = PolygonPipeline_default.scaleToGeodeticHeight(
extrudedPositions,
extrudedHeight,
ellipsoid
);
wallPositions = addWallPositions(
extrudedPositions,
length3 * 2,
wallPositions
);
newPositions.set(positions);
newPositions.set(extrudedPositions, length3);
newPositions.set(wallPositions, length3 * 2);
attributes.position.values = newPositions;
attributes = extrudedAttributes(attributes, vertexFormat);
let i;
const size = length3 / 3;
if (params.shadowVolume) {
const topNormals = attributes.normal.values;
length3 = topNormals.length;
let extrudeNormals = new Float32Array(length3 * 6);
for (i = 0; i < length3; i++) {
topNormals[i] = -topNormals[i];
}
extrudeNormals.set(topNormals, length3);
extrudeNormals = addWallPositions(topNormals, length3 * 4, extrudeNormals);
attributes.extrudeDirection = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: extrudeNormals
});
if (!vertexFormat.normal) {
attributes.normal = void 0;
}
}
if (defined_default(params.offsetAttribute)) {
let applyOffset = new Uint8Array(size * 6);
if (params.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
applyOffset = applyOffset.fill(1, 0, size).fill(1, size * 2, size * 4);
} else {
const applyOffsetValue = params.offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
applyOffset = applyOffset.fill(applyOffsetValue);
}
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
const iLength = indices2.length;
const twoSize = size + size;
const newIndices = IndexDatatype_default.createTypedArray(
newPositions.length / 3,
iLength * 2 + twoSize * 3
);
newIndices.set(indices2);
let index = iLength;
for (i = 0; i < iLength; i += 3) {
const v02 = indices2[i];
const v13 = indices2[i + 1];
const v23 = indices2[i + 2];
newIndices[index++] = v23 + size;
newIndices[index++] = v13 + size;
newIndices[index++] = v02 + size;
}
let UL, LL, UR, LR;
for (i = 0; i < twoSize; i += 2) {
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,
indices: newIndices
};
}
var scratchCartesian14 = new Cartesian3_default();
var scratchCartesian26 = new Cartesian3_default();
var scratchCartographic8 = new Cartographic_default();
function computeOffsetPoints(position1, position2, ellipsoid, halfWidth, min3, max3) {
const direction2 = Cartesian3_default.subtract(
position2,
position1,
scratchCartesian14
);
Cartesian3_default.normalize(direction2, direction2);
const normal2 = ellipsoid.geodeticSurfaceNormal(position1, scratchCartesian26);
const offsetDirection = Cartesian3_default.cross(
direction2,
normal2,
scratchCartesian14
);
Cartesian3_default.multiplyByScalar(offsetDirection, halfWidth, offsetDirection);
let minLat = min3.latitude;
let minLon = min3.longitude;
let maxLat = max3.latitude;
let maxLon = max3.longitude;
Cartesian3_default.add(position1, offsetDirection, scratchCartesian26);
ellipsoid.cartesianToCartographic(scratchCartesian26, scratchCartographic8);
let lat = scratchCartographic8.latitude;
let lon = scratchCartographic8.longitude;
minLat = Math.min(minLat, lat);
minLon = Math.min(minLon, lon);
maxLat = Math.max(maxLat, lat);
maxLon = Math.max(maxLon, lon);
Cartesian3_default.subtract(position1, offsetDirection, scratchCartesian26);
ellipsoid.cartesianToCartographic(scratchCartesian26, scratchCartographic8);
lat = scratchCartographic8.latitude;
lon = scratchCartographic8.longitude;
minLat = Math.min(minLat, lat);
minLon = Math.min(minLon, lon);
maxLat = Math.max(maxLat, lat);
maxLon = Math.max(maxLon, lon);
min3.latitude = minLat;
min3.longitude = minLon;
max3.latitude = maxLat;
max3.longitude = maxLon;
}
var scratchCartesianOffset = new Cartesian3_default();
var scratchCartesianEnds = new Cartesian3_default();
var scratchCartographicMin = new Cartographic_default();
var scratchCartographicMax = new Cartographic_default();
function computeRectangle(positions, ellipsoid, width, cornerType, result) {
positions = scaleToSurface2(positions, ellipsoid);
const cleanPositions = arrayRemoveDuplicates_default(
positions,
Cartesian3_default.equalsEpsilon
);
const length3 = cleanPositions.length;
if (length3 < 2 || width <= 0) {
return new Rectangle_default();
}
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_default.ROUNDED) {
const first = cleanPositions[0];
Cartesian3_default.subtract(first, cleanPositions[1], scratchCartesianOffset);
Cartesian3_default.normalize(scratchCartesianOffset, scratchCartesianOffset);
Cartesian3_default.multiplyByScalar(
scratchCartesianOffset,
halfWidth,
scratchCartesianOffset
);
Cartesian3_default.add(first, scratchCartesianOffset, scratchCartesianEnds);
ellipsoid.cartesianToCartographic(
scratchCartesianEnds,
scratchCartographic8
);
lat = scratchCartographic8.latitude;
lon = scratchCartographic8.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
);
}
for (let i = 0; i < length3 - 1; ++i) {
computeOffsetPoints(
cleanPositions[i],
cleanPositions[i + 1],
ellipsoid,
halfWidth,
scratchCartographicMin,
scratchCartographicMax
);
}
const last = cleanPositions[length3 - 1];
Cartesian3_default.subtract(last, cleanPositions[length3 - 2], scratchCartesianOffset);
Cartesian3_default.normalize(scratchCartesianOffset, scratchCartesianOffset);
Cartesian3_default.multiplyByScalar(
scratchCartesianOffset,
halfWidth,
scratchCartesianOffset
);
Cartesian3_default.add(last, scratchCartesianOffset, scratchCartesianEnds);
computeOffsetPoints(
last,
scratchCartesianEnds,
ellipsoid,
halfWidth,
scratchCartographicMin,
scratchCartographicMax
);
if (cornerType === CornerType_default.ROUNDED) {
ellipsoid.cartesianToCartographic(
scratchCartesianEnds,
scratchCartographic8
);
lat = scratchCartographic8.latitude;
lon = scratchCartographic8.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_default(result) ? result : new Rectangle_default();
rectangle.north = scratchCartographicMax.latitude;
rectangle.south = scratchCartographicMin.latitude;
rectangle.east = scratchCartographicMax.longitude;
rectangle.west = scratchCartographicMin.longitude;
return rectangle;
}
function CorridorGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.positions;
const width = options.width;
Check_default.defined("options.positions", positions);
Check_default.defined("options.width", width);
const height = defaultValue_default(options.height, 0);
const extrudedHeight = defaultValue_default(options.extrudedHeight, height);
this._positions = positions;
this._ellipsoid = Ellipsoid_default.clone(
defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
);
this._vertexFormat = VertexFormat_default.clone(
defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT)
);
this._width = width;
this._height = Math.max(height, extrudedHeight);
this._extrudedHeight = Math.min(height, extrudedHeight);
this._cornerType = defaultValue_default(options.cornerType, CornerType_default.ROUNDED);
this._granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
this._shadowVolume = defaultValue_default(options.shadowVolume, false);
this._workerName = "createCorridorGeometry";
this._offsetAttribute = options.offsetAttribute;
this._rectangle = void 0;
this.packedLength = 1 + positions.length * Cartesian3_default.packedLength + Ellipsoid_default.packedLength + VertexFormat_default.packedLength + 7;
}
CorridorGeometry.pack = function(value, array, startingIndex) {
Check_default.defined("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const positions = value._positions;
const length3 = positions.length;
array[startingIndex++] = length3;
for (let i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
Cartesian3_default.pack(positions[i], array, startingIndex);
}
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.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;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchEllipsoid2 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchVertexFormat2 = new VertexFormat_default();
var scratchOptions7 = {
positions: void 0,
ellipsoid: scratchEllipsoid2,
vertexFormat: scratchVertexFormat2,
width: void 0,
height: void 0,
extrudedHeight: void 0,
cornerType: void 0,
granularity: void 0,
shadowVolume: void 0,
offsetAttribute: void 0
};
CorridorGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const length3 = array[startingIndex++];
const positions = new Array(length3);
for (let i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
positions[i] = Cartesian3_default.unpack(array, startingIndex);
}
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid2);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat2
);
startingIndex += VertexFormat_default.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;
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions7.positions = positions;
scratchOptions7.width = width;
scratchOptions7.height = height;
scratchOptions7.extrudedHeight = extrudedHeight;
scratchOptions7.cornerType = cornerType;
scratchOptions7.granularity = granularity;
scratchOptions7.shadowVolume = shadowVolume;
scratchOptions7.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new CorridorGeometry(scratchOptions7);
}
result._positions = positions;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.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 ? void 0 : offsetAttribute;
return result;
};
CorridorGeometry.computeRectangle = function(options, result) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.positions;
const width = options.width;
Check_default.defined("options.positions", positions);
Check_default.defined("options.width", width);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const cornerType = defaultValue_default(options.cornerType, CornerType_default.ROUNDED);
return computeRectangle(positions, ellipsoid, width, cornerType, result);
};
CorridorGeometry.createGeometry = function(corridorGeometry) {
let positions = corridorGeometry._positions;
const width = corridorGeometry._width;
const ellipsoid = corridorGeometry._ellipsoid;
positions = scaleToSurface2(positions, ellipsoid);
const cleanPositions = arrayRemoveDuplicates_default(
positions,
Cartesian3_default.equalsEpsilon
);
if (cleanPositions.length < 2 || width <= 0) {
return;
}
const height = corridorGeometry._height;
const extrudedHeight = corridorGeometry._extrudedHeight;
const extrude = !Math_default.equalsEpsilon(
height,
extrudedHeight,
0,
Math_default.EPSILON2
);
const vertexFormat = corridorGeometry._vertexFormat;
const params = {
ellipsoid,
positions: cleanPositions,
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(params, vertexFormat);
} else {
const computedPositions = CorridorGeometryLibrary_default.computePositions(params);
attr = combine2(computedPositions, vertexFormat, ellipsoid);
attr.attributes.position.values = PolygonPipeline_default.scaleToGeodeticHeight(
attr.attributes.position.values,
height,
ellipsoid
);
if (defined_default(corridorGeometry._offsetAttribute)) {
const applyOffsetValue = corridorGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const length3 = attr.attributes.position.values.length;
const applyOffset = new Uint8Array(length3 / 3).fill(applyOffsetValue);
attr.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
}
const attributes = attr.attributes;
const boundingSphere = BoundingSphere_default.fromVertices(
attributes.position.values,
void 0,
3
);
if (!vertexFormat.position) {
attr.attributes.position.values = void 0;
}
return new Geometry_default({
attributes,
indices: attr.indices,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere,
offsetAttribute: corridorGeometry._offsetAttribute
});
};
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,
granularity,
extrudedHeight: minHeight,
height: maxHeight,
vertexFormat: VertexFormat_default.POSITION_ONLY,
shadowVolume: true
});
};
Object.defineProperties(CorridorGeometry.prototype, {
rectangle: {
get: function() {
if (!defined_default(this._rectangle)) {
this._rectangle = computeRectangle(
this._positions,
this._ellipsoid,
this._width,
this._cornerType
);
}
return this._rectangle;
}
},
textureCoordinateRotationPoints: {
get: function() {
return [0, 0, 0, 1, 1, 0];
}
}
});
var CorridorGeometry_default = CorridorGeometry;
// node_modules/@cesium/engine/Source/Core/CorridorOutlineGeometry.js
var cartesian13 = new Cartesian3_default();
var cartesian23 = new Cartesian3_default();
var cartesian33 = new Cartesian3_default();
function scaleToSurface3(positions, ellipsoid) {
for (let i = 0; i < positions.length; i++) {
positions[i] = ellipsoid.scaleToGeodeticSurface(positions[i], positions[i]);
}
return positions;
}
function combine3(computedPositions, cornerType) {
const wallIndices = [];
const positions = computedPositions.positions;
const corners2 = computedPositions.corners;
const endPositions = computedPositions.endPositions;
const attributes = new GeometryAttributes_default();
let corner;
let leftCount = 0;
let rightCount = 0;
let i;
let indicesLength = 0;
let length3;
for (i = 0; i < positions.length; i += 2) {
length3 = positions[i].length - 3;
leftCount += length3;
indicesLength += length3 / 3 * 4;
rightCount += positions[i + 1].length - 3;
}
leftCount += 3;
rightCount += 3;
for (i = 0; i < corners2.length; i++) {
corner = corners2[i];
const leftSide = corners2[i].leftPositions;
if (defined_default(leftSide)) {
length3 = leftSide.length;
leftCount += length3;
indicesLength += length3 / 3 * 2;
} else {
length3 = corners2[i].rightPositions.length;
rightCount += length3;
indicesLength += length3 / 3 * 2;
}
}
const addEndPositions = defined_default(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 indices2 = IndexDatatype_default.createTypedArray(size / 3, indicesLength + 4);
let index = 0;
indices2[index++] = front / 3;
indices2[index++] = (back - 2) / 3;
if (addEndPositions) {
wallIndices.push(front / 3);
leftPos = cartesian13;
rightPos = cartesian23;
const firstEndPositions = endPositions[0];
for (i = 0; i < halfLength; i++) {
leftPos = Cartesian3_default.fromArray(
firstEndPositions,
(halfLength - 1 - i) * 3,
leftPos
);
rightPos = Cartesian3_default.fromArray(
firstEndPositions,
(halfLength + i) * 3,
rightPos
);
CorridorGeometryLibrary_default.addAttribute(finalPositions, rightPos, front);
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
leftPos,
void 0,
back
);
LL = front / 3;
LR = LL + 1;
UL = (back - 2) / 3;
UR = UL - 1;
indices2[index++] = UL;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
}
let posIndex = 0;
let rightEdge = positions[posIndex++];
let leftEdge = positions[posIndex++];
finalPositions.set(rightEdge, front);
finalPositions.set(leftEdge, back - leftEdge.length + 1);
length3 = leftEdge.length - 3;
wallIndices.push(front / 3, (back - 2) / 3);
for (i = 0; i < length3; i += 3) {
LL = front / 3;
LR = LL + 1;
UL = (back - 2) / 3;
UR = UL - 1;
indices2[index++] = UL;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
for (i = 0; i < corners2.length; i++) {
let j;
corner = corners2[i];
const l = corner.leftPositions;
const r = corner.rightPositions;
let start;
let outsidePoint = cartesian33;
if (defined_default(l)) {
back -= 3;
start = UR;
wallIndices.push(LR);
for (j = 0; j < l.length / 3; j++) {
outsidePoint = Cartesian3_default.fromArray(l, j * 3, outsidePoint);
indices2[index++] = start - j - 1;
indices2[index++] = start - j;
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
outsidePoint,
void 0,
back
);
back -= 3;
}
wallIndices.push(start - Math.floor(l.length / 6));
if (cornerType === CornerType_default.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_default.fromArray(r, j * 3, outsidePoint);
indices2[index++] = start + j;
indices2[index++] = start + j + 1;
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
outsidePoint,
front
);
front += 3;
}
wallIndices.push(start + Math.floor(r.length / 6));
if (cornerType === CornerType_default.BEVELED) {
wallIndices.push(front / 3 - 1);
}
back -= 3;
}
rightEdge = positions[posIndex++];
leftEdge = positions[posIndex++];
rightEdge.splice(0, 3);
leftEdge.splice(leftEdge.length - 3, 3);
finalPositions.set(rightEdge, front);
finalPositions.set(leftEdge, back - leftEdge.length + 1);
length3 = leftEdge.length - 3;
for (j = 0; j < leftEdge.length; j += 3) {
LR = front / 3;
LL = LR - 1;
UR = (back - 2) / 3;
UL = UR + 1;
indices2[index++] = UL;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
front -= 3;
back += 3;
wallIndices.push(front / 3, (back - 2) / 3);
}
if (addEndPositions) {
front += 3;
back -= 3;
leftPos = cartesian13;
rightPos = cartesian23;
const lastEndPositions = endPositions[1];
for (i = 0; i < halfLength; i++) {
leftPos = Cartesian3_default.fromArray(
lastEndPositions,
(endPositionLength - i - 1) * 3,
leftPos
);
rightPos = Cartesian3_default.fromArray(lastEndPositions, i * 3, rightPos);
CorridorGeometryLibrary_default.addAttribute(
finalPositions,
leftPos,
void 0,
back
);
CorridorGeometryLibrary_default.addAttribute(finalPositions, rightPos, front);
LR = front / 3;
LL = LR - 1;
UR = (back - 2) / 3;
UL = UR + 1;
indices2[index++] = UL;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
front += 3;
back -= 3;
}
wallIndices.push(front / 3);
} else {
wallIndices.push(front / 3, (back - 2) / 3);
}
indices2[index++] = front / 3;
indices2[index++] = (back - 2) / 3;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: finalPositions
});
return {
attributes,
indices: indices2,
wallIndices
};
}
function computePositionsExtruded2(params) {
const ellipsoid = params.ellipsoid;
const computedPositions = CorridorGeometryLibrary_default.computePositions(params);
const attr = combine3(computedPositions, params.cornerType);
const wallIndices = attr.wallIndices;
const height = params.height;
const extrudedHeight = params.extrudedHeight;
const attributes = attr.attributes;
const indices2 = attr.indices;
let positions = attributes.position.values;
let length3 = positions.length;
let extrudedPositions = new Float64Array(length3);
extrudedPositions.set(positions);
const newPositions = new Float64Array(length3 * 2);
positions = PolygonPipeline_default.scaleToGeodeticHeight(
positions,
height,
ellipsoid
);
extrudedPositions = PolygonPipeline_default.scaleToGeodeticHeight(
extrudedPositions,
extrudedHeight,
ellipsoid
);
newPositions.set(positions);
newPositions.set(extrudedPositions, length3);
attributes.position.values = newPositions;
length3 /= 3;
if (defined_default(params.offsetAttribute)) {
let applyOffset = new Uint8Array(length3 * 2);
if (params.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
applyOffset = applyOffset.fill(1, 0, length3);
} else {
const applyOffsetValue = params.offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
applyOffset = applyOffset.fill(applyOffsetValue);
}
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
let i;
const iLength = indices2.length;
const newIndices = IndexDatatype_default.createTypedArray(
newPositions.length / 3,
(iLength + wallIndices.length) * 2
);
newIndices.set(indices2);
let index = iLength;
for (i = 0; i < iLength; i += 2) {
const v02 = indices2[i];
const v13 = indices2[i + 1];
newIndices[index++] = v02 + length3;
newIndices[index++] = v13 + length3;
}
let UL, LL;
for (i = 0; i < wallIndices.length; i++) {
UL = wallIndices[i];
LL = UL + length3;
newIndices[index++] = UL;
newIndices[index++] = LL;
}
return {
attributes,
indices: newIndices
};
}
function CorridorOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.positions;
const width = options.width;
Check_default.typeOf.object("options.positions", positions);
Check_default.typeOf.number("options.width", width);
const height = defaultValue_default(options.height, 0);
const extrudedHeight = defaultValue_default(options.extrudedHeight, height);
this._positions = positions;
this._ellipsoid = Ellipsoid_default.clone(
defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
);
this._width = width;
this._height = Math.max(height, extrudedHeight);
this._extrudedHeight = Math.min(height, extrudedHeight);
this._cornerType = defaultValue_default(options.cornerType, CornerType_default.ROUNDED);
this._granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createCorridorOutlineGeometry";
this.packedLength = 1 + positions.length * Cartesian3_default.packedLength + Ellipsoid_default.packedLength + 6;
}
CorridorOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.typeOf.object("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const positions = value._positions;
const length3 = positions.length;
array[startingIndex++] = length3;
for (let i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
Cartesian3_default.pack(positions[i], array, startingIndex);
}
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
array[startingIndex++] = value._width;
array[startingIndex++] = value._height;
array[startingIndex++] = value._extrudedHeight;
array[startingIndex++] = value._cornerType;
array[startingIndex++] = value._granularity;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchEllipsoid3 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchOptions8 = {
positions: void 0,
ellipsoid: scratchEllipsoid3,
width: void 0,
height: void 0,
extrudedHeight: void 0,
cornerType: void 0,
granularity: void 0,
offsetAttribute: void 0
};
CorridorOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.typeOf.object("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const length3 = array[startingIndex++];
const positions = new Array(length3);
for (let i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
positions[i] = Cartesian3_default.unpack(array, startingIndex);
}
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid3);
startingIndex += Ellipsoid_default.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_default(result)) {
scratchOptions8.positions = positions;
scratchOptions8.width = width;
scratchOptions8.height = height;
scratchOptions8.extrudedHeight = extrudedHeight;
scratchOptions8.cornerType = cornerType;
scratchOptions8.granularity = granularity;
scratchOptions8.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new CorridorOutlineGeometry(scratchOptions8);
}
result._positions = positions;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._width = width;
result._height = height;
result._extrudedHeight = extrudedHeight;
result._cornerType = cornerType;
result._granularity = granularity;
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
CorridorOutlineGeometry.createGeometry = function(corridorOutlineGeometry) {
let positions = corridorOutlineGeometry._positions;
const width = corridorOutlineGeometry._width;
const ellipsoid = corridorOutlineGeometry._ellipsoid;
positions = scaleToSurface3(positions, ellipsoid);
const cleanPositions = arrayRemoveDuplicates_default(
positions,
Cartesian3_default.equalsEpsilon
);
if (cleanPositions.length < 2 || width <= 0) {
return;
}
const height = corridorOutlineGeometry._height;
const extrudedHeight = corridorOutlineGeometry._extrudedHeight;
const extrude = !Math_default.equalsEpsilon(
height,
extrudedHeight,
0,
Math_default.EPSILON2
);
const params = {
ellipsoid,
positions: cleanPositions,
width,
cornerType: corridorOutlineGeometry._cornerType,
granularity: corridorOutlineGeometry._granularity,
saveAttributes: false
};
let attr;
if (extrude) {
params.height = height;
params.extrudedHeight = extrudedHeight;
params.offsetAttribute = corridorOutlineGeometry._offsetAttribute;
attr = computePositionsExtruded2(params);
} else {
const computedPositions = CorridorGeometryLibrary_default.computePositions(params);
attr = combine3(computedPositions, params.cornerType);
attr.attributes.position.values = PolygonPipeline_default.scaleToGeodeticHeight(
attr.attributes.position.values,
height,
ellipsoid
);
if (defined_default(corridorOutlineGeometry._offsetAttribute)) {
const length3 = attr.attributes.position.values.length;
const offsetValue = corridorOutlineGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attr.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
}
const attributes = attr.attributes;
const boundingSphere = BoundingSphere_default.fromVertices(
attributes.position.values,
void 0,
3
);
return new Geometry_default({
attributes,
indices: attr.indices,
primitiveType: PrimitiveType_default.LINES,
boundingSphere,
offsetAttribute: corridorOutlineGeometry._offsetAttribute
});
};
var CorridorOutlineGeometry_default = CorridorOutlineGeometry;
// node_modules/@cesium/engine/Source/DataSources/GroundGeometryUpdater.js
var defaultZIndex = new ConstantProperty_default(0);
function GroundGeometryUpdater(options) {
GeometryUpdater_default.call(this, options);
this._zIndex = 0;
this._terrainOffsetProperty = void 0;
}
if (defined_default(Object.create)) {
GroundGeometryUpdater.prototype = Object.create(GeometryUpdater_default.prototype);
GroundGeometryUpdater.prototype.constructor = GroundGeometryUpdater;
}
Object.defineProperties(GroundGeometryUpdater.prototype, {
zIndex: {
get: function() {
return this._zIndex;
}
},
terrainOffsetProperty: {
get: function() {
return this._terrainOffsetProperty;
}
}
});
GroundGeometryUpdater.prototype._isOnTerrain = function(entity, geometry) {
return this._fillEnabled && !defined_default(geometry.height) && !defined_default(geometry.extrudedHeight) && GroundPrimitive_default.isSupported(this._scene);
};
GroundGeometryUpdater.prototype._getIsClosed = function(options) {
const height = options.height;
const extrudedHeight = options.extrudedHeight;
return height === 0 || defined_default(extrudedHeight) && extrudedHeight !== height;
};
GroundGeometryUpdater.prototype._computeCenter = DeveloperError_default.throwInstantiationError;
GroundGeometryUpdater.prototype._onEntityPropertyChanged = function(entity, propertyName, newValue, oldValue2) {
GeometryUpdater_default.prototype._onEntityPropertyChanged.call(
this,
entity,
propertyName,
newValue,
oldValue2
);
if (this._observedPropertyNames.indexOf(propertyName) === -1) {
return;
}
const geometry = this._entity[this._geometryPropertyName];
if (!defined_default(geometry)) {
return;
}
if (defined_default(geometry.zIndex) && (defined_default(geometry.height) || defined_default(geometry.extrudedHeight))) {
oneTimeWarning_default(oneTimeWarning_default.geometryZIndex);
}
this._zIndex = defaultValue_default(geometry.zIndex, defaultZIndex);
if (defined_default(this._terrainOffsetProperty)) {
this._terrainOffsetProperty.destroy();
this._terrainOffsetProperty = void 0;
}
const heightReferenceProperty = geometry.heightReference;
const extrudedHeightReferenceProperty = geometry.extrudedHeightReference;
if (defined_default(heightReferenceProperty) || defined_default(extrudedHeightReferenceProperty)) {
const centerPosition = new CallbackProperty_default(
this._computeCenter.bind(this),
!this._dynamic
);
this._terrainOffsetProperty = new TerrainOffsetProperty_default(
this._scene,
centerPosition,
heightReferenceProperty,
extrudedHeightReferenceProperty
);
}
};
GroundGeometryUpdater.prototype.destroy = function() {
if (defined_default(this._terrainOffsetProperty)) {
this._terrainOffsetProperty.destroy();
this._terrainOffsetProperty = void 0;
}
GeometryUpdater_default.prototype.destroy.call(this);
};
GroundGeometryUpdater.getGeometryHeight = function(height, heightReference) {
Check_default.defined("heightReference", heightReference);
if (!defined_default(height)) {
if (heightReference !== HeightReference_default.NONE) {
oneTimeWarning_default(oneTimeWarning_default.geometryHeightReference);
}
return;
}
if (heightReference !== HeightReference_default.CLAMP_TO_GROUND) {
return height;
}
return 0;
};
GroundGeometryUpdater.getGeometryExtrudedHeight = function(extrudedHeight, extrudedHeightReference) {
Check_default.defined("extrudedHeightReference", extrudedHeightReference);
if (!defined_default(extrudedHeight)) {
if (extrudedHeightReference !== HeightReference_default.NONE) {
oneTimeWarning_default(oneTimeWarning_default.geometryExtrudedHeightReference);
}
return;
}
if (extrudedHeightReference !== HeightReference_default.CLAMP_TO_GROUND) {
return extrudedHeight;
}
return GroundGeometryUpdater.CLAMP_TO_GROUND;
};
GroundGeometryUpdater.CLAMP_TO_GROUND = "clamp";
GroundGeometryUpdater.computeGeometryOffsetAttribute = function(height, heightReference, extrudedHeight, extrudedHeightReference) {
if (!defined_default(height) || !defined_default(heightReference)) {
heightReference = HeightReference_default.NONE;
}
if (!defined_default(extrudedHeight) || !defined_default(extrudedHeightReference)) {
extrudedHeightReference = HeightReference_default.NONE;
}
let n = 0;
if (heightReference !== HeightReference_default.NONE) {
n++;
}
if (extrudedHeightReference === HeightReference_default.RELATIVE_TO_GROUND) {
n++;
}
if (n === 2) {
return GeometryOffsetAttribute_default.ALL;
}
if (n === 1) {
return GeometryOffsetAttribute_default.TOP;
}
return void 0;
};
var GroundGeometryUpdater_default = GroundGeometryUpdater;
// node_modules/@cesium/engine/Source/DataSources/CorridorGeometryUpdater.js
var scratchColor11 = new Color_default();
var defaultOffset2 = Cartesian3_default.ZERO;
var offsetScratch5 = new Cartesian3_default();
var scratchRectangle4 = new Rectangle_default();
function CorridorGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.positions = void 0;
this.width = void 0;
this.cornerType = void 0;
this.height = void 0;
this.extrudedHeight = void 0;
this.granularity = void 0;
this.offsetAttribute = void 0;
}
function CorridorGeometryUpdater(entity, scene) {
GroundGeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new CorridorGeometryOptions(entity),
geometryPropertyName: "corridor",
observedPropertyNames: ["availability", "corridor"]
});
this._onEntityPropertyChanged(entity, "corridor", entity.corridor, void 0);
}
if (defined_default(Object.create)) {
CorridorGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater_default.prototype
);
CorridorGeometryUpdater.prototype.constructor = CorridorGeometryUpdater;
}
CorridorGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time)
),
offset: void 0,
color: void 0
};
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor11);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
}
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset2,
offsetScratch5
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new CorridorGeometry_default(this._options),
attributes
});
};
CorridorGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor11
);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time)
),
offset: void 0
};
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset2,
offsetScratch5
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new CorridorOutlineGeometry_default(this._options),
attributes
});
};
CorridorGeometryUpdater.prototype._computeCenter = function(time, result) {
const positions = Property_default.getValueOrUndefined(
this._entity.corridor.positions,
time
);
if (!defined_default(positions) || positions.length === 0) {
return;
}
return Cartesian3_default.clone(
positions[Math.floor(positions.length / 2)],
result
);
};
CorridorGeometryUpdater.prototype._isHidden = function(entity, corridor) {
return !defined_default(corridor.positions) || !defined_default(corridor.width) || GeometryUpdater_default.prototype._isHidden.call(this, entity, corridor);
};
CorridorGeometryUpdater.prototype._isDynamic = function(entity, corridor) {
return !corridor.positions.isConstant || !Property_default.isConstant(corridor.height) || !Property_default.isConstant(corridor.extrudedHeight) || !Property_default.isConstant(corridor.granularity) || !Property_default.isConstant(corridor.width) || !Property_default.isConstant(corridor.outlineWidth) || !Property_default.isConstant(corridor.cornerType) || !Property_default.isConstant(corridor.zIndex) || this._onTerrain && !Property_default.isConstant(this._materialProperty) && !(this._materialProperty instanceof ColorMaterialProperty_default);
};
CorridorGeometryUpdater.prototype._setStaticOptions = function(entity, corridor) {
let heightValue = Property_default.getValueOrUndefined(
corridor.height,
Iso8601_default.MINIMUM_VALUE
);
const heightReferenceValue = Property_default.getValueOrDefault(
corridor.heightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
corridor.extrudedHeight,
Iso8601_default.MINIMUM_VALUE
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
corridor.extrudedHeightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
const options = this._options;
options.vertexFormat = this._materialProperty instanceof ColorMaterialProperty_default ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.positions = corridor.positions.getValue(
Iso8601_default.MINIMUM_VALUE,
options.positions
);
options.width = corridor.width.getValue(Iso8601_default.MINIMUM_VALUE);
options.granularity = Property_default.getValueOrUndefined(
corridor.granularity,
Iso8601_default.MINIMUM_VALUE
);
options.cornerType = Property_default.getValueOrUndefined(
corridor.cornerType,
Iso8601_default.MINIMUM_VALUE
);
options.offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
options.height = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
heightReferenceValue
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
CorridorGeometry_default.computeRectangle(options, scratchRectangle4)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
CorridorGeometryUpdater.DynamicGeometryUpdater = DynamicCorridorGeometryUpdater;
function DynamicCorridorGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicCorridorGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicCorridorGeometryUpdater.prototype.constructor = DynamicCorridorGeometryUpdater;
}
DynamicCorridorGeometryUpdater.prototype._isHidden = function(entity, corridor, time) {
const options = this._options;
return !defined_default(options.positions) || !defined_default(options.width) || DynamicGeometryUpdater_default.prototype._isHidden.call(
this,
entity,
corridor,
time
);
};
DynamicCorridorGeometryUpdater.prototype._setOptions = function(entity, corridor, time) {
const options = this._options;
let heightValue = Property_default.getValueOrUndefined(corridor.height, time);
const heightReferenceValue = Property_default.getValueOrDefault(
corridor.heightReference,
time,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
corridor.extrudedHeight,
time
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
corridor.extrudedHeightReference,
time,
HeightReference_default.NONE
);
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
options.positions = Property_default.getValueOrUndefined(corridor.positions, time);
options.width = Property_default.getValueOrUndefined(corridor.width, time);
options.granularity = Property_default.getValueOrUndefined(
corridor.granularity,
time
);
options.cornerType = Property_default.getValueOrUndefined(corridor.cornerType, time);
options.offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
options.height = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
heightReferenceValue
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
CorridorGeometry_default.computeRectangle(options, scratchRectangle4)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
var CorridorGeometryUpdater_default = CorridorGeometryUpdater;
// node_modules/@cesium/engine/Source/DataSources/DataSource.js
function DataSource() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(DataSource.prototype, {
name: {
get: DeveloperError_default.throwInstantiationError
},
clock: {
get: DeveloperError_default.throwInstantiationError
},
entities: {
get: DeveloperError_default.throwInstantiationError
},
isLoading: {
get: DeveloperError_default.throwInstantiationError
},
changedEvent: {
get: DeveloperError_default.throwInstantiationError
},
errorEvent: {
get: DeveloperError_default.throwInstantiationError
},
loadingEvent: {
get: DeveloperError_default.throwInstantiationError
},
show: {
get: DeveloperError_default.throwInstantiationError
},
clustering: {
get: DeveloperError_default.throwInstantiationError
}
});
DataSource.prototype.update = function(time) {
DeveloperError_default.throwInstantiationError();
};
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);
}
};
var DataSource_default = DataSource;
// node_modules/@cesium/engine/Source/Core/EllipsoidalOccluder.js
function EllipsoidalOccluder(ellipsoid, cameraPosition) {
Check_default.typeOf.object("ellipsoid", ellipsoid);
this._ellipsoid = ellipsoid;
this._cameraPosition = new Cartesian3_default();
this._cameraPositionInScaledSpace = new Cartesian3_default();
this._distanceToLimbInScaledSpaceSquared = 0;
if (defined_default(cameraPosition)) {
this.cameraPosition = cameraPosition;
}
}
Object.defineProperties(EllipsoidalOccluder.prototype, {
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
cameraPosition: {
get: function() {
return this._cameraPosition;
},
set: function(cameraPosition) {
const ellipsoid = this._ellipsoid;
const cv = ellipsoid.transformPositionToScaledSpace(
cameraPosition,
this._cameraPositionInScaledSpace
);
const vhMagnitudeSquared = Cartesian3_default.magnitudeSquared(cv) - 1;
Cartesian3_default.clone(cameraPosition, this._cameraPosition);
this._cameraPositionInScaledSpace = cv;
this._distanceToLimbInScaledSpaceSquared = vhMagnitudeSquared;
}
}
});
var scratchCartesian11 = new Cartesian3_default();
EllipsoidalOccluder.prototype.isPointVisible = function(occludee) {
const ellipsoid = this._ellipsoid;
const occludeeScaledSpacePosition = ellipsoid.transformPositionToScaledSpace(
occludee,
scratchCartesian11
);
return isScaledSpacePointVisible(
occludeeScaledSpacePosition,
this._cameraPositionInScaledSpace,
this._distanceToLimbInScaledSpaceSquared
);
};
EllipsoidalOccluder.prototype.isScaledSpacePointVisible = function(occludeeScaledSpacePosition) {
return isScaledSpacePointVisible(
occludeeScaledSpacePosition,
this._cameraPositionInScaledSpace,
this._distanceToLimbInScaledSpaceSquared
);
};
var scratchCameraPositionInScaledSpaceShrunk = new Cartesian3_default();
EllipsoidalOccluder.prototype.isScaledSpacePointVisiblePossiblyUnderEllipsoid = function(occludeeScaledSpacePosition, minimumHeight) {
const ellipsoid = this._ellipsoid;
let vhMagnitudeSquared;
let cv;
if (defined_default(minimumHeight) && minimumHeight < 0 && ellipsoid.minimumRadius > -minimumHeight) {
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;
} else {
cv = this._cameraPositionInScaledSpace;
vhMagnitudeSquared = this._distanceToLimbInScaledSpaceSquared;
}
return isScaledSpacePointVisible(
occludeeScaledSpacePosition,
cv,
vhMagnitudeSquared
);
};
EllipsoidalOccluder.prototype.computeHorizonCullingPoint = function(directionToPoint, positions, result) {
return computeHorizonCullingPointFromPositions(
this._ellipsoid,
directionToPoint,
positions,
result
);
};
var scratchEllipsoidShrunk = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
EllipsoidalOccluder.prototype.computeHorizonCullingPointPossiblyUnderEllipsoid = function(directionToPoint, positions, minimumHeight, result) {
const possiblyShrunkEllipsoid = getPossiblyShrunkEllipsoid(
this._ellipsoid,
minimumHeight,
scratchEllipsoidShrunk
);
return computeHorizonCullingPointFromPositions(
possiblyShrunkEllipsoid,
directionToPoint,
positions,
result
);
};
EllipsoidalOccluder.prototype.computeHorizonCullingPointFromVertices = function(directionToPoint, vertices, stride, center, result) {
return computeHorizonCullingPointFromVertices(
this._ellipsoid,
directionToPoint,
vertices,
stride,
center,
result
);
};
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
);
};
var subsampleScratch = [];
EllipsoidalOccluder.prototype.computeHorizonCullingPointFromRectangle = function(rectangle, ellipsoid, result) {
Check_default.typeOf.object("rectangle", rectangle);
const positions = Rectangle_default.subsample(
rectangle,
ellipsoid,
0,
subsampleScratch
);
const bs = BoundingSphere_default.fromPoints(positions);
if (Cartesian3_default.magnitude(bs.center) < 0.1 * ellipsoid.minimumRadius) {
return void 0;
}
return this.computeHorizonCullingPoint(bs.center, positions, result);
};
var scratchEllipsoidShrunkRadii = new Cartesian3_default();
function getPossiblyShrunkEllipsoid(ellipsoid, minimumHeight, result) {
if (defined_default(minimumHeight) && minimumHeight < 0 && ellipsoid.minimumRadius > -minimumHeight) {
const ellipsoidShrunkRadii = Cartesian3_default.fromElements(
ellipsoid.radii.x + minimumHeight,
ellipsoid.radii.y + minimumHeight,
ellipsoid.radii.z + minimumHeight,
scratchEllipsoidShrunkRadii
);
ellipsoid = Ellipsoid_default.fromCartesian3(ellipsoidShrunkRadii, result);
}
return ellipsoid;
}
function computeHorizonCullingPointFromPositions(ellipsoid, directionToPoint, positions, result) {
Check_default.typeOf.object("directionToPoint", directionToPoint);
Check_default.defined("positions", positions);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
const scaledSpaceDirectionToPoint = computeScaledSpaceDirectionToPoint(
ellipsoid,
directionToPoint
);
let resultMagnitude = 0;
for (let i = 0, len = positions.length; i < len; ++i) {
const position = positions[i];
const candidateMagnitude = computeMagnitude(
ellipsoid,
position,
scaledSpaceDirectionToPoint
);
if (candidateMagnitude < 0) {
return void 0;
}
resultMagnitude = Math.max(resultMagnitude, candidateMagnitude);
}
return magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result);
}
var positionScratch7 = new Cartesian3_default();
function computeHorizonCullingPointFromVertices(ellipsoid, directionToPoint, vertices, stride, center, result) {
Check_default.typeOf.object("directionToPoint", directionToPoint);
Check_default.defined("vertices", vertices);
Check_default.typeOf.number("stride", stride);
if (!defined_default(result)) {
result = new Cartesian3_default();
}
stride = defaultValue_default(stride, 3);
center = defaultValue_default(center, Cartesian3_default.ZERO);
const scaledSpaceDirectionToPoint = computeScaledSpaceDirectionToPoint(
ellipsoid,
directionToPoint
);
let resultMagnitude = 0;
for (let i = 0, len = vertices.length; i < len; i += stride) {
positionScratch7.x = vertices[i] + center.x;
positionScratch7.y = vertices[i + 1] + center.y;
positionScratch7.z = vertices[i + 2] + center.z;
const candidateMagnitude = computeMagnitude(
ellipsoid,
positionScratch7,
scaledSpaceDirectionToPoint
);
if (candidateMagnitude < 0) {
return void 0;
}
resultMagnitude = Math.max(resultMagnitude, candidateMagnitude);
}
return magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result);
}
function isScaledSpacePointVisible(occludeeScaledSpacePosition, cameraPositionInScaledSpace, distanceToLimbInScaledSpaceSquared) {
const cv = cameraPositionInScaledSpace;
const vhMagnitudeSquared = distanceToLimbInScaledSpaceSquared;
const vt = Cartesian3_default.subtract(
occludeeScaledSpacePosition,
cv,
scratchCartesian11
);
const vtDotVc = -Cartesian3_default.dot(vt, cv);
const isOccluded = vhMagnitudeSquared < 0 ? vtDotVc > 0 : vtDotVc > vhMagnitudeSquared && vtDotVc * vtDotVc / Cartesian3_default.magnitudeSquared(vt) > vhMagnitudeSquared;
return !isOccluded;
}
var scaledSpaceScratch = new Cartesian3_default();
var directionScratch = new Cartesian3_default();
function computeMagnitude(ellipsoid, position, scaledSpaceDirectionToPoint) {
const scaledSpacePosition = ellipsoid.transformPositionToScaledSpace(
position,
scaledSpaceScratch
);
let magnitudeSquared = Cartesian3_default.magnitudeSquared(scaledSpacePosition);
let magnitude = Math.sqrt(magnitudeSquared);
const direction2 = Cartesian3_default.divideByScalar(
scaledSpacePosition,
magnitude,
directionScratch
);
magnitudeSquared = Math.max(1, magnitudeSquared);
magnitude = Math.max(1, magnitude);
const cosAlpha = Cartesian3_default.dot(direction2, scaledSpaceDirectionToPoint);
const sinAlpha = Cartesian3_default.magnitude(
Cartesian3_default.cross(direction2, scaledSpaceDirectionToPoint, direction2)
);
const cosBeta = 1 / magnitude;
const sinBeta = Math.sqrt(magnitudeSquared - 1) * cosBeta;
return 1 / (cosAlpha * cosBeta - sinAlpha * sinBeta);
}
function magnitudeToPoint(scaledSpaceDirectionToPoint, resultMagnitude, result) {
if (resultMagnitude <= 0 || resultMagnitude === 1 / 0 || resultMagnitude !== resultMagnitude) {
return void 0;
}
return Cartesian3_default.multiplyByScalar(
scaledSpaceDirectionToPoint,
resultMagnitude,
result
);
}
var directionToPointScratch = new Cartesian3_default();
function computeScaledSpaceDirectionToPoint(ellipsoid, directionToPoint) {
if (Cartesian3_default.equals(directionToPoint, Cartesian3_default.ZERO)) {
return directionToPoint;
}
ellipsoid.transformPositionToScaledSpace(
directionToPoint,
directionToPointScratch
);
return Cartesian3_default.normalize(directionToPointScratch, directionToPointScratch);
}
var EllipsoidalOccluder_default = EllipsoidalOccluder;
// node_modules/@cesium/engine/Source/Scene/PointPrimitive.js
function PointPrimitive(options, pointPrimitiveCollection) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (defined_default(options.disableDepthTestDistance) && options.disableDepthTestDistance < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than or equal to 0.0."
);
}
let translucencyByDistance = options.translucencyByDistance;
let scaleByDistance = options.scaleByDistance;
let distanceDisplayCondition = options.distanceDisplayCondition;
if (defined_default(translucencyByDistance)) {
if (translucencyByDistance.far <= translucencyByDistance.near) {
throw new DeveloperError_default(
"translucencyByDistance.far must be greater than translucencyByDistance.near."
);
}
translucencyByDistance = NearFarScalar_default.clone(translucencyByDistance);
}
if (defined_default(scaleByDistance)) {
if (scaleByDistance.far <= scaleByDistance.near) {
throw new DeveloperError_default(
"scaleByDistance.far must be greater than scaleByDistance.near."
);
}
scaleByDistance = NearFarScalar_default.clone(scaleByDistance);
}
if (defined_default(distanceDisplayCondition)) {
if (distanceDisplayCondition.far <= distanceDisplayCondition.near) {
throw new DeveloperError_default(
"distanceDisplayCondition.far must be greater than distanceDisplayCondition.near."
);
}
distanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition
);
}
this._show = defaultValue_default(options.show, true);
this._position = Cartesian3_default.clone(
defaultValue_default(options.position, Cartesian3_default.ZERO)
);
this._actualPosition = Cartesian3_default.clone(this._position);
this._color = Color_default.clone(defaultValue_default(options.color, Color_default.WHITE));
this._outlineColor = Color_default.clone(
defaultValue_default(options.outlineColor, Color_default.TRANSPARENT)
);
this._outlineWidth = defaultValue_default(options.outlineWidth, 0);
this._pixelSize = defaultValue_default(options.pixelSize, 10);
this._scaleByDistance = scaleByDistance;
this._translucencyByDistance = translucencyByDistance;
this._distanceDisplayCondition = distanceDisplayCondition;
this._disableDepthTestDistance = defaultValue_default(
options.disableDepthTestDistance,
0
);
this._id = options.id;
this._collection = defaultValue_default(options.collection, pointPrimitiveCollection);
this._clusterShow = true;
this._pickId = void 0;
this._pointPrimitiveCollection = pointPrimitiveCollection;
this._dirty = false;
this._index = -1;
}
var SHOW_INDEX5 = PointPrimitive.SHOW_INDEX = 0;
var POSITION_INDEX5 = PointPrimitive.POSITION_INDEX = 1;
var COLOR_INDEX3 = PointPrimitive.COLOR_INDEX = 2;
var OUTLINE_COLOR_INDEX = PointPrimitive.OUTLINE_COLOR_INDEX = 3;
var OUTLINE_WIDTH_INDEX = PointPrimitive.OUTLINE_WIDTH_INDEX = 4;
var PIXEL_SIZE_INDEX = PointPrimitive.PIXEL_SIZE_INDEX = 5;
var SCALE_BY_DISTANCE_INDEX3 = PointPrimitive.SCALE_BY_DISTANCE_INDEX = 6;
var TRANSLUCENCY_BY_DISTANCE_INDEX3 = PointPrimitive.TRANSLUCENCY_BY_DISTANCE_INDEX = 7;
var DISTANCE_DISPLAY_CONDITION_INDEX2 = PointPrimitive.DISTANCE_DISPLAY_CONDITION_INDEX = 8;
var DISABLE_DEPTH_DISTANCE_INDEX = PointPrimitive.DISABLE_DEPTH_DISTANCE_INDEX = 9;
PointPrimitive.NUMBER_OF_PROPERTIES = 10;
function makeDirty3(pointPrimitive, propertyChanged) {
const pointPrimitiveCollection = pointPrimitive._pointPrimitiveCollection;
if (defined_default(pointPrimitiveCollection)) {
pointPrimitiveCollection._updatePointPrimitive(
pointPrimitive,
propertyChanged
);
pointPrimitive._dirty = true;
}
}
Object.defineProperties(PointPrimitive.prototype, {
show: {
get: function() {
return this._show;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._show !== value) {
this._show = value;
makeDirty3(this, SHOW_INDEX5);
}
}
},
position: {
get: function() {
return this._position;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const position = this._position;
if (!Cartesian3_default.equals(position, value)) {
Cartesian3_default.clone(value, position);
Cartesian3_default.clone(value, this._actualPosition);
makeDirty3(this, POSITION_INDEX5);
}
}
},
scaleByDistance: {
get: function() {
return this._scaleByDistance;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
const scaleByDistance = this._scaleByDistance;
if (!NearFarScalar_default.equals(scaleByDistance, value)) {
this._scaleByDistance = NearFarScalar_default.clone(value, scaleByDistance);
makeDirty3(this, SCALE_BY_DISTANCE_INDEX3);
}
}
},
translucencyByDistance: {
get: function() {
return this._translucencyByDistance;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default(
"far distance must be greater than near distance."
);
}
const translucencyByDistance = this._translucencyByDistance;
if (!NearFarScalar_default.equals(translucencyByDistance, value)) {
this._translucencyByDistance = NearFarScalar_default.clone(
value,
translucencyByDistance
);
makeDirty3(this, TRANSLUCENCY_BY_DISTANCE_INDEX3);
}
}
},
pixelSize: {
get: function() {
return this._pixelSize;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._pixelSize !== value) {
this._pixelSize = value;
makeDirty3(this, PIXEL_SIZE_INDEX);
}
}
},
color: {
get: function() {
return this._color;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const color = this._color;
if (!Color_default.equals(color, value)) {
Color_default.clone(value, color);
makeDirty3(this, COLOR_INDEX3);
}
}
},
outlineColor: {
get: function() {
return this._outlineColor;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
const outlineColor = this._outlineColor;
if (!Color_default.equals(outlineColor, value)) {
Color_default.clone(value, outlineColor);
makeDirty3(this, OUTLINE_COLOR_INDEX);
}
}
},
outlineWidth: {
get: function() {
return this._outlineWidth;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required.");
}
if (this._outlineWidth !== value) {
this._outlineWidth = value;
makeDirty3(this, OUTLINE_WIDTH_INDEX);
}
}
},
distanceDisplayCondition: {
get: function() {
return this._distanceDisplayCondition;
},
set: function(value) {
if (defined_default(value) && value.far <= value.near) {
throw new DeveloperError_default("far must be greater than near");
}
if (!DistanceDisplayCondition_default.equals(this._distanceDisplayCondition, value)) {
this._distanceDisplayCondition = DistanceDisplayCondition_default.clone(
value,
this._distanceDisplayCondition
);
makeDirty3(this, DISTANCE_DISPLAY_CONDITION_INDEX2);
}
}
},
disableDepthTestDistance: {
get: function() {
return this._disableDepthTestDistance;
},
set: function(value) {
if (this._disableDepthTestDistance !== value) {
if (!defined_default(value) || value < 0) {
throw new DeveloperError_default(
"disableDepthTestDistance must be greater than or equal to 0.0."
);
}
this._disableDepthTestDistance = value;
makeDirty3(this, DISABLE_DEPTH_DISTANCE_INDEX);
}
}
},
id: {
get: function() {
return this._id;
},
set: function(value) {
this._id = value;
if (defined_default(this._pickId)) {
this._pickId.object.id = value;
}
}
},
pickId: {
get: function() {
return this._pickId;
}
},
clusterShow: {
get: function() {
return this._clusterShow;
},
set: function(value) {
if (this._clusterShow !== value) {
this._clusterShow = value;
makeDirty3(this, SHOW_INDEX5);
}
}
}
});
PointPrimitive.prototype.getPickId = function(context) {
if (!defined_default(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_default.clone(value, this._actualPosition);
makeDirty3(this, POSITION_INDEX5);
};
var tempCartesian32 = new Cartesian4_default();
PointPrimitive._computeActualPosition = function(position, frameState, modelMatrix) {
if (frameState.mode === SceneMode_default.SCENE3D) {
return position;
}
Matrix4_default.multiplyByPoint(modelMatrix, position, tempCartesian32);
return SceneTransforms_default.computeActualWgs84Position(frameState, tempCartesian32);
};
var scratchCartesian44 = new Cartesian4_default();
PointPrimitive._computeScreenSpacePosition = function(modelMatrix, position, scene, result) {
const positionWorld = Matrix4_default.multiplyByVector(
modelMatrix,
Cartesian4_default.fromElements(
position.x,
position.y,
position.z,
1,
scratchCartesian44
),
scratchCartesian44
);
const positionWC2 = SceneTransforms_default.wgs84ToWindowCoordinates(
scene,
positionWorld,
result
);
return positionWC2;
};
PointPrimitive.prototype.computeScreenSpacePosition = function(scene, result) {
const pointPrimitiveCollection = this._pointPrimitiveCollection;
if (!defined_default(result)) {
result = new Cartesian2_default();
}
if (!defined_default(pointPrimitiveCollection)) {
throw new DeveloperError_default("PointPrimitive must be in a collection.");
}
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
const modelMatrix = pointPrimitiveCollection.modelMatrix;
const windowCoordinates = PointPrimitive._computeScreenSpacePosition(
modelMatrix,
this._actualPosition,
scene,
result
);
if (!defined_default(windowCoordinates)) {
return void 0;
}
windowCoordinates.y = scene.canvas.clientHeight - windowCoordinates.y;
return windowCoordinates;
};
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_default(result)) {
result = new BoundingRectangle_default();
}
result.x = x;
result.y = y;
result.width = width;
result.height = height;
return result;
};
PointPrimitive.prototype.equals = function(other) {
return this === other || defined_default(other) && this._id === other._id && Cartesian3_default.equals(this._position, other._position) && Color_default.equals(this._color, other._color) && this._pixelSize === other._pixelSize && this._outlineWidth === other._outlineWidth && this._show === other._show && Color_default.equals(this._outlineColor, other._outlineColor) && NearFarScalar_default.equals(this._scaleByDistance, other._scaleByDistance) && NearFarScalar_default.equals(
this._translucencyByDistance,
other._translucencyByDistance
) && DistanceDisplayCondition_default.equals(
this._distanceDisplayCondition,
other._distanceDisplayCondition
) && this._disableDepthTestDistance === other._disableDepthTestDistance;
};
PointPrimitive.prototype._destroy = function() {
this._pickId = this._pickId && this._pickId.destroy();
this._pointPrimitiveCollection = void 0;
};
var PointPrimitive_default = PointPrimitive;
// node_modules/@cesium/engine/Source/Shaders/PointPrimitiveCollectionFS.js
var PointPrimitiveCollectionFS_default = "in vec4 v_color;\nin vec4 v_outlineColor;\nin float v_innerPercent;\nin float v_pixelDistance;\nin vec4 v_pickColor;\n\nvoid main()\n{\n // The distance in UV space from this fragment to the center of the point, at most 0.5.\n float distanceToCenter = length(gl_PointCoord - vec2(0.5));\n // The max distance stops one pixel shy of the edge to leave space for anti-aliasing.\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\n vec4 color = mix(v_outlineColor, v_color, innerAlpha);\n color.a *= wholeAlpha;\n\n// Fully transparent parts of the billboard are not pickable.\n#if !defined(OPAQUE) && !defined(TRANSLUCENT)\n if (color.a < 0.005) // matches 0/255 and 1/255\n {\n discard;\n }\n#else\n// The billboard is rendered twice. The opaque pass discards translucent fragments\n// and the translucent pass discards opaque fragments.\n#ifdef OPAQUE\n if (color.a < 0.995) // matches < 254/255\n {\n discard;\n }\n#else\n if (color.a >= 0.995) // matches 254/255 and 255/255\n {\n discard;\n }\n#endif\n#endif\n\n out_FragColor = czm_gammaCorrect(color);\n czm_writeLogDepth();\n}\n";
// node_modules/@cesium/engine/Source/Shaders/PointPrimitiveCollectionVS.js
var PointPrimitiveCollectionVS_default = `uniform float u_maxTotalPointSize;
in vec4 positionHighAndSize;
in vec4 positionLowAndOutline;
in vec4 compressedAttribute0; // color, outlineColor, pick color
in vec4 compressedAttribute1; // show, translucency by distance, some free space
in vec4 scaleByDistance; // near, nearScale, far, farScale
in vec3 distanceDisplayConditionAndDisableDepth; // near, far, disableDepthTestDistance
out vec4 v_color;
out vec4 v_outlineColor;
out float v_innerPercent;
out float v_pixelDistance;
out vec4 v_pickColor;
const float SHIFT_LEFT8 = 256.0;
const float SHIFT_RIGHT8 = 1.0 / 256.0;
void main()
{
// Modifying this shader may also require modifications to PointPrimitive._computeScreenSpacePosition
// unpack attributes
vec3 positionHigh = positionHighAndSize.xyz;
vec3 positionLow = positionLowAndOutline.xyz;
float outlineWidthBothSides = 2.0 * positionLowAndOutline.w;
float totalSize = positionHighAndSize.w + outlineWidthBothSides;
float outlinePercent = outlineWidthBothSides / totalSize;
// Scale in response to browser-zoom.
totalSize *= czm_pixelRatio;
float temp = compressedAttribute1.x * SHIFT_RIGHT8;
float show = floor(temp);
#ifdef EYE_DISTANCE_TRANSLUCENCY
vec4 translucencyByDistance;
translucencyByDistance.x = compressedAttribute1.z;
translucencyByDistance.z = compressedAttribute1.w;
translucencyByDistance.y = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;
temp = compressedAttribute1.y * SHIFT_RIGHT8;
translucencyByDistance.w = ((temp - floor(temp)) * SHIFT_LEFT8) / 255.0;
#endif
///////////////////////////////////////////////////////////////////////////
vec4 color;
vec4 outlineColor;
vec4 pickColor;
// compressedAttribute0.z => pickColor.rgb
temp = compressedAttribute0.z * SHIFT_RIGHT8;
pickColor.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
pickColor.g = (temp - floor(temp)) * SHIFT_LEFT8;
pickColor.r = floor(temp);
// compressedAttribute0.x => color.rgb
temp = compressedAttribute0.x * SHIFT_RIGHT8;
color.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
color.g = (temp - floor(temp)) * SHIFT_LEFT8;
color.r = floor(temp);
// compressedAttribute0.y => outlineColor.rgb
temp = compressedAttribute0.y * SHIFT_RIGHT8;
outlineColor.b = (temp - floor(temp)) * SHIFT_LEFT8;
temp = floor(temp) * SHIFT_RIGHT8;
outlineColor.g = (temp - floor(temp)) * SHIFT_LEFT8;
outlineColor.r = floor(temp);
// compressedAttribute0.w => color.a, outlineColor.a, pickColor.a
temp = compressedAttribute0.w * SHIFT_RIGHT8;
pickColor.a = (temp - floor(temp)) * SHIFT_LEFT8;
pickColor = pickColor / 255.0;
temp = floor(temp) * SHIFT_RIGHT8;
outlineColor.a = (temp - floor(temp)) * SHIFT_LEFT8;
outlineColor /= 255.0;
color.a = floor(temp);
color /= 255.0;
///////////////////////////////////////////////////////////////////////////
vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
vec4 positionEC = czm_modelViewRelativeToEye * p;
///////////////////////////////////////////////////////////////////////////
#if defined(EYE_DISTANCE_SCALING) || defined(EYE_DISTANCE_TRANSLUCENCY) || defined(DISTANCE_DISPLAY_CONDITION) || defined(DISABLE_DEPTH_DISTANCE)
float lengthSq;
if (czm_sceneMode == czm_sceneMode2D)
{
// 2D camera distance is a special case
// treat all billboards as flattened to the z=0.0 plane
lengthSq = czm_eyeHeight2D.y;
}
else
{
lengthSq = dot(positionEC.xyz, positionEC.xyz);
}
#endif
#ifdef EYE_DISTANCE_SCALING
totalSize *= czm_nearFarScalar(scaleByDistance, lengthSq);
#endif
if (totalSize > 0.0) {
// Add padding for anti-aliasing on both sides.
totalSize += 3.0;
}
// Clamp to max point size.
totalSize = min(totalSize, u_maxTotalPointSize);
// If size is too small, push vertex behind near plane for clipping.
// Note that context.minimumAliasedPointSize "will be at most 1.0".
if (totalSize < 1.0)
{
positionEC.xyz = vec3(0.0);
totalSize = 1.0;
}
float translucency = 1.0;
#ifdef EYE_DISTANCE_TRANSLUCENCY
translucency = czm_nearFarScalar(translucencyByDistance, lengthSq);
// push vertex behind near plane for clipping
if (translucency < 0.004)
{
positionEC.xyz = vec3(0.0);
}
#endif
#ifdef DISTANCE_DISPLAY_CONDITION
float nearSq = distanceDisplayConditionAndDisableDepth.x;
float farSq = distanceDisplayConditionAndDisableDepth.y;
if (lengthSq < nearSq || lengthSq > farSq) {
// push vertex behind camera to force it to be clipped
positionEC.xyz = vec3(0.0, 0.0, 1.0);
}
#endif
gl_Position = czm_projection * positionEC;
czm_vertexLogDepth();
#ifdef DISABLE_DEPTH_DISTANCE
float disableDepthTestDistance = distanceDisplayConditionAndDisableDepth.z;
if (disableDepthTestDistance == 0.0 && czm_minimumDisableDepthTestDistance != 0.0)
{
disableDepthTestDistance = czm_minimumDisableDepthTestDistance;
}
if (disableDepthTestDistance != 0.0)
{
// Don't try to "multiply both sides" by w. Greater/less-than comparisons won't work for negative values of w.
float zclip = gl_Position.z / gl_Position.w;
bool clipped = (zclip < -1.0 || zclip > 1.0);
if (!clipped && (disableDepthTestDistance < 0.0 || (lengthSq > 0.0 && lengthSq < disableDepthTestDistance)))
{
// Position z on the near plane.
gl_Position.z = -gl_Position.w;
#ifdef LOG_DEPTH
czm_vertexLogDepth(vec4(czm_currentFrustum.x));
#endif
}
}
#endif
v_color = color;
v_color.a *= translucency * show;
v_outlineColor = outlineColor;
v_outlineColor.a *= translucency * show;
v_innerPercent = 1.0 - outlinePercent;
v_pixelDistance = 2.0 / totalSize;
gl_PointSize = totalSize * show;
gl_Position *= show;
v_pickColor = pickColor;
}
`;
// node_modules/@cesium/engine/Source/Scene/PointPrimitiveCollection.js
var SHOW_INDEX6 = PointPrimitive_default.SHOW_INDEX;
var POSITION_INDEX6 = PointPrimitive_default.POSITION_INDEX;
var COLOR_INDEX4 = PointPrimitive_default.COLOR_INDEX;
var OUTLINE_COLOR_INDEX2 = PointPrimitive_default.OUTLINE_COLOR_INDEX;
var OUTLINE_WIDTH_INDEX2 = PointPrimitive_default.OUTLINE_WIDTH_INDEX;
var PIXEL_SIZE_INDEX2 = PointPrimitive_default.PIXEL_SIZE_INDEX;
var SCALE_BY_DISTANCE_INDEX4 = PointPrimitive_default.SCALE_BY_DISTANCE_INDEX;
var TRANSLUCENCY_BY_DISTANCE_INDEX4 = PointPrimitive_default.TRANSLUCENCY_BY_DISTANCE_INDEX;
var DISTANCE_DISPLAY_CONDITION_INDEX3 = PointPrimitive_default.DISTANCE_DISPLAY_CONDITION_INDEX;
var DISABLE_DEPTH_DISTANCE_INDEX2 = PointPrimitive_default.DISABLE_DEPTH_DISTANCE_INDEX;
var NUMBER_OF_PROPERTIES4 = PointPrimitive_default.NUMBER_OF_PROPERTIES;
var attributeLocations5 = {
positionHighAndSize: 0,
positionLowAndOutline: 1,
compressedAttribute0: 2,
compressedAttribute1: 3,
scaleByDistance: 4,
distanceDisplayConditionAndDisableDepth: 5
};
function PointPrimitiveCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._sp = void 0;
this._spTranslucent = void 0;
this._rsOpaque = void 0;
this._rsTranslucent = void 0;
this._vaf = void 0;
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_PROPERTIES4);
this._maxPixelSize = 1;
this._baseVolume = new BoundingSphere_default();
this._baseVolumeWC = new BoundingSphere_default();
this._baseVolume2D = new BoundingSphere_default();
this._boundingVolume = new BoundingSphere_default();
this._boundingVolumeDirty = false;
this._colorCommands = [];
this.show = defaultValue_default(options.show, true);
this.modelMatrix = Matrix4_default.clone(
defaultValue_default(options.modelMatrix, Matrix4_default.IDENTITY)
);
this._modelMatrix = Matrix4_default.clone(Matrix4_default.IDENTITY);
this.debugShowBoundingVolume = defaultValue_default(
options.debugShowBoundingVolume,
false
);
this.blendOption = defaultValue_default(
options.blendOption,
BlendOption_default.OPAQUE_AND_TRANSLUCENT
);
this._blendOption = void 0;
this._mode = SceneMode_default.SCENE3D;
this._maxTotalPointSize = 1;
this._buffersUsage = [
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW,
BufferUsage_default.STATIC_DRAW
];
const that = this;
this._uniforms = {
u_maxTotalPointSize: function() {
return that._maxTotalPointSize;
}
};
}
Object.defineProperties(PointPrimitiveCollection.prototype, {
length: {
get: function() {
removePointPrimitives(this);
return this._pointPrimitives.length;
}
}
});
function destroyPointPrimitives(pointPrimitives) {
const length3 = pointPrimitives.length;
for (let i = 0; i < length3; ++i) {
if (pointPrimitives[i]) {
pointPrimitives[i]._destroy();
}
}
}
PointPrimitiveCollection.prototype.add = function(options) {
const p = new PointPrimitive_default(options, this);
p._index = this._pointPrimitives.length;
this._pointPrimitives.push(p);
this._createVertexArray = true;
return p;
};
PointPrimitiveCollection.prototype.remove = function(pointPrimitive) {
if (this.contains(pointPrimitive)) {
this._pointPrimitives[pointPrimitive._index] = null;
this._pointPrimitivesRemoved = true;
this._createVertexArray = true;
pointPrimitive._destroy();
return true;
}
return false;
};
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 length3 = pointPrimitives.length;
for (let i = 0, j = 0; i < length3; ++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];
};
PointPrimitiveCollection.prototype.contains = function(pointPrimitive) {
return defined_default(pointPrimitive) && pointPrimitive._pointPrimitiveCollection === this;
};
PointPrimitiveCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
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_PROPERTIES4; ++k) {
const newUsage = properties[k] === 0 ? BufferUsage_default.STATIC_DRAW : BufferUsage_default.STREAM_DRAW;
usageChanged = usageChanged || buffersUsage[k] !== newUsage;
buffersUsage[k] = newUsage;
}
return usageChanged;
};
function createVAF2(context, numberOfPointPrimitives, buffersUsage) {
return new VertexArrayFacade_default(
context,
[
{
index: attributeLocations5.positionHighAndSize,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX6]
},
{
index: attributeLocations5.positionLowAndShow,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[POSITION_INDEX6]
},
{
index: attributeLocations5.compressedAttribute0,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[COLOR_INDEX4]
},
{
index: attributeLocations5.compressedAttribute1,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[TRANSLUCENCY_BY_DISTANCE_INDEX4]
},
{
index: attributeLocations5.scaleByDistance,
componentsPerAttribute: 4,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[SCALE_BY_DISTANCE_INDEX4]
},
{
index: attributeLocations5.distanceDisplayConditionAndDisableDepth,
componentsPerAttribute: 3,
componentDatatype: ComponentDatatype_default.FLOAT,
usage: buffersUsage[DISTANCE_DISPLAY_CONDITION_INDEX3]
}
],
numberOfPointPrimitives
);
}
var writePositionScratch2 = new EncodedCartesian3_default();
function writePositionSizeAndOutline(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
const position = pointPrimitive._getActualPosition();
if (pointPrimitiveCollection._mode === SceneMode_default.SCENE3D) {
BoundingSphere_default.expand(
pointPrimitiveCollection._baseVolume,
position,
pointPrimitiveCollection._baseVolume
);
pointPrimitiveCollection._boundingVolumeDirty = true;
}
EncodedCartesian3_default.fromCartesian(position, writePositionScratch2);
const pixelSize = pointPrimitive.pixelSize;
const outlineWidth = pointPrimitive.outlineWidth;
pointPrimitiveCollection._maxPixelSize = Math.max(
pointPrimitiveCollection._maxPixelSize,
pixelSize + outlineWidth
);
const positionHighWriter = vafWriters[attributeLocations5.positionHighAndSize];
const high = writePositionScratch2.high;
positionHighWriter(i, high.x, high.y, high.z, pixelSize);
const positionLowWriter = vafWriters[attributeLocations5.positionLowAndOutline];
const low = writePositionScratch2.low;
positionLowWriter(i, low.x, low.y, low.z, outlineWidth);
}
var LEFT_SHIFT162 = 65536;
var LEFT_SHIFT82 = 256;
function writeCompressedAttrib02(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_default.floatToByte(color.red);
let green = Color_default.floatToByte(color.green);
let blue = Color_default.floatToByte(color.blue);
const compressed0 = red * LEFT_SHIFT162 + green * LEFT_SHIFT82 + blue;
red = Color_default.floatToByte(outlineColor.red);
green = Color_default.floatToByte(outlineColor.green);
blue = Color_default.floatToByte(outlineColor.blue);
const compressed1 = red * LEFT_SHIFT162 + green * LEFT_SHIFT82 + blue;
red = Color_default.floatToByte(pickColor.red);
green = Color_default.floatToByte(pickColor.green);
blue = Color_default.floatToByte(pickColor.blue);
const compressed2 = red * LEFT_SHIFT162 + green * LEFT_SHIFT82 + blue;
const compressed3 = Color_default.floatToByte(color.alpha) * LEFT_SHIFT162 + Color_default.floatToByte(outlineColor.alpha) * LEFT_SHIFT82 + Color_default.floatToByte(pickColor.alpha);
const writer = vafWriters[attributeLocations5.compressedAttribute0];
writer(i, compressed0, compressed1, compressed2, compressed3);
}
function writeCompressedAttrib12(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const translucency = pointPrimitive.translucencyByDistance;
if (defined_default(translucency)) {
near = translucency.near;
nearValue = translucency.nearValue;
far = translucency.far;
farValue = translucency.farValue;
if (nearValue !== 1 || farValue !== 1) {
pointPrimitiveCollection._shaderTranslucencyByDistance = true;
}
}
let show = pointPrimitive.show && pointPrimitive.clusterShow;
if (pointPrimitive.color.alpha === 0 && pointPrimitive.outlineColor.alpha === 0) {
show = false;
}
nearValue = Math_default.clamp(nearValue, 0, 1);
nearValue = nearValue === 1 ? 255 : nearValue * 255 | 0;
const compressed0 = (show ? 1 : 0) * LEFT_SHIFT82 + nearValue;
farValue = Math_default.clamp(farValue, 0, 1);
farValue = farValue === 1 ? 255 : farValue * 255 | 0;
const compressed1 = farValue;
const writer = vafWriters[attributeLocations5.compressedAttribute1];
writer(i, compressed0, compressed1, near, far);
}
function writeScaleByDistance2(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
const writer = vafWriters[attributeLocations5.scaleByDistance];
let near = 0;
let nearValue = 1;
let far = 1;
let farValue = 1;
const scale = pointPrimitive.scaleByDistance;
if (defined_default(scale)) {
near = scale.near;
nearValue = scale.nearValue;
far = scale.far;
farValue = scale.farValue;
if (nearValue !== 1 || farValue !== 1) {
pointPrimitiveCollection._shaderScaleByDistance = true;
}
}
writer(i, near, nearValue, far, farValue);
}
function writeDistanceDisplayConditionAndDepthDisable(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
const i = pointPrimitive._index;
const writer = vafWriters[attributeLocations5.distanceDisplayConditionAndDisableDepth];
let near = 0;
let far = Number.MAX_VALUE;
const distanceDisplayCondition = pointPrimitive.distanceDisplayCondition;
if (defined_default(distanceDisplayCondition)) {
near = distanceDisplayCondition.near;
far = distanceDisplayCondition.far;
near *= near;
far *= far;
pointPrimitiveCollection._shaderDistanceDisplayCondition = true;
}
let disableDepthTestDistance = pointPrimitive.disableDepthTestDistance;
disableDepthTestDistance *= disableDepthTestDistance;
if (disableDepthTestDistance > 0) {
pointPrimitiveCollection._shaderDisableDepthDistance = true;
if (disableDepthTestDistance === Number.POSITIVE_INFINITY) {
disableDepthTestDistance = -1;
}
}
writer(i, near, far, disableDepthTestDistance);
}
function writePointPrimitive(pointPrimitiveCollection, context, vafWriters, pointPrimitive) {
writePositionSizeAndOutline(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeCompressedAttrib02(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeCompressedAttrib12(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeScaleByDistance2(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
writeDistanceDisplayConditionAndDepthDisable(
pointPrimitiveCollection,
context,
vafWriters,
pointPrimitive
);
}
function recomputeActualPositions2(pointPrimitiveCollection, pointPrimitives, length3, frameState, modelMatrix, recomputeBoundingVolume) {
let boundingVolume;
if (frameState.mode === SceneMode_default.SCENE3D) {
boundingVolume = pointPrimitiveCollection._baseVolume;
pointPrimitiveCollection._boundingVolumeDirty = true;
} else {
boundingVolume = pointPrimitiveCollection._baseVolume2D;
}
const positions = [];
for (let i = 0; i < length3; ++i) {
const pointPrimitive = pointPrimitives[i];
const position = pointPrimitive.position;
const actualPosition = PointPrimitive_default._computeActualPosition(
position,
frameState,
modelMatrix
);
if (defined_default(actualPosition)) {
pointPrimitive._setActualPosition(actualPosition);
if (recomputeBoundingVolume) {
positions.push(actualPosition);
} else {
BoundingSphere_default.expand(boundingVolume, actualPosition, boundingVolume);
}
}
}
if (recomputeBoundingVolume) {
BoundingSphere_default.fromPoints(positions, boundingVolume);
}
}
function updateMode3(pointPrimitiveCollection, frameState) {
const mode2 = frameState.mode;
const pointPrimitives = pointPrimitiveCollection._pointPrimitives;
const pointPrimitivesToUpdate = pointPrimitiveCollection._pointPrimitivesToUpdate;
const modelMatrix = pointPrimitiveCollection._modelMatrix;
if (pointPrimitiveCollection._createVertexArray || pointPrimitiveCollection._mode !== mode2 || mode2 !== SceneMode_default.SCENE3D && !Matrix4_default.equals(modelMatrix, pointPrimitiveCollection.modelMatrix)) {
pointPrimitiveCollection._mode = mode2;
Matrix4_default.clone(pointPrimitiveCollection.modelMatrix, modelMatrix);
pointPrimitiveCollection._createVertexArray = true;
if (mode2 === SceneMode_default.SCENE3D || mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions2(
pointPrimitiveCollection,
pointPrimitives,
pointPrimitives.length,
frameState,
modelMatrix,
true
);
}
} else if (mode2 === SceneMode_default.MORPHING) {
recomputeActualPositions2(
pointPrimitiveCollection,
pointPrimitives,
pointPrimitives.length,
frameState,
modelMatrix,
true
);
} else if (mode2 === SceneMode_default.SCENE2D || mode2 === SceneMode_default.COLUMBUS_VIEW) {
recomputeActualPositions2(
pointPrimitiveCollection,
pointPrimitivesToUpdate,
pointPrimitiveCollection._pointPrimitivesToUpdateIndex,
frameState,
modelMatrix,
false
);
}
}
function updateBoundingVolume2(collection, frameState, boundingVolume) {
const pixelSize = frameState.camera.getPixelSize(
boundingVolume,
frameState.context.drawingBufferWidth,
frameState.context.drawingBufferHeight
);
const size = pixelSize * collection._maxPixelSize;
boundingVolume.radius += size;
}
var scratchWriterArray2 = [];
PointPrimitiveCollection.prototype.update = function(frameState) {
removePointPrimitives(this);
if (!this.show) {
return;
}
this._maxTotalPointSize = ContextLimits_default.maximumAliasedPointSize;
updateMode3(this, frameState);
const pointPrimitives = this._pointPrimitives;
const pointPrimitivesLength = pointPrimitives.length;
const pointPrimitivesToUpdate = this._pointPrimitivesToUpdate;
const pointPrimitivesToUpdateLength = this._pointPrimitivesToUpdateIndex;
const properties = this._propertiesChanged;
const createVertexArray7 = this._createVertexArray;
let vafWriters;
const context = frameState.context;
const pass = frameState.passes;
const picking = pass.pick;
if (createVertexArray7 || !picking && this.computeNewBuffersUsage()) {
this._createVertexArray = false;
for (let k = 0; k < NUMBER_OF_PROPERTIES4; ++k) {
properties[k] = 0;
}
this._vaf = this._vaf && this._vaf.destroy();
if (pointPrimitivesLength > 0) {
this._vaf = createVAF2(context, pointPrimitivesLength, this._buffersUsage);
vafWriters = this._vaf.writers;
for (let i = 0; i < pointPrimitivesLength; ++i) {
const pointPrimitive = this._pointPrimitives[i];
pointPrimitive._dirty = false;
writePointPrimitive(this, context, vafWriters, pointPrimitive);
}
this._vaf.commit();
}
this._pointPrimitivesToUpdateIndex = 0;
} else if (pointPrimitivesToUpdateLength > 0) {
const writers = scratchWriterArray2;
writers.length = 0;
if (properties[POSITION_INDEX6] || properties[OUTLINE_WIDTH_INDEX2] || properties[PIXEL_SIZE_INDEX2]) {
writers.push(writePositionSizeAndOutline);
}
if (properties[COLOR_INDEX4] || properties[OUTLINE_COLOR_INDEX2]) {
writers.push(writeCompressedAttrib02);
}
if (properties[SHOW_INDEX6] || properties[TRANSLUCENCY_BY_DISTANCE_INDEX4]) {
writers.push(writeCompressedAttrib12);
}
if (properties[SCALE_BY_DISTANCE_INDEX4]) {
writers.push(writeScaleByDistance2);
}
if (properties[DISTANCE_DISPLAY_CONDITION_INDEX3] || properties[DISABLE_DEPTH_DISTANCE_INDEX2]) {
writers.push(writeDistanceDisplayConditionAndDepthDisable);
}
const numWriters = writers.length;
vafWriters = this._vaf.writers;
if (pointPrimitivesToUpdateLength / pointPrimitivesLength > 0.1) {
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 (pointPrimitivesToUpdateLength > pointPrimitivesLength * 1.5) {
pointPrimitivesToUpdate.length = pointPrimitivesLength;
}
if (!defined_default(this._vaf) || !defined_default(this._vaf.va)) {
return;
}
if (this._boundingVolumeDirty) {
this._boundingVolumeDirty = false;
BoundingSphere_default.transform(
this._baseVolume,
this.modelMatrix,
this._baseVolumeWC
);
}
let boundingVolume;
let modelMatrix = Matrix4_default.IDENTITY;
if (frameState.mode === SceneMode_default.SCENE3D) {
modelMatrix = this.modelMatrix;
boundingVolume = BoundingSphere_default.clone(
this._baseVolumeWC,
this._boundingVolume
);
} else {
boundingVolume = BoundingSphere_default.clone(
this._baseVolume2D,
this._boundingVolume
);
}
updateBoundingVolume2(this, frameState, boundingVolume);
const blendOptionChanged = this._blendOption !== this.blendOption;
this._blendOption = this.blendOption;
if (blendOptionChanged) {
if (this._blendOption === BlendOption_default.OPAQUE || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsOpaque = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: WebGLConstants_default.LEQUAL
},
depthMask: true
});
} else {
this._rsOpaque = void 0;
}
if (this._blendOption === BlendOption_default.TRANSLUCENT || this._blendOption === BlendOption_default.OPAQUE_AND_TRANSLUCENT) {
this._rsTranslucent = RenderState_default.fromCache({
depthTest: {
enabled: true,
func: WebGLConstants_default.LEQUAL
},
depthMask: false,
blending: BlendingState_default.ALPHA_BLEND
});
} else {
this._rsTranslucent = void 0;
}
}
this._shaderDisableDepthDistance = this._shaderDisableDepthDistance || frameState.minimumDisableDepthTestDistance !== 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_default({
sources: [PointPrimitiveCollectionVS_default]
});
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_default.OPAQUE_AND_TRANSLUCENT) {
fs = new ShaderSource_default({
defines: ["OPAQUE"],
sources: [PointPrimitiveCollectionFS_default]
});
this._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
fs = new ShaderSource_default({
defines: ["TRANSLUCENT"],
sources: [PointPrimitiveCollectionFS_default]
});
this._spTranslucent = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
}
if (this._blendOption === BlendOption_default.OPAQUE) {
fs = new ShaderSource_default({
sources: [PointPrimitiveCollectionFS_default]
});
this._sp = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._sp,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
}
if (this._blendOption === BlendOption_default.TRANSLUCENT) {
fs = new ShaderSource_default({
sources: [PointPrimitiveCollectionFS_default]
});
this._spTranslucent = ShaderProgram_default.replaceCache({
context,
shaderProgram: this._spTranslucent,
vertexShaderSource: vs,
fragmentShaderSource: fs,
attributeLocations: attributeLocations5
});
}
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_default.OPAQUE;
const opaqueAndTranslucent = this._blendOption === BlendOption_default.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_default(command)) {
command = colorList[j] = new DrawCommand_default();
}
command.primitiveType = PrimitiveType_default.POINTS;
command.pass = opaqueCommand || !opaqueAndTranslucent ? Pass_default.OPAQUE : Pass_default.TRANSLUCENT;
command.owner = this;
const index = opaqueAndTranslucent ? Math.floor(j / 2) : 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);
}
}
};
PointPrimitiveCollection.prototype.isDestroyed = function() {
return false;
};
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_default(this);
};
var PointPrimitiveCollection_default = PointPrimitiveCollection;
// node_modules/kdbush/index.js
var ARRAY_TYPES = [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array
];
var VERSION = 1;
var HEADER_SIZE = 8;
var KDBush = class {
static from(data) {
if (!(data instanceof ArrayBuffer)) {
throw new Error("Data must be an instance of ArrayBuffer.");
}
const [magic, versionAndType] = new Uint8Array(data, 0, 2);
if (magic !== 219) {
throw new Error("Data does not appear to be in a KDBush format.");
}
const version2 = versionAndType >> 4;
if (version2 !== VERSION) {
throw new Error(`Got v${version2} data when expected v${VERSION}.`);
}
const ArrayType = ARRAY_TYPES[versionAndType & 15];
if (!ArrayType) {
throw new Error("Unrecognized array type.");
}
const [nodeSize] = new Uint16Array(data, 2, 1);
const [numItems] = new Uint32Array(data, 4, 1);
return new KDBush(numItems, nodeSize, ArrayType, data);
}
constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {
if (isNaN(numItems) || numItems < 0)
throw new Error(`Unpexpected numItems value: ${numItems}.`);
this.numItems = +numItems;
this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
this.ArrayType = ArrayType;
this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
const padCoords = (8 - idsByteSize % 8) % 8;
if (arrayTypeIndex < 0) {
throw new Error(`Unexpected typed array class: ${ArrayType}.`);
}
if (data && data instanceof ArrayBuffer) {
this.data = data;
this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
this._pos = numItems * 2;
this._finished = true;
} else {
this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);
this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
this._pos = 0;
this._finished = false;
new Uint8Array(this.data, 0, 2).set([219, (VERSION << 4) + arrayTypeIndex]);
new Uint16Array(this.data, 2, 1)[0] = nodeSize;
new Uint32Array(this.data, 4, 1)[0] = numItems;
}
}
add(x, y) {
const index = this._pos >> 1;
this.ids[index] = index;
this.coords[this._pos++] = x;
this.coords[this._pos++] = y;
return index;
}
finish() {
const numAdded = this._pos >> 1;
if (numAdded !== this.numItems) {
throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
}
sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
this._finished = true;
return this;
}
range(minX, minY, maxX, maxY) {
if (!this._finished)
throw new Error("Data not yet indexed - call index.finish().");
const { ids, coords, nodeSize } = this;
const stack = [0, ids.length - 1, 0];
const result = [];
while (stack.length) {
const axis = stack.pop() || 0;
const right = stack.pop() || 0;
const left = stack.pop() || 0;
if (right - left <= nodeSize) {
for (let i = left; i <= right; i++) {
const x2 = coords[2 * i];
const y2 = coords[2 * i + 1];
if (x2 >= minX && x2 <= maxX && y2 >= minY && y2 <= maxY)
result.push(ids[i]);
}
continue;
}
const m = left + right >> 1;
const x = coords[2 * m];
const y = coords[2 * m + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY)
result.push(ids[m]);
if (axis === 0 ? minX <= x : minY <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(1 - axis);
}
if (axis === 0 ? maxX >= x : maxY >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(1 - axis);
}
}
return result;
}
within(qx, qy, r) {
if (!this._finished)
throw new Error("Data not yet indexed - call index.finish().");
const { ids, coords, nodeSize } = this;
const stack = [0, ids.length - 1, 0];
const result = [];
const r2 = r * r;
while (stack.length) {
const axis = stack.pop() || 0;
const right = stack.pop() || 0;
const left = stack.pop() || 0;
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 = left + right >> 1;
const x = coords[2 * m];
const y = coords[2 * m + 1];
if (sqDist(x, y, qx, qy) <= r2)
result.push(ids[m]);
if (axis === 0 ? qx - r <= x : qy - r <= y) {
stack.push(left);
stack.push(m - 1);
stack.push(1 - axis);
}
if (axis === 0 ? qx + r >= x : qy + r >= y) {
stack.push(m + 1);
stack.push(right);
stack.push(1 - axis);
}
}
return result;
}
};
function sort(ids, coords, nodeSize, left, right, axis) {
if (right - left <= nodeSize)
return;
const m = left + right >> 1;
select(ids, coords, m, left, right, axis);
sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
}
function select(ids, coords, k, left, right, axis) {
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, axis);
}
const t = coords[2 * k + axis];
let i = left;
let j = right;
swapItem(ids, coords, left, k);
if (coords[2 * right + axis] > t)
swapItem(ids, coords, left, right);
while (i < j) {
swapItem(ids, coords, i, j);
i++;
j--;
while (coords[2 * i + axis] < t)
i++;
while (coords[2 * j + axis] > t)
j--;
}
if (coords[2 * left + axis] === 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) {
swap2(ids, i, j);
swap2(coords, 2 * i, 2 * j);
swap2(coords, 2 * i + 1, 2 * j + 1);
}
function swap2(arr, i, j) {
const tmp2 = arr[i];
arr[i] = arr[j];
arr[j] = tmp2;
}
function sqDist(ax, ay, bx, by) {
const dx = ax - bx;
const dy = ay - by;
return dx * dx + dy * dy;
}
// node_modules/@cesium/engine/Source/DataSources/EntityCluster.js
function EntityCluster(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._enabled = defaultValue_default(options.enabled, false);
this._pixelRange = defaultValue_default(options.pixelRange, 80);
this._minimumClusterSize = defaultValue_default(options.minimumClusterSize, 2);
this._clusterBillboards = defaultValue_default(options.clusterBillboards, true);
this._clusterLabels = defaultValue_default(options.clusterLabels, true);
this._clusterPoints = defaultValue_default(options.clusterPoints, true);
this._labelCollection = void 0;
this._billboardCollection = void 0;
this._pointCollection = void 0;
this._clusterBillboardCollection = void 0;
this._clusterLabelCollection = void 0;
this._clusterPointCollection = void 0;
this._collectionIndicesByEntity = {};
this._unusedLabelIndices = [];
this._unusedBillboardIndices = [];
this._unusedPointIndices = [];
this._previousClusters = [];
this._previousHeight = void 0;
this._enabledDirty = false;
this._clusterDirty = false;
this._cluster = void 0;
this._removeEventListener = void 0;
this._clusterEvent = new Event_default();
this.show = defaultValue_default(options.show, true);
}
function expandBoundingBox(bbox, pixelRange) {
bbox.x -= pixelRange;
bbox.y -= pixelRange;
bbox.width += pixelRange * 2;
bbox.height += pixelRange * 2;
}
var labelBoundingBoxScratch = new BoundingRectangle_default();
function getBoundingBox(item, coord, pixelRange, entityCluster, result) {
if (defined_default(item._labelCollection) && entityCluster._clusterLabels) {
result = Label_default.getScreenSpaceBoundingBox(item, coord, result);
} else if (defined_default(item._billboardCollection) && entityCluster._clusterBillboards) {
result = Billboard_default.getScreenSpaceBoundingBox(item, coord, result);
} else if (defined_default(item._pointPrimitiveCollection) && entityCluster._clusterPoints) {
result = PointPrimitive_default.getScreenSpaceBoundingBox(item, coord, result);
}
expandBoundingBox(result, pixelRange);
if (entityCluster._clusterLabels && !defined_default(item._labelCollection) && defined_default(item.id) && hasLabelIndex(entityCluster, item.id.id) && defined_default(item.id._label)) {
const labelIndex = entityCluster._collectionIndicesByEntity[item.id.id].labelIndex;
const label = entityCluster._labelCollection.get(labelIndex);
const labelBBox = Label_default.getScreenSpaceBoundingBox(
label,
coord,
labelBoundingBoxScratch
);
expandBoundingBox(labelBBox, pixelRange);
result = BoundingRectangle_default.union(result, labelBBox, result);
}
return result;
}
function addNonClusteredItem(item, entityCluster) {
item.clusterShow = true;
if (!defined_default(item._labelCollection) && defined_default(item.id) && hasLabelIndex(entityCluster, item.id.id) && defined_default(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_default(entityCluster) && defined_default(entityCluster._collectionIndicesByEntity[entityId]) && defined_default(entityCluster._collectionIndicesByEntity[entityId].labelIndex);
}
function getScreenSpacePositions(collection, points, scene, occluder, entityCluster) {
if (!defined_default(collection)) {
return;
}
const length3 = collection.length;
for (let i = 0; i < length3; ++i) {
const item = collection.get(i);
item.clusterShow = false;
if (!item.show || entityCluster._scene.mode === SceneMode_default.SCENE3D && !occluder.isPointVisible(item.position)) {
continue;
}
const canClusterLabels = entityCluster._clusterLabels && defined_default(item._labelCollection);
const canClusterBillboards = entityCluster._clusterBillboards && defined_default(item.id._billboard);
const canClusterPoints = entityCluster._clusterPoints && defined_default(item.id._point);
if (canClusterLabels && (canClusterPoints || canClusterBillboards)) {
continue;
}
const coord = item.computeScreenSpacePosition(scene);
if (!defined_default(coord)) {
continue;
}
points.push({
index: i,
collection,
clustered: false,
coord
});
}
}
var pointBoundinRectangleScratch = new BoundingRectangle_default();
var totalBoundingRectangleScratch = new BoundingRectangle_default();
var neighborBoundingRectangleScratch = new BoundingRectangle_default();
function createDeclutterCallback(entityCluster) {
return function(amount) {
if (defined_default(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_default(labelCollection) && !defined_default(billboardCollection) && !defined_default(pointCollection) || !entityCluster._clusterBillboards && !entityCluster._clusterLabels && !entityCluster._clusterPoints) {
return;
}
let clusteredLabelCollection = entityCluster._clusterLabelCollection;
let clusteredBillboardCollection = entityCluster._clusterBillboardCollection;
let clusteredPointCollection = entityCluster._clusterPointCollection;
if (defined_default(clusteredLabelCollection)) {
clusteredLabelCollection.removeAll();
} else {
clusteredLabelCollection = entityCluster._clusterLabelCollection = new LabelCollection_default(
{
scene
}
);
}
if (defined_default(clusteredBillboardCollection)) {
clusteredBillboardCollection.removeAll();
} else {
clusteredBillboardCollection = entityCluster._clusterBillboardCollection = new BillboardCollection_default(
{
scene
}
);
}
if (defined_default(clusteredPointCollection)) {
clusteredPointCollection.removeAll();
} else {
clusteredPointCollection = entityCluster._clusterPointCollection = new PointPrimitiveCollection_default();
}
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_default(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 length3;
let bbox;
let neighbors;
let neighborLength;
let neighborIndex;
let neighborPoint;
let ids;
let numPoints;
let collection;
let collectionIndex;
if (points.length > 0) {
const index = new KDBush(points.length, 64, Uint32Array);
for (let p = 0; p < points.length; ++p) {
index.add(points[p].coord.x, points[p].coord.y);
}
index.finish();
if (currentHeight < previousHeight) {
length3 = clusters.length;
for (i = 0; i < length3; ++i) {
const cluster = clusters[i];
if (!occluder.isPointVisible(cluster.position)) {
continue;
}
const coord = Billboard_default._computeScreenSpacePosition(
Matrix4_default.IDENTITY,
cluster.position,
Cartesian3_default.ZERO,
Cartesian2_default.ZERO,
scene
);
if (!defined_default(coord)) {
continue;
}
const factor2 = 1 - currentHeight / previousHeight;
let width = cluster.width = cluster.width * factor2;
let height = cluster.height = cluster.height * factor2;
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;
}
}
}
}
length3 = points.length;
for (i = 0; i < length3; ++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_default.clone(
bbox,
totalBoundingRectangleScratch
);
neighbors = index.range(
bbox.x,
bbox.y,
bbox.x + bbox.width,
bbox.y + bbox.height
);
neighborLength = neighbors.length;
const clusterPosition = Cartesian3_default.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_default.add(
neighborItem.position,
clusterPosition,
clusterPosition
);
BoundingRectangle_default.union(totalBBox, neighborBBox, totalBBox);
++numPoints;
ids.push(neighborItem.id);
}
}
if (numPoints >= minimumClusterSize) {
const position = Cartesian3_default.multiplyByScalar(
clusterPosition,
1 / numPoints,
clusterPosition
);
addCluster(position, numPoints, ids, entityCluster);
newClusters.push({
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 = void 0;
}
if (clusteredBillboardCollection.length === 0) {
clusteredBillboardCollection.destroy();
entityCluster._clusterBillboardCollection = void 0;
}
if (clusteredPointCollection.length === 0) {
clusteredPointCollection.destroy();
entityCluster._clusterPointCollection = void 0;
}
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, {
enabled: {
get: function() {
return this._enabled;
},
set: function(value) {
this._enabledDirty = value !== this._enabled;
this._enabled = value;
}
},
pixelRange: {
get: function() {
return this._pixelRange;
},
set: function(value) {
this._clusterDirty = this._clusterDirty || value !== this._pixelRange;
this._pixelRange = value;
}
},
minimumClusterSize: {
get: function() {
return this._minimumClusterSize;
},
set: function(value) {
this._clusterDirty = this._clusterDirty || value !== this._minimumClusterSize;
this._minimumClusterSize = value;
}
},
clusterEvent: {
get: function() {
return this._clusterEvent;
}
},
clusterBillboards: {
get: function() {
return this._clusterBillboards;
},
set: function(value) {
this._clusterDirty = this._clusterDirty || value !== this._clusterBillboards;
this._clusterBillboards = value;
}
},
clusterLabels: {
get: function() {
return this._clusterLabels;
},
set: function(value) {
this._clusterDirty = this._clusterDirty || value !== this._clusterLabels;
this._clusterLabels = value;
}
},
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_default(this._collectionIndicesByEntity)) {
this._collectionIndicesByEntity = {};
}
let entityIndices = this._collectionIndicesByEntity[entity.id];
if (!defined_default(entityIndices)) {
entityIndices = this._collectionIndicesByEntity[entity.id] = {
billboardIndex: void 0,
labelIndex: void 0,
pointIndex: void 0
};
}
if (defined_default(collection) && defined_default(entityIndices[entityIndexProperty])) {
return collection.get(entityIndices[entityIndexProperty]);
}
if (!defined_default(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 indices2 = entityCluster._collectionIndicesByEntity[entityId];
if (!defined_default(indices2.billboardIndex) && !defined_default(indices2.labelIndex) && !defined_default(indices2.pointIndex)) {
delete entityCluster._collectionIndicesByEntity[entityId];
}
}
EntityCluster.prototype.getLabel = createGetEntity(
"_labelCollection",
LabelCollection_default,
"_unusedLabelIndices",
"labelIndex"
);
EntityCluster.prototype.removeLabel = function(entity) {
const entityIndices = this._collectionIndicesByEntity && this._collectionIndicesByEntity[entity.id];
if (!defined_default(this._labelCollection) || !defined_default(entityIndices) || !defined_default(entityIndices.labelIndex)) {
return;
}
const index = entityIndices.labelIndex;
entityIndices.labelIndex = void 0;
removeEntityIndicesIfUnused(this, entity.id);
const label = this._labelCollection.get(index);
label.show = false;
label.text = "";
label.id = void 0;
this._unusedLabelIndices.push(index);
this._clusterDirty = true;
};
EntityCluster.prototype.getBillboard = createGetEntity(
"_billboardCollection",
BillboardCollection_default,
"_unusedBillboardIndices",
"billboardIndex"
);
EntityCluster.prototype.removeBillboard = function(entity) {
const entityIndices = this._collectionIndicesByEntity && this._collectionIndicesByEntity[entity.id];
if (!defined_default(this._billboardCollection) || !defined_default(entityIndices) || !defined_default(entityIndices.billboardIndex)) {
return;
}
const index = entityIndices.billboardIndex;
entityIndices.billboardIndex = void 0;
removeEntityIndicesIfUnused(this, entity.id);
const billboard = this._billboardCollection.get(index);
billboard.id = void 0;
billboard.show = false;
billboard.image = void 0;
this._unusedBillboardIndices.push(index);
this._clusterDirty = true;
};
EntityCluster.prototype.getPoint = createGetEntity(
"_pointCollection",
PointPrimitiveCollection_default,
"_unusedPointIndices",
"pointIndex"
);
EntityCluster.prototype.removePoint = function(entity) {
const entityIndices = this._collectionIndicesByEntity && this._collectionIndicesByEntity[entity.id];
if (!defined_default(this._pointCollection) || !defined_default(entityIndices) || !defined_default(entityIndices.pointIndex)) {
return;
}
const index = entityIndices.pointIndex;
entityIndices.pointIndex = void 0;
removeEntityIndicesIfUnused(this, entity.id);
const point = this._pointCollection.get(index);
point.show = false;
point.id = void 0;
this._unusedPointIndices.push(index);
this._clusterDirty = true;
};
function disableCollectionClustering(collection) {
if (!defined_default(collection)) {
return;
}
const length3 = collection.length;
for (let i = 0; i < length3; ++i) {
collection.get(i).clusterShow = true;
}
}
function updateEnable(entityCluster) {
if (entityCluster.enabled) {
return;
}
if (defined_default(entityCluster._clusterLabelCollection)) {
entityCluster._clusterLabelCollection.destroy();
}
if (defined_default(entityCluster._clusterBillboardCollection)) {
entityCluster._clusterBillboardCollection.destroy();
}
if (defined_default(entityCluster._clusterPointCollection)) {
entityCluster._clusterPointCollection.destroy();
}
entityCluster._clusterLabelCollection = void 0;
entityCluster._clusterBillboardCollection = void 0;
entityCluster._clusterPointCollection = void 0;
disableCollectionClustering(entityCluster._labelCollection);
disableCollectionClustering(entityCluster._billboardCollection);
disableCollectionClustering(entityCluster._pointCollection);
}
EntityCluster.prototype.update = function(frameState) {
if (!this.show) {
return;
}
let commandList;
if (defined_default(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 (defined_default(this._billboardCollection) && this._billboardCollection.length > 0 && !defined_default(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_default(this._clusterLabelCollection)) {
this._clusterLabelCollection.update(frameState);
}
if (defined_default(this._clusterBillboardCollection)) {
this._clusterBillboardCollection.update(frameState);
}
if (defined_default(this._clusterPointCollection)) {
this._clusterPointCollection.update(frameState);
}
if (defined_default(this._labelCollection)) {
this._labelCollection.update(frameState);
}
if (defined_default(this._billboardCollection)) {
this._billboardCollection.update(frameState);
}
if (defined_default(this._pointCollection)) {
this._pointCollection.update(frameState);
}
};
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_default(this._removeEventListener)) {
this._removeEventListener();
this._removeEventListener = void 0;
}
this._labelCollection = void 0;
this._billboardCollection = void 0;
this._pointCollection = void 0;
this._clusterBillboardCollection = void 0;
this._clusterLabelCollection = void 0;
this._clusterPointCollection = void 0;
this._collectionIndicesByEntity = void 0;
this._unusedLabelIndices = [];
this._unusedBillboardIndices = [];
this._unusedPointIndices = [];
this._previousClusters = [];
this._previousHeight = void 0;
this._enabledDirty = false;
this._pixelRangeDirty = false;
this._minimumClusterSizeDirty = false;
return void 0;
};
var EntityCluster_default = EntityCluster;
// node_modules/@cesium/engine/Source/DataSources/CustomDataSource.js
function CustomDataSource(name) {
this._name = name;
this._clock = void 0;
this._changed = new Event_default();
this._error = new Event_default();
this._isLoading = false;
this._loading = new Event_default();
this._entityCollection = new EntityCollection_default(this);
this._entityCluster = new EntityCluster_default();
}
Object.defineProperties(CustomDataSource.prototype, {
name: {
get: function() {
return this._name;
},
set: function(value) {
if (this._name !== value) {
this._name = value;
this._changed.raiseEvent(this);
}
}
},
clock: {
get: function() {
return this._clock;
},
set: function(value) {
if (this._clock !== value) {
this._clock = value;
this._changed.raiseEvent(this);
}
}
},
entities: {
get: function() {
return this._entityCollection;
}
},
isLoading: {
get: function() {
return this._isLoading;
},
set: function(value) {
DataSource_default.setLoading(this, value);
}
},
changedEvent: {
get: function() {
return this._changed;
}
},
errorEvent: {
get: function() {
return this._error;
}
},
loadingEvent: {
get: function() {
return this._loading;
}
},
show: {
get: function() {
return this._entityCollection.show;
},
set: function(value) {
this._entityCollection.show = value;
}
},
clustering: {
get: function() {
return this._entityCluster;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value must be defined.");
}
this._entityCluster = value;
}
}
});
CustomDataSource.prototype.update = function(time) {
return true;
};
var CustomDataSource_default = CustomDataSource;
// node_modules/@cesium/engine/Source/Core/CylinderGeometryLibrary.js
var CylinderGeometryLibrary = {};
CylinderGeometryLibrary.computePositions = function(length3, topRadius, bottomRadius, slices, fill) {
const topZ = length3 * 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 * Math_default.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;
};
var CylinderGeometryLibrary_default = CylinderGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/CylinderGeometry.js
var radiusScratch = new Cartesian2_default();
var normalScratch3 = new Cartesian3_default();
var bitangentScratch = new Cartesian3_default();
var tangentScratch = new Cartesian3_default();
var positionScratch8 = new Cartesian3_default();
function CylinderGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const length3 = options.length;
const topRadius = options.topRadius;
const bottomRadius = options.bottomRadius;
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
const slices = defaultValue_default(options.slices, 128);
if (!defined_default(length3)) {
throw new DeveloperError_default("options.length must be defined.");
}
if (!defined_default(topRadius)) {
throw new DeveloperError_default("options.topRadius must be defined.");
}
if (!defined_default(bottomRadius)) {
throw new DeveloperError_default("options.bottomRadius must be defined.");
}
if (slices < 3) {
throw new DeveloperError_default(
"options.slices must be greater than or equal to 3."
);
}
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
this._length = length3;
this._topRadius = topRadius;
this._bottomRadius = bottomRadius;
this._vertexFormat = VertexFormat_default.clone(vertexFormat);
this._slices = slices;
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createCylinderGeometry";
}
CylinderGeometry.packedLength = VertexFormat_default.packedLength + 5;
CylinderGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.packedLength;
array[startingIndex++] = value._length;
array[startingIndex++] = value._topRadius;
array[startingIndex++] = value._bottomRadius;
array[startingIndex++] = value._slices;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchVertexFormat3 = new VertexFormat_default();
var scratchOptions9 = {
vertexFormat: scratchVertexFormat3,
length: void 0,
topRadius: void 0,
bottomRadius: void 0,
slices: void 0,
offsetAttribute: void 0
};
CylinderGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat3
);
startingIndex += VertexFormat_default.packedLength;
const length3 = array[startingIndex++];
const topRadius = array[startingIndex++];
const bottomRadius = array[startingIndex++];
const slices = array[startingIndex++];
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions9.length = length3;
scratchOptions9.topRadius = topRadius;
scratchOptions9.bottomRadius = bottomRadius;
scratchOptions9.slices = slices;
scratchOptions9.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new CylinderGeometry(scratchOptions9);
}
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
result._length = length3;
result._topRadius = topRadius;
result._bottomRadius = bottomRadius;
result._slices = slices;
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
CylinderGeometry.createGeometry = function(cylinderGeometry) {
let length3 = cylinderGeometry._length;
const topRadius = cylinderGeometry._topRadius;
const bottomRadius = cylinderGeometry._bottomRadius;
const vertexFormat = cylinderGeometry._vertexFormat;
const slices = cylinderGeometry._slices;
if (length3 <= 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_default.computePositions(
length3,
topRadius,
bottomRadius,
slices,
true
);
const st = vertexFormat.st ? new Float32Array(numVertices * 2) : void 0;
const normals = vertexFormat.normal ? new Float32Array(numVertices * 3) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(numVertices * 3) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(numVertices * 3) : void 0;
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, length3);
const normal2 = normalScratch3;
normal2.z = Math.sin(theta);
const normalScale2 = Math.cos(theta);
let tangent = tangentScratch;
let bitangent = bitangentScratch;
for (i = 0; i < slices; i++) {
const angle = i / slices * Math_default.TWO_PI;
const x = normalScale2 * Math.cos(angle);
const y = normalScale2 * Math.sin(angle);
if (computeNormal) {
normal2.x = x;
normal2.y = y;
if (computeTangent) {
tangent = Cartesian3_default.normalize(
Cartesian3_default.cross(Cartesian3_default.UNIT_Z, normal2, tangent),
tangent
);
}
if (vertexFormat.normal) {
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.z;
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.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_default.normalize(
Cartesian3_default.cross(normal2, 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 indices2 = IndexDatatype_default.createTypedArray(numVertices, numIndices);
let index = 0;
let j = 0;
for (i = 0; i < slices - 1; i++) {
indices2[index++] = j;
indices2[index++] = j + 2;
indices2[index++] = j + 3;
indices2[index++] = j;
indices2[index++] = j + 3;
indices2[index++] = j + 1;
j += 2;
}
indices2[index++] = twoSlices - 2;
indices2[index++] = 0;
indices2[index++] = 1;
indices2[index++] = twoSlices - 2;
indices2[index++] = 1;
indices2[index++] = twoSlices - 1;
for (i = 1; i < slices - 1; i++) {
indices2[index++] = twoSlices + i + 1;
indices2[index++] = twoSlices + i;
indices2[index++] = twoSlices;
}
for (i = 1; i < slices - 1; i++) {
indices2[index++] = threeSlices;
indices2[index++] = threeSlices + i;
indices2[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_default.fromArray(positions, i * 3, positionScratch8);
st[textureCoordIndex++] = (position.x + rad) / (2 * rad);
st[textureCoordIndex++] = (position.y + rad) / (2 * rad);
}
}
const attributes = new GeometryAttributes_default();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: st
});
}
radiusScratch.x = length3 * 0.5;
radiusScratch.y = Math.max(bottomRadius, topRadius);
const boundingSphere = new BoundingSphere_default(
Cartesian3_default.ZERO,
Cartesian2_default.magnitude(radiusScratch)
);
if (defined_default(cylinderGeometry._offsetAttribute)) {
length3 = positions.length;
const offsetValue = cylinderGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere,
offsetAttribute: cylinderGeometry._offsetAttribute
});
};
var unitCylinderGeometry;
CylinderGeometry.getUnitCylinder = function() {
if (!defined_default(unitCylinderGeometry)) {
unitCylinderGeometry = CylinderGeometry.createGeometry(
new CylinderGeometry({
topRadius: 1,
bottomRadius: 1,
length: 1,
vertexFormat: VertexFormat_default.POSITION_ONLY
})
);
}
return unitCylinderGeometry;
};
var CylinderGeometry_default = CylinderGeometry;
// node_modules/@cesium/engine/Source/Core/CylinderOutlineGeometry.js
var radiusScratch2 = new Cartesian2_default();
function CylinderOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const length3 = options.length;
const topRadius = options.topRadius;
const bottomRadius = options.bottomRadius;
const slices = defaultValue_default(options.slices, 128);
const numberOfVerticalLines = Math.max(
defaultValue_default(options.numberOfVerticalLines, 16),
0
);
Check_default.typeOf.number("options.positions", length3);
Check_default.typeOf.number("options.topRadius", topRadius);
Check_default.typeOf.number("options.bottomRadius", bottomRadius);
Check_default.typeOf.number.greaterThanOrEquals("options.slices", slices, 3);
if (defined_default(options.offsetAttribute) && options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
throw new DeveloperError_default(
"GeometryOffsetAttribute.TOP is not a supported options.offsetAttribute for this geometry."
);
}
this._length = length3;
this._topRadius = topRadius;
this._bottomRadius = bottomRadius;
this._slices = slices;
this._numberOfVerticalLines = numberOfVerticalLines;
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createCylinderOutlineGeometry";
}
CylinderOutlineGeometry.packedLength = 6;
CylinderOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(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_default(value._offsetAttribute, -1);
return array;
};
var scratchOptions10 = {
length: void 0,
topRadius: void 0,
bottomRadius: void 0,
slices: void 0,
numberOfVerticalLines: void 0,
offsetAttribute: void 0
};
CylinderOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const length3 = array[startingIndex++];
const topRadius = array[startingIndex++];
const bottomRadius = array[startingIndex++];
const slices = array[startingIndex++];
const numberOfVerticalLines = array[startingIndex++];
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions10.length = length3;
scratchOptions10.topRadius = topRadius;
scratchOptions10.bottomRadius = bottomRadius;
scratchOptions10.slices = slices;
scratchOptions10.numberOfVerticalLines = numberOfVerticalLines;
scratchOptions10.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new CylinderOutlineGeometry(scratchOptions10);
}
result._length = length3;
result._topRadius = topRadius;
result._bottomRadius = bottomRadius;
result._slices = slices;
result._numberOfVerticalLines = numberOfVerticalLines;
result._offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return result;
};
CylinderOutlineGeometry.createGeometry = function(cylinderGeometry) {
let length3 = cylinderGeometry._length;
const topRadius = cylinderGeometry._topRadius;
const bottomRadius = cylinderGeometry._bottomRadius;
const slices = cylinderGeometry._slices;
const numberOfVerticalLines = cylinderGeometry._numberOfVerticalLines;
if (length3 <= 0 || topRadius < 0 || bottomRadius < 0 || topRadius === 0 && bottomRadius === 0) {
return;
}
const numVertices = slices * 2;
const positions = CylinderGeometryLibrary_default.computePositions(
length3,
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 indices2 = IndexDatatype_default.createTypedArray(numVertices, numIndices * 2);
let index = 0;
let i;
for (i = 0; i < slices - 1; i++) {
indices2[index++] = i;
indices2[index++] = i + 1;
indices2[index++] = i + slices;
indices2[index++] = i + 1 + slices;
}
indices2[index++] = slices - 1;
indices2[index++] = 0;
indices2[index++] = slices + slices - 1;
indices2[index++] = slices;
if (numberOfVerticalLines > 0) {
for (i = 0; i < slices; i += numSide) {
indices2[index++] = i;
indices2[index++] = i + slices;
}
}
const attributes = new GeometryAttributes_default();
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
radiusScratch2.x = length3 * 0.5;
radiusScratch2.y = Math.max(bottomRadius, topRadius);
const boundingSphere = new BoundingSphere_default(
Cartesian3_default.ZERO,
Cartesian2_default.magnitude(radiusScratch2)
);
if (defined_default(cylinderGeometry._offsetAttribute)) {
length3 = positions.length;
const offsetValue = cylinderGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES,
boundingSphere,
offsetAttribute: cylinderGeometry._offsetAttribute
});
};
var CylinderOutlineGeometry_default = CylinderOutlineGeometry;
// node_modules/@cesium/engine/Source/DataSources/CylinderGeometryUpdater.js
var defaultOffset3 = Cartesian3_default.ZERO;
var offsetScratch6 = new Cartesian3_default();
var positionScratch9 = new Cartesian3_default();
var scratchColor12 = new Color_default();
function CylinderGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.length = void 0;
this.topRadius = void 0;
this.bottomRadius = void 0;
this.slices = void 0;
this.numberOfVerticalLines = void 0;
this.offsetAttribute = void 0;
}
function CylinderGeometryUpdater(entity, scene) {
GeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new CylinderGeometryOptions(entity),
geometryPropertyName: "cylinder",
observedPropertyNames: [
"availability",
"position",
"orientation",
"cylinder"
]
});
this._onEntityPropertyChanged(entity, "cylinder", entity.cylinder, void 0);
}
if (defined_default(Object.create)) {
CylinderGeometryUpdater.prototype = Object.create(GeometryUpdater_default.prototype);
CylinderGeometryUpdater.prototype.constructor = CylinderGeometryUpdater;
}
Object.defineProperties(CylinderGeometryUpdater.prototype, {
terrainOffsetProperty: {
get: function() {
return this._terrainOffsetProperty;
}
}
});
CylinderGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const show = new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
);
const attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: void 0,
offset: void 0
};
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor12);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
}
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset3,
offsetScratch6
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new CylinderGeometry_default(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.cylinder.heightReference,
this._options.length * 0.5,
this._scene.mapProjection.ellipsoid
),
attributes
});
};
CylinderGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor12
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
),
offset: void 0
};
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset3,
offsetScratch6
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new CylinderOutlineGeometry_default(this._options),
modelMatrix: entity.computeModelMatrixForHeightReference(
time,
entity.cylinder.heightReference,
this._options.length * 0.5,
this._scene.mapProjection.ellipsoid
),
attributes
});
};
CylinderGeometryUpdater.prototype._computeCenter = function(time, result) {
return Property_default.getValueOrUndefined(this._entity.position, time, result);
};
CylinderGeometryUpdater.prototype._isHidden = function(entity, cylinder) {
return !defined_default(entity.position) || !defined_default(cylinder.length) || !defined_default(cylinder.topRadius) || !defined_default(cylinder.bottomRadius) || GeometryUpdater_default.prototype._isHidden.call(this, entity, cylinder);
};
CylinderGeometryUpdater.prototype._isDynamic = function(entity, cylinder) {
return !entity.position.isConstant || !Property_default.isConstant(entity.orientation) || !cylinder.length.isConstant || !cylinder.topRadius.isConstant || !cylinder.bottomRadius.isConstant || !Property_default.isConstant(cylinder.slices) || !Property_default.isConstant(cylinder.outlineWidth) || !Property_default.isConstant(cylinder.numberOfVerticalLines);
};
CylinderGeometryUpdater.prototype._setStaticOptions = function(entity, cylinder) {
const heightReference = Property_default.getValueOrDefault(
cylinder.heightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
const options = this._options;
options.vertexFormat = this._materialProperty instanceof ColorMaterialProperty_default ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.length = cylinder.length.getValue(Iso8601_default.MINIMUM_VALUE);
options.topRadius = cylinder.topRadius.getValue(Iso8601_default.MINIMUM_VALUE);
options.bottomRadius = cylinder.bottomRadius.getValue(Iso8601_default.MINIMUM_VALUE);
options.slices = Property_default.getValueOrUndefined(
cylinder.slices,
Iso8601_default.MINIMUM_VALUE
);
options.numberOfVerticalLines = Property_default.getValueOrUndefined(
cylinder.numberOfVerticalLines,
Iso8601_default.MINIMUM_VALUE
);
options.offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0;
};
CylinderGeometryUpdater.prototype._onEntityPropertyChanged = heightReferenceOnEntityPropertyChanged_default;
CylinderGeometryUpdater.DynamicGeometryUpdater = DynamicCylinderGeometryUpdater;
function DynamicCylinderGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicCylinderGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicCylinderGeometryUpdater.prototype.constructor = DynamicCylinderGeometryUpdater;
}
DynamicCylinderGeometryUpdater.prototype._isHidden = function(entity, cylinder, time) {
const options = this._options;
const position = Property_default.getValueOrUndefined(
entity.position,
time,
positionScratch9
);
return !defined_default(position) || !defined_default(options.length) || !defined_default(options.topRadius) || !defined_default(options.bottomRadius) || DynamicGeometryUpdater_default.prototype._isHidden.call(
this,
entity,
cylinder,
time
);
};
DynamicCylinderGeometryUpdater.prototype._setOptions = function(entity, cylinder, time) {
const heightReference = Property_default.getValueOrDefault(
cylinder.heightReference,
time,
HeightReference_default.NONE
);
const options = this._options;
options.length = Property_default.getValueOrUndefined(cylinder.length, time);
options.topRadius = Property_default.getValueOrUndefined(cylinder.topRadius, time);
options.bottomRadius = Property_default.getValueOrUndefined(
cylinder.bottomRadius,
time
);
options.slices = Property_default.getValueOrUndefined(cylinder.slices, time);
options.numberOfVerticalLines = Property_default.getValueOrUndefined(
cylinder.numberOfVerticalLines,
time
);
options.offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0;
};
var CylinderGeometryUpdater_default = CylinderGeometryUpdater;
// node_modules/@cesium/engine/Source/Core/ClockRange.js
var ClockRange = {
UNBOUNDED: 0,
CLAMPED: 1,
LOOP_STOP: 2
};
var ClockRange_default = Object.freeze(ClockRange);
// node_modules/@cesium/engine/Source/Core/ClockStep.js
var ClockStep = {
TICK_DEPENDENT: 0,
SYSTEM_CLOCK_MULTIPLIER: 1,
SYSTEM_CLOCK: 2
};
var ClockStep_default = Object.freeze(ClockStep);
// node_modules/@cesium/engine/Source/Core/ExtrapolationType.js
var ExtrapolationType = {
NONE: 0,
HOLD: 1,
EXTRAPOLATE: 2
};
var ExtrapolationType_default = Object.freeze(ExtrapolationType);
// node_modules/@cesium/engine/Source/Core/getFilenameFromUri.js
var import_urijs9 = __toESM(require_URI(), 1);
function getFilenameFromUri(uri) {
if (!defined_default(uri)) {
throw new DeveloperError_default("uri is required.");
}
const uriObject = new import_urijs9.default(uri);
uriObject.normalize();
let path = uriObject.path();
const index = path.lastIndexOf("/");
if (index !== -1) {
path = path.substr(index + 1);
}
return path;
}
var getFilenameFromUri_default = getFilenameFromUri;
// node_modules/@cesium/engine/Source/Core/HermitePolynomialApproximation.js
var factorial = Math_default.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;
}
var HermitePolynomialApproximation = {
type: "Hermite"
};
HermitePolynomialApproximation.getRequiredDataPoints = function(degree, inputOrder) {
inputOrder = defaultValue_default(inputOrder, 0);
if (!defined_default(degree)) {
throw new DeveloperError_default("degree is required.");
}
if (degree < 0) {
throw new DeveloperError_default("degree must be 0 or greater.");
}
if (inputOrder < 0) {
throw new DeveloperError_default("inputOrder must be 0 or greater.");
}
return Math.max(Math.floor((degree + 1) / (inputOrder + 1)), 2);
};
HermitePolynomialApproximation.interpolateOrderZero = function(x, xTable, yTable, yStride, result) {
if (!defined_default(result)) {
result = new Array(yStride);
}
let i;
let j;
let d;
let s;
let len;
let index;
const length3 = xTable.length;
const coefficients = new Array(yStride);
for (i = 0; i < yStride; i++) {
result[i] = 0;
const l = new Array(length3);
coefficients[i] = l;
for (j = 0; j < length3; j++) {
l[j] = [];
}
}
const zIndicesLength = length3, zIndices = new Array(zIndicesLength);
for (i = 0; i < zIndicesLength; i++) {
zIndices[i] = i;
}
let highestNonZeroCoef = length3 - 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;
};
var arrayScratch = [];
HermitePolynomialApproximation.interpolate = function(x, xTable, yTable, yStride, inputOrder, outputOrder, result) {
const resultLength = yStride * (outputOrder + 1);
if (!defined_default(result)) {
result = new Array(resultLength);
}
for (let r = 0; r < resultLength; r++) {
result[r] = 0;
}
const length3 = xTable.length;
const zIndices = new Array(length3 * (inputOrder + 1));
let i;
for (i = 0; i < length3; 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 tmp2 = 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 * tmp2);
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 tmp2 = zIndiceslength * (zIndiceslength + 1) / 2;
for (let s = 0; s < yStride; s++) {
const dimOne = Math.floor(s * tmp2);
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 / Math_default.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;
}
if (nonZeroCoefficients) {
highestNonZero = Math.max(highestNonZero, i);
}
}
}
return highestNonZero;
}
var HermitePolynomialApproximation_default = HermitePolynomialApproximation;
// node_modules/@cesium/engine/Source/Core/LagrangePolynomialApproximation.js
var LagrangePolynomialApproximation = {
type: "Lagrange"
};
LagrangePolynomialApproximation.getRequiredDataPoints = function(degree) {
return Math.max(degree + 1, 2);
};
LagrangePolynomialApproximation.interpolateOrderZero = function(x, xTable, yTable, yStride, result) {
if (!defined_default(result)) {
result = new Array(yStride);
}
let i;
let j;
const length3 = xTable.length;
for (i = 0; i < yStride; i++) {
result[i] = 0;
}
for (i = 0; i < length3; i++) {
let coefficient = 1;
for (j = 0; j < length3; 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;
};
var LagrangePolynomialApproximation_default = LagrangePolynomialApproximation;
// node_modules/@cesium/engine/Source/Core/LinearApproximation.js
var LinearApproximation = {
type: "Linear"
};
LinearApproximation.getRequiredDataPoints = function(degree) {
return 2;
};
LinearApproximation.interpolateOrderZero = function(x, xTable, yTable, yStride, result) {
if (xTable.length !== 2) {
throw new DeveloperError_default(
"The xTable provided to the linear interpolator must have exactly two elements."
);
} else if (yStride <= 0) {
throw new DeveloperError_default(
"There must be at least 1 dependent variable for each independent variable."
);
}
if (!defined_default(result)) {
result = new Array(yStride);
}
let i;
let y0;
let y1;
const x0 = xTable[0];
const x1 = xTable[1];
if (x0 === x1) {
throw new DeveloperError_default(
"Divide by zero error: xTable[0] and xTable[1] are equal"
);
}
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;
};
var LinearApproximation_default = LinearApproximation;
// node_modules/@cesium/engine/Source/Core/Spherical.js
function Spherical(clock, cone, magnitude) {
this.clock = defaultValue_default(clock, 0);
this.cone = defaultValue_default(cone, 0);
this.magnitude = defaultValue_default(magnitude, 1);
}
Spherical.fromCartesian3 = function(cartesian34, result) {
Check_default.typeOf.object("cartesian3", cartesian34);
const x = cartesian34.x;
const y = cartesian34.y;
const z = cartesian34.z;
const radialSquared = x * x + y * y;
if (!defined_default(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;
};
Spherical.clone = function(spherical, result) {
if (!defined_default(spherical)) {
return void 0;
}
if (!defined_default(result)) {
return new Spherical(spherical.clock, spherical.cone, spherical.magnitude);
}
result.clock = spherical.clock;
result.cone = spherical.cone;
result.magnitude = spherical.magnitude;
return result;
};
Spherical.normalize = function(spherical, result) {
Check_default.typeOf.object("spherical", spherical);
if (!defined_default(result)) {
return new Spherical(spherical.clock, spherical.cone, 1);
}
result.clock = spherical.clock;
result.cone = spherical.cone;
result.magnitude = 1;
return result;
};
Spherical.equals = function(left, right) {
return left === right || defined_default(left) && defined_default(right) && left.clock === right.clock && left.cone === right.cone && left.magnitude === right.magnitude;
};
Spherical.equalsEpsilon = function(left, right, epsilon) {
epsilon = defaultValue_default(epsilon, 0);
return left === right || defined_default(left) && defined_default(right) && Math.abs(left.clock - right.clock) <= epsilon && Math.abs(left.cone - right.cone) <= epsilon && Math.abs(left.magnitude - right.magnitude) <= epsilon;
};
Spherical.prototype.equals = function(other) {
return Spherical.equals(this, other);
};
Spherical.prototype.clone = function(result) {
return Spherical.clone(this, result);
};
Spherical.prototype.equalsEpsilon = function(other, epsilon) {
return Spherical.equalsEpsilon(this, other, epsilon);
};
Spherical.prototype.toString = function() {
return `(${this.clock}, ${this.cone}, ${this.magnitude})`;
};
var Spherical_default = Spherical;
// node_modules/@cesium/engine/Source/DataSources/CzmlDataSource.js
var import_urijs10 = __toESM(require_URI(), 1);
// node_modules/@cesium/engine/Source/Core/getTimestamp.js
var 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_default = getTimestamp;
// node_modules/@cesium/engine/Source/Core/Clock.js
function Clock(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let currentTime = options.currentTime;
let startTime = options.startTime;
let stopTime = options.stopTime;
if (!defined_default(currentTime)) {
if (defined_default(startTime)) {
currentTime = JulianDate_default.clone(startTime);
} else if (defined_default(stopTime)) {
currentTime = JulianDate_default.addDays(stopTime, -1, new JulianDate_default());
} else {
currentTime = JulianDate_default.now();
}
} else {
currentTime = JulianDate_default.clone(currentTime);
}
if (!defined_default(startTime)) {
startTime = JulianDate_default.clone(currentTime);
} else {
startTime = JulianDate_default.clone(startTime);
}
if (!defined_default(stopTime)) {
stopTime = JulianDate_default.addDays(startTime, 1, new JulianDate_default());
} else {
stopTime = JulianDate_default.clone(stopTime);
}
if (JulianDate_default.greaterThan(startTime, stopTime)) {
throw new DeveloperError_default("startTime must come before stopTime.");
}
this.startTime = startTime;
this.stopTime = stopTime;
this.clockRange = defaultValue_default(options.clockRange, ClockRange_default.UNBOUNDED);
this.canAnimate = defaultValue_default(options.canAnimate, true);
this.onTick = new Event_default();
this.onStop = new Event_default();
this._currentTime = void 0;
this._multiplier = void 0;
this._clockStep = void 0;
this._shouldAnimate = void 0;
this._lastSystemTime = getTimestamp_default();
this.currentTime = currentTime;
this.multiplier = defaultValue_default(options.multiplier, 1);
this.shouldAnimate = defaultValue_default(options.shouldAnimate, false);
this.clockStep = defaultValue_default(
options.clockStep,
ClockStep_default.SYSTEM_CLOCK_MULTIPLIER
);
}
Object.defineProperties(Clock.prototype, {
currentTime: {
get: function() {
return this._currentTime;
},
set: function(value) {
if (JulianDate_default.equals(this._currentTime, value)) {
return;
}
if (this._clockStep === ClockStep_default.SYSTEM_CLOCK) {
this._clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
}
this._currentTime = value;
}
},
multiplier: {
get: function() {
return this._multiplier;
},
set: function(value) {
if (this._multiplier === value) {
return;
}
if (this._clockStep === ClockStep_default.SYSTEM_CLOCK) {
this._clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
}
this._multiplier = value;
}
},
clockStep: {
get: function() {
return this._clockStep;
},
set: function(value) {
if (value === ClockStep_default.SYSTEM_CLOCK) {
this._multiplier = 1;
this._shouldAnimate = true;
this._currentTime = JulianDate_default.now();
}
this._clockStep = value;
}
},
shouldAnimate: {
get: function() {
return this._shouldAnimate;
},
set: function(value) {
if (this._shouldAnimate === value) {
return;
}
if (this._clockStep === ClockStep_default.SYSTEM_CLOCK) {
this._clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
}
this._shouldAnimate = value;
}
}
});
Clock.prototype.tick = function() {
const currentSystemTime = getTimestamp_default();
let currentTime = JulianDate_default.clone(this._currentTime);
if (this.canAnimate && this._shouldAnimate) {
const clockStep = this._clockStep;
if (clockStep === ClockStep_default.SYSTEM_CLOCK) {
currentTime = JulianDate_default.now(currentTime);
} else {
const multiplier = this._multiplier;
if (clockStep === ClockStep_default.TICK_DEPENDENT) {
currentTime = JulianDate_default.addSeconds(
currentTime,
multiplier,
currentTime
);
} else {
const milliseconds = currentSystemTime - this._lastSystemTime;
currentTime = JulianDate_default.addSeconds(
currentTime,
multiplier * (milliseconds / 1e3),
currentTime
);
}
const clockRange = this.clockRange;
const startTime = this.startTime;
const stopTime = this.stopTime;
if (clockRange === ClockRange_default.CLAMPED) {
if (JulianDate_default.lessThan(currentTime, startTime)) {
currentTime = JulianDate_default.clone(startTime, currentTime);
} else if (JulianDate_default.greaterThan(currentTime, stopTime)) {
currentTime = JulianDate_default.clone(stopTime, currentTime);
this.onStop.raiseEvent(this);
}
} else if (clockRange === ClockRange_default.LOOP_STOP) {
if (JulianDate_default.lessThan(currentTime, startTime)) {
currentTime = JulianDate_default.clone(startTime, currentTime);
}
while (JulianDate_default.greaterThan(currentTime, stopTime)) {
currentTime = JulianDate_default.addSeconds(
startTime,
JulianDate_default.secondsDifference(currentTime, stopTime),
currentTime
);
this.onStop.raiseEvent(this);
}
}
}
}
this._currentTime = currentTime;
this._lastSystemTime = currentSystemTime;
this.onTick.raiseEvent(this);
return currentTime;
};
var Clock_default = Clock;
// node_modules/@cesium/engine/Source/DataSources/DataSourceClock.js
function DataSourceClock() {
this._definitionChanged = new Event_default();
this._startTime = void 0;
this._stopTime = void 0;
this._currentTime = void 0;
this._clockRange = void 0;
this._clockStep = void 0;
this._multiplier = void 0;
}
Object.defineProperties(DataSourceClock.prototype, {
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
startTime: createRawPropertyDescriptor_default("startTime"),
stopTime: createRawPropertyDescriptor_default("stopTime"),
currentTime: createRawPropertyDescriptor_default("currentTime"),
clockRange: createRawPropertyDescriptor_default("clockRange"),
clockStep: createRawPropertyDescriptor_default("clockStep"),
multiplier: createRawPropertyDescriptor_default("multiplier")
});
DataSourceClock.prototype.clone = function(result) {
if (!defined_default(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;
};
DataSourceClock.prototype.equals = function(other) {
return this === other || defined_default(other) && JulianDate_default.equals(this.startTime, other.startTime) && JulianDate_default.equals(this.stopTime, other.stopTime) && JulianDate_default.equals(this.currentTime, other.currentTime) && this.clockRange === other.clockRange && this.clockStep === other.clockStep && this.multiplier === other.multiplier;
};
DataSourceClock.prototype.merge = function(source) {
if (!defined_default(source)) {
throw new DeveloperError_default("source is required.");
}
this.startTime = defaultValue_default(this.startTime, source.startTime);
this.stopTime = defaultValue_default(this.stopTime, source.stopTime);
this.currentTime = defaultValue_default(this.currentTime, source.currentTime);
this.clockRange = defaultValue_default(this.clockRange, source.clockRange);
this.clockStep = defaultValue_default(this.clockStep, source.clockStep);
this.multiplier = defaultValue_default(this.multiplier, source.multiplier);
};
DataSourceClock.prototype.getValue = function(result) {
if (!defined_default(result)) {
result = new Clock_default();
}
result.startTime = defaultValue_default(this.startTime, result.startTime);
result.stopTime = defaultValue_default(this.stopTime, result.stopTime);
result.currentTime = defaultValue_default(this.currentTime, result.currentTime);
result.clockRange = defaultValue_default(this.clockRange, result.clockRange);
result.multiplier = defaultValue_default(this.multiplier, result.multiplier);
result.clockStep = defaultValue_default(this.clockStep, result.clockStep);
return result;
};
var DataSourceClock_default = DataSourceClock;
// node_modules/@cesium/engine/Source/DataSources/GridMaterialProperty.js
var defaultColor3 = Color_default.WHITE;
var defaultCellAlpha = 0.1;
var defaultLineCount = new Cartesian2_default(8, 8);
var defaultLineOffset = new Cartesian2_default(0, 0);
var defaultLineThickness = new Cartesian2_default(1, 1);
function GridMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._color = void 0;
this._colorSubscription = void 0;
this._cellAlpha = void 0;
this._cellAlphaSubscription = void 0;
this._lineCount = void 0;
this._lineCountSubscription = void 0;
this._lineThickness = void 0;
this._lineThicknessSubscription = void 0;
this._lineOffset = void 0;
this._lineOffsetSubscription = void 0;
this.color = options.color;
this.cellAlpha = options.cellAlpha;
this.lineCount = options.lineCount;
this.lineThickness = options.lineThickness;
this.lineOffset = options.lineOffset;
}
Object.defineProperties(GridMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._color) && Property_default.isConstant(this._cellAlpha) && Property_default.isConstant(this._lineCount) && Property_default.isConstant(this._lineThickness) && Property_default.isConstant(this._lineOffset);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
color: createPropertyDescriptor_default("color"),
cellAlpha: createPropertyDescriptor_default("cellAlpha"),
lineCount: createPropertyDescriptor_default("lineCount"),
lineThickness: createPropertyDescriptor_default("lineThickness"),
lineOffset: createPropertyDescriptor_default("lineOffset")
});
GridMaterialProperty.prototype.getType = function(time) {
return "Grid";
};
GridMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
defaultColor3,
result.color
);
result.cellAlpha = Property_default.getValueOrDefault(
this._cellAlpha,
time,
defaultCellAlpha
);
result.lineCount = Property_default.getValueOrClonedDefault(
this._lineCount,
time,
defaultLineCount,
result.lineCount
);
result.lineThickness = Property_default.getValueOrClonedDefault(
this._lineThickness,
time,
defaultLineThickness,
result.lineThickness
);
result.lineOffset = Property_default.getValueOrClonedDefault(
this._lineOffset,
time,
defaultLineOffset,
result.lineOffset
);
return result;
};
GridMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof GridMaterialProperty && Property_default.equals(this._color, other._color) && Property_default.equals(this._cellAlpha, other._cellAlpha) && Property_default.equals(this._lineCount, other._lineCount) && Property_default.equals(this._lineThickness, other._lineThickness) && Property_default.equals(this._lineOffset, other._lineOffset);
};
var GridMaterialProperty_default = GridMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/PolylineArrowMaterialProperty.js
function PolylineArrowMaterialProperty(color) {
this._definitionChanged = new Event_default();
this._color = void 0;
this._colorSubscription = void 0;
this.color = color;
}
Object.defineProperties(PolylineArrowMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._color);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
color: createPropertyDescriptor_default("color")
});
PolylineArrowMaterialProperty.prototype.getType = function(time) {
return "PolylineArrow";
};
PolylineArrowMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
Color_default.WHITE,
result.color
);
return result;
};
PolylineArrowMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof PolylineArrowMaterialProperty && Property_default.equals(this._color, other._color);
};
var PolylineArrowMaterialProperty_default = PolylineArrowMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/PolylineDashMaterialProperty.js
var defaultColor4 = Color_default.WHITE;
var defaultGapColor = Color_default.TRANSPARENT;
var defaultDashLength = 16;
var defaultDashPattern = 255;
function PolylineDashMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._color = void 0;
this._colorSubscription = void 0;
this._gapColor = void 0;
this._gapColorSubscription = void 0;
this._dashLength = void 0;
this._dashLengthSubscription = void 0;
this._dashPattern = void 0;
this._dashPatternSubscription = void 0;
this.color = options.color;
this.gapColor = options.gapColor;
this.dashLength = options.dashLength;
this.dashPattern = options.dashPattern;
}
Object.defineProperties(PolylineDashMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._color) && Property_default.isConstant(this._gapColor) && Property_default.isConstant(this._dashLength) && Property_default.isConstant(this._dashPattern);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
color: createPropertyDescriptor_default("color"),
gapColor: createPropertyDescriptor_default("gapColor"),
dashLength: createPropertyDescriptor_default("dashLength"),
dashPattern: createPropertyDescriptor_default("dashPattern")
});
PolylineDashMaterialProperty.prototype.getType = function(time) {
return "PolylineDash";
};
PolylineDashMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
defaultColor4,
result.color
);
result.gapColor = Property_default.getValueOrClonedDefault(
this._gapColor,
time,
defaultGapColor,
result.gapColor
);
result.dashLength = Property_default.getValueOrDefault(
this._dashLength,
time,
defaultDashLength,
result.dashLength
);
result.dashPattern = Property_default.getValueOrDefault(
this._dashPattern,
time,
defaultDashPattern,
result.dashPattern
);
return result;
};
PolylineDashMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof PolylineDashMaterialProperty && Property_default.equals(this._color, other._color) && Property_default.equals(this._gapColor, other._gapColor) && Property_default.equals(this._dashLength, other._dashLength) && Property_default.equals(this._dashPattern, other._dashPattern);
};
var PolylineDashMaterialProperty_default = PolylineDashMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/PolylineGlowMaterialProperty.js
var defaultColor5 = Color_default.WHITE;
var defaultGlowPower = 0.25;
var defaultTaperPower = 1;
function PolylineGlowMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._color = void 0;
this._colorSubscription = void 0;
this._glowPower = void 0;
this._glowPowerSubscription = void 0;
this._taperPower = void 0;
this._taperPowerSubscription = void 0;
this.color = options.color;
this.glowPower = options.glowPower;
this.taperPower = options.taperPower;
}
Object.defineProperties(PolylineGlowMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._color) && Property_default.isConstant(this._glow);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
color: createPropertyDescriptor_default("color"),
glowPower: createPropertyDescriptor_default("glowPower"),
taperPower: createPropertyDescriptor_default("taperPower")
});
PolylineGlowMaterialProperty.prototype.getType = function(time) {
return "PolylineGlow";
};
PolylineGlowMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
defaultColor5,
result.color
);
result.glowPower = Property_default.getValueOrDefault(
this._glowPower,
time,
defaultGlowPower,
result.glowPower
);
result.taperPower = Property_default.getValueOrDefault(
this._taperPower,
time,
defaultTaperPower,
result.taperPower
);
return result;
};
PolylineGlowMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof PolylineGlowMaterialProperty && Property_default.equals(this._color, other._color) && Property_default.equals(this._glowPower, other._glowPower) && Property_default.equals(this._taperPower, other._taperPower);
};
var PolylineGlowMaterialProperty_default = PolylineGlowMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/PolylineOutlineMaterialProperty.js
var defaultColor6 = Color_default.WHITE;
var defaultOutlineColor2 = Color_default.BLACK;
var defaultOutlineWidth = 1;
function PolylineOutlineMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._color = void 0;
this._colorSubscription = void 0;
this._outlineColor = void 0;
this._outlineColorSubscription = void 0;
this._outlineWidth = void 0;
this._outlineWidthSubscription = void 0;
this.color = options.color;
this.outlineColor = options.outlineColor;
this.outlineWidth = options.outlineWidth;
}
Object.defineProperties(PolylineOutlineMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._color) && Property_default.isConstant(this._outlineColor) && Property_default.isConstant(this._outlineWidth);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
color: createPropertyDescriptor_default("color"),
outlineColor: createPropertyDescriptor_default("outlineColor"),
outlineWidth: createPropertyDescriptor_default("outlineWidth")
});
PolylineOutlineMaterialProperty.prototype.getType = function(time) {
return "PolylineOutline";
};
PolylineOutlineMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.color = Property_default.getValueOrClonedDefault(
this._color,
time,
defaultColor6,
result.color
);
result.outlineColor = Property_default.getValueOrClonedDefault(
this._outlineColor,
time,
defaultOutlineColor2,
result.outlineColor
);
result.outlineWidth = Property_default.getValueOrDefault(
this._outlineWidth,
time,
defaultOutlineWidth
);
return result;
};
PolylineOutlineMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof PolylineOutlineMaterialProperty && Property_default.equals(this._color, other._color) && Property_default.equals(this._outlineColor, other._outlineColor) && Property_default.equals(this._outlineWidth, other._outlineWidth);
};
var PolylineOutlineMaterialProperty_default = PolylineOutlineMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/PositionPropertyArray.js
function PositionPropertyArray(value, referenceFrame) {
this._value = void 0;
this._definitionChanged = new Event_default();
this._eventHelper = new EventHelper_default();
this._referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
this.setValue(value);
}
Object.defineProperties(PositionPropertyArray.prototype, {
isConstant: {
get: function() {
const value = this._value;
if (!defined_default(value)) {
return true;
}
const length3 = value.length;
for (let i = 0; i < length3; i++) {
if (!Property_default.isConstant(value[i])) {
return false;
}
}
return true;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
referenceFrame: {
get: function() {
return this._referenceFrame;
}
}
});
PositionPropertyArray.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
PositionPropertyArray.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!defined_default(referenceFrame)) {
throw new DeveloperError_default("referenceFrame is required.");
}
const value = this._value;
if (!defined_default(value)) {
return void 0;
}
const length3 = value.length;
if (!defined_default(result)) {
result = new Array(length3);
}
let i = 0;
let x = 0;
while (i < length3) {
const property = value[i];
const itemValue = property.getValueInReferenceFrame(
time,
referenceFrame,
result[i]
);
if (defined_default(itemValue)) {
result[x] = itemValue;
x++;
}
i++;
}
result.length = x;
return result;
};
PositionPropertyArray.prototype.setValue = function(value) {
const eventHelper = this._eventHelper;
eventHelper.removeAll();
if (defined_default(value)) {
this._value = value.slice();
const length3 = value.length;
for (let i = 0; i < length3; i++) {
const property = value[i];
if (defined_default(property)) {
eventHelper.add(
property.definitionChanged,
PositionPropertyArray.prototype._raiseDefinitionChanged,
this
);
}
}
} else {
this._value = void 0;
}
this._definitionChanged.raiseEvent(this);
};
PositionPropertyArray.prototype.equals = function(other) {
return this === other || other instanceof PositionPropertyArray && this._referenceFrame === other._referenceFrame && Property_default.arrayEquals(this._value, other._value);
};
PositionPropertyArray.prototype._raiseDefinitionChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var PositionPropertyArray_default = PositionPropertyArray;
// node_modules/@cesium/engine/Source/DataSources/PropertyArray.js
function PropertyArray(value) {
this._value = void 0;
this._definitionChanged = new Event_default();
this._eventHelper = new EventHelper_default();
this.setValue(value);
}
Object.defineProperties(PropertyArray.prototype, {
isConstant: {
get: function() {
const value = this._value;
if (!defined_default(value)) {
return true;
}
const length3 = value.length;
for (let i = 0; i < length3; i++) {
if (!Property_default.isConstant(value[i])) {
return false;
}
}
return true;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
}
});
PropertyArray.prototype.getValue = function(time, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
const value = this._value;
if (!defined_default(value)) {
return void 0;
}
const length3 = value.length;
if (!defined_default(result)) {
result = new Array(length3);
}
let i = 0;
let x = 0;
while (i < length3) {
const property = this._value[i];
const itemValue = property.getValue(time, result[i]);
if (defined_default(itemValue)) {
result[x] = itemValue;
x++;
}
i++;
}
result.length = x;
return result;
};
PropertyArray.prototype.setValue = function(value) {
const eventHelper = this._eventHelper;
eventHelper.removeAll();
if (defined_default(value)) {
this._value = value.slice();
const length3 = value.length;
for (let i = 0; i < length3; i++) {
const property = value[i];
if (defined_default(property)) {
eventHelper.add(
property.definitionChanged,
PropertyArray.prototype._raiseDefinitionChanged,
this
);
}
}
} else {
this._value = void 0;
}
this._definitionChanged.raiseEvent(this);
};
PropertyArray.prototype.equals = function(other) {
return this === other || other instanceof PropertyArray && Property_default.arrayEquals(this._value, other._value);
};
PropertyArray.prototype._raiseDefinitionChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var PropertyArray_default = PropertyArray;
// node_modules/@cesium/engine/Source/DataSources/ReferenceProperty.js
function resolve(that) {
let targetProperty = that._targetProperty;
if (!defined_default(targetProperty)) {
let targetEntity = that._targetEntity;
if (!defined_default(targetEntity)) {
targetEntity = that._targetCollection.getById(that._targetId);
if (!defined_default(targetEntity)) {
that._targetEntity = that._targetProperty = void 0;
return;
}
targetEntity.definitionChanged.addEventListener(
ReferenceProperty.prototype._onTargetEntityDefinitionChanged,
that
);
that._targetEntity = targetEntity;
}
const targetPropertyNames = that._targetPropertyNames;
targetProperty = that._targetEntity;
for (let i = 0, len = targetPropertyNames.length; i < len && defined_default(targetProperty); ++i) {
targetProperty = targetProperty[targetPropertyNames[i]];
}
that._targetProperty = targetProperty;
}
return targetProperty;
}
function ReferenceProperty(targetCollection, targetId, targetPropertyNames) {
if (!defined_default(targetCollection)) {
throw new DeveloperError_default("targetCollection is required.");
}
if (!defined_default(targetId) || targetId === "") {
throw new DeveloperError_default("targetId is required.");
}
if (!defined_default(targetPropertyNames) || targetPropertyNames.length === 0) {
throw new DeveloperError_default("targetPropertyNames is required.");
}
for (let i = 0; i < targetPropertyNames.length; i++) {
const item = targetPropertyNames[i];
if (!defined_default(item) || item === "") {
throw new DeveloperError_default("reference contains invalid properties.");
}
}
this._targetCollection = targetCollection;
this._targetId = targetId;
this._targetPropertyNames = targetPropertyNames;
this._targetProperty = void 0;
this._targetEntity = void 0;
this._definitionChanged = new Event_default();
targetCollection.collectionChanged.addEventListener(
ReferenceProperty.prototype._onCollectionChanged,
this
);
}
Object.defineProperties(ReferenceProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(resolve(this));
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
referenceFrame: {
get: function() {
const target = resolve(this);
return defined_default(target) ? target.referenceFrame : void 0;
}
},
targetId: {
get: function() {
return this._targetId;
}
},
targetCollection: {
get: function() {
return this._targetCollection;
}
},
targetPropertyNames: {
get: function() {
return this._targetPropertyNames;
}
},
resolvedProperty: {
get: function() {
return resolve(this);
}
}
});
ReferenceProperty.fromString = function(targetCollection, referenceString) {
if (!defined_default(targetCollection)) {
throw new DeveloperError_default("targetCollection is required.");
}
if (!defined_default(referenceString)) {
throw new DeveloperError_default("referenceString is required.");
}
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);
};
ReferenceProperty.prototype.getValue = function(time, result) {
const target = resolve(this);
return defined_default(target) ? target.getValue(time, result) : void 0;
};
ReferenceProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
const target = resolve(this);
return defined_default(target) ? target.getValueInReferenceFrame(time, referenceFrame, result) : void 0;
};
ReferenceProperty.prototype.getType = function(time) {
const target = resolve(this);
return defined_default(target) ? target.getType(time) : void 0;
};
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 length3 = this._targetPropertyNames.length;
for (let i = 0; i < length3; i++) {
if (names[i] !== otherNames[i]) {
return false;
}
}
return true;
};
ReferenceProperty.prototype._onTargetEntityDefinitionChanged = function(targetEntity, name, value, oldValue2) {
if (defined_default(this._targetProperty) && this._targetPropertyNames[0] === name) {
this._targetProperty = void 0;
this._definitionChanged.raiseEvent(this);
}
};
ReferenceProperty.prototype._onCollectionChanged = function(collection, added, removed) {
let targetEntity = this._targetEntity;
if (defined_default(targetEntity) && removed.indexOf(targetEntity) !== -1) {
targetEntity.definitionChanged.removeEventListener(
ReferenceProperty.prototype._onTargetEntityDefinitionChanged,
this
);
this._targetEntity = this._targetProperty = void 0;
} else if (!defined_default(targetEntity)) {
targetEntity = resolve(this);
if (defined_default(targetEntity)) {
this._definitionChanged.raiseEvent(this);
}
}
};
var ReferenceProperty_default = ReferenceProperty;
// node_modules/@cesium/engine/Source/DataSources/Rotation.js
var Rotation = {
packedLength: 1,
pack: function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex] = value;
return array;
},
unpack: function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
return array[startingIndex];
},
convertPackedArrayForInterpolation: function(packedArray, startingIndex, lastIndex, result) {
if (!defined_default(packedArray)) {
throw new DeveloperError_default("packedArray is required");
}
if (!defined_default(result)) {
result = [];
}
startingIndex = defaultValue_default(startingIndex, 0);
lastIndex = defaultValue_default(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 - Math_default.TWO_PI;
}
previousValue = value;
}
},
unpackInterpolationResult: function(array, sourceArray, firstIndex, lastIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
if (!defined_default(sourceArray)) {
throw new DeveloperError_default("sourceArray is required");
}
result = array[0];
if (result < 0) {
return result + Math_default.TWO_PI;
}
return result;
}
};
var Rotation_default = Rotation;
// node_modules/@cesium/engine/Source/DataSources/SampledProperty.js
var PackableNumber = {
packedLength: 1,
pack: function(value, array, startingIndex) {
startingIndex = defaultValue_default(startingIndex, 0);
array[startingIndex] = value;
},
unpack: function(array, startingIndex, result) {
startingIndex = defaultValue_default(startingIndex, 0);
return array[startingIndex];
}
};
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, epoch2) {
if (date instanceof JulianDate_default) {
return date;
}
if (typeof date === "string") {
return JulianDate_default.fromIso8601(date);
}
return JulianDate_default.addSeconds(epoch2, date, new JulianDate_default());
}
var timesSpliceArgs = [];
var valuesSpliceArgs = [];
function mergeNewSamples(epoch2, 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], epoch2);
timesInsertionPoint = binarySearch_default(times, currentTime, JulianDate_default.compare);
let timesSpliceArgsCount = 0;
let valuesSpliceArgsCount = 0;
if (timesInsertionPoint < 0) {
timesInsertionPoint = ~timesInsertionPoint;
valuesInsertionPoint = timesInsertionPoint * packedLength;
prevItem = void 0;
nextTime = times[timesInsertionPoint];
while (newDataIndex < newData.length) {
currentTime = convertDate(newData[newDataIndex], epoch2);
if (defined_default(prevItem) && JulianDate_default.compare(prevItem, currentTime) >= 0 || defined_default(nextTime) && JulianDate_default.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 {
for (i = 0; i < packedLength; i++) {
newDataIndex++;
values[timesInsertionPoint * packedLength + i] = newData[newDataIndex];
}
newDataIndex++;
}
}
}
function SampledProperty(type, derivativeTypes) {
Check_default.defined("type", type);
let innerType = type;
if (innerType === Number) {
innerType = PackableNumber;
}
let packedLength = innerType.packedLength;
let packedInterpolationLength = defaultValue_default(
innerType.packedInterpolationLength,
packedLength
);
let inputOrder = 0;
let innerDerivativeTypes;
if (defined_default(derivativeTypes)) {
const length3 = derivativeTypes.length;
innerDerivativeTypes = new Array(length3);
for (let i = 0; i < length3; i++) {
let derivativeType = derivativeTypes[i];
if (derivativeType === Number) {
derivativeType = PackableNumber;
}
const derivativePackedLength = derivativeType.packedLength;
packedLength += derivativePackedLength;
packedInterpolationLength += defaultValue_default(
derivativeType.packedInterpolationLength,
derivativePackedLength
);
innerDerivativeTypes[i] = derivativeType;
}
inputOrder = length3;
}
this._type = type;
this._innerType = innerType;
this._interpolationDegree = 1;
this._interpolationAlgorithm = LinearApproximation_default;
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_default();
this._derivativeTypes = derivativeTypes;
this._innerDerivativeTypes = innerDerivativeTypes;
this._inputOrder = inputOrder;
this._forwardExtrapolationType = ExtrapolationType_default.NONE;
this._forwardExtrapolationDuration = 0;
this._backwardExtrapolationType = ExtrapolationType_default.NONE;
this._backwardExtrapolationDuration = 0;
}
Object.defineProperties(SampledProperty.prototype, {
isConstant: {
get: function() {
return this._values.length === 0;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
type: {
get: function() {
return this._type;
}
},
derivativeTypes: {
get: function() {
return this._derivativeTypes;
}
},
interpolationDegree: {
get: function() {
return this._interpolationDegree;
}
},
interpolationAlgorithm: {
get: function() {
return this._interpolationAlgorithm;
}
},
forwardExtrapolationType: {
get: function() {
return this._forwardExtrapolationType;
},
set: function(value) {
if (this._forwardExtrapolationType !== value) {
this._forwardExtrapolationType = value;
this._definitionChanged.raiseEvent(this);
}
}
},
forwardExtrapolationDuration: {
get: function() {
return this._forwardExtrapolationDuration;
},
set: function(value) {
if (this._forwardExtrapolationDuration !== value) {
this._forwardExtrapolationDuration = value;
this._definitionChanged.raiseEvent(this);
}
}
},
backwardExtrapolationType: {
get: function() {
return this._backwardExtrapolationType;
},
set: function(value) {
if (this._backwardExtrapolationType !== value) {
this._backwardExtrapolationType = value;
this._definitionChanged.raiseEvent(this);
}
}
},
backwardExtrapolationDuration: {
get: function() {
return this._backwardExtrapolationDuration;
},
set: function(value) {
if (this._backwardExtrapolationDuration !== value) {
this._backwardExtrapolationDuration = value;
this._definitionChanged.raiseEvent(this);
}
}
}
});
SampledProperty.prototype.getValue = function(time, result) {
Check_default.defined("time", time);
const times = this._times;
const timesLength = times.length;
if (timesLength === 0) {
return void 0;
}
let timeout;
const innerType = this._innerType;
const values = this._values;
let index = binarySearch_default(times, time, JulianDate_default.compare);
if (index < 0) {
index = ~index;
if (index === 0) {
const startTime = times[index];
timeout = this._backwardExtrapolationDuration;
if (this._backwardExtrapolationType === ExtrapolationType_default.NONE || timeout !== 0 && JulianDate_default.secondsDifference(startTime, time) > timeout) {
return void 0;
}
if (this._backwardExtrapolationType === ExtrapolationType_default.HOLD) {
return innerType.unpack(values, 0, result);
}
}
if (index >= timesLength) {
index = timesLength - 1;
const endTime = times[index];
timeout = this._forwardExtrapolationDuration;
if (this._forwardExtrapolationType === ExtrapolationType_default.NONE || timeout !== 0 && JulianDate_default.secondsDifference(time, endTime) > timeout) {
return void 0;
}
if (this._forwardExtrapolationType === ExtrapolationType_default.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 void 0;
}
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 length3 = lastIndex - firstIndex + 1;
for (let i = 0; i < length3; ++i) {
xTable[i] = JulianDate_default.secondsDifference(
times[firstIndex + i],
times[lastIndex]
);
}
if (!defined_default(innerType.convertPackedArrayForInterpolation)) {
let destinationIndex = 0;
const packedLength = this._packedLength;
let sourceIndex = firstIndex * packedLength;
const stop2 = (lastIndex + 1) * packedLength;
while (sourceIndex < stop2) {
yTable[destinationIndex] = values[sourceIndex];
sourceIndex++;
destinationIndex++;
}
} else {
innerType.convertPackedArrayForInterpolation(
values,
firstIndex,
lastIndex,
yTable
);
}
const x = JulianDate_default.secondsDifference(time, times[lastIndex]);
let interpolationResult;
if (inputOrder === 0 || !defined_default(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_default(innerType.unpackInterpolationResult)) {
return innerType.unpack(interpolationResult, 0, result);
}
return innerType.unpackInterpolationResult(
interpolationResult,
values,
firstIndex,
lastIndex,
result
);
}
return innerType.unpack(values, index * this._packedLength, result);
};
SampledProperty.prototype.setInterpolationOptions = function(options) {
if (!defined_default(options)) {
return;
}
let valuesChanged = false;
const interpolationAlgorithm = options.interpolationAlgorithm;
const interpolationDegree = options.interpolationDegree;
if (defined_default(interpolationAlgorithm) && this._interpolationAlgorithm !== interpolationAlgorithm) {
this._interpolationAlgorithm = interpolationAlgorithm;
valuesChanged = true;
}
if (defined_default(interpolationDegree) && this._interpolationDegree !== interpolationDegree) {
this._interpolationDegree = interpolationDegree;
valuesChanged = true;
}
if (valuesChanged) {
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
}
};
SampledProperty.prototype.addSample = function(time, value, derivatives) {
const innerDerivativeTypes = this._innerDerivativeTypes;
const hasDerivatives = defined_default(innerDerivativeTypes);
Check_default.defined("time", time);
Check_default.defined("value", value);
if (hasDerivatives) {
Check_default.defined("derivatives", derivatives);
}
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(
void 0,
this._times,
this._values,
data,
this._packedLength
);
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
};
SampledProperty.prototype.addSamples = function(times, values, derivativeValues) {
const innerDerivativeTypes = this._innerDerivativeTypes;
const hasDerivatives = defined_default(innerDerivativeTypes);
Check_default.defined("times", times);
Check_default.defined("values", values);
if (times.length !== values.length) {
throw new DeveloperError_default("times and values must be the same length.");
}
if (hasDerivatives && (!defined_default(derivativeValues) || derivativeValues.length !== times.length)) {
throw new DeveloperError_default(
"times and derivativeValues must be the same length."
);
}
const innerType = this._innerType;
const length3 = times.length;
const data = [];
for (let i = 0; i < length3; 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(
void 0,
this._times,
this._values,
data,
this._packedLength
);
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
};
SampledProperty.prototype.addSamplesPackedArray = function(packedSamples, epoch2) {
Check_default.defined("packedSamples", packedSamples);
mergeNewSamples(
epoch2,
this._times,
this._values,
packedSamples,
this._packedLength
);
this._updateTableLength = true;
this._definitionChanged.raiseEvent(this);
};
SampledProperty.prototype.removeSample = function(time) {
Check_default.defined("time", time);
const index = binarySearch_default(this._times, time, JulianDate_default.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);
}
SampledProperty.prototype.removeSamples = function(timeInterval) {
Check_default.defined("timeInterval", timeInterval);
const times = this._times;
let startIndex = binarySearch_default(times, timeInterval.start, JulianDate_default.compare);
if (startIndex < 0) {
startIndex = ~startIndex;
} else if (!timeInterval.isStartIncluded) {
++startIndex;
}
let stopIndex = binarySearch_default(times, timeInterval.stop, JulianDate_default.compare);
if (stopIndex < 0) {
stopIndex = ~stopIndex;
} else if (timeInterval.isStopIncluded) {
++stopIndex;
}
removeSamples(this, startIndex, stopIndex - startIndex);
};
SampledProperty.prototype.equals = function(other) {
if (this === other) {
return true;
}
if (!defined_default(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_default(derivativeTypes);
const otherDerivativeTypes = other._derivativeTypes;
const otherHasDerivatives = defined_default(otherDerivativeTypes);
if (hasDerivatives !== otherHasDerivatives) {
return false;
}
let i;
let length3;
if (hasDerivatives) {
length3 = derivativeTypes.length;
if (length3 !== otherDerivativeTypes.length) {
return false;
}
for (i = 0; i < length3; i++) {
if (derivativeTypes[i] !== otherDerivativeTypes[i]) {
return false;
}
}
}
const times = this._times;
const otherTimes = other._times;
length3 = times.length;
if (length3 !== otherTimes.length) {
return false;
}
for (i = 0; i < length3; i++) {
if (!JulianDate_default.equals(times[i], otherTimes[i])) {
return false;
}
}
const values = this._values;
const otherValues = other._values;
length3 = values.length;
for (i = 0; i < length3; i++) {
if (values[i] !== otherValues[i]) {
return false;
}
}
return true;
};
SampledProperty._mergeNewSamples = mergeNewSamples;
var SampledProperty_default = SampledProperty;
// node_modules/@cesium/engine/Source/DataSources/SampledPositionProperty.js
function SampledPositionProperty(referenceFrame, numberOfDerivatives) {
numberOfDerivatives = defaultValue_default(numberOfDerivatives, 0);
let derivativeTypes;
if (numberOfDerivatives > 0) {
derivativeTypes = new Array(numberOfDerivatives);
for (let i = 0; i < numberOfDerivatives; i++) {
derivativeTypes[i] = Cartesian3_default;
}
}
this._numberOfDerivatives = numberOfDerivatives;
this._property = new SampledProperty_default(Cartesian3_default, derivativeTypes);
this._definitionChanged = new Event_default();
this._referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
this._property._definitionChanged.addEventListener(function() {
this._definitionChanged.raiseEvent(this);
}, this);
}
Object.defineProperties(SampledPositionProperty.prototype, {
isConstant: {
get: function() {
return this._property.isConstant;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
referenceFrame: {
get: function() {
return this._referenceFrame;
}
},
interpolationDegree: {
get: function() {
return this._property.interpolationDegree;
}
},
interpolationAlgorithm: {
get: function() {
return this._property.interpolationAlgorithm;
}
},
numberOfDerivatives: {
get: function() {
return this._numberOfDerivatives;
}
},
forwardExtrapolationType: {
get: function() {
return this._property.forwardExtrapolationType;
},
set: function(value) {
this._property.forwardExtrapolationType = value;
}
},
forwardExtrapolationDuration: {
get: function() {
return this._property.forwardExtrapolationDuration;
},
set: function(value) {
this._property.forwardExtrapolationDuration = value;
}
},
backwardExtrapolationType: {
get: function() {
return this._property.backwardExtrapolationType;
},
set: function(value) {
this._property.backwardExtrapolationType = value;
}
},
backwardExtrapolationDuration: {
get: function() {
return this._property.backwardExtrapolationDuration;
},
set: function(value) {
this._property.backwardExtrapolationDuration = value;
}
}
});
SampledPositionProperty.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
SampledPositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
Check_default.defined("time", time);
Check_default.defined("referenceFrame", referenceFrame);
result = this._property.getValue(time, result);
if (defined_default(result)) {
return PositionProperty_default.convertToReferenceFrame(
time,
result,
this._referenceFrame,
referenceFrame,
result
);
}
return void 0;
};
SampledPositionProperty.prototype.setInterpolationOptions = function(options) {
this._property.setInterpolationOptions(options);
};
SampledPositionProperty.prototype.addSample = function(time, position, derivatives) {
const numberOfDerivatives = this._numberOfDerivatives;
if (numberOfDerivatives > 0 && (!defined_default(derivatives) || derivatives.length !== numberOfDerivatives)) {
throw new DeveloperError_default(
"derivatives length must be equal to the number of derivatives."
);
}
this._property.addSample(time, position, derivatives);
};
SampledPositionProperty.prototype.addSamples = function(times, positions, derivatives) {
this._property.addSamples(times, positions, derivatives);
};
SampledPositionProperty.prototype.addSamplesPackedArray = function(packedSamples, epoch2) {
this._property.addSamplesPackedArray(packedSamples, epoch2);
};
SampledPositionProperty.prototype.removeSample = function(time) {
return this._property.removeSample(time);
};
SampledPositionProperty.prototype.removeSamples = function(timeInterval) {
this._property.removeSamples(timeInterval);
};
SampledPositionProperty.prototype.equals = function(other) {
return this === other || other instanceof SampledPositionProperty && Property_default.equals(this._property, other._property) && this._referenceFrame === other._referenceFrame;
};
var SampledPositionProperty_default = SampledPositionProperty;
// node_modules/@cesium/engine/Source/DataSources/StripeOrientation.js
var StripeOrientation = {
HORIZONTAL: 0,
VERTICAL: 1
};
var StripeOrientation_default = Object.freeze(StripeOrientation);
// node_modules/@cesium/engine/Source/DataSources/StripeMaterialProperty.js
var defaultOrientation = StripeOrientation_default.HORIZONTAL;
var defaultEvenColor2 = Color_default.WHITE;
var defaultOddColor2 = Color_default.BLACK;
var defaultOffset4 = 0;
var defaultRepeat3 = 1;
function StripeMaterialProperty(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._definitionChanged = new Event_default();
this._orientation = void 0;
this._orientationSubscription = void 0;
this._evenColor = void 0;
this._evenColorSubscription = void 0;
this._oddColor = void 0;
this._oddColorSubscription = void 0;
this._offset = void 0;
this._offsetSubscription = void 0;
this._repeat = void 0;
this._repeatSubscription = void 0;
this.orientation = options.orientation;
this.evenColor = options.evenColor;
this.oddColor = options.oddColor;
this.offset = options.offset;
this.repeat = options.repeat;
}
Object.defineProperties(StripeMaterialProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._orientation) && Property_default.isConstant(this._evenColor) && Property_default.isConstant(this._oddColor) && Property_default.isConstant(this._offset) && Property_default.isConstant(this._repeat);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
orientation: createPropertyDescriptor_default("orientation"),
evenColor: createPropertyDescriptor_default("evenColor"),
oddColor: createPropertyDescriptor_default("oddColor"),
offset: createPropertyDescriptor_default("offset"),
repeat: createPropertyDescriptor_default("repeat")
});
StripeMaterialProperty.prototype.getType = function(time) {
return "Stripe";
};
StripeMaterialProperty.prototype.getValue = function(time, result) {
if (!defined_default(result)) {
result = {};
}
result.horizontal = Property_default.getValueOrDefault(this._orientation, time, defaultOrientation) === StripeOrientation_default.HORIZONTAL;
result.evenColor = Property_default.getValueOrClonedDefault(
this._evenColor,
time,
defaultEvenColor2,
result.evenColor
);
result.oddColor = Property_default.getValueOrClonedDefault(
this._oddColor,
time,
defaultOddColor2,
result.oddColor
);
result.offset = Property_default.getValueOrDefault(this._offset, time, defaultOffset4);
result.repeat = Property_default.getValueOrDefault(this._repeat, time, defaultRepeat3);
return result;
};
StripeMaterialProperty.prototype.equals = function(other) {
return this === other || other instanceof StripeMaterialProperty && Property_default.equals(this._orientation, other._orientation) && Property_default.equals(this._evenColor, other._evenColor) && Property_default.equals(this._oddColor, other._oddColor) && Property_default.equals(this._offset, other._offset) && Property_default.equals(this._repeat, other._repeat);
};
var StripeMaterialProperty_default = StripeMaterialProperty;
// node_modules/@cesium/engine/Source/DataSources/TimeIntervalCollectionPositionProperty.js
function TimeIntervalCollectionPositionProperty(referenceFrame) {
this._definitionChanged = new Event_default();
this._intervals = new TimeIntervalCollection_default();
this._intervals.changedEvent.addEventListener(
TimeIntervalCollectionPositionProperty.prototype._intervalsChanged,
this
);
this._referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
}
Object.defineProperties(TimeIntervalCollectionPositionProperty.prototype, {
isConstant: {
get: function() {
return this._intervals.isEmpty;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
intervals: {
get: function() {
return this._intervals;
}
},
referenceFrame: {
get: function() {
return this._referenceFrame;
}
}
});
TimeIntervalCollectionPositionProperty.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
TimeIntervalCollectionPositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!defined_default(referenceFrame)) {
throw new DeveloperError_default("referenceFrame is required.");
}
const position = this._intervals.findDataForIntervalContainingDate(time);
if (defined_default(position)) {
return PositionProperty_default.convertToReferenceFrame(
time,
position,
this._referenceFrame,
referenceFrame,
result
);
}
return void 0;
};
TimeIntervalCollectionPositionProperty.prototype.equals = function(other) {
return this === other || other instanceof TimeIntervalCollectionPositionProperty && this._intervals.equals(other._intervals, Property_default.equals) && this._referenceFrame === other._referenceFrame;
};
TimeIntervalCollectionPositionProperty.prototype._intervalsChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var TimeIntervalCollectionPositionProperty_default = TimeIntervalCollectionPositionProperty;
// node_modules/@cesium/engine/Source/DataSources/TimeIntervalCollectionProperty.js
function TimeIntervalCollectionProperty() {
this._definitionChanged = new Event_default();
this._intervals = new TimeIntervalCollection_default();
this._intervals.changedEvent.addEventListener(
TimeIntervalCollectionProperty.prototype._intervalsChanged,
this
);
}
Object.defineProperties(TimeIntervalCollectionProperty.prototype, {
isConstant: {
get: function() {
return this._intervals.isEmpty;
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
intervals: {
get: function() {
return this._intervals;
}
}
});
TimeIntervalCollectionProperty.prototype.getValue = function(time, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required");
}
const value = this._intervals.findDataForIntervalContainingDate(time);
if (defined_default(value) && typeof value.clone === "function") {
return value.clone(result);
}
return value;
};
TimeIntervalCollectionProperty.prototype.equals = function(other) {
return this === other || other instanceof TimeIntervalCollectionProperty && this._intervals.equals(other._intervals, Property_default.equals);
};
TimeIntervalCollectionProperty.prototype._intervalsChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var TimeIntervalCollectionProperty_default = TimeIntervalCollectionProperty;
// node_modules/@cesium/engine/Source/DataSources/VelocityVectorProperty.js
function VelocityVectorProperty(position, normalize2) {
this._position = void 0;
this._subscription = void 0;
this._definitionChanged = new Event_default();
this._normalize = defaultValue_default(normalize2, true);
this.position = position;
}
Object.defineProperties(VelocityVectorProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._position);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
position: {
get: function() {
return this._position;
},
set: function(value) {
const oldValue2 = this._position;
if (oldValue2 !== value) {
if (defined_default(oldValue2)) {
this._subscription();
}
this._position = value;
if (defined_default(value)) {
this._subscription = value._definitionChanged.addEventListener(
function() {
this._definitionChanged.raiseEvent(this);
},
this
);
}
this._definitionChanged.raiseEvent(this);
}
}
},
normalize: {
get: function() {
return this._normalize;
},
set: function(value) {
if (this._normalize === value) {
return;
}
this._normalize = value;
this._definitionChanged.raiseEvent(this);
}
}
});
var position1Scratch = new Cartesian3_default();
var position2Scratch = new Cartesian3_default();
var timeScratch = new JulianDate_default();
var step = 1 / 60;
VelocityVectorProperty.prototype.getValue = function(time, result) {
return this._getValue(time, result);
};
VelocityVectorProperty.prototype._getValue = function(time, velocityResult, positionResult) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required");
}
if (!defined_default(velocityResult)) {
velocityResult = new Cartesian3_default();
}
const property = this._position;
if (Property_default.isConstant(property)) {
return this._normalize ? void 0 : Cartesian3_default.clone(Cartesian3_default.ZERO, velocityResult);
}
let position1 = property.getValue(time, position1Scratch);
let position2 = property.getValue(
JulianDate_default.addSeconds(time, step, timeScratch),
position2Scratch
);
if (!defined_default(position1)) {
return void 0;
}
if (!defined_default(position2)) {
position2 = position1;
position1 = property.getValue(
JulianDate_default.addSeconds(time, -step, timeScratch),
position2Scratch
);
if (!defined_default(position1)) {
return void 0;
}
}
if (Cartesian3_default.equals(position1, position2)) {
return this._normalize ? void 0 : Cartesian3_default.clone(Cartesian3_default.ZERO, velocityResult);
}
if (defined_default(positionResult)) {
position1.clone(positionResult);
}
const velocity = Cartesian3_default.subtract(position2, position1, velocityResult);
if (this._normalize) {
return Cartesian3_default.normalize(velocity, velocityResult);
}
return Cartesian3_default.divideByScalar(velocity, step, velocityResult);
};
VelocityVectorProperty.prototype.equals = function(other) {
return this === other || other instanceof VelocityVectorProperty && Property_default.equals(this._position, other._position);
};
var VelocityVectorProperty_default = VelocityVectorProperty;
// node_modules/@cesium/engine/Source/DataSources/VelocityOrientationProperty.js
function VelocityOrientationProperty(position, ellipsoid) {
this._velocityVectorProperty = new VelocityVectorProperty_default(position, true);
this._subscription = void 0;
this._ellipsoid = void 0;
this._definitionChanged = new Event_default();
this.ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
const that = this;
this._velocityVectorProperty.definitionChanged.addEventListener(function() {
that._definitionChanged.raiseEvent(that);
});
}
Object.defineProperties(VelocityOrientationProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._velocityVectorProperty);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
position: {
get: function() {
return this._velocityVectorProperty.position;
},
set: function(value) {
this._velocityVectorProperty.position = value;
}
},
ellipsoid: {
get: function() {
return this._ellipsoid;
},
set: function(value) {
const oldValue2 = this._ellipsoid;
if (oldValue2 !== value) {
this._ellipsoid = value;
this._definitionChanged.raiseEvent(this);
}
}
}
});
var positionScratch10 = new Cartesian3_default();
var velocityScratch = new Cartesian3_default();
var rotationScratch2 = new Matrix3_default();
VelocityOrientationProperty.prototype.getValue = function(time, result) {
const velocity = this._velocityVectorProperty._getValue(
time,
velocityScratch,
positionScratch10
);
if (!defined_default(velocity)) {
return void 0;
}
Transforms_default.rotationMatrixFromPositionVelocity(
positionScratch10,
velocity,
this._ellipsoid,
rotationScratch2
);
return Quaternion_default.fromRotationMatrix(rotationScratch2, result);
};
VelocityOrientationProperty.prototype.equals = function(other) {
return this === other || other instanceof VelocityOrientationProperty && Property_default.equals(
this._velocityVectorProperty,
other._velocityVectorProperty
) && (this._ellipsoid === other._ellipsoid || this._ellipsoid.equals(other._ellipsoid));
};
var VelocityOrientationProperty_default = VelocityOrientationProperty;
// node_modules/@cesium/engine/Source/DataSources/CzmlDataSource.js
function UnitCartesian3() {
}
UnitCartesian3.packedLength = Cartesian3_default.packedLength;
UnitCartesian3.unpack = Cartesian3_default.unpack;
UnitCartesian3.pack = Cartesian3_default.pack;
var currentId;
function createReferenceProperty(entityCollection, referenceString) {
if (referenceString[0] === "#") {
referenceString = currentId + referenceString;
}
return ReferenceProperty_default.fromString(entityCollection, referenceString);
}
function createSpecializedProperty(type, entityCollection, packetData) {
if (defined_default(packetData.reference)) {
return createReferenceProperty(entityCollection, packetData.reference);
}
if (defined_default(packetData.velocityReference)) {
const referenceProperty = createReferenceProperty(
entityCollection,
packetData.velocityReference
);
switch (type) {
case Cartesian3_default:
case UnitCartesian3:
return new VelocityVectorProperty_default(
referenceProperty,
type === UnitCartesian3
);
case Quaternion_default:
return new VelocityOrientationProperty_default(referenceProperty);
}
}
throw new RuntimeError_default(`${JSON.stringify(packetData)} is not valid CZML.`);
}
function createAdapterProperty(property, adapterFunction) {
return new CallbackProperty_default(function(time, result) {
return adapterFunction(property.getValue(time, result));
}, property.isConstant);
}
var scratchCartesian15 = new Cartesian3_default();
var scratchSpherical = new Spherical_default();
var scratchCartographic9 = new Cartographic_default();
var scratchTimeInterval = new TimeInterval_default();
var scratchQuaternion = new Quaternion_default();
function unwrapColorInterval(czmlInterval) {
let rgbaf = czmlInterval.rgbaf;
if (defined_default(rgbaf)) {
return rgbaf;
}
const rgba = czmlInterval.rgba;
if (!defined_default(rgba)) {
return void 0;
}
const length3 = rgba.length;
if (length3 === Color_default.packedLength) {
return [
Color_default.byteToFloat(rgba[0]),
Color_default.byteToFloat(rgba[1]),
Color_default.byteToFloat(rgba[2]),
Color_default.byteToFloat(rgba[3])
];
}
rgbaf = new Array(length3);
for (let i = 0; i < length3; i += 5) {
rgbaf[i] = rgba[i];
rgbaf[i + 1] = Color_default.byteToFloat(rgba[i + 1]);
rgbaf[i + 2] = Color_default.byteToFloat(rgba[i + 2]);
rgbaf[i + 3] = Color_default.byteToFloat(rgba[i + 3]);
rgbaf[i + 4] = Color_default.byteToFloat(rgba[i + 4]);
}
return rgbaf;
}
function unwrapUriInterval(czmlInterval, sourceUri) {
const uri = defaultValue_default(czmlInterval.uri, czmlInterval);
if (defined_default(sourceUri)) {
return sourceUri.getDerivedResource({
url: uri
});
}
return Resource_default.createIfNeeded(uri);
}
function unwrapRectangleInterval(czmlInterval) {
let wsen = czmlInterval.wsen;
if (defined_default(wsen)) {
return wsen;
}
const wsenDegrees = czmlInterval.wsenDegrees;
if (!defined_default(wsenDegrees)) {
return void 0;
}
const length3 = wsenDegrees.length;
if (length3 === Rectangle_default.packedLength) {
return [
Math_default.toRadians(wsenDegrees[0]),
Math_default.toRadians(wsenDegrees[1]),
Math_default.toRadians(wsenDegrees[2]),
Math_default.toRadians(wsenDegrees[3])
];
}
wsen = new Array(length3);
for (let i = 0; i < length3; i += 5) {
wsen[i] = wsenDegrees[i];
wsen[i + 1] = Math_default.toRadians(wsenDegrees[i + 1]);
wsen[i + 2] = Math_default.toRadians(wsenDegrees[i + 2]);
wsen[i + 3] = Math_default.toRadians(wsenDegrees[i + 3]);
wsen[i + 4] = Math_default.toRadians(wsenDegrees[i + 4]);
}
return wsen;
}
function convertUnitSphericalToCartesian(unitSpherical) {
const length3 = unitSpherical.length;
scratchSpherical.magnitude = 1;
if (length3 === 2) {
scratchSpherical.clock = unitSpherical[0];
scratchSpherical.cone = unitSpherical[1];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3 / 3 * 4);
for (let i = 0, j = 0; i < length3; i += 3, j += 4) {
result[j] = unitSpherical[i];
scratchSpherical.clock = unitSpherical[i + 1];
scratchSpherical.cone = unitSpherical[i + 2];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
result[j + 1] = scratchCartesian15.x;
result[j + 2] = scratchCartesian15.y;
result[j + 3] = scratchCartesian15.z;
}
return result;
}
function convertSphericalToCartesian(spherical) {
const length3 = spherical.length;
if (length3 === 3) {
scratchSpherical.clock = spherical[0];
scratchSpherical.cone = spherical[1];
scratchSpherical.magnitude = spherical[2];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3);
for (let i = 0; i < length3; i += 4) {
result[i] = spherical[i];
scratchSpherical.clock = spherical[i + 1];
scratchSpherical.cone = spherical[i + 2];
scratchSpherical.magnitude = spherical[i + 3];
Cartesian3_default.fromSpherical(scratchSpherical, scratchCartesian15);
result[i + 1] = scratchCartesian15.x;
result[i + 2] = scratchCartesian15.y;
result[i + 3] = scratchCartesian15.z;
}
return result;
}
function convertCartographicRadiansToCartesian(cartographicRadians) {
const length3 = cartographicRadians.length;
if (length3 === 3) {
scratchCartographic9.longitude = cartographicRadians[0];
scratchCartographic9.latitude = cartographicRadians[1];
scratchCartographic9.height = cartographicRadians[2];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3);
for (let i = 0; i < length3; i += 4) {
result[i] = cartographicRadians[i];
scratchCartographic9.longitude = cartographicRadians[i + 1];
scratchCartographic9.latitude = cartographicRadians[i + 2];
scratchCartographic9.height = cartographicRadians[i + 3];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
result[i + 1] = scratchCartesian15.x;
result[i + 2] = scratchCartesian15.y;
result[i + 3] = scratchCartesian15.z;
}
return result;
}
function convertCartographicDegreesToCartesian(cartographicDegrees) {
const length3 = cartographicDegrees.length;
if (length3 === 3) {
scratchCartographic9.longitude = Math_default.toRadians(
cartographicDegrees[0]
);
scratchCartographic9.latitude = Math_default.toRadians(cartographicDegrees[1]);
scratchCartographic9.height = cartographicDegrees[2];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
return [scratchCartesian15.x, scratchCartesian15.y, scratchCartesian15.z];
}
const result = new Array(length3);
for (let i = 0; i < length3; i += 4) {
result[i] = cartographicDegrees[i];
scratchCartographic9.longitude = Math_default.toRadians(
cartographicDegrees[i + 1]
);
scratchCartographic9.latitude = Math_default.toRadians(
cartographicDegrees[i + 2]
);
scratchCartographic9.height = cartographicDegrees[i + 3];
Ellipsoid_default.WGS84.cartographicToCartesian(
scratchCartographic9,
scratchCartesian15
);
result[i + 1] = scratchCartesian15.x;
result[i + 2] = scratchCartesian15.y;
result[i + 3] = scratchCartesian15.z;
}
return result;
}
function unwrapCartesianInterval(czmlInterval) {
const cartesian11 = czmlInterval.cartesian;
if (defined_default(cartesian11)) {
return cartesian11;
}
const cartesianVelocity = czmlInterval.cartesianVelocity;
if (defined_default(cartesianVelocity)) {
return cartesianVelocity;
}
const unitCartesian = czmlInterval.unitCartesian;
if (defined_default(unitCartesian)) {
return unitCartesian;
}
const unitSpherical = czmlInterval.unitSpherical;
if (defined_default(unitSpherical)) {
return convertUnitSphericalToCartesian(unitSpherical);
}
const spherical = czmlInterval.spherical;
if (defined_default(spherical)) {
return convertSphericalToCartesian(spherical);
}
const cartographicRadians = czmlInterval.cartographicRadians;
if (defined_default(cartographicRadians)) {
return convertCartographicRadiansToCartesian(cartographicRadians);
}
const cartographicDegrees = czmlInterval.cartographicDegrees;
if (defined_default(cartographicDegrees)) {
return convertCartographicDegreesToCartesian(cartographicDegrees);
}
throw new RuntimeError_default(
`${JSON.stringify(czmlInterval)} is not a valid CZML interval.`
);
}
function normalizePackedCartesianArray(array, startingIndex) {
Cartesian3_default.unpack(array, startingIndex, scratchCartesian15);
Cartesian3_default.normalize(scratchCartesian15, scratchCartesian15);
Cartesian3_default.pack(scratchCartesian15, array, startingIndex);
}
function unwrapUnitCartesianInterval(czmlInterval) {
const cartesian11 = unwrapCartesianInterval(czmlInterval);
if (cartesian11.length === 3) {
normalizePackedCartesianArray(cartesian11, 0);
return cartesian11;
}
for (let i = 1; i < cartesian11.length; i += 4) {
normalizePackedCartesianArray(cartesian11, i);
}
return cartesian11;
}
function normalizePackedQuaternionArray(array, startingIndex) {
Quaternion_default.unpack(array, startingIndex, scratchQuaternion);
Quaternion_default.normalize(scratchQuaternion, scratchQuaternion);
Quaternion_default.pack(scratchQuaternion, array, startingIndex);
}
function unwrapQuaternionInterval(czmlInterval) {
const unitQuaternion = czmlInterval.unitQuaternion;
if (defined_default(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) {
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_default;
} else if (czmlInterval.hasOwnProperty("cartesian2")) {
return Cartesian2_default;
} else if (czmlInterval.hasOwnProperty("cartesian") || czmlInterval.hasOwnProperty("spherical") || czmlInterval.hasOwnProperty("cartographicRadians") || czmlInterval.hasOwnProperty("cartographicDegrees")) {
return Cartesian3_default;
} else if (czmlInterval.hasOwnProperty("unitCartesian") || czmlInterval.hasOwnProperty("unitSpherical")) {
return UnitCartesian3;
} else if (czmlInterval.hasOwnProperty("rgba") || czmlInterval.hasOwnProperty("rgbaf")) {
return Color_default;
} else if (czmlInterval.hasOwnProperty("arcType")) {
return ArcType_default;
} else if (czmlInterval.hasOwnProperty("classificationType")) {
return ClassificationType_default;
} else if (czmlInterval.hasOwnProperty("colorBlendMode")) {
return ColorBlendMode_default;
} else if (czmlInterval.hasOwnProperty("cornerType")) {
return CornerType_default;
} else if (czmlInterval.hasOwnProperty("heightReference")) {
return HeightReference_default;
} else if (czmlInterval.hasOwnProperty("horizontalOrigin")) {
return HorizontalOrigin_default;
} else if (czmlInterval.hasOwnProperty("date")) {
return JulianDate_default;
} else if (czmlInterval.hasOwnProperty("labelStyle")) {
return LabelStyle_default;
} else if (czmlInterval.hasOwnProperty("number")) {
return Number;
} else if (czmlInterval.hasOwnProperty("nearFarScalar")) {
return NearFarScalar_default;
} else if (czmlInterval.hasOwnProperty("distanceDisplayCondition")) {
return DistanceDisplayCondition_default;
} else if (czmlInterval.hasOwnProperty("object") || czmlInterval.hasOwnProperty("value")) {
return Object;
} else if (czmlInterval.hasOwnProperty("unitQuaternion")) {
return Quaternion_default;
} else if (czmlInterval.hasOwnProperty("shadowMode")) {
return ShadowMode_default;
} else if (czmlInterval.hasOwnProperty("string")) {
return String;
} else if (czmlInterval.hasOwnProperty("stripeOrientation")) {
return StripeOrientation_default;
} else if (czmlInterval.hasOwnProperty("wsen") || czmlInterval.hasOwnProperty("wsenDegrees")) {
return Rectangle_default;
} else if (czmlInterval.hasOwnProperty("uri")) {
return import_urijs10.default;
} else if (czmlInterval.hasOwnProperty("verticalOrigin")) {
return VerticalOrigin_default;
}
return Object;
}
function unwrapInterval(type, czmlInterval, sourceUri) {
switch (type) {
case ArcType_default:
return ArcType_default[defaultValue_default(czmlInterval.arcType, czmlInterval)];
case Array:
return czmlInterval.array;
case Boolean:
return defaultValue_default(czmlInterval["boolean"], czmlInterval);
case BoundingRectangle_default:
return czmlInterval.boundingRectangle;
case Cartesian2_default:
return czmlInterval.cartesian2;
case Cartesian3_default:
return unwrapCartesianInterval(czmlInterval);
case UnitCartesian3:
return unwrapUnitCartesianInterval(czmlInterval);
case Color_default:
return unwrapColorInterval(czmlInterval);
case ClassificationType_default:
return ClassificationType_default[defaultValue_default(czmlInterval.classificationType, czmlInterval)];
case ColorBlendMode_default:
return ColorBlendMode_default[defaultValue_default(czmlInterval.colorBlendMode, czmlInterval)];
case CornerType_default:
return CornerType_default[defaultValue_default(czmlInterval.cornerType, czmlInterval)];
case HeightReference_default:
return HeightReference_default[defaultValue_default(czmlInterval.heightReference, czmlInterval)];
case HorizontalOrigin_default:
return HorizontalOrigin_default[defaultValue_default(czmlInterval.horizontalOrigin, czmlInterval)];
case Image:
return unwrapUriInterval(czmlInterval, sourceUri);
case JulianDate_default:
return JulianDate_default.fromIso8601(
defaultValue_default(czmlInterval.date, czmlInterval)
);
case LabelStyle_default:
return LabelStyle_default[defaultValue_default(czmlInterval.labelStyle, czmlInterval)];
case Number:
return defaultValue_default(czmlInterval.number, czmlInterval);
case NearFarScalar_default:
return czmlInterval.nearFarScalar;
case DistanceDisplayCondition_default:
return czmlInterval.distanceDisplayCondition;
case Object:
return defaultValue_default(
defaultValue_default(czmlInterval.object, czmlInterval.value),
czmlInterval
);
case Quaternion_default:
return unwrapQuaternionInterval(czmlInterval);
case Rotation_default:
return defaultValue_default(czmlInterval.number, czmlInterval);
case ShadowMode_default:
return ShadowMode_default[defaultValue_default(
defaultValue_default(czmlInterval.shadowMode, czmlInterval.shadows),
czmlInterval
)];
case String:
return defaultValue_default(czmlInterval.string, czmlInterval);
case StripeOrientation_default:
return StripeOrientation_default[defaultValue_default(czmlInterval.stripeOrientation, czmlInterval)];
case Rectangle_default:
return unwrapRectangleInterval(czmlInterval);
case import_urijs10.default:
return unwrapUriInterval(czmlInterval, sourceUri);
case VerticalOrigin_default:
return VerticalOrigin_default[defaultValue_default(czmlInterval.verticalOrigin, czmlInterval)];
default:
throw new RuntimeError_default(type);
}
}
var interpolators = {
HERMITE: HermitePolynomialApproximation_default,
LAGRANGE: LagrangePolynomialApproximation_default,
LINEAR: LinearApproximation_default
};
function updateInterpolationSettings(packetData, property) {
const interpolationAlgorithm = packetData.interpolationAlgorithm;
const interpolationDegree = packetData.interpolationDegree;
if (defined_default(interpolationAlgorithm) || defined_default(interpolationDegree)) {
property.setInterpolationOptions({
interpolationAlgorithm: interpolators[interpolationAlgorithm],
interpolationDegree
});
}
const forwardExtrapolationType = packetData.forwardExtrapolationType;
if (defined_default(forwardExtrapolationType)) {
property.forwardExtrapolationType = ExtrapolationType_default[forwardExtrapolationType];
}
const forwardExtrapolationDuration = packetData.forwardExtrapolationDuration;
if (defined_default(forwardExtrapolationDuration)) {
property.forwardExtrapolationDuration = forwardExtrapolationDuration;
}
const backwardExtrapolationType = packetData.backwardExtrapolationType;
if (defined_default(backwardExtrapolationType)) {
property.backwardExtrapolationType = ExtrapolationType_default[backwardExtrapolationType];
}
const backwardExtrapolationDuration = packetData.backwardExtrapolationDuration;
if (defined_default(backwardExtrapolationDuration)) {
property.backwardExtrapolationDuration = backwardExtrapolationDuration;
}
}
var iso8601Scratch = {
iso8601: void 0
};
function intervalFromString(intervalString) {
if (!defined_default(intervalString)) {
return void 0;
}
iso8601Scratch.iso8601 = intervalString;
return TimeInterval_default.fromIso8601(iso8601Scratch);
}
function wrapPropertyInInfiniteInterval(property) {
const interval = Iso8601_default.MAXIMUM_INTERVAL.clone();
interval.data = property;
return interval;
}
function convertPropertyToComposite(property) {
const composite = new CompositeProperty_default();
composite.intervals.addInterval(wrapPropertyInInfiniteInterval(property));
return composite;
}
function convertPositionPropertyToComposite(property) {
const composite = new CompositePositionProperty_default(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_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} else {
combinedInterval = constrainedInterval;
}
}
let packedLength;
let unwrappedInterval;
let unwrappedIntervalLength;
const isValue = !defined_default(packetData.reference) && !defined_default(packetData.velocityReference);
const hasInterval = defined_default(combinedInterval) && !combinedInterval.equals(Iso8601_default.MAXIMUM_INTERVAL);
if (packetData.delete === true) {
if (!hasInterval) {
object[propertyName] = void 0;
return;
}
return removePropertyData(object[propertyName], combinedInterval);
}
let isSampled = false;
if (isValue) {
unwrappedInterval = unwrapInterval(type, packetData, sourceUri);
if (!defined_default(unwrappedInterval)) {
return;
}
packedLength = defaultValue_default(type.packedLength, 1);
unwrappedIntervalLength = defaultValue_default(unwrappedInterval.length, 1);
isSampled = !defined_default(packetData.array) && typeof unwrappedInterval !== "string" && unwrappedIntervalLength > packedLength && type !== Object;
}
const needsUnpacking = typeof type.unpack === "function" && type !== Rotation_default;
if (!isSampled && !hasInterval) {
if (isValue) {
object[propertyName] = new ConstantProperty_default(
needsUnpacking ? type.unpack(unwrappedInterval, 0) : unwrappedInterval
);
} else {
object[propertyName] = createSpecializedProperty(
type,
entityCollection,
packetData
);
}
return;
}
let property = object[propertyName];
let epoch2;
const packetEpoch = packetData.epoch;
if (defined_default(packetEpoch)) {
epoch2 = JulianDate_default.fromIso8601(packetEpoch);
}
if (isSampled && !hasInterval) {
if (!(property instanceof SampledProperty_default)) {
object[propertyName] = property = new SampledProperty_default(type);
}
property.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, property);
return;
}
let interval;
if (!isSampled && hasInterval) {
combinedInterval = combinedInterval.clone();
if (isValue) {
combinedInterval.data = needsUnpacking ? type.unpack(unwrappedInterval, 0) : unwrappedInterval;
} else {
combinedInterval.data = createSpecializedProperty(
type,
entityCollection,
packetData
);
}
if (!defined_default(property)) {
object[propertyName] = property = isValue ? new TimeIntervalCollectionProperty_default() : new CompositeProperty_default();
}
if (isValue && property instanceof TimeIntervalCollectionProperty_default) {
property.intervals.addInterval(combinedInterval);
} else if (property instanceof CompositeProperty_default) {
if (isValue) {
combinedInterval.data = new ConstantProperty_default(combinedInterval.data);
}
property.intervals.addInterval(combinedInterval);
} else {
object[propertyName] = property = convertPropertyToComposite(property);
if (isValue) {
combinedInterval.data = new ConstantProperty_default(combinedInterval.data);
}
property.intervals.addInterval(combinedInterval);
}
return;
}
if (!defined_default(property)) {
object[propertyName] = property = new CompositeProperty_default();
}
if (!(property instanceof CompositeProperty_default)) {
object[propertyName] = property = convertPropertyToComposite(property);
}
const intervals = property.intervals;
interval = intervals.findInterval(combinedInterval);
if (!defined_default(interval) || !(interval.data instanceof SampledProperty_default)) {
interval = combinedInterval.clone();
interval.data = new SampledProperty_default(type);
intervals.addInterval(interval);
}
interval.data.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, interval.data);
}
function removePropertyData(property, interval) {
if (property instanceof SampledProperty_default) {
property.removeSamples(interval);
return;
} else if (property instanceof TimeIntervalCollectionProperty_default) {
property.intervals.removeInterval(interval);
return;
} else if (property instanceof CompositeProperty_default) {
const intervals = property.intervals;
for (let i = 0; i < intervals.length; ++i) {
const intersection = TimeInterval_default.intersect(
intervals.get(i),
interval,
scratchTimeInterval
);
if (!intersection.isEmpty) {
removePropertyData(intersection.data, interval);
}
}
intervals.removeInterval(interval);
return;
}
}
function processPacketData(type, object, propertyName, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(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_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} else {
combinedInterval = constrainedInterval;
}
}
const numberOfDerivatives = defined_default(packetData.cartesianVelocity) ? 1 : 0;
const packedLength = Cartesian3_default.packedLength * (numberOfDerivatives + 1);
let unwrappedInterval;
let unwrappedIntervalLength;
const isValue = !defined_default(packetData.reference);
const hasInterval = defined_default(combinedInterval) && !combinedInterval.equals(Iso8601_default.MAXIMUM_INTERVAL);
if (packetData.delete === true) {
if (!hasInterval) {
object[propertyName] = void 0;
return;
}
return removePositionPropertyData(object[propertyName], combinedInterval);
}
let referenceFrame;
let isSampled = false;
if (isValue) {
if (defined_default(packetData.referenceFrame)) {
referenceFrame = ReferenceFrame_default[packetData.referenceFrame];
}
referenceFrame = defaultValue_default(referenceFrame, ReferenceFrame_default.FIXED);
unwrappedInterval = unwrapCartesianInterval(packetData);
unwrappedIntervalLength = defaultValue_default(unwrappedInterval.length, 1);
isSampled = unwrappedIntervalLength > packedLength;
}
if (!isSampled && !hasInterval) {
if (isValue) {
object[propertyName] = new ConstantPositionProperty_default(
Cartesian3_default.unpack(unwrappedInterval),
referenceFrame
);
} else {
object[propertyName] = createReferenceProperty(
entityCollection,
packetData.reference
);
}
return;
}
let property = object[propertyName];
let epoch2;
const packetEpoch = packetData.epoch;
if (defined_default(packetEpoch)) {
epoch2 = JulianDate_default.fromIso8601(packetEpoch);
}
if (isSampled && !hasInterval) {
if (!(property instanceof SampledPositionProperty_default) || defined_default(referenceFrame) && property.referenceFrame !== referenceFrame) {
object[propertyName] = property = new SampledPositionProperty_default(
referenceFrame,
numberOfDerivatives
);
}
property.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, property);
return;
}
let interval;
if (!isSampled && hasInterval) {
combinedInterval = combinedInterval.clone();
if (isValue) {
combinedInterval.data = Cartesian3_default.unpack(unwrappedInterval);
} else {
combinedInterval.data = createReferenceProperty(
entityCollection,
packetData.reference
);
}
if (!defined_default(property)) {
if (isValue) {
property = new TimeIntervalCollectionPositionProperty_default(referenceFrame);
} else {
property = new CompositePositionProperty_default(referenceFrame);
}
object[propertyName] = property;
}
if (isValue && property instanceof TimeIntervalCollectionPositionProperty_default && defined_default(referenceFrame) && property.referenceFrame === referenceFrame) {
property.intervals.addInterval(combinedInterval);
} else if (property instanceof CompositePositionProperty_default) {
if (isValue) {
combinedInterval.data = new ConstantPositionProperty_default(
combinedInterval.data,
referenceFrame
);
}
property.intervals.addInterval(combinedInterval);
} else {
object[propertyName] = property = convertPositionPropertyToComposite(
property
);
if (isValue) {
combinedInterval.data = new ConstantPositionProperty_default(
combinedInterval.data,
referenceFrame
);
}
property.intervals.addInterval(combinedInterval);
}
return;
}
if (!defined_default(property)) {
object[propertyName] = property = new CompositePositionProperty_default(
referenceFrame
);
} else if (!(property instanceof CompositePositionProperty_default)) {
object[propertyName] = property = convertPositionPropertyToComposite(
property
);
}
const intervals = property.intervals;
interval = intervals.findInterval(combinedInterval);
if (!defined_default(interval) || !(interval.data instanceof SampledPositionProperty_default) || defined_default(referenceFrame) && interval.data.referenceFrame !== referenceFrame) {
interval = combinedInterval.clone();
interval.data = new SampledPositionProperty_default(
referenceFrame,
numberOfDerivatives
);
intervals.addInterval(interval);
}
interval.data.addSamplesPackedArray(unwrappedInterval, epoch2);
updateInterpolationSettings(packetData, interval.data);
}
function removePositionPropertyData(property, interval) {
if (property instanceof SampledPositionProperty_default) {
property.removeSamples(interval);
return;
} else if (property instanceof TimeIntervalCollectionPositionProperty_default) {
property.intervals.removeInterval(interval);
return;
} else if (property instanceof CompositePositionProperty_default) {
const intervals = property.intervals;
for (let i = 0; i < intervals.length; ++i) {
const intersection = TimeInterval_default.intersect(
intervals.get(i),
interval,
scratchTimeInterval
);
if (!intersection.isEmpty) {
removePositionPropertyData(intersection.data, interval);
}
}
intervals.removeInterval(interval);
return;
}
}
function processPositionPacketData(object, propertyName, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(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_default(packetData.references)) {
processReferencesArrayPacketData(
object,
propertyName,
packetData.references,
packetData.interval,
entityCollection,
PropertyArray_default,
CompositeProperty_default
);
} else {
if (defined_default(packetData.cartesian2)) {
packetData.array = Cartesian2_default.unpackArray(packetData.cartesian2);
} else if (defined_default(packetData.cartesian)) {
packetData.array = Cartesian2_default.unpackArray(packetData.cartesian);
}
if (defined_default(packetData.array)) {
processPacketData(
Array,
object,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
}
function processMaterialProperty(object, propertyName, packetData, constrainedInterval, sourceUri, entityCollection) {
let combinedInterval = intervalFromString(packetData.interval);
if (defined_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} else {
combinedInterval = constrainedInterval;
}
}
let property = object[propertyName];
let existingMaterial;
let existingInterval;
if (defined_default(combinedInterval)) {
if (!(property instanceof CompositeMaterialProperty_default)) {
property = new CompositeMaterialProperty_default();
object[propertyName] = property;
}
const thisIntervals = property.intervals;
existingInterval = thisIntervals.findInterval({
start: combinedInterval.start,
stop: combinedInterval.stop
});
if (defined_default(existingInterval)) {
existingMaterial = existingInterval.data;
} else {
existingInterval = combinedInterval.clone();
thisIntervals.addInterval(existingInterval);
}
} else {
existingMaterial = property;
}
let materialData;
if (defined_default(packetData.solidColor)) {
if (!(existingMaterial instanceof ColorMaterialProperty_default)) {
existingMaterial = new ColorMaterialProperty_default();
}
materialData = packetData.solidColor;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
void 0,
entityCollection
);
} else if (defined_default(packetData.grid)) {
if (!(existingMaterial instanceof GridMaterialProperty_default)) {
existingMaterial = new GridMaterialProperty_default();
}
materialData = packetData.grid;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"cellAlpha",
materialData.cellAlpha,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"lineCount",
materialData.lineCount,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"lineThickness",
materialData.lineThickness,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"lineOffset",
materialData.lineOffset,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.image)) {
if (!(existingMaterial instanceof ImageMaterialProperty_default)) {
existingMaterial = new ImageMaterialProperty_default();
}
materialData = packetData.image;
processPacketData(
Image,
existingMaterial,
"image",
materialData.image,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"repeat",
materialData.repeat,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
existingMaterial,
"transparent",
materialData.transparent,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.stripe)) {
if (!(existingMaterial instanceof StripeMaterialProperty_default)) {
existingMaterial = new StripeMaterialProperty_default();
}
materialData = packetData.stripe;
processPacketData(
StripeOrientation_default,
existingMaterial,
"orientation",
materialData.orientation,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"evenColor",
materialData.evenColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"oddColor",
materialData.oddColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"offset",
materialData.offset,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"repeat",
materialData.repeat,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.polylineOutline)) {
if (!(existingMaterial instanceof PolylineOutlineMaterialProperty_default)) {
existingMaterial = new PolylineOutlineMaterialProperty_default();
}
materialData = packetData.polylineOutline;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"outlineColor",
materialData.outlineColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"outlineWidth",
materialData.outlineWidth,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.polylineGlow)) {
if (!(existingMaterial instanceof PolylineGlowMaterialProperty_default)) {
existingMaterial = new PolylineGlowMaterialProperty_default();
}
materialData = packetData.polylineGlow;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"glowPower",
materialData.glowPower,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"taperPower",
materialData.taperPower,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.polylineArrow)) {
if (!(existingMaterial instanceof PolylineArrowMaterialProperty_default)) {
existingMaterial = new PolylineArrowMaterialProperty_default();
}
materialData = packetData.polylineArrow;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
void 0,
entityCollection
);
} else if (defined_default(packetData.polylineDash)) {
if (!(existingMaterial instanceof PolylineDashMaterialProperty_default)) {
existingMaterial = new PolylineDashMaterialProperty_default();
}
materialData = packetData.polylineDash;
processPacketData(
Color_default,
existingMaterial,
"color",
materialData.color,
void 0,
void 0,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"gapColor",
materialData.gapColor,
void 0,
void 0,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"dashLength",
materialData.dashLength,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Number,
existingMaterial,
"dashPattern",
materialData.dashPattern,
void 0,
sourceUri,
entityCollection
);
} else if (defined_default(packetData.checkerboard)) {
if (!(existingMaterial instanceof CheckerboardMaterialProperty_default)) {
existingMaterial = new CheckerboardMaterialProperty_default();
}
materialData = packetData.checkerboard;
processPacketData(
Color_default,
existingMaterial,
"evenColor",
materialData.evenColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
existingMaterial,
"oddColor",
materialData.oddColor,
void 0,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
existingMaterial,
"repeat",
materialData.repeat,
void 0,
sourceUri,
entityCollection
);
}
if (defined_default(existingInterval)) {
existingInterval.data = existingMaterial;
} else {
object[propertyName] = existingMaterial;
}
}
function processMaterialPacketData(object, propertyName, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(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_default(nameData)) {
entity.name = packet.name;
}
}
function processDescription(entity, packet, entityCollection, sourceUri) {
const descriptionData = packet.description;
if (defined_default(descriptionData)) {
processPacketData(
String,
entity,
"description",
descriptionData,
void 0,
sourceUri,
entityCollection
);
}
}
function processPosition(entity, packet, entityCollection, sourceUri) {
const positionData = packet.position;
if (defined_default(positionData)) {
processPositionPacketData(
entity,
"position",
positionData,
void 0,
sourceUri,
entityCollection
);
}
}
function processViewFrom(entity, packet, entityCollection, sourceUri) {
const viewFromData = packet.viewFrom;
if (defined_default(viewFromData)) {
processPacketData(
Cartesian3_default,
entity,
"viewFrom",
viewFromData,
void 0,
sourceUri,
entityCollection
);
}
}
function processOrientation(entity, packet, entityCollection, sourceUri) {
const orientationData = packet.orientation;
if (defined_default(orientationData)) {
processPacketData(
Quaternion_default,
entity,
"orientation",
orientationData,
void 0,
sourceUri,
entityCollection
);
}
}
function processProperties(entity, packet, entityCollection, sourceUri) {
const propertiesData = packet.properties;
if (defined_default(propertiesData)) {
if (!defined_default(entity.properties)) {
entity.properties = new PropertyBag_default();
}
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],
void 0,
sourceUri,
entityCollection
);
}
} else {
processProperty(
getPropertyType(propertyData),
entity.properties,
key,
propertyData,
void 0,
sourceUri,
entityCollection
);
}
}
}
}
}
function processReferencesArrayPacketData(object, propertyName, references, interval, entityCollection, PropertyArrayType, CompositePropertyArrayType) {
const properties = references.map(function(reference) {
return createReferenceProperty(entityCollection, reference);
});
if (defined_default(interval)) {
interval = intervalFromString(interval);
let property = object[propertyName];
if (!(property instanceof CompositePropertyArrayType)) {
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_default(references)) {
processReferencesArrayPacketData(
object,
propertyName,
references,
packetData.interval,
entityCollection,
PropertyArray_default,
CompositeProperty_default
);
} else {
processPacketData(
Array,
object,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
function processArray(object, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; ++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_default(references)) {
processReferencesArrayPacketData(
object,
propertyName,
references,
packetData.interval,
entityCollection,
PositionPropertyArray_default,
CompositePositionProperty_default
);
} else {
if (defined_default(packetData.cartesian)) {
packetData.array = Cartesian3_default.unpackArray(packetData.cartesian);
} else if (defined_default(packetData.cartographicRadians)) {
packetData.array = Cartesian3_default.fromRadiansArrayHeights(
packetData.cartographicRadians
);
} else if (defined_default(packetData.cartographicDegrees)) {
packetData.array = Cartesian3_default.fromDegreesArrayHeights(
packetData.cartographicDegrees
);
}
if (defined_default(packetData.array)) {
processPacketData(
Array,
object,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
}
function processPositionArray(object, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; ++i) {
processPositionArrayPacketData(
object,
propertyName,
packetData[i],
entityCollection
);
}
} else {
processPositionArrayPacketData(
object,
propertyName,
packetData,
entityCollection
);
}
}
function unpackCartesianArray(array) {
return Cartesian3_default.unpackArray(array);
}
function unpackCartographicRadiansArray(array) {
return Cartesian3_default.fromRadiansArrayHeights(array);
}
function unpackCartographicDegreesArray(array) {
return Cartesian3_default.fromDegreesArrayHeights(array);
}
function processPositionArrayOfArraysPacketData(object, propertyName, packetData, entityCollection) {
const references = packetData.references;
if (defined_default(references)) {
const properties = references.map(function(referenceArray) {
const tempObj = {};
processReferencesArrayPacketData(
tempObj,
"positions",
referenceArray,
packetData.interval,
entityCollection,
PositionPropertyArray_default,
CompositePositionProperty_default
);
return tempObj.positions;
});
object[propertyName] = new PositionPropertyArray_default(properties);
} else {
if (defined_default(packetData.cartesian)) {
packetData.array = packetData.cartesian.map(unpackCartesianArray);
} else if (defined_default(packetData.cartographicRadians)) {
packetData.array = packetData.cartographicRadians.map(
unpackCartographicRadiansArray
);
} else if (defined_default(packetData.cartographicDegrees)) {
packetData.array = packetData.cartographicDegrees.map(
unpackCartographicDegreesArray
);
}
if (defined_default(packetData.array)) {
processPacketData(
Array,
object,
propertyName,
packetData,
void 0,
void 0,
entityCollection
);
}
}
}
function processPositionArrayOfArrays(object, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; ++i) {
processPositionArrayOfArraysPacketData(
object,
propertyName,
packetData[i],
entityCollection
);
}
} else {
processPositionArrayOfArraysPacketData(
object,
propertyName,
packetData,
entityCollection
);
}
}
function processShape(object, propertyName, packetData, entityCollection) {
if (!defined_default(packetData)) {
return;
}
if (Array.isArray(packetData)) {
for (let i = 0, length3 = packetData.length; i < length3; 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_default(packetData)) {
return;
}
let intervals;
if (Array.isArray(packetData)) {
for (let i = 0, len = packetData.length; i < len; ++i) {
if (!defined_default(intervals)) {
intervals = new TimeIntervalCollection_default();
}
intervals.addInterval(intervalFromString(packetData[i]));
}
} else {
intervals = new TimeIntervalCollection_default();
intervals.addInterval(intervalFromString(packetData));
}
entity.availability = intervals;
}
function processAlignedAxis(billboard, packetData, interval, sourceUri, entityCollection) {
if (!defined_default(packetData)) {
return;
}
processPacketData(
UnitCartesian3,
billboard,
"alignedAxis",
packetData,
interval,
sourceUri,
entityCollection
);
}
function processBillboard(entity, packet, entityCollection, sourceUri) {
const billboardData = packet.billboard;
if (!defined_default(billboardData)) {
return;
}
const interval = intervalFromString(billboardData.interval);
let billboard = entity.billboard;
if (!defined_default(billboard)) {
entity.billboard = billboard = new BillboardGraphics_default();
}
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_default,
billboard,
"pixelOffset",
billboardData.pixelOffset,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
billboard,
"eyeOffset",
billboardData.eyeOffset,
interval,
sourceUri,
entityCollection
);
processPacketData(
HorizontalOrigin_default,
billboard,
"horizontalOrigin",
billboardData.horizontalOrigin,
interval,
sourceUri,
entityCollection
);
processPacketData(
VerticalOrigin_default,
billboard,
"verticalOrigin",
billboardData.verticalOrigin,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
billboard,
"heightReference",
billboardData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
billboard,
"color",
billboardData.color,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rotation_default,
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_default,
billboard,
"scaleByDistance",
billboardData.scaleByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
billboard,
"translucencyByDistance",
billboardData.translucencyByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
billboard,
"pixelOffsetScaleByDistance",
billboardData.pixelOffsetScaleByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
BoundingRectangle_default,
billboard,
"imageSubRegion",
billboardData.imageSubRegion,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
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_default(boxData)) {
return;
}
const interval = intervalFromString(boxData.interval);
let box = entity.box;
if (!defined_default(box)) {
entity.box = box = new BoxGraphics_default();
}
processPacketData(
Boolean,
box,
"show",
boxData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
box,
"dimensions",
boxData.dimensions,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
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_default,
box,
"outlineColor",
boxData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
box,
"outlineWidth",
boxData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
box,
"shadows",
boxData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
box,
"distanceDisplayCondition",
boxData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processCorridor(entity, packet, entityCollection, sourceUri) {
const corridorData = packet.corridor;
if (!defined_default(corridorData)) {
return;
}
const interval = intervalFromString(corridorData.interval);
let corridor = entity.corridor;
if (!defined_default(corridor)) {
entity.corridor = corridor = new CorridorGraphics_default();
}
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_default,
corridor,
"heightReference",
corridorData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
corridor,
"extrudedHeight",
corridorData.extrudedHeight,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
corridor,
"extrudedHeightReference",
corridorData.extrudedHeightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
CornerType_default,
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_default,
corridor,
"outlineColor",
corridorData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
corridor,
"outlineWidth",
corridorData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
corridor,
"shadows",
corridorData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
corridor,
"distanceDisplayCondition",
corridorData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
processPacketData(
ClassificationType_default,
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_default(cylinderData)) {
return;
}
const interval = intervalFromString(cylinderData.interval);
let cylinder = entity.cylinder;
if (!defined_default(cylinder)) {
entity.cylinder = cylinder = new CylinderGraphics_default();
}
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_default,
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_default,
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_default,
cylinder,
"shadows",
cylinderData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
cylinder,
"distanceDisplayCondition",
cylinderData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processDocument(packet, dataSource) {
const version2 = packet.version;
if (defined_default(version2)) {
if (typeof version2 === "string") {
const tokens = version2.split(".");
if (tokens.length === 2) {
if (tokens[0] !== "1") {
throw new RuntimeError_default("Cesium only supports CZML version 1.");
}
dataSource._version = version2;
}
}
}
if (!defined_default(dataSource._version)) {
throw new RuntimeError_default(
"CZML version information invalid. It is expected to be a property on the document object in the . version format."
);
}
const documentPacket = dataSource._documentPacket;
if (defined_default(packet.name)) {
documentPacket.name = packet.name;
}
const clockPacket = packet.clock;
if (defined_default(clockPacket)) {
const clock = documentPacket.clock;
if (!defined_default(clock)) {
documentPacket.clock = {
interval: clockPacket.interval,
currentTime: clockPacket.currentTime,
range: clockPacket.range,
step: clockPacket.step,
multiplier: clockPacket.multiplier
};
} else {
clock.interval = defaultValue_default(clockPacket.interval, clock.interval);
clock.currentTime = defaultValue_default(
clockPacket.currentTime,
clock.currentTime
);
clock.range = defaultValue_default(clockPacket.range, clock.range);
clock.step = defaultValue_default(clockPacket.step, clock.step);
clock.multiplier = defaultValue_default(clockPacket.multiplier, clock.multiplier);
}
}
}
function processEllipse(entity, packet, entityCollection, sourceUri) {
const ellipseData = packet.ellipse;
if (!defined_default(ellipseData)) {
return;
}
const interval = intervalFromString(ellipseData.interval);
let ellipse = entity.ellipse;
if (!defined_default(ellipse)) {
entity.ellipse = ellipse = new EllipseGraphics_default();
}
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_default,
ellipse,
"heightReference",
ellipseData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
ellipse,
"extrudedHeight",
ellipseData.extrudedHeight,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
ellipse,
"extrudedHeightReference",
ellipseData.extrudedHeightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rotation_default,
ellipse,
"rotation",
ellipseData.rotation,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rotation_default,
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_default,
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_default,
ellipse,
"shadows",
ellipseData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
ellipse,
"distanceDisplayCondition",
ellipseData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
processPacketData(
ClassificationType_default,
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_default(ellipsoidData)) {
return;
}
const interval = intervalFromString(ellipsoidData.interval);
let ellipsoid = entity.ellipsoid;
if (!defined_default(ellipsoid)) {
entity.ellipsoid = ellipsoid = new EllipsoidGraphics_default();
}
processPacketData(
Boolean,
ellipsoid,
"show",
ellipsoidData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
ellipsoid,
"radii",
ellipsoidData.radii,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
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_default,
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_default,
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_default,
ellipsoid,
"shadows",
ellipsoidData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
ellipsoid,
"distanceDisplayCondition",
ellipsoidData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processLabel(entity, packet, entityCollection, sourceUri) {
const labelData = packet.label;
if (!defined_default(labelData)) {
return;
}
const interval = intervalFromString(labelData.interval);
let label = entity.label;
if (!defined_default(label)) {
entity.label = label = new LabelGraphics_default();
}
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_default,
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_default,
label,
"backgroundColor",
labelData.backgroundColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
label,
"backgroundPadding",
labelData.backgroundPadding,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian2_default,
label,
"pixelOffset",
labelData.pixelOffset,
interval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
label,
"eyeOffset",
labelData.eyeOffset,
interval,
sourceUri,
entityCollection
);
processPacketData(
HorizontalOrigin_default,
label,
"horizontalOrigin",
labelData.horizontalOrigin,
interval,
sourceUri,
entityCollection
);
processPacketData(
VerticalOrigin_default,
label,
"verticalOrigin",
labelData.verticalOrigin,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
label,
"heightReference",
labelData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
label,
"fillColor",
labelData.fillColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
label,
"outlineColor",
labelData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
label,
"outlineWidth",
labelData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
label,
"translucencyByDistance",
labelData.translucencyByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
label,
"pixelOffsetScaleByDistance",
labelData.pixelOffsetScaleByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
label,
"scaleByDistance",
labelData.scaleByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
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_default(modelData)) {
return;
}
const interval = intervalFromString(modelData.interval);
let model = entity.model;
if (!defined_default(model)) {
entity.model = model = new ModelGraphics_default();
}
processPacketData(
Boolean,
model,
"show",
modelData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
import_urijs10.default,
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_default,
model,
"shadows",
modelData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
model,
"heightReference",
modelData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
model,
"silhouetteColor",
modelData.silhouetteColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
model,
"silhouetteSize",
modelData.silhouetteSize,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
model,
"color",
modelData.color,
interval,
sourceUri,
entityCollection
);
processPacketData(
ColorBlendMode_default,
model,
"colorBlendMode",
modelData.colorBlendMode,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
model,
"colorBlendAmount",
modelData.colorBlendAmount,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
model,
"distanceDisplayCondition",
modelData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
let i, len;
const nodeTransformationsData = modelData.nodeTransformations;
if (defined_default(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_default(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_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} 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_default(nodeTransformationData)) {
continue;
}
if (!defined_default(nodeTransformations)) {
model.nodeTransformations = nodeTransformations = new PropertyBag_default();
}
if (!nodeTransformations.hasProperty(nodeName)) {
nodeTransformations.addProperty(nodeName);
}
let nodeTransformation = nodeTransformations[nodeName];
if (!defined_default(nodeTransformation)) {
nodeTransformations[nodeName] = nodeTransformation = new NodeTransformationProperty_default();
}
processPacketData(
Cartesian3_default,
nodeTransformation,
"translation",
nodeTransformationData.translation,
combinedInterval,
sourceUri,
entityCollection
);
processPacketData(
Quaternion_default,
nodeTransformation,
"rotation",
nodeTransformationData.rotation,
combinedInterval,
sourceUri,
entityCollection
);
processPacketData(
Cartesian3_default,
nodeTransformation,
"scale",
nodeTransformationData.scale,
combinedInterval,
sourceUri,
entityCollection
);
}
}
function processArticulations(model, articulationsData, constrainedInterval, sourceUri, entityCollection) {
let combinedInterval = intervalFromString(articulationsData.interval);
if (defined_default(constrainedInterval)) {
if (defined_default(combinedInterval)) {
combinedInterval = TimeInterval_default.intersect(
combinedInterval,
constrainedInterval,
scratchTimeInterval
);
} 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_default(articulationStageData)) {
continue;
}
if (!defined_default(articulations)) {
model.articulations = articulations = new PropertyBag_default();
}
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_default(pathData)) {
return;
}
const interval = intervalFromString(pathData.interval);
let path = entity.path;
if (!defined_default(path)) {
entity.path = path = new PathGraphics_default();
}
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_default,
path,
"distanceDisplayCondition",
pathData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processPoint(entity, packet, entityCollection, sourceUri) {
const pointData = packet.point;
if (!defined_default(pointData)) {
return;
}
const interval = intervalFromString(pointData.interval);
let point = entity.point;
if (!defined_default(point)) {
entity.point = point = new PointGraphics_default();
}
processPacketData(
Boolean,
point,
"show",
pointData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
point,
"pixelSize",
pointData.pixelSize,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
point,
"heightReference",
pointData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
point,
"color",
pointData.color,
interval,
sourceUri,
entityCollection
);
processPacketData(
Color_default,
point,
"outlineColor",
pointData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
point,
"outlineWidth",
pointData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
point,
"scaleByDistance",
pointData.scaleByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
NearFarScalar_default,
point,
"translucencyByDistance",
pointData.translucencyByDistance,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
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_default();
}
Object.defineProperties(PolygonHierarchyProperty.prototype, {
isConstant: {
get: function() {
const positions = this.polygon._positions;
const holes = this.polygon._holes;
return (!defined_default(positions) || positions.isConstant) && (!defined_default(holes) || holes.isConstant);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
}
});
PolygonHierarchyProperty.prototype.getValue = function(time, result) {
let positions;
if (defined_default(this.polygon._positions)) {
positions = this.polygon._positions.getValue(time);
}
let holes;
if (defined_default(this.polygon._holes)) {
holes = this.polygon._holes.getValue(time);
if (defined_default(holes)) {
holes = holes.map(function(holePositions) {
return new PolygonHierarchy_default(holePositions);
});
}
}
if (!defined_default(result)) {
return new PolygonHierarchy_default(positions, holes);
}
result.positions = positions;
result.holes = holes;
return result;
};
PolygonHierarchyProperty.prototype.equals = function(other) {
return this === other || other instanceof PolygonHierarchyProperty && Property_default.equals(this.polygon._positions, other.polygon._positions) && Property_default.equals(this.polygon._holes, other.polygon._holes);
};
function processPolygon(entity, packet, entityCollection, sourceUri) {
const polygonData = packet.polygon;
if (!defined_default(polygonData)) {
return;
}
const interval = intervalFromString(polygonData.interval);
let polygon = entity.polygon;
if (!defined_default(polygon)) {
entity.polygon = polygon = new PolygonGraphics_default();
}
processPacketData(
Boolean,
polygon,
"show",
polygonData.show,
interval,
sourceUri,
entityCollection
);
processPositionArray(
polygon,
"_positions",
polygonData.positions,
entityCollection
);
processPositionArrayOfArrays(
polygon,
"_holes",
polygonData.holes,
entityCollection
);
if (defined_default(polygon._positions) || defined_default(polygon._holes)) {
polygon.hierarchy = new PolygonHierarchyProperty(polygon);
}
processPacketData(
Number,
polygon,
"height",
polygonData.height,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
polygon,
"heightReference",
polygonData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
polygon,
"extrudedHeight",
polygonData.extrudedHeight,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
polygon,
"extrudedHeightReference",
polygonData.extrudedHeightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rotation_default,
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_default,
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_default,
polygon,
"arcType",
polygonData.arcType,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
polygon,
"shadows",
polygonData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
polygon,
"distanceDisplayCondition",
polygonData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
processPacketData(
ClassificationType_default,
polygon,
"classificationType",
polygonData.classificationType,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
polygon,
"zIndex",
polygonData.zIndex,
interval,
sourceUri,
entityCollection
);
}
function adaptFollowSurfaceToArcType(followSurface) {
return followSurface ? ArcType_default.GEODESIC : ArcType_default.NONE;
}
function processPolyline(entity, packet, entityCollection, sourceUri) {
const polylineData = packet.polyline;
if (!defined_default(polylineData)) {
return;
}
const interval = intervalFromString(polylineData.interval);
let polyline = entity.polyline;
if (!defined_default(polyline)) {
entity.polyline = polyline = new PolylineGraphics_default();
}
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_default,
polyline,
"arcType",
polylineData.arcType,
interval,
sourceUri,
entityCollection
);
processPacketData(
Boolean,
polyline,
"clampToGround",
polylineData.clampToGround,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
polyline,
"shadows",
polylineData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
polyline,
"distanceDisplayCondition",
polylineData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
processPacketData(
ClassificationType_default,
polyline,
"classificationType",
polylineData.classificationType,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
polyline,
"zIndex",
polylineData.zIndex,
interval,
sourceUri,
entityCollection
);
if (defined_default(polylineData.followSurface) && !defined_default(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_default(polylineVolumeData)) {
return;
}
const interval = intervalFromString(polylineVolumeData.interval);
let polylineVolume = entity.polylineVolume;
if (!defined_default(polylineVolume)) {
entity.polylineVolume = polylineVolume = new PolylineVolumeGraphics_default();
}
processPositionArray(
polylineVolume,
"positions",
polylineVolumeData.positions,
entityCollection
);
processShape(
polylineVolume,
"shape",
polylineVolumeData.shape,
entityCollection
);
processPacketData(
Boolean,
polylineVolume,
"show",
polylineVolumeData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
CornerType_default,
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_default,
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_default,
polylineVolume,
"shadows",
polylineVolumeData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
polylineVolume,
"distanceDisplayCondition",
polylineVolumeData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processRectangle(entity, packet, entityCollection, sourceUri) {
const rectangleData = packet.rectangle;
if (!defined_default(rectangleData)) {
return;
}
const interval = intervalFromString(rectangleData.interval);
let rectangle = entity.rectangle;
if (!defined_default(rectangle)) {
entity.rectangle = rectangle = new RectangleGraphics_default();
}
processPacketData(
Boolean,
rectangle,
"show",
rectangleData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rectangle_default,
rectangle,
"coordinates",
rectangleData.coordinates,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
rectangle,
"height",
rectangleData.height,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
rectangle,
"heightReference",
rectangleData.heightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
rectangle,
"extrudedHeight",
rectangleData.extrudedHeight,
interval,
sourceUri,
entityCollection
);
processPacketData(
HeightReference_default,
rectangle,
"extrudedHeightReference",
rectangleData.extrudedHeightReference,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rotation_default,
rectangle,
"rotation",
rectangleData.rotation,
interval,
sourceUri,
entityCollection
);
processPacketData(
Rotation_default,
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_default,
rectangle,
"outlineColor",
rectangleData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
rectangle,
"outlineWidth",
rectangleData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
rectangle,
"shadows",
rectangleData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
rectangle,
"distanceDisplayCondition",
rectangleData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
processPacketData(
ClassificationType_default,
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_default(tilesetData)) {
return;
}
const interval = intervalFromString(tilesetData.interval);
let tileset = entity.tileset;
if (!defined_default(tileset)) {
entity.tileset = tileset = new Cesium3DTilesetGraphics_default();
}
processPacketData(
Boolean,
tileset,
"show",
tilesetData.show,
interval,
sourceUri,
entityCollection
);
processPacketData(
import_urijs10.default,
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_default(wallData)) {
return;
}
const interval = intervalFromString(wallData.interval);
let wall = entity.wall;
if (!defined_default(wall)) {
entity.wall = wall = new WallGraphics_default();
}
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_default,
wall,
"outlineColor",
wallData.outlineColor,
interval,
sourceUri,
entityCollection
);
processPacketData(
Number,
wall,
"outlineWidth",
wallData.outlineWidth,
interval,
sourceUri,
entityCollection
);
processPacketData(
ShadowMode_default,
wall,
"shadows",
wallData.shadows,
interval,
sourceUri,
entityCollection
);
processPacketData(
DistanceDisplayCondition_default,
wall,
"distanceDisplayCondition",
wallData.distanceDisplayCondition,
interval,
sourceUri,
entityCollection
);
}
function processCzmlPacket(packet, entityCollection, updaterFunctions, sourceUri, dataSource) {
let objectId = packet.id;
if (!defined_default(objectId)) {
objectId = createGuid_default();
}
currentId = objectId;
if (!defined_default(dataSource._version) && objectId !== "document") {
throw new RuntimeError_default(
"The first CZML packet is required to be the document object."
);
}
if (packet["delete"] === true) {
entityCollection.removeById(objectId);
} else if (objectId === "document") {
processDocument(packet, dataSource);
} else {
const entity = entityCollection.getOrCreateEntity(objectId);
const parentId = packet.parent;
if (defined_default(parentId)) {
entity.parent = entityCollection.getOrCreateEntity(parentId);
}
for (let i = updaterFunctions.length - 1; i > -1; i--) {
updaterFunctions[i](entity, packet, entityCollection, sourceUri);
}
}
currentId = void 0;
}
function updateClock(dataSource) {
let clock;
const clockPacket = dataSource._documentPacket.clock;
if (!defined_default(clockPacket)) {
if (!defined_default(dataSource._clock)) {
const availability = dataSource._entityCollection.computeAvailability();
if (!availability.start.equals(Iso8601_default.MINIMUM_VALUE)) {
const startTime = availability.start;
const stopTime = availability.stop;
const totalSeconds = JulianDate_default.secondsDifference(stopTime, startTime);
const multiplier = Math.round(totalSeconds / 120);
clock = new DataSourceClock_default();
clock.startTime = JulianDate_default.clone(startTime);
clock.stopTime = JulianDate_default.clone(stopTime);
clock.clockRange = ClockRange_default.LOOP_STOP;
clock.multiplier = multiplier;
clock.currentTime = JulianDate_default.clone(startTime);
clock.clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
dataSource._clock = clock;
return true;
}
}
return false;
}
if (defined_default(dataSource._clock)) {
clock = dataSource._clock.clone();
} else {
clock = new DataSourceClock_default();
clock.startTime = Iso8601_default.MINIMUM_VALUE.clone();
clock.stopTime = Iso8601_default.MAXIMUM_VALUE.clone();
clock.currentTime = Iso8601_default.MINIMUM_VALUE.clone();
clock.clockRange = ClockRange_default.LOOP_STOP;
clock.clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
clock.multiplier = 1;
}
const interval = intervalFromString(clockPacket.interval);
if (defined_default(interval)) {
clock.startTime = interval.start;
clock.stopTime = interval.stop;
}
if (defined_default(clockPacket.currentTime)) {
clock.currentTime = JulianDate_default.fromIso8601(clockPacket.currentTime);
}
if (defined_default(clockPacket.range)) {
clock.clockRange = defaultValue_default(
ClockRange_default[clockPacket.range],
ClockRange_default.LOOP_STOP
);
}
if (defined_default(clockPacket.step)) {
clock.clockStep = defaultValue_default(
ClockStep_default[clockPacket.step],
ClockStep_default.SYSTEM_CLOCK_MULTIPLIER
);
}
if (defined_default(clockPacket.multiplier)) {
clock.multiplier = clockPacket.multiplier;
}
if (!clock.equals(dataSource._clock)) {
dataSource._clock = clock.clone(dataSource._clock);
return true;
}
return false;
}
function load(dataSource, czml, options, clear2) {
if (!defined_default(czml)) {
throw new DeveloperError_default("czml is required.");
}
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let promise = czml;
let sourceUri = options.sourceUri;
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
dataSource._credit = credit;
if (typeof czml === "string" || czml instanceof Resource_default) {
czml = Resource_default.createIfNeeded(czml);
promise = czml.fetchJson();
sourceUri = defaultValue_default(sourceUri, czml.clone());
const resourceCredits = dataSource._resourceCredits;
const credits = czml.credits;
if (defined_default(credits)) {
const length3 = credits.length;
for (let i = 0; i < length3; i++) {
resourceCredits.push(credits[i]);
}
}
}
sourceUri = Resource_default.createIfNeeded(sourceUri);
DataSource_default.setLoading(dataSource, true);
return Promise.resolve(promise).then(function(czml2) {
return loadCzml(dataSource, czml2, sourceUri, clear2);
}).catch(function(error) {
DataSource_default.setLoading(dataSource, false);
dataSource._error.raiseEvent(dataSource, error);
console.log(error);
return Promise.reject(error);
});
}
function loadCzml(dataSource, czml, sourceUri, clear2) {
DataSource_default.setLoading(dataSource, true);
const entityCollection = dataSource._entityCollection;
if (clear2) {
dataSource._version = void 0;
dataSource._documentPacket = new DocumentPacket();
entityCollection.removeAll();
}
CzmlDataSource._processCzml(
czml,
entityCollection,
sourceUri,
void 0,
dataSource
);
let raiseChangedEvent = updateClock(dataSource);
const documentPacket = dataSource._documentPacket;
if (defined_default(documentPacket.name) && dataSource._name !== documentPacket.name) {
dataSource._name = documentPacket.name;
raiseChangedEvent = true;
} else if (!defined_default(dataSource._name) && defined_default(sourceUri)) {
dataSource._name = getFilenameFromUri_default(sourceUri.getUrlComponent());
raiseChangedEvent = true;
}
DataSource_default.setLoading(dataSource, false);
if (raiseChangedEvent) {
dataSource._changed.raiseEvent(dataSource);
}
return dataSource;
}
function DocumentPacket() {
this.name = void 0;
this.clock = void 0;
}
function CzmlDataSource(name) {
this._name = name;
this._changed = new Event_default();
this._error = new Event_default();
this._isLoading = false;
this._loading = new Event_default();
this._clock = void 0;
this._documentPacket = new DocumentPacket();
this._version = void 0;
this._entityCollection = new EntityCollection_default(this);
this._entityCluster = new EntityCluster_default();
this._credit = void 0;
this._resourceCredits = [];
}
CzmlDataSource.load = function(czml, options) {
return new CzmlDataSource().load(czml, options);
};
Object.defineProperties(CzmlDataSource.prototype, {
name: {
get: function() {
return this._name;
}
},
clock: {
get: function() {
return this._clock;
}
},
entities: {
get: function() {
return this._entityCollection;
}
},
isLoading: {
get: function() {
return this._isLoading;
}
},
changedEvent: {
get: function() {
return this._changed;
}
},
errorEvent: {
get: function() {
return this._error;
}
},
loadingEvent: {
get: function() {
return this._loading;
}
},
show: {
get: function() {
return this._entityCollection.show;
},
set: function(value) {
this._entityCollection.show = value;
}
},
clustering: {
get: function() {
return this._entityCluster;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value must be defined.");
}
this._entityCluster = value;
}
},
credit: {
get: function() {
return this._credit;
}
}
});
CzmlDataSource.updaters = [
processBillboard,
processBox,
processCorridor,
processCylinder,
processEllipse,
processEllipsoid,
processLabel,
processModel,
processName,
processDescription,
processPath,
processPoint,
processPolygon,
processPolyline,
processPolylineVolume,
processProperties,
processRectangle,
processPosition,
processTileset,
processViewFrom,
processWall,
processOrientation,
processAvailability
];
CzmlDataSource.prototype.process = function(czml, options) {
return load(this, czml, options, false);
};
CzmlDataSource.prototype.load = function(czml, options) {
return load(this, czml, options, true);
};
CzmlDataSource.prototype.update = function(time) {
return true;
};
CzmlDataSource.processPacketData = processPacketData;
CzmlDataSource.processPositionPacketData = processPositionPacketData;
CzmlDataSource.processMaterialPacketData = processMaterialPacketData;
CzmlDataSource._processCzml = function(czml, entityCollection, sourceUri, updaterFunctions, dataSource) {
updaterFunctions = defaultValue_default(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
);
}
};
var CzmlDataSource_default = CzmlDataSource;
// node_modules/@cesium/engine/Source/DataSources/DataSourceCollection.js
function DataSourceCollection() {
this._dataSources = [];
this._dataSourceAdded = new Event_default();
this._dataSourceRemoved = new Event_default();
this._dataSourceMoved = new Event_default();
}
Object.defineProperties(DataSourceCollection.prototype, {
length: {
get: function() {
return this._dataSources.length;
}
},
dataSourceAdded: {
get: function() {
return this._dataSourceAdded;
}
},
dataSourceRemoved: {
get: function() {
return this._dataSourceRemoved;
}
},
dataSourceMoved: {
get: function() {
return this._dataSourceMoved;
}
}
});
DataSourceCollection.prototype.add = function(dataSource) {
if (!defined_default(dataSource)) {
throw new DeveloperError_default("dataSource is required.");
}
const that = this;
const dataSources = this._dataSources;
return Promise.resolve(dataSource).then(function(value) {
if (dataSources === that._dataSources) {
that._dataSources.push(value);
that._dataSourceAdded.raiseEvent(that, value);
}
return value;
});
};
DataSourceCollection.prototype.remove = function(dataSource, destroy) {
destroy = defaultValue_default(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;
};
DataSourceCollection.prototype.removeAll = function(destroy) {
destroy = defaultValue_default(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 = [];
};
DataSourceCollection.prototype.contains = function(dataSource) {
return this.indexOf(dataSource) !== -1;
};
DataSourceCollection.prototype.indexOf = function(dataSource) {
return this._dataSources.indexOf(dataSource);
};
DataSourceCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
return this._dataSources[index];
};
DataSourceCollection.prototype.getByName = function(name) {
if (!defined_default(name)) {
throw new DeveloperError_default("name is required.");
}
return this._dataSources.filter(function(dataSource) {
return dataSource.name === name;
});
};
function getIndex2(dataSources, dataSource) {
if (!defined_default(dataSource)) {
throw new DeveloperError_default("dataSource is required.");
}
const index = dataSources.indexOf(dataSource);
if (index === -1) {
throw new DeveloperError_default("dataSource is not in this collection.");
}
return index;
}
function swapDataSources(collection, i, j) {
const arr = collection._dataSources;
const length3 = arr.length - 1;
i = Math_default.clamp(i, 0, length3);
j = Math_default.clamp(j, 0, length3);
if (i === j) {
return;
}
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
collection.dataSourceMoved.raiseEvent(temp, j, i);
}
DataSourceCollection.prototype.raise = function(dataSource) {
const index = getIndex2(this._dataSources, dataSource);
swapDataSources(this, index, index + 1);
};
DataSourceCollection.prototype.lower = function(dataSource) {
const index = getIndex2(this._dataSources, dataSource);
swapDataSources(this, index, index - 1);
};
DataSourceCollection.prototype.raiseToTop = function(dataSource) {
const index = getIndex2(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
);
};
DataSourceCollection.prototype.lowerToBottom = function(dataSource) {
const index = getIndex2(this._dataSources, dataSource);
if (index === 0) {
return;
}
this._dataSources.splice(index, 1);
this._dataSources.splice(0, 0, dataSource);
this.dataSourceMoved.raiseEvent(dataSource, 0, index);
};
DataSourceCollection.prototype.isDestroyed = function() {
return false;
};
DataSourceCollection.prototype.destroy = function() {
this.removeAll(true);
return destroyObject_default(this);
};
var DataSourceCollection_default = DataSourceCollection;
// node_modules/@cesium/engine/Source/Scene/PrimitiveCollection.js
function PrimitiveCollection(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._primitives = [];
this._guid = createGuid_default();
this._zIndex = void 0;
this.show = defaultValue_default(options.show, true);
this.destroyPrimitives = defaultValue_default(options.destroyPrimitives, true);
}
Object.defineProperties(PrimitiveCollection.prototype, {
length: {
get: function() {
return this._primitives.length;
}
}
});
PrimitiveCollection.prototype.add = function(primitive, index) {
const hasIndex = defined_default(index);
if (!defined_default(primitive)) {
throw new DeveloperError_default("primitive is required.");
}
if (hasIndex) {
if (index < 0) {
throw new DeveloperError_default("index must be greater than or equal to zero.");
} else if (index > this._primitives.length) {
throw new DeveloperError_default(
"index must be less than or equal to the number of primitives."
);
}
}
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;
};
PrimitiveCollection.prototype.remove = function(primitive) {
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;
}
}
return false;
};
PrimitiveCollection.prototype.removeAndDestroy = function(primitive) {
const removed = this.remove(primitive);
if (removed && !this.destroyPrimitives) {
primitive.destroy();
}
return removed;
};
PrimitiveCollection.prototype.removeAll = function() {
const primitives = this._primitives;
const length3 = primitives.length;
for (let i = 0; i < length3; ++i) {
delete primitives[i]._external._composites[this._guid];
if (this.destroyPrimitives) {
primitives[i].destroy();
}
}
this._primitives = [];
};
PrimitiveCollection.prototype.contains = function(primitive) {
return !!(defined_default(primitive) && primitive._external && primitive._external._composites && primitive._external._composites[this._guid]);
};
function getPrimitiveIndex(compositePrimitive, primitive) {
if (!compositePrimitive.contains(primitive)) {
throw new DeveloperError_default("primitive is not in this collection.");
}
return compositePrimitive._primitives.indexOf(primitive);
}
PrimitiveCollection.prototype.raise = function(primitive) {
if (defined_default(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;
}
}
};
PrimitiveCollection.prototype.raiseToTop = function(primitive) {
if (defined_default(primitive)) {
const index = getPrimitiveIndex(this, primitive);
const primitives = this._primitives;
if (index !== primitives.length - 1) {
primitives.splice(index, 1);
primitives.push(primitive);
}
}
};
PrimitiveCollection.prototype.lower = function(primitive) {
if (defined_default(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;
}
}
};
PrimitiveCollection.prototype.lowerToBottom = function(primitive) {
if (defined_default(primitive)) {
const index = getPrimitiveIndex(this, primitive);
const primitives = this._primitives;
if (index !== 0) {
primitives.splice(index, 1);
primitives.unshift(primitive);
}
}
};
PrimitiveCollection.prototype.get = function(index) {
if (!defined_default(index)) {
throw new DeveloperError_default("index is required.");
}
return this._primitives[index];
};
PrimitiveCollection.prototype.update = function(frameState) {
if (!this.show) {
return;
}
const primitives = this._primitives;
for (let i = 0; i < primitives.length; ++i) {
primitives[i].update(frameState);
}
};
PrimitiveCollection.prototype.prePassesUpdate = function(frameState) {
const primitives = this._primitives;
for (let i = 0; i < primitives.length; ++i) {
const primitive = primitives[i];
if (defined_default(primitive.prePassesUpdate)) {
primitive.prePassesUpdate(frameState);
}
}
};
PrimitiveCollection.prototype.updateForPass = function(frameState, passState) {
const primitives = this._primitives;
for (let i = 0; i < primitives.length; ++i) {
const primitive = primitives[i];
if (defined_default(primitive.updateForPass)) {
primitive.updateForPass(frameState, passState);
}
}
};
PrimitiveCollection.prototype.postPassesUpdate = function(frameState) {
const primitives = this._primitives;
for (let i = 0; i < primitives.length; ++i) {
const primitive = primitives[i];
if (defined_default(primitive.postPassesUpdate)) {
primitive.postPassesUpdate(frameState);
}
}
};
PrimitiveCollection.prototype.isDestroyed = function() {
return false;
};
PrimitiveCollection.prototype.destroy = function() {
this.removeAll();
return destroyObject_default(this);
};
var PrimitiveCollection_default = PrimitiveCollection;
// node_modules/@cesium/engine/Source/Scene/OrderedGroundPrimitiveCollection.js
function OrderedGroundPrimitiveCollection() {
this._length = 0;
this._collections = {};
this._collectionsArray = [];
this.show = true;
}
Object.defineProperties(OrderedGroundPrimitiveCollection.prototype, {
length: {
get: function() {
return this._length;
}
}
});
OrderedGroundPrimitiveCollection.prototype.add = function(primitive, zIndex) {
Check_default.defined("primitive", primitive);
if (defined_default(zIndex)) {
Check_default.typeOf.number("zIndex", zIndex);
}
zIndex = defaultValue_default(zIndex, 0);
let collection = this._collections[zIndex];
if (!defined_default(collection)) {
collection = new PrimitiveCollection_default({ 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;
};
OrderedGroundPrimitiveCollection.prototype.set = function(primitive, zIndex) {
Check_default.defined("primitive", primitive);
Check_default.typeOf.number("zIndex", zIndex);
if (zIndex === primitive._zIndex) {
return primitive;
}
this.remove(primitive, true);
this.add(primitive, zIndex);
return primitive;
};
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] = void 0;
collection.destroy();
}
return result;
}
return false;
};
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;
};
OrderedGroundPrimitiveCollection.prototype.contains = function(primitive) {
if (!defined_default(primitive)) {
return false;
}
const collection = this._collections[primitive._zIndex];
return defined_default(collection) && collection.contains(primitive);
};
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);
}
};
OrderedGroundPrimitiveCollection.prototype.isDestroyed = function() {
return false;
};
OrderedGroundPrimitiveCollection.prototype.destroy = function() {
this.removeAll();
return destroyObject_default(this);
};
var OrderedGroundPrimitiveCollection_default = OrderedGroundPrimitiveCollection;
// node_modules/@cesium/engine/Source/DataSources/DynamicGeometryBatch.js
function DynamicGeometryBatch(primitives, orderedGroundPrimitives) {
this._primitives = primitives;
this._orderedGroundPrimitives = orderedGroundPrimitives;
this._dynamicUpdaters = new AssociativeArray_default();
}
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_default(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_default(updater) && defined_default(updater.getBoundingSphere)) {
return updater.getBoundingSphere(result);
}
return BoundingSphereState_default.FAILED;
};
var DynamicGeometryBatch_default = DynamicGeometryBatch;
// node_modules/@cesium/engine/Source/Core/EllipseGeometryLibrary.js
var EllipseGeometryLibrary = {};
var rotAxis = new Cartesian3_default();
var tempVec = new Cartesian3_default();
var unitQuat = new Quaternion_default();
var rotMtx = new Matrix3_default();
function pointOnEllipsoid(theta, rotation, northVec, eastVec, aSqr, ab, bSqr, mag, unitPos, result) {
const azimuth = theta + rotation;
Cartesian3_default.multiplyByScalar(eastVec, Math.cos(azimuth), rotAxis);
Cartesian3_default.multiplyByScalar(northVec, Math.sin(azimuth), tempVec);
Cartesian3_default.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;
Quaternion_default.fromAxisAngle(rotAxis, angle, unitQuat);
Matrix3_default.fromQuaternion(unitQuat, rotMtx);
Matrix3_default.multiplyByVector(rotMtx, unitPos, result);
Cartesian3_default.normalize(result, result);
Cartesian3_default.multiplyByScalar(result, mag, result);
return result;
}
var scratchCartesian16 = new Cartesian3_default();
var scratchCartesian27 = new Cartesian3_default();
var scratchCartesian37 = new Cartesian3_default();
var scratchNormal2 = new Cartesian3_default();
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 length3 = positions.length;
const bottomOffset = extrude ? length3 : 0;
for (let i = 0; i < length3; i += 3) {
const i1 = i + 1;
const i2 = i + 2;
const position = Cartesian3_default.fromArray(positions, i, scratchCartesian16);
ellipsoid.scaleToGeodeticSurface(position, position);
const extrudedPosition = Cartesian3_default.clone(position, scratchCartesian27);
const normal2 = ellipsoid.geodeticSurfaceNormal(position, scratchNormal2);
const scaledNormal = Cartesian3_default.multiplyByScalar(
normal2,
height,
scratchCartesian37
);
Cartesian3_default.add(position, scaledNormal, position);
if (extrude) {
Cartesian3_default.multiplyByScalar(normal2, extrudedHeight, scaledNormal);
Cartesian3_default.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;
};
var unitPosScratch = new Cartesian3_default();
var eastVecScratch = new Cartesian3_default();
var northVecScratch = new Cartesian3_default();
EllipseGeometryLibrary.computeEllipsePositions = function(options, addFillPositions, addEdgePositions) {
const semiMinorAxis = options.semiMinorAxis;
const semiMajorAxis = options.semiMajorAxis;
const rotation = options.rotation;
const center = options.center;
const granularity = options.granularity * 8;
const aSqr = semiMinorAxis * semiMinorAxis;
const bSqr = semiMajorAxis * semiMajorAxis;
const ab = semiMajorAxis * semiMinorAxis;
const mag = Cartesian3_default.magnitude(center);
const unitPos = Cartesian3_default.normalize(center, unitPosScratch);
let eastVec = Cartesian3_default.cross(Cartesian3_default.UNIT_Z, center, eastVecScratch);
eastVec = Cartesian3_default.normalize(eastVec, eastVec);
const northVec = Cartesian3_default.cross(unitPos, eastVec, northVecScratch);
let numPts = 1 + Math.ceil(Math_default.PI_OVER_TWO / granularity);
const deltaTheta = Math_default.PI_OVER_TWO / (numPts - 1);
let theta = Math_default.PI_OVER_TWO - numPts * deltaTheta;
if (theta < 0) {
numPts -= Math.ceil(Math.abs(theta) / deltaTheta);
}
const size = 2 * (numPts * (numPts + 2));
const positions = addFillPositions ? new Array(size * 3) : void 0;
let positionIndex = 0;
let position = scratchCartesian16;
let reflectedPosition = scratchCartesian27;
const outerPositionsLength = numPts * 4 * 3;
let outerRightIndex = outerPositionsLength - 1;
let outerLeftIndex = 0;
const outerPositions = addEdgePositions ? new Array(outerPositionsLength) : void 0;
let i;
let j;
let numInterior;
let t;
let interiorPosition;
theta = Math_default.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 = Math_default.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_default.lerp(
position,
reflectedPosition,
t,
scratchCartesian37
);
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 = Math_default.PI_OVER_TWO - (i + 1) * deltaTheta;
}
for (i = numPts; i > 1; --i) {
theta = Math_default.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_default.lerp(
position,
reflectedPosition,
t,
scratchCartesian37
);
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 = Math_default.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;
};
var EllipseGeometryLibrary_default = EllipseGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/EllipseGeometry.js
var scratchCartesian17 = new Cartesian3_default();
var scratchCartesian28 = new Cartesian3_default();
var scratchCartesian38 = new Cartesian3_default();
var scratchCartesian45 = new Cartesian3_default();
var texCoordScratch = new Cartesian2_default();
var textureMatrixScratch = new Matrix3_default();
var tangentMatrixScratch = new Matrix3_default();
var quaternionScratch2 = new Quaternion_default();
var scratchNormal3 = new Cartesian3_default();
var scratchTangent = new Cartesian3_default();
var scratchBitangent = new Cartesian3_default();
var scratchCartographic10 = new Cartographic_default();
var projectedCenterScratch = new Cartesian3_default();
var scratchMinTexCoord = new Cartesian2_default();
var scratchMaxTexCoord = new Cartesian2_default();
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) : void 0;
const normals = vertexFormat.normal ? new Float32Array(size * 3) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(size * 3) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(size * 3) : void 0;
const extrudeNormals = shadowVolume ? new Float32Array(size * 3) : void 0;
let textureCoordIndex = 0;
let normal2 = scratchNormal3;
let tangent = scratchTangent;
let bitangent = scratchBitangent;
const projection = new GeographicProjection_default(ellipsoid);
const projectedCenter = projection.project(
ellipsoid.cartesianToCartographic(center, scratchCartographic10),
projectedCenterScratch
);
const geodeticNormal = ellipsoid.scaleToGeodeticSurface(
center,
scratchCartesian17
);
ellipsoid.geodeticSurfaceNormal(geodeticNormal, geodeticNormal);
let textureMatrix = textureMatrixScratch;
let tangentMatrix = tangentMatrixScratch;
if (stRotation !== 0) {
let rotation = Quaternion_default.fromAxisAngle(
geodeticNormal,
stRotation,
quaternionScratch2
);
textureMatrix = Matrix3_default.fromQuaternion(rotation, textureMatrix);
rotation = Quaternion_default.fromAxisAngle(
geodeticNormal,
-stRotation,
quaternionScratch2
);
tangentMatrix = Matrix3_default.fromQuaternion(rotation, tangentMatrix);
} else {
textureMatrix = Matrix3_default.clone(Matrix3_default.IDENTITY, textureMatrix);
tangentMatrix = Matrix3_default.clone(Matrix3_default.IDENTITY, tangentMatrix);
}
const minTexCoord = Cartesian2_default.fromElements(
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
scratchMinTexCoord
);
const maxTexCoord = Cartesian2_default.fromElements(
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY,
scratchMaxTexCoord
);
let length3 = positions.length;
const bottomOffset = extrude ? length3 : 0;
const stOffset = bottomOffset / 3 * 2;
for (let i = 0; i < length3; i += 3) {
const i1 = i + 1;
const i2 = i + 2;
const position = Cartesian3_default.fromArray(positions, i, scratchCartesian17);
if (vertexFormat.st) {
const rotatedPoint = Matrix3_default.multiplyByVector(
textureMatrix,
position,
scratchCartesian28
);
const projectedPoint = projection.project(
ellipsoid.cartesianToCartographic(rotatedPoint, scratchCartographic10),
scratchCartesian38
);
Cartesian3_default.subtract(projectedPoint, projectedCenter, projectedPoint);
texCoordScratch.x = (projectedPoint.x + semiMajorAxis) / (2 * semiMajorAxis);
texCoordScratch.y = (projectedPoint.y + semiMinorAxis) / (2 * 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) {
normal2 = ellipsoid.geodeticSurfaceNormal(position, normal2);
if (shadowVolume) {
extrudeNormals[i + bottomOffset] = -normal2.x;
extrudeNormals[i1 + bottomOffset] = -normal2.y;
extrudeNormals[i2 + bottomOffset] = -normal2.z;
}
if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
if (vertexFormat.tangent || vertexFormat.bitangent) {
tangent = Cartesian3_default.normalize(
Cartesian3_default.cross(Cartesian3_default.UNIT_Z, normal2, tangent),
tangent
);
Matrix3_default.multiplyByVector(tangentMatrix, tangent, tangent);
}
if (vertexFormat.normal) {
normals[i] = normal2.x;
normals[i1] = normal2.y;
normals[i2] = normal2.z;
if (extrude) {
normals[i + bottomOffset] = -normal2.x;
normals[i1 + bottomOffset] = -normal2.y;
normals[i2 + bottomOffset] = -normal2.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_default.normalize(
Cartesian3_default.cross(normal2, 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) {
length3 = textureCoordinates.length;
for (let k = 0; k < length3; 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_default();
if (vertexFormat.position) {
const finalPositions = EllipseGeometryLibrary_default.raisePositionsToHeight(
positions,
options,
extrude
);
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: finalPositions
});
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: textureCoordinates
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
if (shadowVolume) {
attributes.extrudeDirection = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: extrudeNormals
});
}
if (extrude && defined_default(options.offsetAttribute)) {
let offsetAttribute = new Uint8Array(size);
if (options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
} else {
const offsetValue = options.offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
offsetAttribute = offsetAttribute.fill(offsetValue);
}
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: offsetAttribute
});
}
return attributes;
}
function topIndices(numPts) {
const indices2 = new Array(12 * (numPts * (numPts + 1)) - 6);
let indicesIndex = 0;
let prevIndex;
let numInterior;
let positionIndex;
let i;
let j;
prevIndex = 0;
positionIndex = 1;
for (i = 0; i < 3; i++) {
indices2[indicesIndex++] = positionIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
}
for (i = 2; i < numPts + 1; ++i) {
positionIndex = i * (i + 1) - 1;
prevIndex = (i - 1) * i - 1;
indices2[indicesIndex++] = positionIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
numInterior = 2 * i;
for (j = 0; j < numInterior - 1; ++j) {
indices2[indicesIndex++] = positionIndex;
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
}
indices2[indicesIndex++] = positionIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
}
numInterior = numPts * 2;
++positionIndex;
++prevIndex;
for (i = 0; i < numInterior - 1; ++i) {
indices2[indicesIndex++] = positionIndex;
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
}
indices2[indicesIndex++] = positionIndex;
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex++;
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex;
++prevIndex;
for (i = numPts - 1; i > 1; --i) {
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
numInterior = 2 * i;
for (j = 0; j < numInterior - 1; ++j) {
indices2[indicesIndex++] = positionIndex;
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
}
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = positionIndex++;
}
for (i = 0; i < 3; i++) {
indices2[indicesIndex++] = prevIndex++;
indices2[indicesIndex++] = prevIndex;
indices2[indicesIndex++] = positionIndex;
}
return indices2;
}
var boundingSphereCenter = new Cartesian3_default();
function computeEllipse(options) {
const center = options.center;
boundingSphereCenter = Cartesian3_default.multiplyByScalar(
options.ellipsoid.geodeticSurfaceNormal(center, boundingSphereCenter),
options.height,
boundingSphereCenter
);
boundingSphereCenter = Cartesian3_default.add(
center,
boundingSphereCenter,
boundingSphereCenter
);
const boundingSphere = new BoundingSphere_default(
boundingSphereCenter,
options.semiMajorAxis
);
const cep = EllipseGeometryLibrary_default.computeEllipsePositions(
options,
true,
false
);
const positions = cep.positions;
const numPts = cep.numPts;
const attributes = computeTopBottomAttributes(positions, options, false);
let indices2 = topIndices(numPts);
indices2 = IndexDatatype_default.createTypedArray(positions.length / 3, indices2);
return {
boundingSphere,
attributes,
indices: indices2
};
}
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) : void 0;
const normals = vertexFormat.normal ? new Float32Array(size * 3) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(size * 3) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(size * 3) : void 0;
const shadowVolume = options.shadowVolume;
const extrudeNormals = shadowVolume ? new Float32Array(size * 3) : void 0;
let textureCoordIndex = 0;
let normal2 = scratchNormal3;
let tangent = scratchTangent;
let bitangent = scratchBitangent;
const projection = new GeographicProjection_default(ellipsoid);
const projectedCenter = projection.project(
ellipsoid.cartesianToCartographic(center, scratchCartographic10),
projectedCenterScratch
);
const geodeticNormal = ellipsoid.scaleToGeodeticSurface(
center,
scratchCartesian17
);
ellipsoid.geodeticSurfaceNormal(geodeticNormal, geodeticNormal);
const rotation = Quaternion_default.fromAxisAngle(
geodeticNormal,
stRotation,
quaternionScratch2
);
const textureMatrix = Matrix3_default.fromQuaternion(rotation, textureMatrixScratch);
const minTexCoord = Cartesian2_default.fromElements(
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
scratchMinTexCoord
);
const maxTexCoord = Cartesian2_default.fromElements(
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY,
scratchMaxTexCoord
);
let length3 = positions.length;
const stOffset = length3 / 3 * 2;
for (let i = 0; i < length3; i += 3) {
const i1 = i + 1;
const i2 = i + 2;
let position = Cartesian3_default.fromArray(positions, i, scratchCartesian17);
let extrudedPosition;
if (vertexFormat.st) {
const rotatedPoint = Matrix3_default.multiplyByVector(
textureMatrix,
position,
scratchCartesian28
);
const projectedPoint = projection.project(
ellipsoid.cartesianToCartographic(rotatedPoint, scratchCartographic10),
scratchCartesian38
);
Cartesian3_default.subtract(projectedPoint, projectedCenter, projectedPoint);
texCoordScratch.x = (projectedPoint.x + semiMajorAxis) / (2 * semiMajorAxis);
texCoordScratch.y = (projectedPoint.y + semiMinorAxis) / (2 * 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_default.clone(position, scratchCartesian28);
normal2 = ellipsoid.geodeticSurfaceNormal(position, normal2);
if (shadowVolume) {
extrudeNormals[i + length3] = -normal2.x;
extrudeNormals[i1 + length3] = -normal2.y;
extrudeNormals[i2 + length3] = -normal2.z;
}
let scaledNormal = Cartesian3_default.multiplyByScalar(
normal2,
height,
scratchCartesian45
);
position = Cartesian3_default.add(position, scaledNormal, position);
scaledNormal = Cartesian3_default.multiplyByScalar(
normal2,
extrudedHeight,
scaledNormal
);
extrudedPosition = Cartesian3_default.add(
extrudedPosition,
scaledNormal,
extrudedPosition
);
if (vertexFormat.position) {
finalPositions[i + length3] = extrudedPosition.x;
finalPositions[i1 + length3] = extrudedPosition.y;
finalPositions[i2 + length3] = extrudedPosition.z;
finalPositions[i] = position.x;
finalPositions[i1] = position.y;
finalPositions[i2] = position.z;
}
if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
bitangent = Cartesian3_default.clone(normal2, bitangent);
const next = Cartesian3_default.fromArray(
positions,
(i + 3) % length3,
scratchCartesian45
);
Cartesian3_default.subtract(next, position, next);
const bottom = Cartesian3_default.subtract(
extrudedPosition,
position,
scratchCartesian38
);
normal2 = Cartesian3_default.normalize(
Cartesian3_default.cross(bottom, next, normal2),
normal2
);
if (vertexFormat.normal) {
normals[i] = normal2.x;
normals[i1] = normal2.y;
normals[i2] = normal2.z;
normals[i + length3] = normal2.x;
normals[i1 + length3] = normal2.y;
normals[i2 + length3] = normal2.z;
}
if (vertexFormat.tangent) {
tangent = Cartesian3_default.normalize(
Cartesian3_default.cross(bitangent, normal2, tangent),
tangent
);
tangents[i] = tangent.x;
tangents[i1] = tangent.y;
tangents[i2] = tangent.z;
tangents[i + length3] = tangent.x;
tangents[i + 1 + length3] = tangent.y;
tangents[i + 2 + length3] = tangent.z;
}
if (vertexFormat.bitangent) {
bitangents[i] = bitangent.x;
bitangents[i1] = bitangent.y;
bitangents[i2] = bitangent.z;
bitangents[i + length3] = bitangent.x;
bitangents[i1 + length3] = bitangent.y;
bitangents[i2 + length3] = bitangent.z;
}
}
}
if (vertexFormat.st) {
length3 = textureCoordinates.length;
for (let k = 0; k < length3; 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_default();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: finalPositions
});
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: textureCoordinates
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
if (shadowVolume) {
attributes.extrudeDirection = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: extrudeNormals
});
}
if (defined_default(options.offsetAttribute)) {
let offsetAttribute = new Uint8Array(size);
if (options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
} else {
const offsetValue = options.offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
offsetAttribute = offsetAttribute.fill(offsetValue);
}
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: offsetAttribute
});
}
return attributes;
}
function computeWallIndices(positions) {
const length3 = positions.length / 3;
const indices2 = IndexDatatype_default.createTypedArray(length3, length3 * 6);
let index = 0;
for (let i = 0; i < length3; i++) {
const UL = i;
const LL = i + length3;
const UR = (UL + 1) % length3;
const LR = UR + length3;
indices2[index++] = UL;
indices2[index++] = LL;
indices2[index++] = UR;
indices2[index++] = UR;
indices2[index++] = LL;
indices2[index++] = LR;
}
return indices2;
}
var topBoundingSphere2 = new BoundingSphere_default();
var bottomBoundingSphere2 = new BoundingSphere_default();
function computeExtrudedEllipse(options) {
const center = options.center;
const ellipsoid = options.ellipsoid;
const semiMajorAxis = options.semiMajorAxis;
let scaledNormal = Cartesian3_default.multiplyByScalar(
ellipsoid.geodeticSurfaceNormal(center, scratchCartesian17),
options.height,
scratchCartesian17
);
topBoundingSphere2.center = Cartesian3_default.add(
center,
scaledNormal,
topBoundingSphere2.center
);
topBoundingSphere2.radius = semiMajorAxis;
scaledNormal = Cartesian3_default.multiplyByScalar(
ellipsoid.geodeticSurfaceNormal(center, scaledNormal),
options.extrudedHeight,
scaledNormal
);
bottomBoundingSphere2.center = Cartesian3_default.add(
center,
scaledNormal,
bottomBoundingSphere2.center
);
bottomBoundingSphere2.radius = semiMajorAxis;
const cep = EllipseGeometryLibrary_default.computeEllipsePositions(
options,
true,
true
);
const positions = cep.positions;
const numPts = cep.numPts;
const outerPositions = cep.outerPositions;
const boundingSphere = BoundingSphere_default.union(
topBoundingSphere2,
bottomBoundingSphere2
);
const topBottomAttributes = computeTopBottomAttributes(
positions,
options,
true
);
let indices2 = topIndices(numPts);
const length3 = indices2.length;
indices2.length = length3 * 2;
const posLength = positions.length / 3;
for (let i = 0; i < length3; i += 3) {
indices2[i + length3] = indices2[i + 2] + posLength;
indices2[i + 1 + length3] = indices2[i + 1] + posLength;
indices2[i + 2 + length3] = indices2[i] + posLength;
}
const topBottomIndices = IndexDatatype_default.createTypedArray(
posLength * 2 / 3,
indices2
);
const topBottomGeo = new Geometry_default({
attributes: topBottomAttributes,
indices: topBottomIndices,
primitiveType: PrimitiveType_default.TRIANGLES
});
const wallAttributes = computeWallAttributes(outerPositions, options);
indices2 = computeWallIndices(outerPositions);
const wallIndices = IndexDatatype_default.createTypedArray(
outerPositions.length * 2 / 3,
indices2
);
const wallGeo = new Geometry_default({
attributes: wallAttributes,
indices: wallIndices,
primitiveType: PrimitiveType_default.TRIANGLES
});
const geo = GeometryPipeline_default.combineInstances([
new GeometryInstance_default({
geometry: topBottomGeo
}),
new GeometryInstance_default({
geometry: wallGeo
})
]);
return {
boundingSphere,
attributes: geo[0].attributes,
indices: geo[0].indices
};
}
function computeRectangle2(center, semiMajorAxis, semiMinorAxis, rotation, granularity, ellipsoid, result) {
const cep = EllipseGeometryLibrary_default.computeEllipsePositions(
{
center,
semiMajorAxis,
semiMinorAxis,
rotation,
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_default.fromArray(positionsFlat, i * 3);
}
const rectangle = Rectangle_default.fromCartesianArray(positions, ellipsoid, result);
if (rectangle.width > Math_default.PI) {
rectangle.north = rectangle.north > 0 ? Math_default.PI_OVER_TWO - Math_default.EPSILON7 : rectangle.north;
rectangle.south = rectangle.south < 0 ? Math_default.EPSILON7 - Math_default.PI_OVER_TWO : rectangle.south;
rectangle.east = Math_default.PI;
rectangle.west = -Math_default.PI;
}
return rectangle;
}
function EllipseGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const center = options.center;
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const semiMajorAxis = options.semiMajorAxis;
const semiMinorAxis = options.semiMinorAxis;
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
Check_default.defined("options.center", center);
Check_default.typeOf.number("options.semiMajorAxis", semiMajorAxis);
Check_default.typeOf.number("options.semiMinorAxis", semiMinorAxis);
if (semiMajorAxis < semiMinorAxis) {
throw new DeveloperError_default(
"semiMajorAxis must be greater than or equal to the semiMinorAxis."
);
}
if (granularity <= 0) {
throw new DeveloperError_default("granularity must be greater than zero.");
}
const height = defaultValue_default(options.height, 0);
const extrudedHeight = defaultValue_default(options.extrudedHeight, height);
this._center = Cartesian3_default.clone(center);
this._semiMajorAxis = semiMajorAxis;
this._semiMinorAxis = semiMinorAxis;
this._ellipsoid = Ellipsoid_default.clone(ellipsoid);
this._rotation = defaultValue_default(options.rotation, 0);
this._stRotation = defaultValue_default(options.stRotation, 0);
this._height = Math.max(extrudedHeight, height);
this._granularity = granularity;
this._vertexFormat = VertexFormat_default.clone(vertexFormat);
this._extrudedHeight = Math.min(extrudedHeight, height);
this._shadowVolume = defaultValue_default(options.shadowVolume, false);
this._workerName = "createEllipseGeometry";
this._offsetAttribute = options.offsetAttribute;
this._rectangle = void 0;
this._textureCoordinateRotationPoints = void 0;
}
EllipseGeometry.packedLength = Cartesian3_default.packedLength + Ellipsoid_default.packedLength + VertexFormat_default.packedLength + 9;
EllipseGeometry.pack = function(value, array, startingIndex) {
Check_default.defined("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._center, array, startingIndex);
startingIndex += Cartesian3_default.packedLength;
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.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;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchCenter6 = new Cartesian3_default();
var scratchEllipsoid4 = new Ellipsoid_default();
var scratchVertexFormat4 = new VertexFormat_default();
var scratchOptions11 = {
center: scratchCenter6,
ellipsoid: scratchEllipsoid4,
vertexFormat: scratchVertexFormat4,
semiMajorAxis: void 0,
semiMinorAxis: void 0,
rotation: void 0,
stRotation: void 0,
height: void 0,
granularity: void 0,
extrudedHeight: void 0,
shadowVolume: void 0,
offsetAttribute: void 0
};
EllipseGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const center = Cartesian3_default.unpack(array, startingIndex, scratchCenter6);
startingIndex += Cartesian3_default.packedLength;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid4);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat4
);
startingIndex += VertexFormat_default.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;
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions11.height = height;
scratchOptions11.extrudedHeight = extrudedHeight;
scratchOptions11.granularity = granularity;
scratchOptions11.stRotation = stRotation;
scratchOptions11.rotation = rotation;
scratchOptions11.semiMajorAxis = semiMajorAxis;
scratchOptions11.semiMinorAxis = semiMinorAxis;
scratchOptions11.shadowVolume = shadowVolume;
scratchOptions11.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new EllipseGeometry(scratchOptions11);
}
result._center = Cartesian3_default.clone(center, result._center);
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.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 ? void 0 : offsetAttribute;
return result;
};
EllipseGeometry.computeRectangle = function(options, result) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const center = options.center;
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const semiMajorAxis = options.semiMajorAxis;
const semiMinorAxis = options.semiMinorAxis;
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const rotation = defaultValue_default(options.rotation, 0);
Check_default.defined("options.center", center);
Check_default.typeOf.number("options.semiMajorAxis", semiMajorAxis);
Check_default.typeOf.number("options.semiMinorAxis", semiMinorAxis);
if (semiMajorAxis < semiMinorAxis) {
throw new DeveloperError_default(
"semiMajorAxis must be greater than or equal to the semiMinorAxis."
);
}
if (granularity <= 0) {
throw new DeveloperError_default("granularity must be greater than zero.");
}
return computeRectangle2(
center,
semiMajorAxis,
semiMinorAxis,
rotation,
granularity,
ellipsoid,
result
);
};
EllipseGeometry.createGeometry = function(ellipseGeometry) {
if (ellipseGeometry._semiMajorAxis <= 0 || ellipseGeometry._semiMinorAxis <= 0) {
return;
}
const height = ellipseGeometry._height;
const extrudedHeight = ellipseGeometry._extrudedHeight;
const extrude = !Math_default.equalsEpsilon(
height,
extrudedHeight,
0,
Math_default.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,
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(options);
} else {
geometry = computeEllipse(options);
if (defined_default(ellipseGeometry._offsetAttribute)) {
const length3 = geometry.attributes.position.values.length;
const offsetValue = ellipseGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
}
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere: geometry.boundingSphere,
offsetAttribute: ellipseGeometry._offsetAttribute
});
};
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,
rotation: ellipseGeometry._rotation,
stRotation: ellipseGeometry._stRotation,
granularity,
extrudedHeight: minHeight,
height: maxHeight,
vertexFormat: VertexFormat_default.POSITION_ONLY,
shadowVolume: true
});
};
function textureCoordinateRotationPoints(ellipseGeometry) {
const stRotation = -ellipseGeometry._stRotation;
if (stRotation === 0) {
return [0, 0, 0, 1, 1, 0];
}
const cep = EllipseGeometryLibrary_default.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_default.fromArray(positionsFlat, i * 3);
}
const ellipsoid = ellipseGeometry._ellipsoid;
const boundingRectangle = ellipseGeometry.rectangle;
return Geometry_default._textureCoordinateRotationPoints(
positions,
stRotation,
ellipsoid,
boundingRectangle
);
}
Object.defineProperties(EllipseGeometry.prototype, {
rectangle: {
get: function() {
if (!defined_default(this._rectangle)) {
this._rectangle = computeRectangle2(
this._center,
this._semiMajorAxis,
this._semiMinorAxis,
this._rotation,
this._granularity,
this._ellipsoid
);
}
return this._rectangle;
}
},
textureCoordinateRotationPoints: {
get: function() {
if (!defined_default(this._textureCoordinateRotationPoints)) {
this._textureCoordinateRotationPoints = textureCoordinateRotationPoints(
this
);
}
return this._textureCoordinateRotationPoints;
}
}
});
var EllipseGeometry_default = EllipseGeometry;
// node_modules/@cesium/engine/Source/Core/EllipseOutlineGeometry.js
var scratchCartesian18 = new Cartesian3_default();
var boundingSphereCenter2 = new Cartesian3_default();
function computeEllipse2(options) {
const center = options.center;
boundingSphereCenter2 = Cartesian3_default.multiplyByScalar(
options.ellipsoid.geodeticSurfaceNormal(center, boundingSphereCenter2),
options.height,
boundingSphereCenter2
);
boundingSphereCenter2 = Cartesian3_default.add(
center,
boundingSphereCenter2,
boundingSphereCenter2
);
const boundingSphere = new BoundingSphere_default(
boundingSphereCenter2,
options.semiMajorAxis
);
const positions = EllipseGeometryLibrary_default.computeEllipsePositions(
options,
false,
true
).outerPositions;
const attributes = new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: EllipseGeometryLibrary_default.raisePositionsToHeight(
positions,
options,
false
)
})
});
const length3 = positions.length / 3;
const indices2 = IndexDatatype_default.createTypedArray(length3, length3 * 2);
let index = 0;
for (let i = 0; i < length3; ++i) {
indices2[index++] = i;
indices2[index++] = (i + 1) % length3;
}
return {
boundingSphere,
attributes,
indices: indices2
};
}
var topBoundingSphere3 = new BoundingSphere_default();
var bottomBoundingSphere3 = new BoundingSphere_default();
function computeExtrudedEllipse2(options) {
const center = options.center;
const ellipsoid = options.ellipsoid;
const semiMajorAxis = options.semiMajorAxis;
let scaledNormal = Cartesian3_default.multiplyByScalar(
ellipsoid.geodeticSurfaceNormal(center, scratchCartesian18),
options.height,
scratchCartesian18
);
topBoundingSphere3.center = Cartesian3_default.add(
center,
scaledNormal,
topBoundingSphere3.center
);
topBoundingSphere3.radius = semiMajorAxis;
scaledNormal = Cartesian3_default.multiplyByScalar(
ellipsoid.geodeticSurfaceNormal(center, scaledNormal),
options.extrudedHeight,
scaledNormal
);
bottomBoundingSphere3.center = Cartesian3_default.add(
center,
scaledNormal,
bottomBoundingSphere3.center
);
bottomBoundingSphere3.radius = semiMajorAxis;
let positions = EllipseGeometryLibrary_default.computeEllipsePositions(
options,
false,
true
).outerPositions;
const attributes = new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: EllipseGeometryLibrary_default.raisePositionsToHeight(
positions,
options,
true
)
})
});
positions = attributes.position.values;
const boundingSphere = BoundingSphere_default.union(
topBoundingSphere3,
bottomBoundingSphere3
);
let length3 = positions.length / 3;
if (defined_default(options.offsetAttribute)) {
let applyOffset = new Uint8Array(length3);
if (options.offsetAttribute === GeometryOffsetAttribute_default.TOP) {
applyOffset = applyOffset.fill(1, 0, length3 / 2);
} else {
const offsetValue = options.offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
applyOffset = applyOffset.fill(offsetValue);
}
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
let numberOfVerticalLines = defaultValue_default(options.numberOfVerticalLines, 16);
numberOfVerticalLines = Math_default.clamp(
numberOfVerticalLines,
0,
length3 / 2
);
const indices2 = IndexDatatype_default.createTypedArray(
length3,
length3 * 2 + numberOfVerticalLines * 2
);
length3 /= 2;
let index = 0;
let i;
for (i = 0; i < length3; ++i) {
indices2[index++] = i;
indices2[index++] = (i + 1) % length3;
indices2[index++] = i + length3;
indices2[index++] = (i + 1) % length3 + length3;
}
let numSide;
if (numberOfVerticalLines > 0) {
const numSideLines = Math.min(numberOfVerticalLines, length3);
numSide = Math.round(length3 / numSideLines);
const maxI = Math.min(numSide * numberOfVerticalLines, length3);
for (i = 0; i < maxI; i += numSide) {
indices2[index++] = i;
indices2[index++] = i + length3;
}
}
return {
boundingSphere,
attributes,
indices: indices2
};
}
function EllipseOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const center = options.center;
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const semiMajorAxis = options.semiMajorAxis;
const semiMinorAxis = options.semiMinorAxis;
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
if (!defined_default(center)) {
throw new DeveloperError_default("center is required.");
}
if (!defined_default(semiMajorAxis)) {
throw new DeveloperError_default("semiMajorAxis is required.");
}
if (!defined_default(semiMinorAxis)) {
throw new DeveloperError_default("semiMinorAxis is required.");
}
if (semiMajorAxis < semiMinorAxis) {
throw new DeveloperError_default(
"semiMajorAxis must be greater than or equal to the semiMinorAxis."
);
}
if (granularity <= 0) {
throw new DeveloperError_default("granularity must be greater than zero.");
}
const height = defaultValue_default(options.height, 0);
const extrudedHeight = defaultValue_default(options.extrudedHeight, height);
this._center = Cartesian3_default.clone(center);
this._semiMajorAxis = semiMajorAxis;
this._semiMinorAxis = semiMinorAxis;
this._ellipsoid = Ellipsoid_default.clone(ellipsoid);
this._rotation = defaultValue_default(options.rotation, 0);
this._height = Math.max(extrudedHeight, height);
this._granularity = granularity;
this._extrudedHeight = Math.min(extrudedHeight, height);
this._numberOfVerticalLines = Math.max(
defaultValue_default(options.numberOfVerticalLines, 16),
0
);
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createEllipseOutlineGeometry";
}
EllipseOutlineGeometry.packedLength = Cartesian3_default.packedLength + Ellipsoid_default.packedLength + 8;
EllipseOutlineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._center, array, startingIndex);
startingIndex += Cartesian3_default.packedLength;
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.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_default(value._offsetAttribute, -1);
return array;
};
var scratchCenter7 = new Cartesian3_default();
var scratchEllipsoid5 = new Ellipsoid_default();
var scratchOptions12 = {
center: scratchCenter7,
ellipsoid: scratchEllipsoid5,
semiMajorAxis: void 0,
semiMinorAxis: void 0,
rotation: void 0,
height: void 0,
granularity: void 0,
extrudedHeight: void 0,
numberOfVerticalLines: void 0,
offsetAttribute: void 0
};
EllipseOutlineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
const center = Cartesian3_default.unpack(array, startingIndex, scratchCenter7);
startingIndex += Cartesian3_default.packedLength;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid5);
startingIndex += Ellipsoid_default.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_default(result)) {
scratchOptions12.height = height;
scratchOptions12.extrudedHeight = extrudedHeight;
scratchOptions12.granularity = granularity;
scratchOptions12.rotation = rotation;
scratchOptions12.semiMajorAxis = semiMajorAxis;
scratchOptions12.semiMinorAxis = semiMinorAxis;
scratchOptions12.numberOfVerticalLines = numberOfVerticalLines;
scratchOptions12.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new EllipseOutlineGeometry(scratchOptions12);
}
result._center = Cartesian3_default.clone(center, result._center);
result._ellipsoid = Ellipsoid_default.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 ? void 0 : offsetAttribute;
return result;
};
EllipseOutlineGeometry.createGeometry = function(ellipseGeometry) {
if (ellipseGeometry._semiMajorAxis <= 0 || ellipseGeometry._semiMinorAxis <= 0) {
return;
}
const height = ellipseGeometry._height;
const extrudedHeight = ellipseGeometry._extrudedHeight;
const extrude = !Math_default.equalsEpsilon(
height,
extrudedHeight,
0,
Math_default.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,
granularity: ellipseGeometry._granularity,
numberOfVerticalLines: ellipseGeometry._numberOfVerticalLines
};
let geometry;
if (extrude) {
options.extrudedHeight = extrudedHeight;
options.offsetAttribute = ellipseGeometry._offsetAttribute;
geometry = computeExtrudedEllipse2(options);
} else {
geometry = computeEllipse2(options);
if (defined_default(ellipseGeometry._offsetAttribute)) {
const length3 = geometry.attributes.position.values.length;
const offsetValue = ellipseGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
}
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: PrimitiveType_default.LINES,
boundingSphere: geometry.boundingSphere,
offsetAttribute: ellipseGeometry._offsetAttribute
});
};
var EllipseOutlineGeometry_default = EllipseOutlineGeometry;
// node_modules/@cesium/engine/Source/DataSources/EllipseGeometryUpdater.js
var scratchColor13 = new Color_default();
var defaultOffset5 = Cartesian3_default.ZERO;
var offsetScratch7 = new Cartesian3_default();
var scratchRectangle5 = new Rectangle_default();
function EllipseGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.center = void 0;
this.semiMajorAxis = void 0;
this.semiMinorAxis = void 0;
this.rotation = void 0;
this.height = void 0;
this.extrudedHeight = void 0;
this.granularity = void 0;
this.stRotation = void 0;
this.numberOfVerticalLines = void 0;
this.offsetAttribute = void 0;
}
function EllipseGeometryUpdater(entity, scene) {
GroundGeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new EllipseGeometryOptions(entity),
geometryPropertyName: "ellipse",
observedPropertyNames: ["availability", "position", "ellipse"]
});
this._onEntityPropertyChanged(entity, "ellipse", entity.ellipse, void 0);
}
if (defined_default(Object.create)) {
EllipseGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater_default.prototype
);
EllipseGeometryUpdater.prototype.constructor = EllipseGeometryUpdater;
}
EllipseGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time)
),
offset: void 0,
color: void 0
};
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor13);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
}
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset5,
offsetScratch7
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new EllipseGeometry_default(this._options),
attributes
});
};
EllipseGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor13
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
),
offset: void 0
};
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset5,
offsetScratch7
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new EllipseOutlineGeometry_default(this._options),
attributes
});
};
EllipseGeometryUpdater.prototype._computeCenter = function(time, result) {
return Property_default.getValueOrUndefined(this._entity.position, time, result);
};
EllipseGeometryUpdater.prototype._isHidden = function(entity, ellipse) {
const position = entity.position;
return !defined_default(position) || !defined_default(ellipse.semiMajorAxis) || !defined_default(ellipse.semiMinorAxis) || GeometryUpdater_default.prototype._isHidden.call(this, entity, ellipse);
};
EllipseGeometryUpdater.prototype._isDynamic = function(entity, ellipse) {
return !entity.position.isConstant || !ellipse.semiMajorAxis.isConstant || !ellipse.semiMinorAxis.isConstant || !Property_default.isConstant(ellipse.rotation) || !Property_default.isConstant(ellipse.height) || !Property_default.isConstant(ellipse.extrudedHeight) || !Property_default.isConstant(ellipse.granularity) || !Property_default.isConstant(ellipse.stRotation) || !Property_default.isConstant(ellipse.outlineWidth) || !Property_default.isConstant(ellipse.numberOfVerticalLines) || !Property_default.isConstant(ellipse.zIndex) || this._onTerrain && !Property_default.isConstant(this._materialProperty) && !(this._materialProperty instanceof ColorMaterialProperty_default);
};
EllipseGeometryUpdater.prototype._setStaticOptions = function(entity, ellipse) {
let heightValue = Property_default.getValueOrUndefined(
ellipse.height,
Iso8601_default.MINIMUM_VALUE
);
const heightReferenceValue = Property_default.getValueOrDefault(
ellipse.heightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
ellipse.extrudedHeight,
Iso8601_default.MINIMUM_VALUE
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
ellipse.extrudedHeightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
const options = this._options;
options.vertexFormat = this._materialProperty instanceof ColorMaterialProperty_default ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.center = entity.position.getValue(
Iso8601_default.MINIMUM_VALUE,
options.center
);
options.semiMajorAxis = ellipse.semiMajorAxis.getValue(
Iso8601_default.MINIMUM_VALUE,
options.semiMajorAxis
);
options.semiMinorAxis = ellipse.semiMinorAxis.getValue(
Iso8601_default.MINIMUM_VALUE,
options.semiMinorAxis
);
options.rotation = Property_default.getValueOrUndefined(
ellipse.rotation,
Iso8601_default.MINIMUM_VALUE
);
options.granularity = Property_default.getValueOrUndefined(
ellipse.granularity,
Iso8601_default.MINIMUM_VALUE
);
options.stRotation = Property_default.getValueOrUndefined(
ellipse.stRotation,
Iso8601_default.MINIMUM_VALUE
);
options.numberOfVerticalLines = Property_default.getValueOrUndefined(
ellipse.numberOfVerticalLines,
Iso8601_default.MINIMUM_VALUE
);
options.offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
options.height = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
heightReferenceValue
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
EllipseGeometry_default.computeRectangle(options, scratchRectangle5)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
EllipseGeometryUpdater.DynamicGeometryUpdater = DynamicEllipseGeometryUpdater;
function DynamicEllipseGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicEllipseGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicEllipseGeometryUpdater.prototype.constructor = DynamicEllipseGeometryUpdater;
}
DynamicEllipseGeometryUpdater.prototype._isHidden = function(entity, ellipse, time) {
const options = this._options;
return !defined_default(options.center) || !defined_default(options.semiMajorAxis) || !defined_default(options.semiMinorAxis) || DynamicGeometryUpdater_default.prototype._isHidden.call(this, entity, ellipse, time);
};
DynamicEllipseGeometryUpdater.prototype._setOptions = function(entity, ellipse, time) {
const options = this._options;
let heightValue = Property_default.getValueOrUndefined(ellipse.height, time);
const heightReferenceValue = Property_default.getValueOrDefault(
ellipse.heightReference,
time,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
ellipse.extrudedHeight,
time
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
ellipse.extrudedHeightReference,
time,
HeightReference_default.NONE
);
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
options.center = Property_default.getValueOrUndefined(
entity.position,
time,
options.center
);
options.semiMajorAxis = Property_default.getValueOrUndefined(
ellipse.semiMajorAxis,
time
);
options.semiMinorAxis = Property_default.getValueOrUndefined(
ellipse.semiMinorAxis,
time
);
options.rotation = Property_default.getValueOrUndefined(ellipse.rotation, time);
options.granularity = Property_default.getValueOrUndefined(ellipse.granularity, time);
options.stRotation = Property_default.getValueOrUndefined(ellipse.stRotation, time);
options.numberOfVerticalLines = Property_default.getValueOrUndefined(
ellipse.numberOfVerticalLines,
time
);
options.offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
options.height = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
heightReferenceValue
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
EllipseGeometry_default.computeRectangle(options, scratchRectangle5)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
var EllipseGeometryUpdater_default = EllipseGeometryUpdater;
// node_modules/@cesium/engine/Source/Core/EllipsoidGeometry.js
var scratchPosition8 = new Cartesian3_default();
var scratchNormal4 = new Cartesian3_default();
var scratchTangent2 = new Cartesian3_default();
var scratchBitangent2 = new Cartesian3_default();
var scratchNormalST = new Cartesian3_default();
var defaultRadii2 = new Cartesian3_default(1, 1, 1);
var cos3 = Math.cos;
var sin3 = Math.sin;
function EllipsoidGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const radii = defaultValue_default(options.radii, defaultRadii2);
const innerRadii = defaultValue_default(options.innerRadii, radii);
const minimumClock = defaultValue_default(options.minimumClock, 0);
const maximumClock = defaultValue_default(options.maximumClock, Math_default.TWO_PI);
const minimumCone = defaultValue_default(options.minimumCone, 0);
const maximumCone = defaultValue_default(options.maximumCone, Math_default.PI);
const stackPartitions = Math.round(defaultValue_default(options.stackPartitions, 64));
const slicePartitions = Math.round(defaultValue_default(options.slicePartitions, 64));
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
if (slicePartitions < 3) {
throw new DeveloperError_default(
"options.slicePartitions cannot be less than three."
);
}
if (stackPartitions < 3) {
throw new DeveloperError_default(
"options.stackPartitions cannot be less than three."
);
}
this._radii = Cartesian3_default.clone(radii);
this._innerRadii = Cartesian3_default.clone(innerRadii);
this._minimumClock = minimumClock;
this._maximumClock = maximumClock;
this._minimumCone = minimumCone;
this._maximumCone = maximumCone;
this._stackPartitions = stackPartitions;
this._slicePartitions = slicePartitions;
this._vertexFormat = VertexFormat_default.clone(vertexFormat);
this._offsetAttribute = options.offsetAttribute;
this._workerName = "createEllipsoidGeometry";
}
EllipsoidGeometry.packedLength = 2 * Cartesian3_default.packedLength + VertexFormat_default.packedLength + 7;
EllipsoidGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
Cartesian3_default.pack(value._radii, array, startingIndex);
startingIndex += Cartesian3_default.packedLength;
Cartesian3_default.pack(value._innerRadii, array, startingIndex);
startingIndex += Cartesian3_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.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_default(value._offsetAttribute, -1);
return array;
};
var scratchRadii2 = new Cartesian3_default();
var scratchInnerRadii2 = new Cartesian3_default();
var scratchVertexFormat5 = new VertexFormat_default();
var scratchOptions13 = {
radii: scratchRadii2,
innerRadii: scratchInnerRadii2,
vertexFormat: scratchVertexFormat5,
minimumClock: void 0,
maximumClock: void 0,
minimumCone: void 0,
maximumCone: void 0,
stackPartitions: void 0,
slicePartitions: void 0,
offsetAttribute: void 0
};
EllipsoidGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
const radii = Cartesian3_default.unpack(array, startingIndex, scratchRadii2);
startingIndex += Cartesian3_default.packedLength;
const innerRadii = Cartesian3_default.unpack(array, startingIndex, scratchInnerRadii2);
startingIndex += Cartesian3_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat5
);
startingIndex += VertexFormat_default.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_default(result)) {
scratchOptions13.minimumClock = minimumClock;
scratchOptions13.maximumClock = maximumClock;
scratchOptions13.minimumCone = minimumCone;
scratchOptions13.maximumCone = maximumCone;
scratchOptions13.stackPartitions = stackPartitions;
scratchOptions13.slicePartitions = slicePartitions;
scratchOptions13.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new EllipsoidGeometry(scratchOptions13);
}
result._radii = Cartesian3_default.clone(radii, result._radii);
result._innerRadii = Cartesian3_default.clone(innerRadii, result._innerRadii);
result._vertexFormat = VertexFormat_default.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 ? void 0 : offsetAttribute;
return result;
};
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;
let slicePartitions = ellipsoidGeometry._slicePartitions + 1;
let stackPartitions = ellipsoidGeometry._stackPartitions + 1;
slicePartitions = Math.round(
slicePartitions * Math.abs(maximumClock - minimumClock) / Math_default.TWO_PI
);
stackPartitions = Math.round(
stackPartitions * Math.abs(maximumCone - minimumCone) / Math_default.PI
);
if (slicePartitions < 2) {
slicePartitions = 2;
}
if (stackPartitions < 2) {
stackPartitions = 2;
}
let i;
let j;
let index = 0;
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;
let extraIndices = 0;
let vertexMultiplier = 1;
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;
if (minimumCone > 0) {
isTopOpen = true;
extraIndices += slicePartitions - 1;
}
if (maximumCone < Math.PI) {
isBotOpen = true;
extraIndices += slicePartitions - 1;
}
if ((maximumClock - minimumClock) % Math_default.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);
const indexCount = slicePartitions * stackPartitions * vertexMultiplier;
const numIndices = 6 * (indexCount + extraIndices + 1 - (slicePartitions + stackPartitions) * vertexMultiplier);
const indices2 = IndexDatatype_default.createTypedArray(indexCount, numIndices);
const normals = vertexFormat.normal ? new Float32Array(vertexCount * 3) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(vertexCount * 3) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(vertexCount * 3) : void 0;
const st = vertexFormat.st ? new Float32Array(vertexCount * 2) : void 0;
const sinPhi = new Array(numPhis);
const cosPhi = new Array(numPhis);
for (i = 0; i < numPhis; i++) {
sinPhi[i] = sin3(phis[i]);
cosPhi[i] = cos3(phis[i]);
}
const sinTheta = new Array(numThetas);
const cosTheta = new Array(numThetas);
for (j = 0; j < numThetas; j++) {
cosTheta[j] = cos3(thetas[j]);
sinTheta[j] = sin3(thetas[j]);
}
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];
}
}
let vertexIndex = vertexCount / 2;
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];
isInner[vertexIndex] = true;
if (i > 0 && i !== numPhis - 1 && j !== 0 && j !== numThetas - 1) {
negateNormal[vertexIndex] = true;
}
vertexIndex++;
}
}
}
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++) {
indices2[index++] = bottomOffset + j;
indices2[index++] = bottomOffset + j + 1;
indices2[index++] = topOffset + j + 1;
indices2[index++] = bottomOffset + j;
indices2[index++] = topOffset + j + 1;
indices2[index++] = topOffset + j;
}
}
if (hasInnerSurface) {
const offset2 = numPhis * numThetas;
for (i = 1; i < numPhis - 2; i++) {
topOffset = offset2 + i * numThetas;
bottomOffset = offset2 + (i + 1) * numThetas;
for (j = 1; j < numThetas - 2; j++) {
indices2[index++] = bottomOffset + j;
indices2[index++] = topOffset + j;
indices2[index++] = topOffset + j + 1;
indices2[index++] = bottomOffset + j;
indices2[index++] = topOffset + j + 1;
indices2[index++] = bottomOffset + j + 1;
}
}
}
let outerOffset;
let innerOffset;
if (hasInnerSurface) {
if (isTopOpen) {
innerOffset = numPhis * numThetas;
for (i = 1; i < numThetas - 2; i++) {
indices2[index++] = i;
indices2[index++] = i + 1;
indices2[index++] = innerOffset + i + 1;
indices2[index++] = i;
indices2[index++] = innerOffset + i + 1;
indices2[index++] = innerOffset + i;
}
}
if (isBotOpen) {
outerOffset = numPhis * numThetas - numThetas;
innerOffset = numPhis * numThetas * vertexMultiplier - numThetas;
for (i = 1; i < numThetas - 2; i++) {
indices2[index++] = outerOffset + i + 1;
indices2[index++] = outerOffset + i;
indices2[index++] = innerOffset + i;
indices2[index++] = outerOffset + i + 1;
indices2[index++] = innerOffset + i;
indices2[index++] = innerOffset + i + 1;
}
}
}
if (isClockOpen) {
for (i = 1; i < numPhis - 2; i++) {
innerOffset = numThetas * numPhis + numThetas * i;
outerOffset = numThetas * i;
indices2[index++] = innerOffset;
indices2[index++] = outerOffset + numThetas;
indices2[index++] = outerOffset;
indices2[index++] = innerOffset;
indices2[index++] = innerOffset + numThetas;
indices2[index++] = outerOffset + numThetas;
}
for (i = 1; i < numPhis - 2; i++) {
innerOffset = numThetas * numPhis + numThetas * (i + 1) - 1;
outerOffset = numThetas * (i + 1) - 1;
indices2[index++] = outerOffset + numThetas;
indices2[index++] = innerOffset;
indices2[index++] = outerOffset;
indices2[index++] = outerOffset + numThetas;
indices2[index++] = innerOffset + numThetas;
indices2[index++] = innerOffset;
}
}
const attributes = new GeometryAttributes_default();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
}
let stIndex = 0;
let normalIndex = 0;
let tangentIndex = 0;
let bitangentIndex = 0;
const vertexCountHalf = vertexCount / 2;
let ellipsoid;
const ellipsoidOuter = Ellipsoid_default.fromCartesian3(radii);
const ellipsoidInner = Ellipsoid_default.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_default.fromArray(positions, i * 3, scratchPosition8);
const normal2 = ellipsoid.geodeticSurfaceNormal(position, scratchNormal4);
if (negateNormal[i]) {
Cartesian3_default.negate(normal2, normal2);
}
if (vertexFormat.st) {
const normalST = Cartesian2_default.negate(normal2, scratchNormalST);
st[stIndex++] = Math.atan2(normalST.y, normalST.x) / Math_default.TWO_PI + 0.5;
st[stIndex++] = Math.asin(normal2.z) / Math.PI + 0.5;
}
if (vertexFormat.normal) {
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.z;
}
if (vertexFormat.tangent || vertexFormat.bitangent) {
const tangent = scratchTangent2;
let tangetOffset = 0;
let unit;
if (isInner[i]) {
tangetOffset = vertexCountHalf;
}
if (!isTopOpen && i >= tangetOffset && i < tangetOffset + numThetas * 2) {
unit = Cartesian3_default.UNIT_X;
} else {
unit = Cartesian3_default.UNIT_Z;
}
Cartesian3_default.cross(unit, normal2, tangent);
Cartesian3_default.normalize(tangent, tangent);
if (vertexFormat.tangent) {
tangents[tangentIndex++] = tangent.x;
tangents[tangentIndex++] = tangent.y;
tangents[tangentIndex++] = tangent.z;
}
if (vertexFormat.bitangent) {
const bitangent = Cartesian3_default.cross(normal2, tangent, scratchBitangent2);
Cartesian3_default.normalize(bitangent, bitangent);
bitangents[bitangentIndex++] = bitangent.x;
bitangents[bitangentIndex++] = bitangent.y;
bitangents[bitangentIndex++] = bitangent.z;
}
}
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: st
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
}
if (defined_default(ellipsoidGeometry._offsetAttribute)) {
const length3 = positions.length;
const offsetValue = ellipsoidGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere: BoundingSphere_default.fromEllipsoid(ellipsoidOuter),
offsetAttribute: ellipsoidGeometry._offsetAttribute
});
};
var unitEllipsoidGeometry;
EllipsoidGeometry.getUnitEllipsoid = function() {
if (!defined_default(unitEllipsoidGeometry)) {
unitEllipsoidGeometry = EllipsoidGeometry.createGeometry(
new EllipsoidGeometry({
radii: new Cartesian3_default(1, 1, 1),
vertexFormat: VertexFormat_default.POSITION_ONLY
})
);
}
return unitEllipsoidGeometry;
};
var EllipsoidGeometry_default = EllipsoidGeometry;
// node_modules/@cesium/engine/Source/DataSources/EllipsoidGeometryUpdater.js
var defaultMaterial2 = new ColorMaterialProperty_default(Color_default.WHITE);
var defaultOffset6 = Cartesian3_default.ZERO;
var offsetScratch8 = new Cartesian3_default();
var radiiScratch = new Cartesian3_default();
var innerRadiiScratch = new Cartesian3_default();
var scratchColor14 = new Color_default();
var unitSphere = new Cartesian3_default(1, 1, 1);
function EllipsoidGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.radii = void 0;
this.innerRadii = void 0;
this.minimumClock = void 0;
this.maximumClock = void 0;
this.minimumCone = void 0;
this.maximumCone = void 0;
this.stackPartitions = void 0;
this.slicePartitions = void 0;
this.subdivisions = void 0;
this.offsetAttribute = void 0;
}
function EllipsoidGeometryUpdater(entity, scene) {
GeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new EllipsoidGeometryOptions(entity),
geometryPropertyName: "ellipsoid",
observedPropertyNames: [
"availability",
"position",
"orientation",
"ellipsoid"
]
});
this._onEntityPropertyChanged(
entity,
"ellipsoid",
entity.ellipsoid,
void 0
);
}
if (defined_default(Object.create)) {
EllipsoidGeometryUpdater.prototype = Object.create(GeometryUpdater_default.prototype);
EllipsoidGeometryUpdater.prototype.constructor = EllipsoidGeometryUpdater;
}
Object.defineProperties(EllipsoidGeometryUpdater.prototype, {
terrainOffsetProperty: {
get: function() {
return this._terrainOffsetProperty;
}
}
});
EllipsoidGeometryUpdater.prototype.createFillGeometryInstance = function(time, skipModelMatrix, modelMatrixResult) {
Check_default.defined("time", time);
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
let color;
const show = new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
);
const attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color: void 0,
offset: void 0
};
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor14);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
attributes.color = color;
}
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset6,
offsetScratch8
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new EllipsoidGeometry_default(this._options),
modelMatrix: skipModelMatrix ? void 0 : entity.computeModelMatrixForHeightReference(
time,
entity.ellipsoid.heightReference,
this._options.radii.z * 0.5,
this._scene.mapProjection.ellipsoid,
modelMatrixResult
),
attributes
});
};
EllipsoidGeometryUpdater.prototype.createOutlineGeometryInstance = function(time, skipModelMatrix, modelMatrixResult) {
Check_default.defined("time", time);
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor14
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
),
offset: void 0
};
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset6,
offsetScratch8
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new EllipsoidOutlineGeometry_default(this._options),
modelMatrix: skipModelMatrix ? void 0 : entity.computeModelMatrixForHeightReference(
time,
entity.ellipsoid.heightReference,
this._options.radii.z * 0.5,
this._scene.mapProjection.ellipsoid,
modelMatrixResult
),
attributes
});
};
EllipsoidGeometryUpdater.prototype._computeCenter = function(time, result) {
return Property_default.getValueOrUndefined(this._entity.position, time, result);
};
EllipsoidGeometryUpdater.prototype._isHidden = function(entity, ellipsoid) {
return !defined_default(entity.position) || !defined_default(ellipsoid.radii) || GeometryUpdater_default.prototype._isHidden.call(this, entity, ellipsoid);
};
EllipsoidGeometryUpdater.prototype._isDynamic = function(entity, ellipsoid) {
return !entity.position.isConstant || !Property_default.isConstant(entity.orientation) || !ellipsoid.radii.isConstant || !Property_default.isConstant(ellipsoid.innerRadii) || !Property_default.isConstant(ellipsoid.stackPartitions) || !Property_default.isConstant(ellipsoid.slicePartitions) || !Property_default.isConstant(ellipsoid.outlineWidth) || !Property_default.isConstant(ellipsoid.minimumClock) || !Property_default.isConstant(ellipsoid.maximumClock) || !Property_default.isConstant(ellipsoid.minimumCone) || !Property_default.isConstant(ellipsoid.maximumCone) || !Property_default.isConstant(ellipsoid.subdivisions);
};
EllipsoidGeometryUpdater.prototype._setStaticOptions = function(entity, ellipsoid) {
const heightReference = Property_default.getValueOrDefault(
ellipsoid.heightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
const options = this._options;
options.vertexFormat = this._materialProperty instanceof ColorMaterialProperty_default ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.radii = ellipsoid.radii.getValue(
Iso8601_default.MINIMUM_VALUE,
options.radii
);
options.innerRadii = Property_default.getValueOrUndefined(
ellipsoid.innerRadii,
options.radii
);
options.minimumClock = Property_default.getValueOrUndefined(
ellipsoid.minimumClock,
Iso8601_default.MINIMUM_VALUE
);
options.maximumClock = Property_default.getValueOrUndefined(
ellipsoid.maximumClock,
Iso8601_default.MINIMUM_VALUE
);
options.minimumCone = Property_default.getValueOrUndefined(
ellipsoid.minimumCone,
Iso8601_default.MINIMUM_VALUE
);
options.maximumCone = Property_default.getValueOrUndefined(
ellipsoid.maximumCone,
Iso8601_default.MINIMUM_VALUE
);
options.stackPartitions = Property_default.getValueOrUndefined(
ellipsoid.stackPartitions,
Iso8601_default.MINIMUM_VALUE
);
options.slicePartitions = Property_default.getValueOrUndefined(
ellipsoid.slicePartitions,
Iso8601_default.MINIMUM_VALUE
);
options.subdivisions = Property_default.getValueOrUndefined(
ellipsoid.subdivisions,
Iso8601_default.MINIMUM_VALUE
);
options.offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0;
};
EllipsoidGeometryUpdater.prototype._onEntityPropertyChanged = heightReferenceOnEntityPropertyChanged_default;
EllipsoidGeometryUpdater.DynamicGeometryUpdater = DynamicEllipsoidGeometryUpdater;
function DynamicEllipsoidGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
this._scene = geometryUpdater._scene;
this._modelMatrix = new Matrix4_default();
this._attributes = void 0;
this._outlineAttributes = void 0;
this._lastSceneMode = void 0;
this._lastShow = void 0;
this._lastOutlineShow = void 0;
this._lastOutlineWidth = void 0;
this._lastOutlineColor = void 0;
this._lastOffset = new Cartesian3_default();
this._material = {};
}
if (defined_default(Object.create)) {
DynamicEllipsoidGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicEllipsoidGeometryUpdater.prototype.constructor = DynamicEllipsoidGeometryUpdater;
}
DynamicEllipsoidGeometryUpdater.prototype.update = function(time) {
Check_default.defined("time", time);
const entity = this._entity;
const ellipsoid = entity.ellipsoid;
if (!entity.isShowing || !entity.isAvailable(time) || !Property_default.getValueOrDefault(ellipsoid.show, time, true)) {
if (defined_default(this._primitive)) {
this._primitive.show = false;
}
if (defined_default(this._outlinePrimitive)) {
this._outlinePrimitive.show = false;
}
return;
}
const radii = Property_default.getValueOrUndefined(
ellipsoid.radii,
time,
radiiScratch
);
let modelMatrix = defined_default(radii) ? entity.computeModelMatrixForHeightReference(
time,
ellipsoid.heightReference,
radii.z * 0.5,
this._scene.mapProjection.ellipsoid,
this._modelMatrix
) : void 0;
if (!defined_default(modelMatrix) || !defined_default(radii)) {
if (defined_default(this._primitive)) {
this._primitive.show = false;
}
if (defined_default(this._outlinePrimitive)) {
this._outlinePrimitive.show = false;
}
return;
}
const showFill = Property_default.getValueOrDefault(ellipsoid.fill, time, true);
const showOutline = Property_default.getValueOrDefault(
ellipsoid.outline,
time,
false
);
const outlineColor = Property_default.getValueOrClonedDefault(
ellipsoid.outlineColor,
time,
Color_default.BLACK,
scratchColor14
);
const material = MaterialProperty_default.getValue(
time,
defaultValue_default(ellipsoid.material, defaultMaterial2),
this._material
);
const innerRadii = Property_default.getValueOrUndefined(
ellipsoid.innerRadii,
time,
innerRadiiScratch
);
const minimumClock = Property_default.getValueOrUndefined(
ellipsoid.minimumClock,
time
);
const maximumClock = Property_default.getValueOrUndefined(
ellipsoid.maximumClock,
time
);
const minimumCone = Property_default.getValueOrUndefined(ellipsoid.minimumCone, time);
const maximumCone = Property_default.getValueOrUndefined(ellipsoid.maximumCone, time);
const stackPartitions = Property_default.getValueOrUndefined(
ellipsoid.stackPartitions,
time
);
const slicePartitions = Property_default.getValueOrUndefined(
ellipsoid.slicePartitions,
time
);
const subdivisions = Property_default.getValueOrUndefined(
ellipsoid.subdivisions,
time
);
const outlineWidth = Property_default.getValueOrDefault(
ellipsoid.outlineWidth,
time,
1
);
const heightReference = Property_default.getValueOrDefault(
ellipsoid.heightReference,
time,
HeightReference_default.NONE
);
const offsetAttribute = heightReference !== HeightReference_default.NONE ? GeometryOffsetAttribute_default.ALL : void 0;
const sceneMode = this._scene.mode;
const in3D = sceneMode === SceneMode_default.SCENE3D && heightReference === HeightReference_default.NONE;
const options = this._options;
const shadows = this._geometryUpdater.shadowsProperty.getValue(time);
const distanceDisplayConditionProperty = this._geometryUpdater.distanceDisplayConditionProperty;
const distanceDisplayCondition = distanceDisplayConditionProperty.getValue(
time
);
const offset2 = Property_default.getValueOrDefault(
this._geometryUpdater.terrainOffsetProperty,
time,
defaultOffset6,
offsetScratch8
);
const rebuildPrimitives = !in3D || this._lastSceneMode !== sceneMode || !defined_default(this._primitive) || options.stackPartitions !== stackPartitions || options.slicePartitions !== slicePartitions || defined_default(innerRadii) && !Cartesian3_default.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 = void 0;
this._outlinePrimitive = void 0;
this._lastSceneMode = sceneMode;
this._lastOutlineWidth = outlineWidth;
options.stackPartitions = stackPartitions;
options.slicePartitions = slicePartitions;
options.subdivisions = subdivisions;
options.offsetAttribute = offsetAttribute;
options.radii = Cartesian3_default.clone(in3D ? unitSphere : radii, options.radii);
if (defined_default(innerRadii)) {
if (in3D) {
const mag = Cartesian3_default.magnitude(radii);
options.innerRadii = Cartesian3_default.fromElements(
innerRadii.x / mag,
innerRadii.y / mag,
innerRadii.z / mag,
options.innerRadii
);
} else {
options.innerRadii = Cartesian3_default.clone(innerRadii, options.innerRadii);
}
} else {
options.innerRadii = void 0;
}
options.minimumClock = minimumClock;
options.maximumClock = maximumClock;
options.minimumCone = minimumCone;
options.maximumCone = maximumCone;
const appearance = new MaterialAppearance_default({
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_default({
geometryInstances: fillInstance,
appearance,
asynchronous: false,
shadows
})
);
const outlineInstance = this._geometryUpdater.createOutlineGeometryInstance(
time,
in3D,
this._modelMatrix
);
this._outlinePrimitive = primitives.add(
new Primitive_default({
geometryInstances: outlineInstance,
appearance: new PerInstanceColorAppearance_default({
flat: true,
translucent: outlineInstance.attributes.color.value[3] !== 255,
renderState: {
lineWidth: this._geometryUpdater._scene.clampLineWidth(
outlineWidth
)
}
}),
asynchronous: false,
shadows
})
);
this._lastShow = showFill;
this._lastOutlineShow = showOutline;
this._lastOutlineColor = Color_default.clone(outlineColor, this._lastOutlineColor);
this._lastDistanceDisplayCondition = distanceDisplayCondition;
this._lastOffset = Cartesian3_default.clone(offset2, this._lastOffset);
} else if (this._primitive.ready) {
const primitive = this._primitive;
const outlinePrimitive = this._outlinePrimitive;
primitive.show = true;
outlinePrimitive.show = true;
primitive.appearance.material = material;
let attributes = this._attributes;
if (!defined_default(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(entity);
this._attributes = attributes;
}
if (showFill !== this._lastShow) {
attributes.show = ShowGeometryInstanceAttribute_default.toValue(
showFill,
attributes.show
);
this._lastShow = showFill;
}
let outlineAttributes = this._outlineAttributes;
if (!defined_default(outlineAttributes)) {
outlineAttributes = outlinePrimitive.getGeometryInstanceAttributes(
entity
);
this._outlineAttributes = outlineAttributes;
}
if (showOutline !== this._lastOutlineShow) {
outlineAttributes.show = ShowGeometryInstanceAttribute_default.toValue(
showOutline,
outlineAttributes.show
);
this._lastOutlineShow = showOutline;
}
if (!Color_default.equals(outlineColor, this._lastOutlineColor)) {
outlineAttributes.color = ColorGeometryInstanceAttribute_default.toValue(
outlineColor,
outlineAttributes.color
);
Color_default.clone(outlineColor, this._lastOutlineColor);
}
if (!DistanceDisplayCondition_default.equals(
distanceDisplayCondition,
this._lastDistanceDisplayCondition
)) {
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition
);
outlineAttributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
outlineAttributes.distanceDisplayCondition
);
DistanceDisplayCondition_default.clone(
distanceDisplayCondition,
this._lastDistanceDisplayCondition
);
}
if (!Cartesian3_default.equals(offset2, this._lastOffset)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.toValue(
offset2,
attributes.offset
);
outlineAttributes.offset = OffsetGeometryInstanceAttribute_default.toValue(
offset2,
attributes.offset
);
Cartesian3_default.clone(offset2, this._lastOffset);
}
}
if (in3D) {
radii.x = Math.max(radii.x, 1e-3);
radii.y = Math.max(radii.y, 1e-3);
radii.z = Math.max(radii.z, 1e-3);
modelMatrix = Matrix4_default.multiplyByScale(modelMatrix, radii, modelMatrix);
this._primitive.modelMatrix = modelMatrix;
this._outlinePrimitive.modelMatrix = modelMatrix;
}
};
var EllipsoidGeometryUpdater_default = EllipsoidGeometryUpdater;
// node_modules/@cesium/engine/Source/Core/PlaneGeometry.js
function PlaneGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
this._vertexFormat = vertexFormat;
this._workerName = "createPlaneGeometry";
}
PlaneGeometry.packedLength = VertexFormat_default.packedLength;
PlaneGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
return array;
};
var scratchVertexFormat6 = new VertexFormat_default();
var scratchOptions14 = {
vertexFormat: scratchVertexFormat6
};
PlaneGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat6
);
if (!defined_default(result)) {
return new PlaneGeometry(scratchOptions14);
}
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
return result;
};
var min = new Cartesian3_default(-0.5, -0.5, 0);
var max = new Cartesian3_default(0.5, 0.5, 0);
PlaneGeometry.createGeometry = function(planeGeometry) {
const vertexFormat = planeGeometry._vertexFormat;
const attributes = new GeometryAttributes_default();
let indices2;
let positions;
if (vertexFormat.position) {
positions = new Float64Array(4 * 3);
positions[0] = min.x;
positions[1] = min.y;
positions[2] = 0;
positions[3] = max.x;
positions[4] = min.y;
positions[5] = 0;
positions[6] = max.x;
positions[7] = max.y;
positions[8] = 0;
positions[9] = min.x;
positions[10] = max.y;
positions[11] = 0;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
if (vertexFormat.normal) {
const normals = new Float32Array(4 * 3);
normals[0] = 0;
normals[1] = 0;
normals[2] = 1;
normals[3] = 0;
normals[4] = 0;
normals[5] = 1;
normals[6] = 0;
normals[7] = 0;
normals[8] = 1;
normals[9] = 0;
normals[10] = 0;
normals[11] = 1;
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.st) {
const texCoords = new Float32Array(4 * 2);
texCoords[0] = 0;
texCoords[1] = 0;
texCoords[2] = 1;
texCoords[3] = 0;
texCoords[4] = 1;
texCoords[5] = 1;
texCoords[6] = 0;
texCoords[7] = 1;
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: texCoords
});
}
if (vertexFormat.tangent) {
const tangents = new Float32Array(4 * 3);
tangents[0] = 1;
tangents[1] = 0;
tangents[2] = 0;
tangents[3] = 1;
tangents[4] = 0;
tangents[5] = 0;
tangents[6] = 1;
tangents[7] = 0;
tangents[8] = 0;
tangents[9] = 1;
tangents[10] = 0;
tangents[11] = 0;
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
const bitangents = new Float32Array(4 * 3);
bitangents[0] = 0;
bitangents[1] = 1;
bitangents[2] = 0;
bitangents[3] = 0;
bitangents[4] = 1;
bitangents[5] = 0;
bitangents[6] = 0;
bitangents[7] = 1;
bitangents[8] = 0;
bitangents[9] = 0;
bitangents[10] = 1;
bitangents[11] = 0;
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
indices2 = new Uint16Array(2 * 3);
indices2[0] = 0;
indices2[1] = 1;
indices2[2] = 2;
indices2[3] = 0;
indices2[4] = 2;
indices2[5] = 3;
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere: new BoundingSphere_default(Cartesian3_default.ZERO, Math.sqrt(2))
});
};
var PlaneGeometry_default = PlaneGeometry;
// node_modules/@cesium/engine/Source/Core/PlaneOutlineGeometry.js
function PlaneOutlineGeometry() {
this._workerName = "createPlaneOutlineGeometry";
}
PlaneOutlineGeometry.packedLength = 0;
PlaneOutlineGeometry.pack = function(value, array) {
Check_default.defined("value", value);
Check_default.defined("array", array);
return array;
};
PlaneOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
if (!defined_default(result)) {
return new PlaneOutlineGeometry();
}
return result;
};
var min2 = new Cartesian3_default(-0.5, -0.5, 0);
var max2 = new Cartesian3_default(0.5, 0.5, 0);
PlaneOutlineGeometry.createGeometry = function() {
const attributes = new GeometryAttributes_default();
const indices2 = new Uint16Array(4 * 2);
const positions = new Float64Array(4 * 3);
positions[0] = min2.x;
positions[1] = min2.y;
positions[2] = min2.z;
positions[3] = max2.x;
positions[4] = min2.y;
positions[5] = min2.z;
positions[6] = max2.x;
positions[7] = max2.y;
positions[8] = min2.z;
positions[9] = min2.x;
positions[10] = max2.y;
positions[11] = min2.z;
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
indices2[0] = 0;
indices2[1] = 1;
indices2[2] = 1;
indices2[3] = 2;
indices2[4] = 2;
indices2[5] = 3;
indices2[6] = 3;
indices2[7] = 0;
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES,
boundingSphere: new BoundingSphere_default(Cartesian3_default.ZERO, Math.sqrt(2))
});
};
var PlaneOutlineGeometry_default = PlaneOutlineGeometry;
// node_modules/@cesium/engine/Source/DataSources/PlaneGeometryUpdater.js
var positionScratch11 = new Cartesian3_default();
var scratchColor15 = new Color_default();
function PlaneGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.plane = void 0;
this.dimensions = void 0;
}
function PlaneGeometryUpdater(entity, scene) {
GeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new PlaneGeometryOptions(entity),
geometryPropertyName: "plane",
observedPropertyNames: ["availability", "position", "orientation", "plane"]
});
this._onEntityPropertyChanged(entity, "plane", entity.plane, void 0);
}
if (defined_default(Object.create)) {
PlaneGeometryUpdater.prototype = Object.create(GeometryUpdater_default.prototype);
PlaneGeometryUpdater.prototype.constructor = PlaneGeometryUpdater;
}
PlaneGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
let attributes;
let color;
const show = new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
);
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor15);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color
};
} else {
attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute
};
}
const planeGraphics = entity.plane;
const options = this._options;
let modelMatrix = entity.computeModelMatrix(time);
const plane = Property_default.getValueOrDefault(
planeGraphics.plane,
time,
options.plane
);
const dimensions = Property_default.getValueOrUndefined(
planeGraphics.dimensions,
time,
options.dimensions
);
options.plane = plane;
options.dimensions = dimensions;
modelMatrix = createPrimitiveMatrix(
plane,
dimensions,
modelMatrix,
modelMatrix
);
return new GeometryInstance_default({
id: entity,
geometry: new PlaneGeometry_default(this._options),
modelMatrix,
attributes
});
};
PlaneGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor15
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const planeGraphics = entity.plane;
const options = this._options;
let modelMatrix = entity.computeModelMatrix(time);
const plane = Property_default.getValueOrDefault(
planeGraphics.plane,
time,
options.plane
);
const dimensions = Property_default.getValueOrUndefined(
planeGraphics.dimensions,
time,
options.dimensions
);
options.plane = plane;
options.dimensions = dimensions;
modelMatrix = createPrimitiveMatrix(
plane,
dimensions,
modelMatrix,
modelMatrix
);
return new GeometryInstance_default({
id: entity,
geometry: new PlaneOutlineGeometry_default(),
modelMatrix,
attributes: {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
)
}
});
};
PlaneGeometryUpdater.prototype._isHidden = function(entity, plane) {
return !defined_default(plane.plane) || !defined_default(plane.dimensions) || !defined_default(entity.position) || GeometryUpdater_default.prototype._isHidden.call(this, entity, plane);
};
PlaneGeometryUpdater.prototype._getIsClosed = function(options) {
return false;
};
PlaneGeometryUpdater.prototype._isDynamic = function(entity, plane) {
return !entity.position.isConstant || !Property_default.isConstant(entity.orientation) || !plane.plane.isConstant || !plane.dimensions.isConstant || !Property_default.isConstant(plane.outlineWidth);
};
PlaneGeometryUpdater.prototype._setStaticOptions = function(entity, plane) {
const isColorMaterial = this._materialProperty instanceof ColorMaterialProperty_default;
const options = this._options;
options.vertexFormat = isColorMaterial ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.plane = plane.plane.getValue(Iso8601_default.MINIMUM_VALUE, options.plane);
options.dimensions = plane.dimensions.getValue(
Iso8601_default.MINIMUM_VALUE,
options.dimensions
);
};
PlaneGeometryUpdater.DynamicGeometryUpdater = DynamicPlaneGeometryUpdater;
function DynamicPlaneGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicPlaneGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicPlaneGeometryUpdater.prototype.constructor = DynamicPlaneGeometryUpdater;
}
DynamicPlaneGeometryUpdater.prototype._isHidden = function(entity, plane, time) {
const options = this._options;
const position = Property_default.getValueOrUndefined(
entity.position,
time,
positionScratch11
);
return !defined_default(position) || !defined_default(options.plane) || !defined_default(options.dimensions) || DynamicGeometryUpdater_default.prototype._isHidden.call(this, entity, plane, time);
};
DynamicPlaneGeometryUpdater.prototype._setOptions = function(entity, plane, time) {
const options = this._options;
options.plane = Property_default.getValueOrDefault(plane.plane, time, options.plane);
options.dimensions = Property_default.getValueOrUndefined(
plane.dimensions,
time,
options.dimensions
);
};
var scratchAxis2 = new Cartesian3_default();
var scratchUp = new Cartesian3_default();
var scratchTranslation = new Cartesian3_default();
var scratchScale4 = new Cartesian3_default();
var scratchRotation2 = new Matrix3_default();
var scratchRotationScale2 = new Matrix3_default();
var scratchLocalTransform = new Matrix4_default();
function createPrimitiveMatrix(plane, dimensions, transform3, result) {
const normal2 = plane.normal;
const distance2 = plane.distance;
const translation3 = Cartesian3_default.multiplyByScalar(
normal2,
-distance2,
scratchTranslation
);
let up = Cartesian3_default.clone(Cartesian3_default.UNIT_Z, scratchUp);
if (Math_default.equalsEpsilon(
Math.abs(Cartesian3_default.dot(up, normal2)),
1,
Math_default.EPSILON8
)) {
up = Cartesian3_default.clone(Cartesian3_default.UNIT_Y, up);
}
const left = Cartesian3_default.cross(up, normal2, scratchAxis2);
up = Cartesian3_default.cross(normal2, left, up);
Cartesian3_default.normalize(left, left);
Cartesian3_default.normalize(up, up);
const rotationMatrix = scratchRotation2;
Matrix3_default.setColumn(rotationMatrix, 0, left, rotationMatrix);
Matrix3_default.setColumn(rotationMatrix, 1, up, rotationMatrix);
Matrix3_default.setColumn(rotationMatrix, 2, normal2, rotationMatrix);
const scale = Cartesian3_default.fromElements(
dimensions.x,
dimensions.y,
1,
scratchScale4
);
const rotationScaleMatrix = Matrix3_default.multiplyByScale(
rotationMatrix,
scale,
scratchRotationScale2
);
const localTransform = Matrix4_default.fromRotationTranslation(
rotationScaleMatrix,
translation3,
scratchLocalTransform
);
return Matrix4_default.multiplyTransformation(transform3, localTransform, result);
}
PlaneGeometryUpdater.createPrimitiveMatrix = createPrimitiveMatrix;
var PlaneGeometryUpdater_default = PlaneGeometryUpdater;
// node_modules/@cesium/engine/Source/Core/CoplanarPolygonGeometry.js
var scratchPosition9 = new Cartesian3_default();
var scratchBR = new BoundingRectangle_default();
var stScratch = new Cartesian2_default();
var textureCoordinatesOrigin = new Cartesian2_default();
var scratchNormal5 = new Cartesian3_default();
var scratchTangent3 = new Cartesian3_default();
var scratchBitangent3 = new Cartesian3_default();
var centerScratch3 = new Cartesian3_default();
var axis1Scratch = new Cartesian3_default();
var axis2Scratch = new Cartesian3_default();
var quaternionScratch3 = new Quaternion_default();
var textureMatrixScratch2 = new Matrix3_default();
var tangentRotationScratch = new Matrix3_default();
var surfaceNormalScratch = new Cartesian3_default();
function createGeometryFromPolygon(polygon, vertexFormat, boundingRectangle, stRotation, hardcodedTextureCoordinates, projectPointTo2D, normal2, tangent, bitangent) {
const positions = polygon.positions;
let indices2 = PolygonPipeline_default.triangulate(polygon.positions2D, polygon.holes);
if (indices2.length < 3) {
indices2 = [0, 1, 2];
}
const newIndices = IndexDatatype_default.createTypedArray(
positions.length,
indices2.length
);
newIndices.set(indices2);
let textureMatrix = textureMatrixScratch2;
if (stRotation !== 0) {
let rotation = Quaternion_default.fromAxisAngle(
normal2,
stRotation,
quaternionScratch3
);
textureMatrix = Matrix3_default.fromQuaternion(rotation, textureMatrix);
if (vertexFormat.tangent || vertexFormat.bitangent) {
rotation = Quaternion_default.fromAxisAngle(
normal2,
-stRotation,
quaternionScratch3
);
const tangentRotation = Matrix3_default.fromQuaternion(
rotation,
tangentRotationScratch
);
tangent = Cartesian3_default.normalize(
Matrix3_default.multiplyByVector(tangentRotation, tangent, tangent),
tangent
);
if (vertexFormat.bitangent) {
bitangent = Cartesian3_default.normalize(
Cartesian3_default.cross(normal2, tangent, bitangent),
bitangent
);
}
}
} else {
textureMatrix = Matrix3_default.clone(Matrix3_default.IDENTITY, textureMatrix);
}
const stOrigin = textureCoordinatesOrigin;
if (vertexFormat.st) {
stOrigin.x = boundingRectangle.x;
stOrigin.y = boundingRectangle.y;
}
const length3 = positions.length;
const size = length3 * 3;
const flatPositions2 = new Float64Array(size);
const normals = vertexFormat.normal ? new Float32Array(size) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(size) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(size) : void 0;
const textureCoordinates = vertexFormat.st ? new Float32Array(length3 * 2) : void 0;
let positionIndex = 0;
let normalIndex = 0;
let bitangentIndex = 0;
let tangentIndex = 0;
let stIndex = 0;
for (let i = 0; i < length3; i++) {
const position = positions[i];
flatPositions2[positionIndex++] = position.x;
flatPositions2[positionIndex++] = position.y;
flatPositions2[positionIndex++] = position.z;
if (vertexFormat.st) {
if (defined_default(hardcodedTextureCoordinates) && hardcodedTextureCoordinates.positions.length === length3) {
textureCoordinates[stIndex++] = hardcodedTextureCoordinates.positions[i].x;
textureCoordinates[stIndex++] = hardcodedTextureCoordinates.positions[i].y;
} else {
const p = Matrix3_default.multiplyByVector(
textureMatrix,
position,
scratchPosition9
);
const st = projectPointTo2D(p, stScratch);
Cartesian2_default.subtract(st, stOrigin, st);
const stx = Math_default.clamp(st.x / boundingRectangle.width, 0, 1);
const sty = Math_default.clamp(st.y / boundingRectangle.height, 0, 1);
textureCoordinates[stIndex++] = stx;
textureCoordinates[stIndex++] = sty;
}
}
if (vertexFormat.normal) {
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.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_default();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: flatPositions2
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: textureCoordinates
});
}
return new Geometry_default({
attributes,
indices: newIndices,
primitiveType: PrimitiveType_default.TRIANGLES
});
}
function CoplanarPolygonGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const polygonHierarchy = options.polygonHierarchy;
const textureCoordinates = options.textureCoordinates;
Check_default.defined("options.polygonHierarchy", polygonHierarchy);
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
this._vertexFormat = VertexFormat_default.clone(vertexFormat);
this._polygonHierarchy = polygonHierarchy;
this._stRotation = defaultValue_default(options.stRotation, 0);
this._ellipsoid = Ellipsoid_default.clone(
defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
);
this._workerName = "createCoplanarPolygonGeometry";
this._textureCoordinates = textureCoordinates;
this.packedLength = PolygonGeometryLibrary_default.computeHierarchyPackedLength(
polygonHierarchy,
Cartesian3_default
) + VertexFormat_default.packedLength + Ellipsoid_default.packedLength + (defined_default(textureCoordinates) ? PolygonGeometryLibrary_default.computeHierarchyPackedLength(
textureCoordinates,
Cartesian2_default
) : 1) + 2;
}
CoplanarPolygonGeometry.fromPositions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.positions", options.positions);
const newOptions2 = {
polygonHierarchy: {
positions: options.positions
},
vertexFormat: options.vertexFormat,
stRotation: options.stRotation,
ellipsoid: options.ellipsoid,
textureCoordinates: options.textureCoordinates
};
return new CoplanarPolygonGeometry(newOptions2);
};
CoplanarPolygonGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
startingIndex = PolygonGeometryLibrary_default.packPolygonHierarchy(
value._polygonHierarchy,
array,
startingIndex,
Cartesian3_default
);
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.packedLength;
array[startingIndex++] = value._stRotation;
if (defined_default(value._textureCoordinates)) {
startingIndex = PolygonGeometryLibrary_default.packPolygonHierarchy(
value._textureCoordinates,
array,
startingIndex,
Cartesian2_default
);
} else {
array[startingIndex++] = -1;
}
array[startingIndex++] = value.packedLength;
return array;
};
var scratchEllipsoid6 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchVertexFormat7 = new VertexFormat_default();
var scratchOptions15 = {
polygonHierarchy: {}
};
CoplanarPolygonGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const polygonHierarchy = PolygonGeometryLibrary_default.unpackPolygonHierarchy(
array,
startingIndex,
Cartesian3_default
);
startingIndex = polygonHierarchy.startingIndex;
delete polygonHierarchy.startingIndex;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid6);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat7
);
startingIndex += VertexFormat_default.packedLength;
const stRotation = array[startingIndex++];
const textureCoordinates = array[startingIndex] === -1 ? void 0 : PolygonGeometryLibrary_default.unpackPolygonHierarchy(
array,
startingIndex,
Cartesian2_default
);
if (defined_default(textureCoordinates)) {
startingIndex = textureCoordinates.startingIndex;
delete textureCoordinates.startingIndex;
} else {
startingIndex++;
}
const packedLength = array[startingIndex++];
if (!defined_default(result)) {
result = new CoplanarPolygonGeometry(scratchOptions15);
}
result._polygonHierarchy = polygonHierarchy;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
result._stRotation = stRotation;
result._textureCoordinates = textureCoordinates;
result.packedLength = packedLength;
return result;
};
CoplanarPolygonGeometry.createGeometry = function(polygonGeometry) {
const vertexFormat = polygonGeometry._vertexFormat;
const polygonHierarchy = polygonGeometry._polygonHierarchy;
const stRotation = polygonGeometry._stRotation;
const textureCoordinates = polygonGeometry._textureCoordinates;
const hasTextureCoordinates = defined_default(textureCoordinates);
let outerPositions = polygonHierarchy.positions;
outerPositions = arrayRemoveDuplicates_default(
outerPositions,
Cartesian3_default.equalsEpsilon,
true
);
if (outerPositions.length < 3) {
return;
}
let normal2 = scratchNormal5;
let tangent = scratchTangent3;
let bitangent = scratchBitangent3;
let axis1 = axis1Scratch;
const axis2 = axis2Scratch;
const validGeometry = CoplanarPolygonGeometryLibrary_default.computeProjectTo2DArguments(
outerPositions,
centerScratch3,
axis1,
axis2
);
if (!validGeometry) {
return void 0;
}
normal2 = Cartesian3_default.cross(axis1, axis2, normal2);
normal2 = Cartesian3_default.normalize(normal2, normal2);
if (!Cartesian3_default.equalsEpsilon(
centerScratch3,
Cartesian3_default.ZERO,
Math_default.EPSILON6
)) {
const surfaceNormal = polygonGeometry._ellipsoid.geodeticSurfaceNormal(
centerScratch3,
surfaceNormalScratch
);
if (Cartesian3_default.dot(normal2, surfaceNormal) < 0) {
normal2 = Cartesian3_default.negate(normal2, normal2);
axis1 = Cartesian3_default.negate(axis1, axis1);
}
}
const projectPoints = CoplanarPolygonGeometryLibrary_default.createProjectPointsTo2DFunction(
centerScratch3,
axis1,
axis2
);
const projectPoint = CoplanarPolygonGeometryLibrary_default.createProjectPointTo2DFunction(
centerScratch3,
axis1,
axis2
);
if (vertexFormat.tangent) {
tangent = Cartesian3_default.clone(axis1, tangent);
}
if (vertexFormat.bitangent) {
bitangent = Cartesian3_default.clone(axis2, bitangent);
}
const results = PolygonGeometryLibrary_default.polygonsFromHierarchy(
polygonHierarchy,
hasTextureCoordinates,
projectPoints,
false
);
const hierarchy = results.hierarchy;
const polygons = results.polygons;
const dummyFunction = function(identity) {
return identity;
};
const textureCoordinatePolygons = hasTextureCoordinates ? PolygonGeometryLibrary_default.polygonsFromHierarchy(
textureCoordinates,
true,
dummyFunction,
false
).polygons : void 0;
if (hierarchy.length === 0) {
return;
}
outerPositions = hierarchy[0].outerRing;
const boundingSphere = BoundingSphere_default.fromPoints(outerPositions);
const boundingRectangle = PolygonGeometryLibrary_default.computeBoundingRectangle(
normal2,
projectPoint,
outerPositions,
stRotation,
scratchBR
);
const geometries = [];
for (let i = 0; i < polygons.length; i++) {
const geometryInstance = new GeometryInstance_default({
geometry: createGeometryFromPolygon(
polygons[i],
vertexFormat,
boundingRectangle,
stRotation,
hasTextureCoordinates ? textureCoordinatePolygons[i] : void 0,
projectPoint,
normal2,
tangent,
bitangent
)
});
geometries.push(geometryInstance);
}
const geometry = GeometryPipeline_default.combineInstances(geometries)[0];
geometry.attributes.position.values = new Float64Array(
geometry.attributes.position.values
);
geometry.indices = IndexDatatype_default.createTypedArray(
geometry.attributes.position.values.length / 3,
geometry.indices
);
const attributes = geometry.attributes;
if (!vertexFormat.position) {
delete attributes.position;
}
return new Geometry_default({
attributes,
indices: geometry.indices,
primitiveType: geometry.primitiveType,
boundingSphere
});
};
var CoplanarPolygonGeometry_default = CoplanarPolygonGeometry;
// node_modules/@cesium/engine/Source/Core/PolygonGeometry.js
var scratchCarto1 = new Cartographic_default();
var scratchCarto2 = new Cartographic_default();
function adjustPosHeightsForNormal(position, p1, p2, ellipsoid) {
const carto12 = ellipsoid.cartesianToCartographic(position, scratchCarto1);
const height = carto12.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);
}
var scratchBoundingRectangle = new BoundingRectangle_default();
var scratchPosition10 = new Cartesian3_default();
var scratchNormal6 = new Cartesian3_default();
var scratchTangent4 = new Cartesian3_default();
var scratchBitangent4 = new Cartesian3_default();
var p1Scratch3 = new Cartesian3_default();
var p2Scratch3 = new Cartesian3_default();
var scratchPerPosNormal = new Cartesian3_default();
var scratchPerPosTangent = new Cartesian3_default();
var scratchPerPosBitangent = new Cartesian3_default();
var appendTextureCoordinatesOrigin = new Cartesian2_default();
var appendTextureCoordinatesCartesian2 = new Cartesian2_default();
var appendTextureCoordinatesCartesian3 = new Cartesian3_default();
var appendTextureCoordinatesQuaternion = new Quaternion_default();
var appendTextureCoordinatesMatrix3 = new Matrix3_default();
var tangentMatrixScratch2 = new Matrix3_default();
function computeAttributes(options) {
const vertexFormat = options.vertexFormat;
const geometry = options.geometry;
const shadowVolume = options.shadowVolume;
const flatPositions2 = geometry.attributes.position.values;
const flatTexcoords = defined_default(geometry.attributes.st) ? geometry.attributes.st.values : void 0;
let length3 = flatPositions2.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) {
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 * (length3 / 3)) : void 0;
let normals;
if (vertexFormat.normal) {
if (perPositionHeight && top && !wall) {
normals = geometry.attributes.normal.values;
} else {
normals = new Float32Array(length3);
}
}
const tangents = vertexFormat.tangent ? new Float32Array(length3) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(length3) : void 0;
const extrudeNormals = shadowVolume ? new Float32Array(length3) : void 0;
let textureCoordIndex = 0;
let attrIndex = 0;
let normal2 = scratchNormal6;
let tangent = scratchTangent4;
let bitangent = scratchBitangent4;
let recomputeNormal = true;
let textureMatrix = appendTextureCoordinatesMatrix3;
let tangentRotationMatrix = tangentMatrixScratch2;
if (stRotation !== 0) {
let rotation = Quaternion_default.fromAxisAngle(
tangentPlane._plane.normal,
stRotation,
appendTextureCoordinatesQuaternion
);
textureMatrix = Matrix3_default.fromQuaternion(rotation, textureMatrix);
rotation = Quaternion_default.fromAxisAngle(
tangentPlane._plane.normal,
-stRotation,
appendTextureCoordinatesQuaternion
);
tangentRotationMatrix = Matrix3_default.fromQuaternion(
rotation,
tangentRotationMatrix
);
} else {
textureMatrix = Matrix3_default.clone(Matrix3_default.IDENTITY, textureMatrix);
tangentRotationMatrix = Matrix3_default.clone(
Matrix3_default.IDENTITY,
tangentRotationMatrix
);
}
let bottomOffset = 0;
let bottomOffset2 = 0;
if (top && bottom) {
bottomOffset = length3 / 2;
bottomOffset2 = length3 / 3;
length3 /= 2;
}
for (let i = 0; i < length3; i += 3) {
const position = Cartesian3_default.fromArray(
flatPositions2,
i,
appendTextureCoordinatesCartesian3
);
if (vertexFormat.st) {
if (!defined_default(flatTexcoords)) {
let p = Matrix3_default.multiplyByVector(
textureMatrix,
position,
scratchPosition10
);
p = ellipsoid.scaleToGeodeticSurface(p, p);
const st = tangentPlane.projectPointOntoPlane(
p,
appendTextureCoordinatesCartesian2
);
Cartesian2_default.subtract(st, origin, st);
const stx = Math_default.clamp(st.x / boundingRectangle.width, 0, 1);
const sty = Math_default.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 < length3) {
const p1 = Cartesian3_default.fromArray(flatPositions2, i + 3, p1Scratch3);
if (recomputeNormal) {
const p2 = Cartesian3_default.fromArray(
flatPositions2,
i + length3,
p2Scratch3
);
if (perPositionHeight) {
adjustPosHeightsForNormal(position, p1, p2, ellipsoid);
}
Cartesian3_default.subtract(p1, position, p1);
Cartesian3_default.subtract(p2, position, p2);
normal2 = Cartesian3_default.normalize(
Cartesian3_default.cross(p2, p1, normal2),
normal2
);
recomputeNormal = false;
}
if (Cartesian3_default.equalsEpsilon(p1, position, Math_default.EPSILON10)) {
recomputeNormal = true;
}
}
if (vertexFormat.tangent || vertexFormat.bitangent) {
bitangent = ellipsoid.geodeticSurfaceNormal(position, bitangent);
if (vertexFormat.tangent) {
tangent = Cartesian3_default.normalize(
Cartesian3_default.cross(bitangent, normal2, tangent),
tangent
);
}
}
} else {
normal2 = ellipsoid.geodeticSurfaceNormal(position, normal2);
if (vertexFormat.tangent || vertexFormat.bitangent) {
if (perPositionHeight) {
scratchPerPosNormal = Cartesian3_default.fromArray(
normals,
attrIndex,
scratchPerPosNormal
);
scratchPerPosTangent = Cartesian3_default.cross(
Cartesian3_default.UNIT_Z,
scratchPerPosNormal,
scratchPerPosTangent
);
scratchPerPosTangent = Cartesian3_default.normalize(
Matrix3_default.multiplyByVector(
tangentRotationMatrix,
scratchPerPosTangent,
scratchPerPosTangent
),
scratchPerPosTangent
);
if (vertexFormat.bitangent) {
scratchPerPosBitangent = Cartesian3_default.normalize(
Cartesian3_default.cross(
scratchPerPosNormal,
scratchPerPosTangent,
scratchPerPosBitangent
),
scratchPerPosBitangent
);
}
}
tangent = Cartesian3_default.cross(Cartesian3_default.UNIT_Z, normal2, tangent);
tangent = Cartesian3_default.normalize(
Matrix3_default.multiplyByVector(tangentRotationMatrix, tangent, tangent),
tangent
);
if (vertexFormat.bitangent) {
bitangent = Cartesian3_default.normalize(
Cartesian3_default.cross(normal2, tangent, bitangent),
bitangent
);
}
}
}
if (vertexFormat.normal) {
if (options.wall) {
normals[attrIndex + bottomOffset] = normal2.x;
normals[attrIndex1 + bottomOffset] = normal2.y;
normals[attrIndex2 + bottomOffset] = normal2.z;
} else if (bottom) {
normals[attrIndex + bottomOffset] = -normal2.x;
normals[attrIndex1 + bottomOffset] = -normal2.y;
normals[attrIndex2 + bottomOffset] = -normal2.z;
}
if (top && !perPositionHeight || wall) {
normals[attrIndex] = normal2.x;
normals[attrIndex1] = normal2.y;
normals[attrIndex2] = normal2.z;
}
}
if (shadowVolume) {
if (wall) {
normal2 = ellipsoid.geodeticSurfaceNormal(position, normal2);
}
extrudeNormals[attrIndex + bottomOffset] = -normal2.x;
extrudeNormals[attrIndex1 + bottomOffset] = -normal2.y;
extrudeNormals[attrIndex2 + bottomOffset] = -normal2.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_default(flatTexcoords)) {
geometry.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: textureCoordinates
});
}
if (vertexFormat.normal) {
geometry.attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.tangent) {
geometry.attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
geometry.attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
if (shadowVolume) {
geometry.attributes.extrudeDirection = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: extrudeNormals
});
}
}
if (options.extrude && defined_default(options.offsetAttribute)) {
const size = flatPositions2.length / 3;
let offsetAttribute = new Uint8Array(size);
if (options.offsetAttribute === GeometryOffsetAttribute_default.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_default.NONE ? 0 : 1;
offsetAttribute = offsetAttribute.fill(offsetValue);
}
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: offsetAttribute
});
}
return geometry;
}
var startCartographicScratch2 = new Cartographic_default();
var endCartographicScratch2 = new Cartographic_default();
var idlCross = {
westOverIDL: 0,
eastOverIDL: 0
};
var ellipsoidGeodesic2 = new EllipsoidGeodesic_default();
function computeRectangle3(positions, ellipsoid, arcType, granularity, result) {
result = defaultValue_default(result, new Rectangle_default());
if (!defined_default(positions) || positions.length < 3) {
result.west = 0;
result.north = 0;
result.south = 0;
result.east = 0;
return result;
}
if (arcType === ArcType_default.RHUMB) {
return Rectangle_default.fromCartesianArray(positions, ellipsoid, result);
}
if (!ellipsoidGeodesic2.ellipsoid.equals(ellipsoid)) {
ellipsoidGeodesic2 = new EllipsoidGeodesic_default(void 0, void 0, 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 / Math_default.chordLength(granularity, ellipsoid.maximumRadius);
const positionsLength = positions.length;
let endCartographic = ellipsoid.cartesianToCartographic(
positions[0],
endCartographicScratch2
);
let startCartographic = startCartographicScratch2;
let swap5;
for (let i = 1; i < positionsLength; i++) {
swap5 = startCartographic;
startCartographic = endCartographic;
endCartographic = ellipsoid.cartesianToCartographic(positions[i], swap5);
ellipsoidGeodesic2.setEndPoints(startCartographic, endCartographic);
interpolateAndGrowRectangle(
ellipsoidGeodesic2,
inverseChordLength,
result,
idlCross
);
}
swap5 = startCartographic;
startCartographic = endCartographic;
endCartographic = ellipsoid.cartesianToCartographic(positions[0], swap5);
ellipsoidGeodesic2.setEndPoints(startCartographic, endCartographic);
interpolateAndGrowRectangle(
ellipsoidGeodesic2,
inverseChordLength,
result,
idlCross
);
if (result.east - result.west > idlCross.eastOverIDL - idlCross.westOverIDL) {
result.west = idlCross.westOverIDL;
result.east = idlCross.eastOverIDL;
if (result.east > Math_default.PI) {
result.east = result.east - Math_default.TWO_PI;
}
if (result.west > Math_default.PI) {
result.west = result.west - Math_default.TWO_PI;
}
}
return result;
}
var interpolatedCartographicScratch2 = new Cartographic_default();
function interpolateAndGrowRectangle(ellipsoidGeodesic3, inverseChordLength, result, idlCross2) {
const segmentLength = ellipsoidGeodesic3.surfaceDistance;
const numPoints = Math.ceil(segmentLength * inverseChordLength);
const subsegmentDistance = numPoints > 0 ? segmentLength / (numPoints - 1) : Number.POSITIVE_INFINITY;
let interpolationDistance = 0;
for (let i = 0; i < numPoints; i++) {
const interpolatedCartographic = ellipsoidGeodesic3.interpolateUsingSurfaceDistance(
interpolationDistance,
interpolatedCartographicScratch2
);
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 + Math_default.TWO_PI;
idlCross2.westOverIDL = Math.min(idlCross2.westOverIDL, lonAdjusted);
idlCross2.eastOverIDL = Math.max(idlCross2.eastOverIDL, lonAdjusted);
}
}
var createGeometryFromPositionsExtrudedPositions = [];
function createGeometryFromPositionsExtruded(ellipsoid, polygon, textureCoordinates, granularity, hierarchy, perPositionHeight, closeTop, closeBottom, vertexFormat, arcType) {
const geos = {
walls: []
};
let i;
if (closeTop || closeBottom) {
const topGeo = PolygonGeometryLibrary_default.createGeometryFromPositions(
ellipsoid,
polygon,
textureCoordinates,
granularity,
perPositionHeight,
vertexFormat,
arcType
);
const edgePoints = topGeo.attributes.position.values;
const indices2 = topGeo.indices;
let numPositions;
let newIndices;
if (closeTop && closeBottom) {
const topBottomPositions = edgePoints.concat(edgePoints);
numPositions = topBottomPositions.length / 3;
newIndices = IndexDatatype_default.createTypedArray(
numPositions,
indices2.length * 2
);
newIndices.set(indices2);
const ilength = indices2.length;
const length3 = numPositions / 2;
for (i = 0; i < ilength; i += 3) {
const i0 = newIndices[i] + length3;
const i1 = newIndices[i + 1] + length3;
const i2 = newIndices[i + 2] + length3;
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_default(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_default.createTypedArray(numPositions, indices2.length);
for (i = 0; i < indices2.length; i += 3) {
newIndices[i] = indices2[i + 2];
newIndices[i + 1] = indices2[i + 1];
newIndices[i + 2] = indices2[i];
}
topGeo.indices = newIndices;
}
geos.topAndBottom = new GeometryInstance_default({
geometry: topGeo
});
}
let outerRing = hierarchy.outerRing;
let tangentPlane = EllipsoidTangentPlane_default.fromPoints(outerRing, ellipsoid);
let positions2D = tangentPlane.projectPointsOntoPlane(
outerRing,
createGeometryFromPositionsExtrudedPositions
);
let windingOrder = PolygonPipeline_default.computeWindingOrder2D(positions2D);
if (windingOrder === WindingOrder_default.CLOCKWISE) {
outerRing = outerRing.slice().reverse();
}
let wallGeo = PolygonGeometryLibrary_default.computeWallGeometry(
outerRing,
textureCoordinates,
ellipsoid,
granularity,
perPositionHeight,
arcType
);
geos.walls.push(
new GeometryInstance_default({
geometry: wallGeo
})
);
const holes = hierarchy.holes;
for (i = 0; i < holes.length; i++) {
let hole = holes[i];
tangentPlane = EllipsoidTangentPlane_default.fromPoints(hole, ellipsoid);
positions2D = tangentPlane.projectPointsOntoPlane(
hole,
createGeometryFromPositionsExtrudedPositions
);
windingOrder = PolygonPipeline_default.computeWindingOrder2D(positions2D);
if (windingOrder === WindingOrder_default.COUNTER_CLOCKWISE) {
hole = hole.slice().reverse();
}
wallGeo = PolygonGeometryLibrary_default.computeWallGeometry(
hole,
textureCoordinates,
ellipsoid,
granularity,
perPositionHeight,
arcType
);
geos.walls.push(
new GeometryInstance_default({
geometry: wallGeo
})
);
}
return geos;
}
function PolygonGeometry(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.polygonHierarchy", options.polygonHierarchy);
if (defined_default(options.perPositionHeight) && options.perPositionHeight && defined_default(options.height)) {
throw new DeveloperError_default(
"Cannot use both options.perPositionHeight and options.height"
);
}
if (defined_default(options.arcType) && options.arcType !== ArcType_default.GEODESIC && options.arcType !== ArcType_default.RHUMB) {
throw new DeveloperError_default(
"Invalid arcType. Valid options are ArcType.GEODESIC and ArcType.RHUMB."
);
}
const polygonHierarchy = options.polygonHierarchy;
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const stRotation = defaultValue_default(options.stRotation, 0);
const textureCoordinates = options.textureCoordinates;
const perPositionHeight = defaultValue_default(options.perPositionHeight, false);
const perPositionHeightExtrude = perPositionHeight && defined_default(options.extrudedHeight);
let height = defaultValue_default(options.height, 0);
let extrudedHeight = defaultValue_default(options.extrudedHeight, height);
if (!perPositionHeightExtrude) {
const h = Math.max(height, extrudedHeight);
extrudedHeight = Math.min(height, extrudedHeight);
height = h;
}
this._vertexFormat = VertexFormat_default.clone(vertexFormat);
this._ellipsoid = Ellipsoid_default.clone(ellipsoid);
this._granularity = granularity;
this._stRotation = stRotation;
this._height = height;
this._extrudedHeight = extrudedHeight;
this._closeTop = defaultValue_default(options.closeTop, true);
this._closeBottom = defaultValue_default(options.closeBottom, true);
this._polygonHierarchy = polygonHierarchy;
this._perPositionHeight = perPositionHeight;
this._perPositionHeightExtrude = perPositionHeightExtrude;
this._shadowVolume = defaultValue_default(options.shadowVolume, false);
this._workerName = "createPolygonGeometry";
this._offsetAttribute = options.offsetAttribute;
this._arcType = defaultValue_default(options.arcType, ArcType_default.GEODESIC);
this._rectangle = void 0;
this._textureCoordinateRotationPoints = void 0;
this._textureCoordinates = textureCoordinates;
this.packedLength = PolygonGeometryLibrary_default.computeHierarchyPackedLength(
polygonHierarchy,
Cartesian3_default
) + Ellipsoid_default.packedLength + VertexFormat_default.packedLength + (textureCoordinates ? PolygonGeometryLibrary_default.computeHierarchyPackedLength(
textureCoordinates,
Cartesian2_default
) : 1) + 12;
}
PolygonGeometry.fromPositions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.positions", options.positions);
const newOptions2 = {
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(newOptions2);
};
PolygonGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
startingIndex = PolygonGeometryLibrary_default.packPolygonHierarchy(
value._polygonHierarchy,
array,
startingIndex,
Cartesian3_default
);
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.packedLength;
array[startingIndex++] = value._height;
array[startingIndex++] = value._extrudedHeight;
array[startingIndex++] = value._granularity;
array[startingIndex++] = value._stRotation;
array[startingIndex++] = value._perPositionHeightExtrude ? 1 : 0;
array[startingIndex++] = value._perPositionHeight ? 1 : 0;
array[startingIndex++] = value._closeTop ? 1 : 0;
array[startingIndex++] = value._closeBottom ? 1 : 0;
array[startingIndex++] = value._shadowVolume ? 1 : 0;
array[startingIndex++] = defaultValue_default(value._offsetAttribute, -1);
array[startingIndex++] = value._arcType;
if (defined_default(value._textureCoordinates)) {
startingIndex = PolygonGeometryLibrary_default.packPolygonHierarchy(
value._textureCoordinates,
array,
startingIndex,
Cartesian2_default
);
} else {
array[startingIndex++] = -1;
}
array[startingIndex++] = value.packedLength;
return array;
};
var scratchEllipsoid7 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchVertexFormat8 = new VertexFormat_default();
var dummyOptions = {
polygonHierarchy: {}
};
PolygonGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const polygonHierarchy = PolygonGeometryLibrary_default.unpackPolygonHierarchy(
array,
startingIndex,
Cartesian3_default
);
startingIndex = polygonHierarchy.startingIndex;
delete polygonHierarchy.startingIndex;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid7);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat8
);
startingIndex += VertexFormat_default.packedLength;
const height = array[startingIndex++];
const extrudedHeight = array[startingIndex++];
const granularity = array[startingIndex++];
const stRotation = array[startingIndex++];
const perPositionHeightExtrude = array[startingIndex++] === 1;
const perPositionHeight = array[startingIndex++] === 1;
const closeTop = array[startingIndex++] === 1;
const closeBottom = array[startingIndex++] === 1;
const shadowVolume = array[startingIndex++] === 1;
const offsetAttribute = array[startingIndex++];
const arcType = array[startingIndex++];
const textureCoordinates = array[startingIndex] === -1 ? void 0 : PolygonGeometryLibrary_default.unpackPolygonHierarchy(
array,
startingIndex,
Cartesian2_default
);
if (defined_default(textureCoordinates)) {
startingIndex = textureCoordinates.startingIndex;
delete textureCoordinates.startingIndex;
} else {
startingIndex++;
}
const packedLength = array[startingIndex++];
if (!defined_default(result)) {
result = new PolygonGeometry(dummyOptions);
}
result._polygonHierarchy = polygonHierarchy;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.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 ? void 0 : offsetAttribute;
result._arcType = arcType;
result._textureCoordinates = textureCoordinates;
result.packedLength = packedLength;
return result;
};
PolygonGeometry.computeRectangle = function(options, result) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.polygonHierarchy", options.polygonHierarchy);
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const arcType = defaultValue_default(options.arcType, ArcType_default.GEODESIC);
if (arcType !== ArcType_default.GEODESIC && arcType !== ArcType_default.RHUMB) {
throw new DeveloperError_default(
"Invalid arcType. Valid options are ArcType.GEODESIC and ArcType.RHUMB."
);
}
const polygonHierarchy = options.polygonHierarchy;
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
return computeRectangle3(
polygonHierarchy.positions,
ellipsoid,
arcType,
granularity,
result
);
};
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_default(textureCoordinates);
let outerPositions = polygonHierarchy.positions;
if (outerPositions.length < 3) {
return;
}
const tangentPlane = EllipsoidTangentPlane_default.fromPoints(
outerPositions,
ellipsoid
);
const results = PolygonGeometryLibrary_default.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_default.polygonsFromHierarchy(
textureCoordinates,
true,
dummyFunction,
false
).polygons : void 0;
if (hierarchy.length === 0) {
return;
}
outerPositions = hierarchy[0].outerRing;
const boundingRectangle = PolygonGeometryLibrary_default.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 || !Math_default.equalsEpsilon(height, extrudedHeight, 0, Math_default.EPSILON2);
const options = {
perPositionHeight,
vertexFormat,
geometry: void 0,
tangentPlane,
boundingRectangle,
ellipsoid,
stRotation,
textureCoordinates: void 0,
bottom: false,
top: true,
wall: false,
extrude: false,
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(
ellipsoid,
polygons[i],
hasTextureCoordinates ? textureCoordinatePolygons[i] : void 0,
granularity,
hierarchy[i],
perPositionHeight,
closeTop,
closeBottom,
vertexFormat,
arcType
);
let topAndBottom;
if (closeTop && closeBottom) {
topAndBottom = splitGeometry.topAndBottom;
options.geometry = PolygonGeometryLibrary_default.scaleToGeodeticHeightExtruded(
topAndBottom.geometry,
height,
extrudedHeight,
ellipsoid,
perPositionHeight
);
} else if (closeTop) {
topAndBottom = splitGeometry.topAndBottom;
topAndBottom.geometry.attributes.position.values = PolygonPipeline_default.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_default.scaleToGeodeticHeight(
topAndBottom.geometry.attributes.position.values,
extrudedHeight,
ellipsoid,
true
);
options.geometry = topAndBottom.geometry;
}
if (closeTop || closeBottom) {
options.wall = false;
topAndBottom.geometry = computeAttributes(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_default.scaleToGeodeticHeightExtruded(
wall.geometry,
height,
extrudedHeight,
ellipsoid,
perPositionHeight
);
wall.geometry = computeAttributes(options);
geometries.push(wall);
}
}
} else {
for (i = 0; i < polygons.length; i++) {
const geometryInstance = new GeometryInstance_default({
geometry: PolygonGeometryLibrary_default.createGeometryFromPositions(
ellipsoid,
polygons[i],
hasTextureCoordinates ? textureCoordinatePolygons[i] : void 0,
granularity,
perPositionHeight,
vertexFormat,
arcType
)
});
geometryInstance.geometry.attributes.position.values = PolygonPipeline_default.scaleToGeodeticHeight(
geometryInstance.geometry.attributes.position.values,
height,
ellipsoid,
!perPositionHeight
);
options.geometry = geometryInstance.geometry;
geometryInstance.geometry = computeAttributes(options);
if (defined_default(polygonGeometry._offsetAttribute)) {
const length3 = geometryInstance.geometry.attributes.position.values.length;
const offsetValue = polygonGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
geometryInstance.geometry.attributes.applyOffset = new GeometryAttribute_default(
{
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
}
);
}
geometries.push(geometryInstance);
}
}
const geometry = GeometryPipeline_default.combineInstances(geometries)[0];
geometry.attributes.position.values = new Float64Array(
geometry.attributes.position.values
);
geometry.indices = IndexDatatype_default.createTypedArray(
geometry.attributes.position.values.length / 3,
geometry.indices
);
const attributes = geometry.attributes;
const boundingSphere = BoundingSphere_default.fromVertices(
attributes.position.values
);
if (!vertexFormat.position) {
delete attributes.position;
}
return new Geometry_default({
attributes,
indices: geometry.indices,
primitiveType: geometry.primitiveType,
boundingSphere,
offsetAttribute: polygonGeometry._offsetAttribute
});
};
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,
stRotation: polygonGeometry._stRotation,
granularity,
perPositionHeight: false,
extrudedHeight: minHeight,
height: maxHeight,
vertexFormat: VertexFormat_default.POSITION_ONLY,
shadowVolume: true,
arcType: polygonGeometry._arcType
});
};
function textureCoordinateRotationPoints2(polygonGeometry) {
const stRotation = -polygonGeometry._stRotation;
if (stRotation === 0) {
return [0, 0, 0, 1, 1, 0];
}
const ellipsoid = polygonGeometry._ellipsoid;
const positions = polygonGeometry._polygonHierarchy.positions;
const boundingRectangle = polygonGeometry.rectangle;
return Geometry_default._textureCoordinateRotationPoints(
positions,
stRotation,
ellipsoid,
boundingRectangle
);
}
Object.defineProperties(PolygonGeometry.prototype, {
rectangle: {
get: function() {
if (!defined_default(this._rectangle)) {
const positions = this._polygonHierarchy.positions;
this._rectangle = computeRectangle3(
positions,
this._ellipsoid,
this._arcType,
this._granularity
);
}
return this._rectangle;
}
},
textureCoordinateRotationPoints: {
get: function() {
if (!defined_default(this._textureCoordinateRotationPoints)) {
this._textureCoordinateRotationPoints = textureCoordinateRotationPoints2(
this
);
}
return this._textureCoordinateRotationPoints;
}
}
});
var PolygonGeometry_default = PolygonGeometry;
// node_modules/@cesium/engine/Source/Core/PolygonOutlineGeometry.js
var createGeometryFromPositionsPositions = [];
var createGeometryFromPositionsSubdivided = [];
function createGeometryFromPositions2(ellipsoid, positions, minDistance, perPositionHeight, arcType) {
const tangentPlane = EllipsoidTangentPlane_default.fromPoints(positions, ellipsoid);
const positions2D = tangentPlane.projectPointsOntoPlane(
positions,
createGeometryFromPositionsPositions
);
const originalWindingOrder = PolygonPipeline_default.computeWindingOrder2D(
positions2D
);
if (originalWindingOrder === WindingOrder_default.CLOCKWISE) {
positions2D.reverse();
positions = positions.slice().reverse();
}
let subdividedPositions;
let i;
let length3 = positions.length;
let index = 0;
if (!perPositionHeight) {
let numVertices = 0;
if (arcType === ArcType_default.GEODESIC) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary_default.subdivideLineCount(
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
} else if (arcType === ArcType_default.RHUMB) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary_default.subdivideRhumbLineCount(
ellipsoid,
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
}
subdividedPositions = new Float64Array(numVertices * 3);
for (i = 0; i < length3; i++) {
let tempPositions;
if (arcType === ArcType_default.GEODESIC) {
tempPositions = PolygonGeometryLibrary_default.subdivideLine(
positions[i],
positions[(i + 1) % length3],
minDistance,
createGeometryFromPositionsSubdivided
);
} else if (arcType === ArcType_default.RHUMB) {
tempPositions = PolygonGeometryLibrary_default.subdivideRhumbLine(
ellipsoid,
positions[i],
positions[(i + 1) % length3],
minDistance,
createGeometryFromPositionsSubdivided
);
}
const tempPositionsLength = tempPositions.length;
for (let j = 0; j < tempPositionsLength; ++j) {
subdividedPositions[index++] = tempPositions[j];
}
}
} else {
subdividedPositions = new Float64Array(length3 * 2 * 3);
for (i = 0; i < length3; i++) {
const p0 = positions[i];
const p1 = positions[(i + 1) % length3];
subdividedPositions[index++] = p0.x;
subdividedPositions[index++] = p0.y;
subdividedPositions[index++] = p0.z;
subdividedPositions[index++] = p1.x;
subdividedPositions[index++] = p1.y;
subdividedPositions[index++] = p1.z;
}
}
length3 = subdividedPositions.length / 3;
const indicesSize = length3 * 2;
const indices2 = IndexDatatype_default.createTypedArray(length3, indicesSize);
index = 0;
for (i = 0; i < length3 - 1; i++) {
indices2[index++] = i;
indices2[index++] = i + 1;
}
indices2[index++] = length3 - 1;
indices2[index++] = 0;
return new GeometryInstance_default({
geometry: new Geometry_default({
attributes: new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: subdividedPositions
})
}),
indices: indices2,
primitiveType: PrimitiveType_default.LINES
})
});
}
function createGeometryFromPositionsExtruded2(ellipsoid, positions, minDistance, perPositionHeight, arcType) {
const tangentPlane = EllipsoidTangentPlane_default.fromPoints(positions, ellipsoid);
const positions2D = tangentPlane.projectPointsOntoPlane(
positions,
createGeometryFromPositionsPositions
);
const originalWindingOrder = PolygonPipeline_default.computeWindingOrder2D(
positions2D
);
if (originalWindingOrder === WindingOrder_default.CLOCKWISE) {
positions2D.reverse();
positions = positions.slice().reverse();
}
let subdividedPositions;
let i;
let length3 = positions.length;
const corners2 = new Array(length3);
let index = 0;
if (!perPositionHeight) {
let numVertices = 0;
if (arcType === ArcType_default.GEODESIC) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary_default.subdivideLineCount(
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
} else if (arcType === ArcType_default.RHUMB) {
for (i = 0; i < length3; i++) {
numVertices += PolygonGeometryLibrary_default.subdivideRhumbLineCount(
ellipsoid,
positions[i],
positions[(i + 1) % length3],
minDistance
);
}
}
subdividedPositions = new Float64Array(numVertices * 3 * 2);
for (i = 0; i < length3; ++i) {
corners2[i] = index / 3;
let tempPositions;
if (arcType === ArcType_default.GEODESIC) {
tempPositions = PolygonGeometryLibrary_default.subdivideLine(
positions[i],
positions[(i + 1) % length3],
minDistance,
createGeometryFromPositionsSubdivided
);
} else if (arcType === ArcType_default.RHUMB) {
tempPositions = PolygonGeometryLibrary_default.subdivideRhumbLine(
ellipsoid,
positions[i],
positions[(i + 1) % length3],
minDistance,
createGeometryFromPositionsSubdivided
);
}
const tempPositionsLength = tempPositions.length;
for (let j = 0; j < tempPositionsLength; ++j) {
subdividedPositions[index++] = tempPositions[j];
}
}
} else {
subdividedPositions = new Float64Array(length3 * 2 * 3 * 2);
for (i = 0; i < length3; ++i) {
corners2[i] = index / 3;
const p0 = positions[i];
const p1 = positions[(i + 1) % length3];
subdividedPositions[index++] = p0.x;
subdividedPositions[index++] = p0.y;
subdividedPositions[index++] = p0.z;
subdividedPositions[index++] = p1.x;
subdividedPositions[index++] = p1.y;
subdividedPositions[index++] = p1.z;
}
}
length3 = subdividedPositions.length / (3 * 2);
const cornersLength = corners2.length;
const indicesSize = (length3 * 2 + cornersLength) * 2;
const indices2 = IndexDatatype_default.createTypedArray(
length3 + cornersLength,
indicesSize
);
index = 0;
for (i = 0; i < length3; ++i) {
indices2[index++] = i;
indices2[index++] = (i + 1) % length3;
indices2[index++] = i + length3;
indices2[index++] = (i + 1) % length3 + length3;
}
for (i = 0; i < cornersLength; i++) {
const corner = corners2[i];
indices2[index++] = corner;
indices2[index++] = corner + length3;
}
return new GeometryInstance_default({
geometry: new Geometry_default({
attributes: new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: subdividedPositions
})
}),
indices: indices2,
primitiveType: PrimitiveType_default.LINES
})
});
}
function PolygonOutlineGeometry(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.polygonHierarchy", options.polygonHierarchy);
if (options.perPositionHeight && defined_default(options.height)) {
throw new DeveloperError_default(
"Cannot use both options.perPositionHeight and options.height"
);
}
if (defined_default(options.arcType) && options.arcType !== ArcType_default.GEODESIC && options.arcType !== ArcType_default.RHUMB) {
throw new DeveloperError_default(
"Invalid arcType. Valid options are ArcType.GEODESIC and ArcType.RHUMB."
);
}
const polygonHierarchy = options.polygonHierarchy;
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const perPositionHeight = defaultValue_default(options.perPositionHeight, false);
const perPositionHeightExtrude = perPositionHeight && defined_default(options.extrudedHeight);
const arcType = defaultValue_default(options.arcType, ArcType_default.GEODESIC);
let height = defaultValue_default(options.height, 0);
let extrudedHeight = defaultValue_default(options.extrudedHeight, height);
if (!perPositionHeightExtrude) {
const h = Math.max(height, extrudedHeight);
extrudedHeight = Math.min(height, extrudedHeight);
height = h;
}
this._ellipsoid = Ellipsoid_default.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";
this.packedLength = PolygonGeometryLibrary_default.computeHierarchyPackedLength(
polygonHierarchy,
Cartesian3_default
) + Ellipsoid_default.packedLength + 8;
}
PolygonOutlineGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
startingIndex = PolygonGeometryLibrary_default.packPolygonHierarchy(
value._polygonHierarchy,
array,
startingIndex,
Cartesian3_default
);
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
array[startingIndex++] = value._height;
array[startingIndex++] = value._extrudedHeight;
array[startingIndex++] = value._granularity;
array[startingIndex++] = value._perPositionHeightExtrude ? 1 : 0;
array[startingIndex++] = value._perPositionHeight ? 1 : 0;
array[startingIndex++] = value._arcType;
array[startingIndex++] = defaultValue_default(value._offsetAttribute, -1);
array[startingIndex] = value.packedLength;
return array;
};
var scratchEllipsoid8 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var dummyOptions2 = {
polygonHierarchy: {}
};
PolygonOutlineGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const polygonHierarchy = PolygonGeometryLibrary_default.unpackPolygonHierarchy(
array,
startingIndex,
Cartesian3_default
);
startingIndex = polygonHierarchy.startingIndex;
delete polygonHierarchy.startingIndex;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid8);
startingIndex += Ellipsoid_default.packedLength;
const height = array[startingIndex++];
const extrudedHeight = array[startingIndex++];
const granularity = array[startingIndex++];
const perPositionHeightExtrude = array[startingIndex++] === 1;
const perPositionHeight = array[startingIndex++] === 1;
const arcType = array[startingIndex++];
const offsetAttribute = array[startingIndex++];
const packedLength = array[startingIndex];
if (!defined_default(result)) {
result = new PolygonOutlineGeometry(dummyOptions2);
}
result._polygonHierarchy = polygonHierarchy;
result._ellipsoid = Ellipsoid_default.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 ? void 0 : offsetAttribute;
result.packedLength = packedLength;
return result;
};
PolygonOutlineGeometry.fromPositions = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.defined("options.positions", options.positions);
const newOptions2 = {
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(newOptions2);
};
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_default.polygonOutlinesFromHierarchy(
polygonHierarchy,
!perPositionHeight,
ellipsoid
);
if (polygons.length === 0) {
return void 0;
}
let geometryInstance;
const geometries = [];
const minDistance = Math_default.chordLength(
granularity,
ellipsoid.maximumRadius
);
const height = polygonGeometry._height;
const extrudedHeight = polygonGeometry._extrudedHeight;
const extrude = polygonGeometry._perPositionHeightExtrude || !Math_default.equalsEpsilon(height, extrudedHeight, 0, Math_default.EPSILON2);
let offsetValue;
let i;
if (extrude) {
for (i = 0; i < polygons.length; i++) {
geometryInstance = createGeometryFromPositionsExtruded2(
ellipsoid,
polygons[i],
minDistance,
perPositionHeight,
arcType
);
geometryInstance.geometry = PolygonGeometryLibrary_default.scaleToGeodeticHeightExtruded(
geometryInstance.geometry,
height,
extrudedHeight,
ellipsoid,
perPositionHeight
);
if (defined_default(polygonGeometry._offsetAttribute)) {
const size = geometryInstance.geometry.attributes.position.values.length / 3;
let offsetAttribute = new Uint8Array(size);
if (polygonGeometry._offsetAttribute === GeometryOffsetAttribute_default.TOP) {
offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
} else {
offsetValue = polygonGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
offsetAttribute = offsetAttribute.fill(offsetValue);
}
geometryInstance.geometry.attributes.applyOffset = new GeometryAttribute_default(
{
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: offsetAttribute
}
);
}
geometries.push(geometryInstance);
}
} else {
for (i = 0; i < polygons.length; i++) {
geometryInstance = createGeometryFromPositions2(
ellipsoid,
polygons[i],
minDistance,
perPositionHeight,
arcType
);
geometryInstance.geometry.attributes.position.values = PolygonPipeline_default.scaleToGeodeticHeight(
geometryInstance.geometry.attributes.position.values,
height,
ellipsoid,
!perPositionHeight
);
if (defined_default(polygonGeometry._offsetAttribute)) {
const length3 = geometryInstance.geometry.attributes.position.values.length;
offsetValue = polygonGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
geometryInstance.geometry.attributes.applyOffset = new GeometryAttribute_default(
{
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
}
);
}
geometries.push(geometryInstance);
}
}
const geometry = GeometryPipeline_default.combineInstances(geometries)[0];
const boundingSphere = BoundingSphere_default.fromVertices(
geometry.attributes.position.values
);
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: geometry.primitiveType,
boundingSphere,
offsetAttribute: polygonGeometry._offsetAttribute
});
};
var PolygonOutlineGeometry_default = PolygonOutlineGeometry;
// node_modules/@cesium/engine/Source/DataSources/PolygonGeometryUpdater.js
var heightAndPerPositionHeightWarning = "Entity polygons cannot have both height and perPositionHeight. height will be ignored";
var heightReferenceAndPerPositionHeightWarning = "heightReference is not supported for entity polygons with perPositionHeight. heightReference will be ignored";
var scratchColor16 = new Color_default();
var defaultOffset7 = Cartesian3_default.ZERO;
var offsetScratch9 = new Cartesian3_default();
var scratchRectangle6 = new Rectangle_default();
var scratch2DPositions = [];
var cart2Scratch = new Cartesian2_default();
function PolygonGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.polygonHierarchy = void 0;
this.perPositionHeight = void 0;
this.closeTop = void 0;
this.closeBottom = void 0;
this.height = void 0;
this.extrudedHeight = void 0;
this.granularity = void 0;
this.stRotation = void 0;
this.offsetAttribute = void 0;
this.arcType = void 0;
this.textureCoordinates = void 0;
}
function PolygonGeometryUpdater(entity, scene) {
GroundGeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new PolygonGeometryOptions(entity),
geometryPropertyName: "polygon",
observedPropertyNames: ["availability", "polygon"]
});
this._onEntityPropertyChanged(entity, "polygon", entity.polygon, void 0);
}
if (defined_default(Object.create)) {
PolygonGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater_default.prototype
);
PolygonGeometryUpdater.prototype.constructor = PolygonGeometryUpdater;
}
PolygonGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const options = this._options;
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time)
),
offset: void 0,
color: void 0
};
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor16);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
}
if (defined_default(options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset7,
offsetScratch9
)
);
}
let geometry;
if (options.perPositionHeight && !defined_default(options.extrudedHeight)) {
geometry = new CoplanarPolygonGeometry_default(options);
} else {
geometry = new PolygonGeometry_default(options);
}
return new GeometryInstance_default({
id: entity,
geometry,
attributes
});
};
PolygonGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const options = this._options;
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor16
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
),
offset: void 0
};
if (defined_default(options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset7,
offsetScratch9
)
);
}
let geometry;
if (options.perPositionHeight && !defined_default(options.extrudedHeight)) {
geometry = new CoplanarPolygonOutlineGeometry_default(options);
} else {
geometry = new PolygonOutlineGeometry_default(options);
}
return new GeometryInstance_default({
id: entity,
geometry,
attributes
});
};
PolygonGeometryUpdater.prototype._computeCenter = function(time, result) {
const hierarchy = Property_default.getValueOrUndefined(
this._entity.polygon.hierarchy,
time
);
if (!defined_default(hierarchy)) {
return;
}
const positions = hierarchy.positions;
if (positions.length === 0) {
return;
}
const ellipsoid = this._scene.mapProjection.ellipsoid;
const tangentPlane = EllipsoidTangentPlane_default.fromPoints(positions, ellipsoid);
const positions2D = tangentPlane.projectPointsOntoPlane(
positions,
scratch2DPositions
);
const length3 = positions2D.length;
let area = 0;
let j = length3 - 1;
let centroid2D = new Cartesian2_default();
for (let i = 0; i < length3; j = i++) {
const p1 = positions2D[i];
const p2 = positions2D[j];
const f = p1.x * p2.y - p2.x * p1.y;
let sum = Cartesian2_default.add(p1, p2, cart2Scratch);
sum = Cartesian2_default.multiplyByScalar(sum, f, sum);
centroid2D = Cartesian2_default.add(centroid2D, sum, centroid2D);
area += f;
}
const a3 = 1 / (area * 3);
centroid2D = Cartesian2_default.multiplyByScalar(centroid2D, a3, centroid2D);
return tangentPlane.projectPointOntoEllipsoid(centroid2D, result);
};
PolygonGeometryUpdater.prototype._isHidden = function(entity, polygon) {
return !defined_default(polygon.hierarchy) || GeometryUpdater_default.prototype._isHidden.call(this, entity, polygon);
};
PolygonGeometryUpdater.prototype._isOnTerrain = function(entity, polygon) {
const onTerrain = GroundGeometryUpdater_default.prototype._isOnTerrain.call(
this,
entity,
polygon
);
const perPositionHeightProperty = polygon.perPositionHeight;
const perPositionHeightEnabled = defined_default(perPositionHeightProperty) && (perPositionHeightProperty.isConstant ? perPositionHeightProperty.getValue(Iso8601_default.MINIMUM_VALUE) : true);
return onTerrain && !perPositionHeightEnabled;
};
PolygonGeometryUpdater.prototype._isDynamic = function(entity, polygon) {
return !polygon.hierarchy.isConstant || !Property_default.isConstant(polygon.height) || !Property_default.isConstant(polygon.extrudedHeight) || !Property_default.isConstant(polygon.granularity) || !Property_default.isConstant(polygon.stRotation) || !Property_default.isConstant(polygon.textureCoordinates) || !Property_default.isConstant(polygon.outlineWidth) || !Property_default.isConstant(polygon.perPositionHeight) || !Property_default.isConstant(polygon.closeTop) || !Property_default.isConstant(polygon.closeBottom) || !Property_default.isConstant(polygon.zIndex) || !Property_default.isConstant(polygon.arcType) || this._onTerrain && !Property_default.isConstant(this._materialProperty) && !(this._materialProperty instanceof ColorMaterialProperty_default);
};
PolygonGeometryUpdater.prototype._setStaticOptions = function(entity, polygon) {
const isColorMaterial = this._materialProperty instanceof ColorMaterialProperty_default;
const options = this._options;
options.vertexFormat = isColorMaterial ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
const hierarchyValue = polygon.hierarchy.getValue(Iso8601_default.MINIMUM_VALUE);
let heightValue = Property_default.getValueOrUndefined(
polygon.height,
Iso8601_default.MINIMUM_VALUE
);
const heightReferenceValue = Property_default.getValueOrDefault(
polygon.heightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
polygon.extrudedHeight,
Iso8601_default.MINIMUM_VALUE
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
polygon.extrudedHeightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
const perPositionHeightValue = Property_default.getValueOrDefault(
polygon.perPositionHeight,
Iso8601_default.MINIMUM_VALUE,
false
);
heightValue = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
heightReferenceValue
);
let offsetAttribute;
if (perPositionHeightValue) {
if (defined_default(heightValue)) {
heightValue = void 0;
oneTimeWarning_default(heightAndPerPositionHeightWarning);
}
if (heightReferenceValue !== HeightReference_default.NONE && perPositionHeightValue) {
heightValue = void 0;
oneTimeWarning_default(heightReferenceAndPerPositionHeightWarning);
}
} else {
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
}
options.polygonHierarchy = hierarchyValue;
options.granularity = Property_default.getValueOrUndefined(
polygon.granularity,
Iso8601_default.MINIMUM_VALUE
);
options.stRotation = Property_default.getValueOrUndefined(
polygon.stRotation,
Iso8601_default.MINIMUM_VALUE
);
options.perPositionHeight = perPositionHeightValue;
options.closeTop = Property_default.getValueOrDefault(
polygon.closeTop,
Iso8601_default.MINIMUM_VALUE,
true
);
options.closeBottom = Property_default.getValueOrDefault(
polygon.closeBottom,
Iso8601_default.MINIMUM_VALUE,
true
);
options.offsetAttribute = offsetAttribute;
options.height = heightValue;
options.arcType = Property_default.getValueOrDefault(
polygon.arcType,
Iso8601_default.MINIMUM_VALUE,
ArcType_default.GEODESIC
);
options.textureCoordinates = Property_default.getValueOrUndefined(
polygon.textureCoordinates,
Iso8601_default.MINIMUM_VALUE
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
PolygonGeometry_default.computeRectangle(options, scratchRectangle6)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
PolygonGeometryUpdater.prototype._getIsClosed = function(options) {
const height = options.height;
const extrudedHeight = options.extrudedHeight;
const isExtruded = defined_default(extrudedHeight) && extrudedHeight !== height;
return !options.perPositionHeight && (!isExtruded && height === 0 || isExtruded && options.closeTop && options.closeBottom);
};
PolygonGeometryUpdater.DynamicGeometryUpdater = DyanmicPolygonGeometryUpdater;
function DyanmicPolygonGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DyanmicPolygonGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DyanmicPolygonGeometryUpdater.prototype.constructor = DyanmicPolygonGeometryUpdater;
}
DyanmicPolygonGeometryUpdater.prototype._isHidden = function(entity, polygon, time) {
return !defined_default(this._options.polygonHierarchy) || DynamicGeometryUpdater_default.prototype._isHidden.call(this, entity, polygon, time);
};
DyanmicPolygonGeometryUpdater.prototype._setOptions = function(entity, polygon, time) {
const options = this._options;
options.polygonHierarchy = Property_default.getValueOrUndefined(
polygon.hierarchy,
time
);
let heightValue = Property_default.getValueOrUndefined(polygon.height, time);
const heightReferenceValue = Property_default.getValueOrDefault(
polygon.heightReference,
time,
HeightReference_default.NONE
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
polygon.extrudedHeightReference,
time,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
polygon.extrudedHeight,
time
);
const perPositionHeightValue = Property_default.getValueOrUndefined(
polygon.perPositionHeight,
time
);
heightValue = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
extrudedHeightReferenceValue
);
let offsetAttribute;
if (perPositionHeightValue) {
if (defined_default(heightValue)) {
heightValue = void 0;
oneTimeWarning_default(heightAndPerPositionHeightWarning);
}
if (heightReferenceValue !== HeightReference_default.NONE && perPositionHeightValue) {
heightValue = void 0;
oneTimeWarning_default(heightReferenceAndPerPositionHeightWarning);
}
} else {
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
}
options.granularity = Property_default.getValueOrUndefined(polygon.granularity, time);
options.stRotation = Property_default.getValueOrUndefined(polygon.stRotation, time);
options.textureCoordinates = Property_default.getValueOrUndefined(
polygon.textureCoordinates,
time
);
options.perPositionHeight = Property_default.getValueOrUndefined(
polygon.perPositionHeight,
time
);
options.closeTop = Property_default.getValueOrDefault(polygon.closeTop, time, true);
options.closeBottom = Property_default.getValueOrDefault(
polygon.closeBottom,
time,
true
);
options.offsetAttribute = offsetAttribute;
options.height = heightValue;
options.arcType = Property_default.getValueOrDefault(
polygon.arcType,
time,
ArcType_default.GEODESIC
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
PolygonGeometry_default.computeRectangle(options, scratchRectangle6)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
var PolygonGeometryUpdater_default = PolygonGeometryUpdater;
// node_modules/@cesium/engine/Source/Core/PolylineVolumeGeometry.js
function computeAttributes2(combinedPositions, shape, boundingRectangle, vertexFormat) {
const attributes = new GeometryAttributes_default();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: combinedPositions
});
}
const shapeLength = shape.length;
const vertexCount = combinedPositions.length / 3;
const length3 = (vertexCount - shapeLength * 2) / (shapeLength * 2);
const firstEndIndices = PolygonPipeline_default.triangulate(shape);
const indicesCount = (length3 - 1) * shapeLength * 6 + firstEndIndices.length * 2;
const indices2 = IndexDatatype_default.createTypedArray(vertexCount, indicesCount);
let i, j;
let ll, ul, ur, lr;
const offset2 = shapeLength * 2;
let index = 0;
for (i = 0; i < length3 - 1; i++) {
for (j = 0; j < shapeLength - 1; j++) {
ll = j * 2 + i * shapeLength * 2;
lr = ll + offset2;
ul = ll + 1;
ur = ul + offset2;
indices2[index++] = ul;
indices2[index++] = ll;
indices2[index++] = ur;
indices2[index++] = ur;
indices2[index++] = ll;
indices2[index++] = lr;
}
ll = shapeLength * 2 - 2 + i * shapeLength * 2;
ul = ll + 1;
ur = ul + offset2;
lr = ll + offset2;
indices2[index++] = ul;
indices2[index++] = ll;
indices2[index++] = ur;
indices2[index++] = ur;
indices2[index++] = ll;
indices2[index++] = lr;
}
if (vertexFormat.st || vertexFormat.tangent || vertexFormat.bitangent) {
const st = new Float32Array(vertexCount * 2);
const lengthSt = 1 / (length3 - 1);
const heightSt = 1 / boundingRectangle.height;
const heightOffset = boundingRectangle.height / 2;
let s, t;
let stindex = 0;
for (i = 0; i < length3; 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 = (length3 - 1) * lengthSt;
t = heightSt * (shape[j].y + heightOffset);
st[stindex++] = s;
st[stindex++] = t;
}
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: new Float32Array(st)
});
}
const endOffset = vertexCount - shapeLength * 2;
for (i = 0; i < firstEndIndices.length; i += 3) {
const v02 = firstEndIndices[i] + endOffset;
const v13 = firstEndIndices[i + 1] + endOffset;
const v23 = firstEndIndices[i + 2] + endOffset;
indices2[index++] = v02;
indices2[index++] = v13;
indices2[index++] = v23;
indices2[index++] = v23 + shapeLength;
indices2[index++] = v13 + shapeLength;
indices2[index++] = v02 + shapeLength;
}
let geometry = new Geometry_default({
attributes,
indices: indices2,
boundingSphere: BoundingSphere_default.fromVertices(combinedPositions),
primitiveType: PrimitiveType_default.TRIANGLES
});
if (vertexFormat.normal) {
geometry = GeometryPipeline_default.computeNormal(geometry);
}
if (vertexFormat.tangent || vertexFormat.bitangent) {
try {
geometry = GeometryPipeline_default.computeTangentAndBitangent(geometry);
} catch (e) {
oneTimeWarning_default(
"polyline-volume-tangent-bitangent",
"Unable to compute tangents and bitangents for polyline volume geometry"
);
}
if (!vertexFormat.tangent) {
geometry.attributes.tangent = void 0;
}
if (!vertexFormat.bitangent) {
geometry.attributes.bitangent = void 0;
}
if (!vertexFormat.st) {
geometry.attributes.st = void 0;
}
}
return geometry;
}
function PolylineVolumeGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.polylinePositions;
const shape = options.shapePositions;
if (!defined_default(positions)) {
throw new DeveloperError_default("options.polylinePositions is required.");
}
if (!defined_default(shape)) {
throw new DeveloperError_default("options.shapePositions is required.");
}
this._positions = positions;
this._shape = shape;
this._ellipsoid = Ellipsoid_default.clone(
defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
);
this._cornerType = defaultValue_default(options.cornerType, CornerType_default.ROUNDED);
this._vertexFormat = VertexFormat_default.clone(
defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT)
);
this._granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
this._workerName = "createPolylineVolumeGeometry";
let numComponents = 1 + positions.length * Cartesian3_default.packedLength;
numComponents += 1 + shape.length * Cartesian2_default.packedLength;
this.packedLength = numComponents + Ellipsoid_default.packedLength + VertexFormat_default.packedLength + 2;
}
PolylineVolumeGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
const positions = value._positions;
let length3 = positions.length;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
Cartesian3_default.pack(positions[i], array, startingIndex);
}
const shape = value._shape;
length3 = shape.length;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Cartesian2_default.packedLength) {
Cartesian2_default.pack(shape[i], array, startingIndex);
}
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.packedLength;
array[startingIndex++] = value._cornerType;
array[startingIndex] = value._granularity;
return array;
};
var scratchEllipsoid9 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchVertexFormat9 = new VertexFormat_default();
var scratchOptions16 = {
polylinePositions: void 0,
shapePositions: void 0,
ellipsoid: scratchEllipsoid9,
vertexFormat: scratchVertexFormat9,
cornerType: void 0,
granularity: void 0
};
PolylineVolumeGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
let length3 = array[startingIndex++];
const positions = new Array(length3);
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
positions[i] = Cartesian3_default.unpack(array, startingIndex);
}
length3 = array[startingIndex++];
const shape = new Array(length3);
for (i = 0; i < length3; ++i, startingIndex += Cartesian2_default.packedLength) {
shape[i] = Cartesian2_default.unpack(array, startingIndex);
}
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid9);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat9
);
startingIndex += VertexFormat_default.packedLength;
const cornerType = array[startingIndex++];
const granularity = array[startingIndex];
if (!defined_default(result)) {
scratchOptions16.polylinePositions = positions;
scratchOptions16.shapePositions = shape;
scratchOptions16.cornerType = cornerType;
scratchOptions16.granularity = granularity;
return new PolylineVolumeGeometry(scratchOptions16);
}
result._positions = positions;
result._shape = shape;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
result._cornerType = cornerType;
result._granularity = granularity;
return result;
};
var brScratch = new BoundingRectangle_default();
PolylineVolumeGeometry.createGeometry = function(polylineVolumeGeometry) {
const positions = polylineVolumeGeometry._positions;
const cleanPositions = arrayRemoveDuplicates_default(
positions,
Cartesian3_default.equalsEpsilon
);
let shape2D = polylineVolumeGeometry._shape;
shape2D = PolylineVolumeGeometryLibrary_default.removeDuplicatesFromShape(shape2D);
if (cleanPositions.length < 2 || shape2D.length < 3) {
return void 0;
}
if (PolygonPipeline_default.computeWindingOrder2D(shape2D) === WindingOrder_default.CLOCKWISE) {
shape2D.reverse();
}
const boundingRectangle = BoundingRectangle_default.fromPoints(shape2D, brScratch);
const computedPositions = PolylineVolumeGeometryLibrary_default.computePositions(
cleanPositions,
shape2D,
boundingRectangle,
polylineVolumeGeometry,
true
);
return computeAttributes2(
computedPositions,
shape2D,
boundingRectangle,
polylineVolumeGeometry._vertexFormat
);
};
var PolylineVolumeGeometry_default = PolylineVolumeGeometry;
// node_modules/@cesium/engine/Source/Core/PolylineVolumeOutlineGeometry.js
function computeAttributes3(positions, shape) {
const attributes = new GeometryAttributes_default();
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.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 indices2 = IndexDatatype_default.createTypedArray(
vertexCount,
2 * shapeLength * (shapeCount + 1)
);
let i, j;
let index = 0;
i = 0;
let offset2 = i * shapeLength;
for (j = 0; j < shapeLength - 1; j++) {
indices2[index++] = j + offset2;
indices2[index++] = j + offset2 + 1;
}
indices2[index++] = shapeLength - 1 + offset2;
indices2[index++] = offset2;
i = shapeCount - 1;
offset2 = i * shapeLength;
for (j = 0; j < shapeLength - 1; j++) {
indices2[index++] = j + offset2;
indices2[index++] = j + offset2 + 1;
}
indices2[index++] = shapeLength - 1 + offset2;
indices2[index++] = offset2;
for (i = 0; i < shapeCount - 1; i++) {
const firstOffset = shapeLength * i;
const secondOffset = firstOffset + shapeLength;
for (j = 0; j < shapeLength; j++) {
indices2[index++] = j + firstOffset;
indices2[index++] = j + secondOffset;
}
}
const geometry = new Geometry_default({
attributes,
indices: IndexDatatype_default.createTypedArray(vertexCount, indices2),
boundingSphere: BoundingSphere_default.fromVertices(positions),
primitiveType: PrimitiveType_default.LINES
});
return geometry;
}
function PolylineVolumeOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.polylinePositions;
const shape = options.shapePositions;
if (!defined_default(positions)) {
throw new DeveloperError_default("options.polylinePositions is required.");
}
if (!defined_default(shape)) {
throw new DeveloperError_default("options.shapePositions is required.");
}
this._positions = positions;
this._shape = shape;
this._ellipsoid = Ellipsoid_default.clone(
defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
);
this._cornerType = defaultValue_default(options.cornerType, CornerType_default.ROUNDED);
this._granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
this._workerName = "createPolylineVolumeOutlineGeometry";
let numComponents = 1 + positions.length * Cartesian3_default.packedLength;
numComponents += 1 + shape.length * Cartesian2_default.packedLength;
this.packedLength = numComponents + Ellipsoid_default.packedLength + 2;
}
PolylineVolumeOutlineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
const positions = value._positions;
let length3 = positions.length;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
Cartesian3_default.pack(positions[i], array, startingIndex);
}
const shape = value._shape;
length3 = shape.length;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Cartesian2_default.packedLength) {
Cartesian2_default.pack(shape[i], array, startingIndex);
}
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
array[startingIndex++] = value._cornerType;
array[startingIndex] = value._granularity;
return array;
};
var scratchEllipsoid10 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchOptions17 = {
polylinePositions: void 0,
shapePositions: void 0,
ellipsoid: scratchEllipsoid10,
height: void 0,
cornerType: void 0,
granularity: void 0
};
PolylineVolumeOutlineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
let length3 = array[startingIndex++];
const positions = new Array(length3);
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
positions[i] = Cartesian3_default.unpack(array, startingIndex);
}
length3 = array[startingIndex++];
const shape = new Array(length3);
for (i = 0; i < length3; ++i, startingIndex += Cartesian2_default.packedLength) {
shape[i] = Cartesian2_default.unpack(array, startingIndex);
}
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid10);
startingIndex += Ellipsoid_default.packedLength;
const cornerType = array[startingIndex++];
const granularity = array[startingIndex];
if (!defined_default(result)) {
scratchOptions17.polylinePositions = positions;
scratchOptions17.shapePositions = shape;
scratchOptions17.cornerType = cornerType;
scratchOptions17.granularity = granularity;
return new PolylineVolumeOutlineGeometry(scratchOptions17);
}
result._positions = positions;
result._shape = shape;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._cornerType = cornerType;
result._granularity = granularity;
return result;
};
var brScratch2 = new BoundingRectangle_default();
PolylineVolumeOutlineGeometry.createGeometry = function(polylineVolumeOutlineGeometry) {
const positions = polylineVolumeOutlineGeometry._positions;
const cleanPositions = arrayRemoveDuplicates_default(
positions,
Cartesian3_default.equalsEpsilon
);
let shape2D = polylineVolumeOutlineGeometry._shape;
shape2D = PolylineVolumeGeometryLibrary_default.removeDuplicatesFromShape(shape2D);
if (cleanPositions.length < 2 || shape2D.length < 3) {
return void 0;
}
if (PolygonPipeline_default.computeWindingOrder2D(shape2D) === WindingOrder_default.CLOCKWISE) {
shape2D.reverse();
}
const boundingRectangle = BoundingRectangle_default.fromPoints(shape2D, brScratch2);
const computedPositions = PolylineVolumeGeometryLibrary_default.computePositions(
cleanPositions,
shape2D,
boundingRectangle,
polylineVolumeOutlineGeometry,
false
);
return computeAttributes3(computedPositions, shape2D);
};
var PolylineVolumeOutlineGeometry_default = PolylineVolumeOutlineGeometry;
// node_modules/@cesium/engine/Source/DataSources/PolylineVolumeGeometryUpdater.js
var scratchColor17 = new Color_default();
function PolylineVolumeGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.polylinePositions = void 0;
this.shapePositions = void 0;
this.cornerType = void 0;
this.granularity = void 0;
}
function PolylineVolumeGeometryUpdater(entity, scene) {
GeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new PolylineVolumeGeometryOptions(entity),
geometryPropertyName: "polylineVolume",
observedPropertyNames: ["availability", "polylineVolume"]
});
this._onEntityPropertyChanged(
entity,
"polylineVolume",
entity.polylineVolume,
void 0
);
}
if (defined_default(Object.create)) {
PolylineVolumeGeometryUpdater.prototype = Object.create(
GeometryUpdater_default.prototype
);
PolylineVolumeGeometryUpdater.prototype.constructor = PolylineVolumeGeometryUpdater;
}
PolylineVolumeGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
let attributes;
let color;
const show = new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
);
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor17);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color
};
} else {
attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute
};
}
return new GeometryInstance_default({
id: entity,
geometry: new PolylineVolumeGeometry_default(this._options),
attributes
});
};
PolylineVolumeGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor17
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
return new GeometryInstance_default({
id: entity,
geometry: new PolylineVolumeOutlineGeometry_default(this._options),
attributes: {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
)
}
});
};
PolylineVolumeGeometryUpdater.prototype._isHidden = function(entity, polylineVolume) {
return !defined_default(polylineVolume.positions) || !defined_default(polylineVolume.shape) || GeometryUpdater_default.prototype._isHidden.call(this, entity, polylineVolume);
};
PolylineVolumeGeometryUpdater.prototype._isDynamic = function(entity, polylineVolume) {
return !polylineVolume.positions.isConstant || !polylineVolume.shape.isConstant || !Property_default.isConstant(polylineVolume.granularity) || !Property_default.isConstant(polylineVolume.outlineWidth) || !Property_default.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_default;
options.vertexFormat = isColorMaterial ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.polylinePositions = polylineVolume.positions.getValue(
Iso8601_default.MINIMUM_VALUE,
options.polylinePositions
);
options.shapePositions = polylineVolume.shape.getValue(
Iso8601_default.MINIMUM_VALUE,
options.shape
);
options.granularity = defined_default(granularity) ? granularity.getValue(Iso8601_default.MINIMUM_VALUE) : void 0;
options.cornerType = defined_default(cornerType) ? cornerType.getValue(Iso8601_default.MINIMUM_VALUE) : void 0;
};
PolylineVolumeGeometryUpdater.DynamicGeometryUpdater = DynamicPolylineVolumeGeometryUpdater;
function DynamicPolylineVolumeGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicPolylineVolumeGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicPolylineVolumeGeometryUpdater.prototype.constructor = DynamicPolylineVolumeGeometryUpdater;
}
DynamicPolylineVolumeGeometryUpdater.prototype._isHidden = function(entity, polylineVolume, time) {
const options = this._options;
return !defined_default(options.polylinePositions) || !defined_default(options.shapePositions) || DynamicGeometryUpdater_default.prototype._isHidden.call(
this,
entity,
polylineVolume,
time
);
};
DynamicPolylineVolumeGeometryUpdater.prototype._setOptions = function(entity, polylineVolume, time) {
const options = this._options;
options.polylinePositions = Property_default.getValueOrUndefined(
polylineVolume.positions,
time,
options.polylinePositions
);
options.shapePositions = Property_default.getValueOrUndefined(
polylineVolume.shape,
time
);
options.granularity = Property_default.getValueOrUndefined(
polylineVolume.granularity,
time
);
options.cornerType = Property_default.getValueOrUndefined(
polylineVolume.cornerType,
time
);
};
var PolylineVolumeGeometryUpdater_default = PolylineVolumeGeometryUpdater;
// node_modules/@cesium/engine/Source/Core/RectangleGeometry.js
var positionScratch12 = new Cartesian3_default();
var normalScratch4 = new Cartesian3_default();
var tangentScratch2 = new Cartesian3_default();
var bitangentScratch2 = new Cartesian3_default();
var rectangleScratch2 = new Rectangle_default();
var stScratch2 = new Cartesian2_default();
var bottomBoundingSphere4 = new BoundingSphere_default();
var topBoundingSphere4 = new BoundingSphere_default();
function createAttributes(vertexFormat, attributes) {
const geo = new Geometry_default({
attributes: new GeometryAttributes_default(),
primitiveType: PrimitiveType_default.TRIANGLES
});
geo.attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: attributes.positions
});
if (vertexFormat.normal) {
geo.attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: attributes.normals
});
}
if (vertexFormat.tangent) {
geo.attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: attributes.tangents
});
}
if (vertexFormat.bitangent) {
geo.attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: attributes.bitangents
});
}
return geo;
}
function calculateAttributes(positions, vertexFormat, ellipsoid, tangentRotationMatrix) {
const length3 = positions.length;
const normals = vertexFormat.normal ? new Float32Array(length3) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(length3) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(length3) : void 0;
let attrIndex = 0;
const bitangent = bitangentScratch2;
const tangent = tangentScratch2;
let normal2 = normalScratch4;
if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
for (let i = 0; i < length3; i += 3) {
const p = Cartesian3_default.fromArray(positions, i, positionScratch12);
const attrIndex1 = attrIndex + 1;
const attrIndex2 = attrIndex + 2;
normal2 = ellipsoid.geodeticSurfaceNormal(p, normal2);
if (vertexFormat.tangent || vertexFormat.bitangent) {
Cartesian3_default.cross(Cartesian3_default.UNIT_Z, normal2, tangent);
Matrix3_default.multiplyByVector(tangentRotationMatrix, tangent, tangent);
Cartesian3_default.normalize(tangent, tangent);
if (vertexFormat.bitangent) {
Cartesian3_default.normalize(
Cartesian3_default.cross(normal2, tangent, bitangent),
bitangent
);
}
}
if (vertexFormat.normal) {
normals[attrIndex] = normal2.x;
normals[attrIndex1] = normal2.y;
normals[attrIndex2] = normal2.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,
normals,
tangents,
bitangents
});
}
var v1Scratch = new Cartesian3_default();
var v2Scratch = new Cartesian3_default();
function calculateAttributesWall(positions, vertexFormat, ellipsoid) {
const length3 = positions.length;
const normals = vertexFormat.normal ? new Float32Array(length3) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(length3) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(length3) : void 0;
let normalIndex = 0;
let tangentIndex = 0;
let bitangentIndex = 0;
let recomputeNormal = true;
let bitangent = bitangentScratch2;
let tangent = tangentScratch2;
let normal2 = normalScratch4;
if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
for (let i = 0; i < length3; i += 6) {
const p = Cartesian3_default.fromArray(positions, i, positionScratch12);
const p1 = Cartesian3_default.fromArray(positions, (i + 6) % length3, v1Scratch);
if (recomputeNormal) {
const p2 = Cartesian3_default.fromArray(positions, (i + 3) % length3, v2Scratch);
Cartesian3_default.subtract(p1, p, p1);
Cartesian3_default.subtract(p2, p, p2);
normal2 = Cartesian3_default.normalize(Cartesian3_default.cross(p2, p1, normal2), normal2);
recomputeNormal = false;
}
if (Cartesian3_default.equalsEpsilon(p1, p, Math_default.EPSILON10)) {
recomputeNormal = true;
}
if (vertexFormat.tangent || vertexFormat.bitangent) {
bitangent = ellipsoid.geodeticSurfaceNormal(p, bitangent);
if (vertexFormat.tangent) {
tangent = Cartesian3_default.normalize(
Cartesian3_default.cross(bitangent, normal2, tangent),
tangent
);
}
}
if (vertexFormat.normal) {
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.z;
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.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,
normals,
tangents,
bitangents
});
}
function constructRectangle2(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) : void 0;
const textureCoordinates = vertexFormat.st ? new Float32Array(size * 2) : void 0;
let posIndex = 0;
let stIndex = 0;
const position = positionScratch12;
const st = stScratch2;
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_default.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_default.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_default.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 || minY < 0 || maxX > 1 || maxY > 1)) {
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 indices2 = IndexDatatype_default.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;
indices2[indicesIndex++] = upperLeft;
indices2[indicesIndex++] = lowerLeft;
indices2[indicesIndex++] = upperRight;
indices2[indicesIndex++] = upperRight;
indices2[indicesIndex++] = lowerLeft;
indices2[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;
indices2[indicesIndex++] = northIndex;
indices2[indicesIndex++] = p1;
indices2[indicesIndex++] = p2;
++index;
}
}
if (southCap) {
index = (rowHeight - 1) * width;
for (i = 0; i < width - 1; i++) {
p1 = index;
p2 = p1 + 1;
indices2[indicesIndex++] = p1;
indices2[indicesIndex++] = southIndex;
indices2[indicesIndex++] = p2;
++index;
}
}
}
geo.indices = indices2;
if (vertexFormat.st) {
geo.attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: textureCoordinates
});
}
return geo;
}
function addWallPositions2(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;
}
var scratchVertexFormat10 = new VertexFormat_default();
function constructExtrudedRectangle2(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_default.clone(
vertexFormat,
scratchVertexFormat10
);
newVertexFormat.normal = true;
rectangleGeometry._vertexFormat = newVertexFormat;
}
const topBottomGeo = constructRectangle2(rectangleGeometry, computedOptions);
if (shadowVolume) {
rectangleGeometry._vertexFormat = vertexFormat;
}
let topPositions = PolygonPipeline_default.scaleToGeodeticHeight(
topBottomGeo.attributes.position.values,
maxHeight,
ellipsoid,
false
);
topPositions = new Float64Array(topPositions);
let length3 = topPositions.length;
const newLength = length3 * 2;
const positions = new Float64Array(newLength);
positions.set(topPositions);
const bottomPositions = PolygonPipeline_default.scaleToGeodeticHeight(
topBottomGeo.attributes.position.values,
minHeight,
ellipsoid
);
positions.set(bottomPositions, length3);
topBottomGeo.attributes.position.values = positions;
const normals = vertexFormat.normal ? new Float32Array(newLength) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(newLength) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(newLength) : void 0;
const textures = vertexFormat.st ? new Float32Array(newLength / 3 * 2) : void 0;
let topSt;
let topNormals;
if (vertexFormat.normal) {
topNormals = topBottomGeo.attributes.normal.values;
normals.set(topNormals);
for (i = 0; i < length3; i++) {
topNormals[i] = -topNormals[i];
}
normals.set(topNormals, length3);
topBottomGeo.attributes.normal.values = normals;
}
if (shadowVolume) {
topNormals = topBottomGeo.attributes.normal.values;
if (!vertexFormat.normal) {
topBottomGeo.attributes.normal = void 0;
}
const extrudeNormals = new Float32Array(newLength);
for (i = 0; i < length3; i++) {
topNormals[i] = -topNormals[i];
}
extrudeNormals.set(topNormals, length3);
topBottomGeo.attributes.extrudeDirection = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: extrudeNormals
});
}
let offsetValue;
const hasOffsets = defined_default(offsetAttributeValue);
if (hasOffsets) {
const size = length3 / 3 * 2;
let offsetAttribute = new Uint8Array(size);
if (offsetAttributeValue === GeometryOffsetAttribute_default.TOP) {
offsetAttribute = offsetAttribute.fill(1, 0, size / 2);
} else {
offsetValue = offsetAttributeValue === GeometryOffsetAttribute_default.NONE ? 0 : 1;
offsetAttribute = offsetAttribute.fill(offsetValue);
}
topBottomGeo.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: offsetAttribute
});
}
if (vertexFormat.tangent) {
const topTangents = topBottomGeo.attributes.tangent.values;
tangents.set(topTangents);
for (i = 0; i < length3; i++) {
topTangents[i] = -topTangents[i];
}
tangents.set(topTangents, length3);
topBottomGeo.attributes.tangent.values = tangents;
}
if (vertexFormat.bitangent) {
const topBitangents = topBottomGeo.attributes.bitangent.values;
bitangents.set(topBitangents);
bitangents.set(topBitangents, length3);
topBottomGeo.attributes.bitangent.values = bitangents;
}
if (vertexFormat.st) {
topSt = topBottomGeo.attributes.st.values;
textures.set(topSt);
textures.set(topSt, length3 / 3 * 2);
topBottomGeo.attributes.st.values = textures;
}
const indices2 = topBottomGeo.indices;
const indicesLength = indices2.length;
const posLength = length3 / 3;
const newIndices = IndexDatatype_default.createTypedArray(
newLength / 3,
indicesLength * 2
);
newIndices.set(indices2);
for (i = 0; i < indicesLength; i += 3) {
newIndices[i + indicesLength] = indices2[i + 2] + posLength;
newIndices[i + 1 + indicesLength] = indices2[i + 1] + posLength;
newIndices[i + 2 + indicesLength] = indices2[i] + posLength;
}
topBottomGeo.indices = newIndices;
const northCap = computedOptions.northCap;
const southCap = computedOptions.southCap;
let rowHeight = height;
let widthMultiplier = 2;
let perimeterPositions = 0;
let corners2 = 4;
let dupliateCorners = 4;
if (northCap) {
widthMultiplier -= 1;
rowHeight -= 1;
perimeterPositions += 1;
corners2 -= 2;
dupliateCorners -= 1;
}
if (southCap) {
widthMultiplier -= 1;
rowHeight -= 1;
perimeterPositions += 1;
corners2 -= 2;
dupliateCorners -= 1;
}
perimeterPositions += widthMultiplier * width + 2 * rowHeight - corners2;
const wallCount = (perimeterPositions + dupliateCorners) * 2;
let wallPositions = new Float64Array(wallCount * 3);
const wallExtrudeNormals = shadowVolume ? new Float32Array(wallCount * 3) : void 0;
let wallOffsetAttribute = hasOffsets ? new Uint8Array(wallCount) : void 0;
let wallTextures = vertexFormat.st ? new Float32Array(wallCount * 2) : void 0;
const computeTopOffsets = offsetAttributeValue === GeometryOffsetAttribute_default.TOP;
if (hasOffsets && !computeTopOffsets) {
offsetValue = offsetAttributeValue === GeometryOffsetAttribute_default.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 = addWallPositions2(
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 = addWallPositions2(
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++) {
wallPositions = addWallPositions2(
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 = addWallPositions2(
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 = addWallPositions2(
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++) {
wallPositions = addWallPositions2(
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_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: wallTextures
});
}
if (shadowVolume) {
geo.attributes.extrudeDirection = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: wallExtrudeNormals
});
}
if (hasOffsets) {
geo.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: wallOffsetAttribute
});
}
const wallIndices = IndexDatatype_default.createTypedArray(
wallCount,
perimeterPositions * 6
);
let upperLeft;
let lowerLeft;
let lowerRight;
let upperRight;
length3 = wallPositions.length / 3;
let index = 0;
for (i = 0; i < length3 - 1; i += 2) {
upperLeft = i;
upperRight = (upperLeft + 2) % length3;
const p1 = Cartesian3_default.fromArray(wallPositions, upperLeft * 3, v1Scratch);
const p2 = Cartesian3_default.fromArray(wallPositions, upperRight * 3, v2Scratch);
if (Cartesian3_default.equalsEpsilon(p1, p2, Math_default.EPSILON10)) {
continue;
}
lowerLeft = (upperLeft + 1) % length3;
lowerRight = (lowerLeft + 2) % length3;
wallIndices[index++] = upperLeft;
wallIndices[index++] = lowerLeft;
wallIndices[index++] = upperRight;
wallIndices[index++] = upperRight;
wallIndices[index++] = lowerLeft;
wallIndices[index++] = lowerRight;
}
geo.indices = wallIndices;
geo = GeometryPipeline_default.combineInstances([
new GeometryInstance_default({
geometry: topBottomGeo
}),
new GeometryInstance_default({
geometry: geo
})
]);
return geo[0];
}
var scratchRectanglePoints = [
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default(),
new Cartesian3_default()
];
var nwScratch2 = new Cartographic_default();
var stNwScratch = new Cartographic_default();
function computeRectangle4(rectangle, granularity, rotation, ellipsoid, result) {
if (rotation === 0) {
return Rectangle_default.clone(rectangle, result);
}
const computedOptions = RectangleGeometryLibrary_default.computeOptions(
rectangle,
granularity,
rotation,
0,
rectangleScratch2,
nwScratch2
);
const height = computedOptions.height;
const width = computedOptions.width;
const positions = scratchRectanglePoints;
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
0,
0,
positions[0]
);
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
0,
width - 1,
positions[1]
);
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
height - 1,
0,
positions[2]
);
RectangleGeometryLibrary_default.computePosition(
computedOptions,
ellipsoid,
false,
height - 1,
width - 1,
positions[3]
);
return Rectangle_default.fromCartesianArray(positions, ellipsoid, result);
}
function RectangleGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const rectangle = options.rectangle;
Check_default.typeOf.object("rectangle", rectangle);
Rectangle_default.validate(rectangle);
if (rectangle.north < rectangle.south) {
throw new DeveloperError_default(
"options.rectangle.north must be greater than or equal to options.rectangle.south"
);
}
const height = defaultValue_default(options.height, 0);
const extrudedHeight = defaultValue_default(options.extrudedHeight, height);
this._rectangle = Rectangle_default.clone(rectangle);
this._granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
this._ellipsoid = Ellipsoid_default.clone(
defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
);
this._surfaceHeight = Math.max(height, extrudedHeight);
this._rotation = defaultValue_default(options.rotation, 0);
this._stRotation = defaultValue_default(options.stRotation, 0);
this._vertexFormat = VertexFormat_default.clone(
defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT)
);
this._extrudedHeight = Math.min(height, extrudedHeight);
this._shadowVolume = defaultValue_default(options.shadowVolume, false);
this._workerName = "createRectangleGeometry";
this._offsetAttribute = options.offsetAttribute;
this._rotatedRectangle = void 0;
this._textureCoordinateRotationPoints = void 0;
}
RectangleGeometry.packedLength = Rectangle_default.packedLength + Ellipsoid_default.packedLength + VertexFormat_default.packedLength + 7;
RectangleGeometry.pack = function(value, array, startingIndex) {
Check_default.typeOf.object("value", value);
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
Rectangle_default.pack(value._rectangle, array, startingIndex);
startingIndex += Rectangle_default.packedLength;
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.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;
array[startingIndex] = defaultValue_default(value._offsetAttribute, -1);
return array;
};
var scratchRectangle7 = new Rectangle_default();
var scratchEllipsoid11 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchOptions18 = {
rectangle: scratchRectangle7,
ellipsoid: scratchEllipsoid11,
vertexFormat: scratchVertexFormat10,
granularity: void 0,
height: void 0,
rotation: void 0,
stRotation: void 0,
extrudedHeight: void 0,
shadowVolume: void 0,
offsetAttribute: void 0
};
RectangleGeometry.unpack = function(array, startingIndex, result) {
Check_default.defined("array", array);
startingIndex = defaultValue_default(startingIndex, 0);
const rectangle = Rectangle_default.unpack(array, startingIndex, scratchRectangle7);
startingIndex += Rectangle_default.packedLength;
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid11);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat10
);
startingIndex += VertexFormat_default.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;
const offsetAttribute = array[startingIndex];
if (!defined_default(result)) {
scratchOptions18.granularity = granularity;
scratchOptions18.height = surfaceHeight;
scratchOptions18.rotation = rotation;
scratchOptions18.stRotation = stRotation;
scratchOptions18.extrudedHeight = extrudedHeight;
scratchOptions18.shadowVolume = shadowVolume;
scratchOptions18.offsetAttribute = offsetAttribute === -1 ? void 0 : offsetAttribute;
return new RectangleGeometry(scratchOptions18);
}
result._rectangle = Rectangle_default.clone(rectangle, result._rectangle);
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.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 ? void 0 : offsetAttribute;
return result;
};
RectangleGeometry.computeRectangle = function(options, result) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const rectangle = options.rectangle;
Check_default.typeOf.object("rectangle", rectangle);
Rectangle_default.validate(rectangle);
if (rectangle.north < rectangle.south) {
throw new DeveloperError_default(
"options.rectangle.north must be greater than or equal to options.rectangle.south"
);
}
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const rotation = defaultValue_default(options.rotation, 0);
return computeRectangle4(rectangle, granularity, rotation, ellipsoid, result);
};
var tangentRotationMatrixScratch = new Matrix3_default();
var quaternionScratch4 = new Quaternion_default();
var centerScratch4 = new Cartographic_default();
RectangleGeometry.createGeometry = function(rectangleGeometry) {
if (Math_default.equalsEpsilon(
rectangleGeometry._rectangle.north,
rectangleGeometry._rectangle.south,
Math_default.EPSILON10
) || Math_default.equalsEpsilon(
rectangleGeometry._rectangle.east,
rectangleGeometry._rectangle.west,
Math_default.EPSILON10
)) {
return void 0;
}
let rectangle = rectangleGeometry._rectangle;
const ellipsoid = rectangleGeometry._ellipsoid;
const rotation = rectangleGeometry._rotation;
const stRotation = rectangleGeometry._stRotation;
const vertexFormat = rectangleGeometry._vertexFormat;
const computedOptions = RectangleGeometryLibrary_default.computeOptions(
rectangle,
rectangleGeometry._granularity,
rotation,
stRotation,
rectangleScratch2,
nwScratch2,
stNwScratch
);
const tangentRotationMatrix = tangentRotationMatrixScratch;
if (stRotation !== 0 || rotation !== 0) {
const center = Rectangle_default.center(rectangle, centerScratch4);
const axis = ellipsoid.geodeticSurfaceNormalCartographic(center, v1Scratch);
Quaternion_default.fromAxisAngle(axis, -stRotation, quaternionScratch4);
Matrix3_default.fromQuaternion(quaternionScratch4, tangentRotationMatrix);
} else {
Matrix3_default.clone(Matrix3_default.IDENTITY, tangentRotationMatrix);
}
const surfaceHeight = rectangleGeometry._surfaceHeight;
const extrudedHeight = rectangleGeometry._extrudedHeight;
const extrude = !Math_default.equalsEpsilon(
surfaceHeight,
extrudedHeight,
0,
Math_default.EPSILON2
);
computedOptions.lonScalar = 1 / rectangleGeometry._rectangle.width;
computedOptions.latScalar = 1 / rectangleGeometry._rectangle.height;
computedOptions.tangentRotationMatrix = tangentRotationMatrix;
let geometry;
let boundingSphere;
rectangle = rectangleGeometry._rectangle;
if (extrude) {
geometry = constructExtrudedRectangle2(rectangleGeometry, computedOptions);
const topBS = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
surfaceHeight,
topBoundingSphere4
);
const bottomBS = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
extrudedHeight,
bottomBoundingSphere4
);
boundingSphere = BoundingSphere_default.union(topBS, bottomBS);
} else {
geometry = constructRectangle2(rectangleGeometry, computedOptions);
geometry.attributes.position.values = PolygonPipeline_default.scaleToGeodeticHeight(
geometry.attributes.position.values,
surfaceHeight,
ellipsoid,
false
);
if (defined_default(rectangleGeometry._offsetAttribute)) {
const length3 = geometry.attributes.position.values.length;
const offsetValue = rectangleGeometry._offsetAttribute === GeometryOffsetAttribute_default.NONE ? 0 : 1;
const applyOffset = new Uint8Array(length3 / 3).fill(offsetValue);
geometry.attributes.applyOffset = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 1,
values: applyOffset
});
}
boundingSphere = BoundingSphere_default.fromRectangle3D(
rectangle,
ellipsoid,
surfaceHeight
);
}
if (!vertexFormat.position) {
delete geometry.attributes.position;
}
return new Geometry_default({
attributes: geometry.attributes,
indices: geometry.indices,
primitiveType: geometry.primitiveType,
boundingSphere,
offsetAttribute: rectangleGeometry._offsetAttribute
});
};
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,
stRotation: rectangleGeometry._stRotation,
granularity,
extrudedHeight: maxHeight,
height: minHeight,
vertexFormat: VertexFormat_default.POSITION_ONLY,
shadowVolume: true
});
};
var unrotatedTextureRectangleScratch = new Rectangle_default();
var points2DScratch3 = [new Cartesian2_default(), new Cartesian2_default(), new Cartesian2_default()];
var rotation2DScratch2 = new Matrix2_default();
var rectangleCenterScratch3 = new Cartographic_default();
function textureCoordinateRotationPoints3(rectangleGeometry) {
if (rectangleGeometry._stRotation === 0) {
return [0, 0, 0, 1, 1, 0];
}
const rectangle = Rectangle_default.clone(
rectangleGeometry._rectangle,
unrotatedTextureRectangleScratch
);
const granularity = rectangleGeometry._granularity;
const ellipsoid = rectangleGeometry._ellipsoid;
const rotation = rectangleGeometry._rotation - rectangleGeometry._stRotation;
const unrotatedTextureRectangle = computeRectangle4(
rectangle,
granularity,
rotation,
ellipsoid,
unrotatedTextureRectangleScratch
);
const points2D = points2DScratch3;
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_default.fromRotation(
rectangleGeometry._stRotation,
rotation2DScratch2
);
const boundingRectangleCenter = Rectangle_default.center(
boundingRectangle,
rectangleCenterScratch3
);
for (let i = 0; i < 3; ++i) {
const point2D = points2D[i];
point2D.x -= boundingRectangleCenter.longitude;
point2D.y -= boundingRectangleCenter.latitude;
Matrix2_default.multiplyByVector(toDesiredInComputed, point2D, point2D);
point2D.x += boundingRectangleCenter.longitude;
point2D.y += boundingRectangleCenter.latitude;
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_default.pack(minXYCorner, result);
Cartesian2_default.pack(maxYCorner, result, 2);
Cartesian2_default.pack(maxXCorner, result, 4);
return result;
}
Object.defineProperties(RectangleGeometry.prototype, {
rectangle: {
get: function() {
if (!defined_default(this._rotatedRectangle)) {
this._rotatedRectangle = computeRectangle4(
this._rectangle,
this._granularity,
this._rotation,
this._ellipsoid
);
}
return this._rotatedRectangle;
}
},
textureCoordinateRotationPoints: {
get: function() {
if (!defined_default(this._textureCoordinateRotationPoints)) {
this._textureCoordinateRotationPoints = textureCoordinateRotationPoints3(
this
);
}
return this._textureCoordinateRotationPoints;
}
}
});
var RectangleGeometry_default = RectangleGeometry;
// node_modules/@cesium/engine/Source/DataSources/RectangleGeometryUpdater.js
var scratchColor18 = new Color_default();
var defaultOffset8 = Cartesian3_default.ZERO;
var offsetScratch10 = new Cartesian3_default();
var scratchRectangle8 = new Rectangle_default();
var scratchCenterRect = new Rectangle_default();
var scratchCarto3 = new Cartographic_default();
function RectangleGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.rectangle = void 0;
this.height = void 0;
this.extrudedHeight = void 0;
this.granularity = void 0;
this.stRotation = void 0;
this.rotation = void 0;
this.offsetAttribute = void 0;
}
function RectangleGeometryUpdater(entity, scene) {
GroundGeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new RectangleGeometryOptions(entity),
geometryPropertyName: "rectangle",
observedPropertyNames: ["availability", "rectangle"]
});
this._onEntityPropertyChanged(
entity,
"rectangle",
entity.rectangle,
void 0
);
}
if (defined_default(Object.create)) {
RectangleGeometryUpdater.prototype = Object.create(
GroundGeometryUpdater_default.prototype
);
RectangleGeometryUpdater.prototype.constructor = RectangleGeometryUpdater;
}
RectangleGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
this._distanceDisplayConditionProperty.getValue(time)
),
offset: void 0,
color: void 0
};
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor18);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
}
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset8,
offsetScratch10
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new RectangleGeometry_default(this._options),
attributes
});
};
RectangleGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor18
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const attributes = {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
),
offset: void 0
};
if (defined_default(this._options.offsetAttribute)) {
attributes.offset = OffsetGeometryInstanceAttribute_default.fromCartesian3(
Property_default.getValueOrDefault(
this._terrainOffsetProperty,
time,
defaultOffset8,
offsetScratch10
)
);
}
return new GeometryInstance_default({
id: entity,
geometry: new RectangleOutlineGeometry_default(this._options),
attributes
});
};
RectangleGeometryUpdater.prototype._computeCenter = function(time, result) {
const rect = Property_default.getValueOrUndefined(
this._entity.rectangle.coordinates,
time,
scratchCenterRect
);
if (!defined_default(rect)) {
return;
}
const center = Rectangle_default.center(rect, scratchCarto3);
return Cartographic_default.toCartesian(center, Ellipsoid_default.WGS84, result);
};
RectangleGeometryUpdater.prototype._isHidden = function(entity, rectangle) {
return !defined_default(rectangle.coordinates) || GeometryUpdater_default.prototype._isHidden.call(this, entity, rectangle);
};
RectangleGeometryUpdater.prototype._isDynamic = function(entity, rectangle) {
return !rectangle.coordinates.isConstant || !Property_default.isConstant(rectangle.height) || !Property_default.isConstant(rectangle.extrudedHeight) || !Property_default.isConstant(rectangle.granularity) || !Property_default.isConstant(rectangle.stRotation) || !Property_default.isConstant(rectangle.rotation) || !Property_default.isConstant(rectangle.outlineWidth) || !Property_default.isConstant(rectangle.zIndex) || this._onTerrain && !Property_default.isConstant(this._materialProperty) && !(this._materialProperty instanceof ColorMaterialProperty_default);
};
RectangleGeometryUpdater.prototype._setStaticOptions = function(entity, rectangle) {
const isColorMaterial = this._materialProperty instanceof ColorMaterialProperty_default;
let heightValue = Property_default.getValueOrUndefined(
rectangle.height,
Iso8601_default.MINIMUM_VALUE
);
const heightReferenceValue = Property_default.getValueOrDefault(
rectangle.heightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
rectangle.extrudedHeight,
Iso8601_default.MINIMUM_VALUE
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
rectangle.extrudedHeightReference,
Iso8601_default.MINIMUM_VALUE,
HeightReference_default.NONE
);
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
const options = this._options;
options.vertexFormat = isColorMaterial ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.rectangle = rectangle.coordinates.getValue(
Iso8601_default.MINIMUM_VALUE,
options.rectangle
);
options.granularity = Property_default.getValueOrUndefined(
rectangle.granularity,
Iso8601_default.MINIMUM_VALUE
);
options.stRotation = Property_default.getValueOrUndefined(
rectangle.stRotation,
Iso8601_default.MINIMUM_VALUE
);
options.rotation = Property_default.getValueOrUndefined(
rectangle.rotation,
Iso8601_default.MINIMUM_VALUE
);
options.offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
options.height = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
heightReferenceValue
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
RectangleGeometry_default.computeRectangle(options, scratchRectangle8)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
RectangleGeometryUpdater.DynamicGeometryUpdater = DynamicRectangleGeometryUpdater;
function DynamicRectangleGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicRectangleGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicRectangleGeometryUpdater.prototype.constructor = DynamicRectangleGeometryUpdater;
}
DynamicRectangleGeometryUpdater.prototype._isHidden = function(entity, rectangle, time) {
return !defined_default(this._options.rectangle) || DynamicGeometryUpdater_default.prototype._isHidden.call(
this,
entity,
rectangle,
time
);
};
DynamicRectangleGeometryUpdater.prototype._setOptions = function(entity, rectangle, time) {
const options = this._options;
let heightValue = Property_default.getValueOrUndefined(rectangle.height, time);
const heightReferenceValue = Property_default.getValueOrDefault(
rectangle.heightReference,
time,
HeightReference_default.NONE
);
let extrudedHeightValue = Property_default.getValueOrUndefined(
rectangle.extrudedHeight,
time
);
const extrudedHeightReferenceValue = Property_default.getValueOrDefault(
rectangle.extrudedHeightReference,
time,
HeightReference_default.NONE
);
if (defined_default(extrudedHeightValue) && !defined_default(heightValue)) {
heightValue = 0;
}
options.rectangle = Property_default.getValueOrUndefined(
rectangle.coordinates,
time,
options.rectangle
);
options.granularity = Property_default.getValueOrUndefined(
rectangle.granularity,
time
);
options.stRotation = Property_default.getValueOrUndefined(rectangle.stRotation, time);
options.rotation = Property_default.getValueOrUndefined(rectangle.rotation, time);
options.offsetAttribute = GroundGeometryUpdater_default.computeGeometryOffsetAttribute(
heightValue,
heightReferenceValue,
extrudedHeightValue,
extrudedHeightReferenceValue
);
options.height = GroundGeometryUpdater_default.getGeometryHeight(
heightValue,
heightReferenceValue
);
extrudedHeightValue = GroundGeometryUpdater_default.getGeometryExtrudedHeight(
extrudedHeightValue,
extrudedHeightReferenceValue
);
if (extrudedHeightValue === GroundGeometryUpdater_default.CLAMP_TO_GROUND) {
extrudedHeightValue = ApproximateTerrainHeights_default.getMinimumMaximumHeights(
RectangleGeometry_default.computeRectangle(options, scratchRectangle8)
).minimumTerrainHeight;
}
options.extrudedHeight = extrudedHeightValue;
};
var RectangleGeometryUpdater_default = RectangleGeometryUpdater;
// node_modules/@cesium/engine/Source/DataSources/StaticGeometryColorBatch.js
var colorScratch2 = new Color_default();
var distanceDisplayConditionScratch2 = new DistanceDisplayCondition_default();
var defaultDistanceDisplayCondition2 = new DistanceDisplayCondition_default();
var defaultOffset9 = Cartesian3_default.ZERO;
var offsetScratch11 = new Cartesian3_default();
function Batch(primitives, translucent, appearanceType, depthFailAppearanceType, depthFailMaterialProperty, closed, shadows) {
this.translucent = translucent;
this.appearanceType = appearanceType;
this.depthFailAppearanceType = depthFailAppearanceType;
this.depthFailMaterialProperty = depthFailMaterialProperty;
this.depthFailMaterial = void 0;
this.closed = closed;
this.shadows = shadows;
this.primitives = primitives;
this.createPrimitive = false;
this.waitingOnCreate = false;
this.primitive = void 0;
this.oldPrimitive = void 0;
this.geometry = new AssociativeArray_default();
this.updaters = new AssociativeArray_default();
this.updatersWithAttributes = new AssociativeArray_default();
this.attributes = new AssociativeArray_default();
this.subscriptions = new AssociativeArray_default();
this.showsUpdated = new AssociativeArray_default();
this.itemsToRemove = [];
this.invalidated = false;
let removeMaterialSubscription;
if (defined_default(depthFailMaterialProperty)) {
removeMaterialSubscription = depthFailMaterialProperty.definitionChanged.addEventListener(
Batch.prototype.onMaterialChanged,
this
);
}
this.removeMaterialSubscription = removeMaterialSubscription;
}
Batch.prototype.onMaterialChanged = function() {
this.invalidated = true;
};
Batch.prototype.isMaterial = function(updater) {
const material = this.depthFailMaterialProperty;
const updaterMaterial = updater.depthFailMaterialProperty;
if (updaterMaterial === material) {
return true;
}
if (defined_default(material)) {
return material.equals(updaterMaterial);
}
return false;
};
Batch.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_default.isConstant(updater.distanceDisplayConditionProperty) || !Property_default.isConstant(updater.terrainOffsetProperty)) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(function(entity, propertyName, newValue, oldValue2) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
})
);
}
};
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 unsubscribe2 = this.subscriptions.get(id);
if (defined_default(unsubscribe2)) {
unsubscribe2();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
Batch.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_default(primitive)) {
if (!defined_default(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
let depthFailAppearance;
if (defined_default(this.depthFailAppearanceType)) {
if (defined_default(this.depthFailMaterialProperty)) {
this.depthFailMaterial = MaterialProperty_default.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial
);
}
depthFailAppearance = new this.depthFailAppearanceType({
material: this.depthFailMaterial,
translucent: this.translucent,
closed: this.closed
});
}
primitive = new Primitive_default({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new this.appearanceType({
translucent: this.translucent,
closed: this.closed
}),
depthFailAppearance,
shadows: this.shadows
});
primitives.add(primitive);
isUpdated = false;
} else {
if (defined_default(primitive)) {
primitives.remove(primitive);
primitive = void 0;
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
this.waitingOnCreate = true;
} else if (defined_default(primitive) && primitive.ready) {
primitive.show = true;
if (defined_default(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = void 0;
}
if (defined_default(this.depthFailAppearanceType) && !(this.depthFailMaterialProperty instanceof ColorMaterialProperty_default)) {
this.depthFailMaterial = MaterialProperty_default.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial
);
this.primitive.depthFailAppearance.material = this.depthFailMaterial;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length3 = updatersWithAttributes.length;
const waitingOnCreate = this.waitingOnCreate;
for (i = 0; i < length3; i++) {
const updater = updatersWithAttributes[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined_default(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_default.getValueOrDefault(
colorProperty,
time,
Color_default.WHITE,
colorScratch2
);
if (!Color_default.equals(attributes._lastColor, resultColor)) {
attributes._lastColor = Color_default.clone(
resultColor,
attributes._lastColor
);
attributes.color = ColorGeometryInstanceAttribute_default.toValue(
resultColor,
attributes.color
);
if (this.translucent && attributes.color[3] === 255 || !this.translucent && attributes.color[3] !== 255) {
this.itemsToRemove[removedCount++] = updater;
}
}
}
if (defined_default(this.depthFailAppearanceType) && updater.depthFailMaterialProperty instanceof ColorMaterialProperty_default && (!updater.depthFailMaterialProperty.isConstant || waitingOnCreate)) {
const depthFailColorProperty = updater.depthFailMaterialProperty.color;
const depthColor = Property_default.getValueOrDefault(
depthFailColorProperty,
time,
Color_default.WHITE,
colorScratch2
);
if (!Color_default.equals(attributes._lastDepthFailColor, depthColor)) {
attributes._lastDepthFailColor = Color_default.clone(
depthColor,
attributes._lastDepthFailColor
);
attributes.depthFailColor = ColorGeometryInstanceAttribute_default.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_default.toValue(
show,
attributes.show
);
}
const distanceDisplayConditionProperty = updater.distanceDisplayConditionProperty;
if (!Property_default.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property_default.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition2,
distanceDisplayConditionScratch2
);
if (!DistanceDisplayCondition_default.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
)) {
attributes._lastDistanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
);
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition
);
}
}
const offsetProperty = updater.terrainOffsetProperty;
if (!Property_default.isConstant(offsetProperty)) {
const offset2 = Property_default.getValueOrDefault(
offsetProperty,
time,
defaultOffset9,
offsetScratch11
);
if (!Cartesian3_default.equals(offset2, attributes._lastOffset)) {
attributes._lastOffset = Cartesian3_default.clone(
offset2,
attributes._lastOffset
);
attributes.offset = OffsetGeometryInstanceAttribute_default.toValue(
offset2,
attributes.offset
);
}
}
}
this.updateShows(primitive);
this.waitingOnCreate = false;
} else if (defined_default(primitive) && !primitive.ready) {
isUpdated = false;
}
this.itemsToRemove.length = removedCount;
return isUpdated;
};
Batch.prototype.updateShows = function(primitive) {
const showsUpdated = this.showsUpdated.values;
const length3 = showsUpdated.length;
for (let i = 0; i < length3; i++) {
const updater = showsUpdated[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined_default(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_default.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_default.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (!defined_default(attributes) || !defined_default(attributes.boundingSphere) || defined_default(attributes.show) && attributes.show[0] === 0) {
return BoundingSphereState_default.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState_default.DONE;
};
Batch.prototype.destroy = function() {
const primitive = this.primitive;
const primitives = this.primitives;
if (defined_default(primitive)) {
primitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
}
if (defined_default(this.removeMaterialSubscription)) {
this.removeMaterialSubscription();
}
};
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 length3 = items.length;
for (let i = 0; i < length3; i++) {
const item = items[i];
if (item.isMaterial(updater)) {
item.add(updater, instance);
return;
}
}
const batch = new Batch(
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 length3 = items.length;
for (let i = length3 - 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 length3 = items.length;
for (let i = 0; i < length3; ++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 length3 = items.length;
let i;
for (i = length3 - 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();
}
}
length3 = items.length;
for (i = 0; i < length3; ++i) {
isUpdated = items[i].update(time) && isUpdated;
}
return isUpdated;
}
StaticGeometryColorBatch.prototype.update = function(time) {
let isUpdated = updateItems(this, this._solidItems, time, true);
isUpdated = updateItems(this, this._translucentItems, time, isUpdated) && isUpdated;
const solidsMoved = moveItems(this, this._solidItems, time);
const translucentsMoved = moveItems(this, this._translucentItems, time);
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 length3 = items.length;
for (let i = 0; i < length3; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState_default.FAILED;
}
StaticGeometryColorBatch.prototype.getBoundingSphere = function(updater, result) {
const boundingSphere = getBoundingSphere(this._solidItems, updater, result);
if (boundingSphere === BoundingSphereState_default.FAILED) {
return getBoundingSphere(this._translucentItems, updater, result);
}
return boundingSphere;
};
function removeAllPrimitives(items) {
const length3 = items.length;
for (let i = 0; i < length3; i++) {
items[i].destroy();
}
items.length = 0;
}
StaticGeometryColorBatch.prototype.removeAllPrimitives = function() {
removeAllPrimitives(this._solidItems);
removeAllPrimitives(this._translucentItems);
};
var StaticGeometryColorBatch_default = StaticGeometryColorBatch;
// node_modules/@cesium/engine/Source/DataSources/StaticGeometryPerMaterialBatch.js
var distanceDisplayConditionScratch3 = new DistanceDisplayCondition_default();
var defaultDistanceDisplayCondition3 = new DistanceDisplayCondition_default();
var defaultOffset10 = Cartesian3_default.ZERO;
var offsetScratch12 = new Cartesian3_default();
function Batch2(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_default();
this.createPrimitive = true;
this.primitive = void 0;
this.oldPrimitive = void 0;
this.geometry = new AssociativeArray_default();
this.material = void 0;
this.depthFailMaterial = void 0;
this.updatersWithAttributes = new AssociativeArray_default();
this.attributes = new AssociativeArray_default();
this.invalidated = false;
this.removeMaterialSubscription = materialProperty.definitionChanged.addEventListener(
Batch2.prototype.onMaterialChanged,
this
);
this.subscriptions = new AssociativeArray_default();
this.showsUpdated = new AssociativeArray_default();
}
Batch2.prototype.onMaterialChanged = function() {
this.invalidated = true;
};
Batch2.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_default(material) && material.equals(updaterMaterial);
equals = (!defined_default(depthFailMaterial) && !defined_default(updaterDepthFailMaterial) || defined_default(depthFailMaterial) && depthFailMaterial.equals(updaterDepthFailMaterial)) && equals;
return equals;
};
Batch2.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_default.isConstant(updater.distanceDisplayConditionProperty) || !Property_default.isConstant(updater.terrainOffsetProperty)) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(function(entity, propertyName, newValue, oldValue2) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
})
);
}
this.createPrimitive = true;
};
Batch2.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 unsubscribe2 = this.subscriptions.get(id);
if (defined_default(unsubscribe2)) {
unsubscribe2();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
var colorScratch3 = new Color_default();
Batch2.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_default(primitive)) {
if (!defined_default(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
this.material = MaterialProperty_default.getValue(
time,
this.materialProperty,
this.material
);
let depthFailAppearance;
if (defined_default(this.depthFailMaterialProperty)) {
this.depthFailMaterial = MaterialProperty_default.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial
);
depthFailAppearance = new this.depthFailAppearanceType({
material: this.depthFailMaterial,
translucent: this.depthFailMaterial.isTranslucent(),
closed: this.closed
});
}
primitive = new Primitive_default({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new this.appearanceType({
material: this.material,
translucent: this.material.isTranslucent(),
closed: this.closed
}),
depthFailAppearance,
shadows: this.shadows
});
primitives.add(primitive);
isUpdated = false;
} else {
if (defined_default(primitive)) {
primitives.remove(primitive);
primitive = void 0;
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
} else if (defined_default(primitive) && primitive.ready) {
primitive.show = true;
if (defined_default(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = void 0;
}
this.material = MaterialProperty_default.getValue(
time,
this.materialProperty,
this.material
);
this.primitive.appearance.material = this.material;
if (defined_default(this.depthFailAppearanceType) && !(this.depthFailMaterialProperty instanceof ColorMaterialProperty_default)) {
this.depthFailMaterial = MaterialProperty_default.getValue(
time,
this.depthFailMaterialProperty,
this.depthFailMaterial
);
this.primitive.depthFailAppearance.material = this.depthFailMaterial;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length3 = updatersWithAttributes.length;
for (i = 0; i < length3; 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_default(attributes)) {
attributes = primitive.getGeometryInstanceAttributes(instance.id);
this.attributes.set(instance.id.id, attributes);
}
if (defined_default(this.depthFailAppearanceType) && this.depthFailMaterialProperty instanceof ColorMaterialProperty_default && !updater.depthFailMaterialProperty.isConstant) {
const depthFailColorProperty = updater.depthFailMaterialProperty.color;
const depthFailColor = Property_default.getValueOrDefault(
depthFailColorProperty,
time,
Color_default.WHITE,
colorScratch3
);
if (!Color_default.equals(attributes._lastDepthFailColor, depthFailColor)) {
attributes._lastDepthFailColor = Color_default.clone(
depthFailColor,
attributes._lastDepthFailColor
);
attributes.depthFailColor = ColorGeometryInstanceAttribute_default.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_default.toValue(
show,
attributes.show
);
}
const distanceDisplayConditionProperty = updater.distanceDisplayConditionProperty;
if (!Property_default.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property_default.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition3,
distanceDisplayConditionScratch3
);
if (!DistanceDisplayCondition_default.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
)) {
attributes._lastDistanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
);
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition
);
}
}
const offsetProperty = updater.terrainOffsetProperty;
if (!Property_default.isConstant(offsetProperty)) {
const offset2 = Property_default.getValueOrDefault(
offsetProperty,
time,
defaultOffset10,
offsetScratch12
);
if (!Cartesian3_default.equals(offset2, attributes._lastOffset)) {
attributes._lastOffset = Cartesian3_default.clone(
offset2,
attributes._lastOffset
);
attributes.offset = OffsetGeometryInstanceAttribute_default.toValue(
offset2,
attributes.offset
);
}
}
}
this.updateShows(primitive);
} else if (defined_default(primitive) && !primitive.ready) {
isUpdated = false;
}
return isUpdated;
};
Batch2.prototype.updateShows = function(primitive) {
const showsUpdated = this.showsUpdated.values;
const length3 = showsUpdated.length;
for (let i = 0; i < length3; 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_default(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_default.toValue(
show,
attributes.show
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch2.prototype.contains = function(updater) {
return this.updaters.contains(updater.id);
};
Batch2.prototype.getBoundingSphere = function(updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState_default.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (!defined_default(attributes) || !defined_default(attributes.boundingSphere) || defined_default(attributes.show) && attributes.show[0] === 0) {
return BoundingSphereState_default.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState_default.DONE;
};
Batch2.prototype.destroy = function() {
const primitive = this.primitive;
const primitives = this.primitives;
if (defined_default(primitive)) {
primitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
}
this.removeMaterialSubscription();
};
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 length3 = items.length;
for (let i = 0; i < length3; i++) {
const item = items[i];
if (item.isMaterial(updater)) {
item.add(time, updater);
return;
}
}
const batch = new Batch2(
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 length3 = items.length;
for (let i = length3 - 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 length3 = items.length;
for (i = length3 - 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 length3 = items.length;
for (let i = 0; i < length3; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState_default.FAILED;
};
StaticGeometryPerMaterialBatch.prototype.removeAllPrimitives = function() {
const items = this._items;
const length3 = items.length;
for (let i = 0; i < length3; i++) {
items[i].destroy();
}
this._items.length = 0;
};
var StaticGeometryPerMaterialBatch_default = StaticGeometryPerMaterialBatch;
// node_modules/@cesium/engine/node_modules/quickselect/index.js
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;
swap3(arr, left, k);
if (compare(arr[right], t) > 0)
swap3(arr, left, right);
while (i < j) {
swap3(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)
swap3(arr, left, j);
else {
j++;
swap3(arr, j, right);
}
if (j <= k)
left = j + 1;
if (k <= j)
right = j - 1;
}
}
function swap3(arr, i, j) {
var tmp2 = arr[i];
arr[i] = arr[j];
arr[j] = tmp2;
}
function defaultCompare(a3, b) {
return a3 < b ? -1 : a3 > b ? 1 : 0;
}
// node_modules/@cesium/engine/node_modules/rbush/index.js
var RBush = class {
constructor(maxEntries = 9) {
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(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(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;
}
let node = this._build(data.slice(), 0, data.length - 1, 0);
if (!this.data.children.length) {
this.data = node;
} else if (this.data.height === node.height) {
this._splitRoot(this.data, node);
} else {
if (this.data.height < node.height) {
const tmpNode = this.data;
this.data = node;
node = tmpNode;
}
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;
while (node || path.length) {
if (!node) {
node = path.pop();
parent = path[path.length - 1];
i = indexes.pop();
goingUp = true;
}
if (node.leaf) {
const index = findItem(item, node.children, equalsFn);
if (index !== -1) {
node.children.splice(index, 1);
path.push(node);
this._condense(path);
return this;
}
}
if (!goingUp && !node.leaf && contains(node, bbox)) {
path.push(node);
indexes.push(i);
i = 0;
parent = node;
node = node.children[0];
} else if (parent) {
i++;
node = parent.children[i];
goingUp = false;
} else
node = null;
}
return this;
}
toBBox(item) {
return item;
}
compareMinX(a3, b) {
return a3.minX - b.minX;
}
compareMinY(a3, b) {
return a3.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) {
node = createNode(items.slice(left, right + 1));
calcBBox(node, this.toBBox);
return node;
}
if (!height) {
height = Math.ceil(Math.log(N) / Math.log(M));
M = Math.ceil(N / Math.pow(M, height - 1));
}
node = createNode([]);
node.leaf = false;
node.height = height;
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);
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;
if (enlargement < minEnlargement) {
minEnlargement = enlargement;
minArea = area < minArea ? area : minArea;
targetNode = child;
} else if (enlargement === minEnlargement) {
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 = [];
const node = this._chooseSubtree(bbox, this.data, level, insertPath);
node.children.push(item);
extend(node, bbox);
while (level >= 0) {
if (insertPath[level].children.length > this._maxEntries) {
this._split(insertPath, level);
level--;
} else
break;
}
this._adjustParentBBoxes(bbox, insertPath, level);
}
_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) {
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);
if (overlap < minOverlap) {
minOverlap = overlap;
index = i;
minArea = area < minArea ? area : minArea;
} else if (overlap === minOverlap) {
if (area < minArea) {
minArea = area;
index = i;
}
}
}
return index || M - m;
}
_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 (xMargin < yMargin)
node.children.sort(compareMinX);
}
_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) {
for (let i = level; i >= 0; i--) {
extend(path[i], bbox);
}
}
_condense(path) {
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;
}
function calcBBox(node, toBBox) {
distBBox(node, 0, node.children.length, toBBox, node);
}
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(a3, b) {
a3.minX = Math.min(a3.minX, b.minX);
a3.minY = Math.min(a3.minY, b.minY);
a3.maxX = Math.max(a3.maxX, b.maxX);
a3.maxY = Math.max(a3.maxY, b.maxY);
return a3;
}
function compareNodeMinX(a3, b) {
return a3.minX - b.minX;
}
function compareNodeMinY(a3, b) {
return a3.minY - b.minY;
}
function bboxArea(a3) {
return (a3.maxX - a3.minX) * (a3.maxY - a3.minY);
}
function bboxMargin(a3) {
return a3.maxX - a3.minX + (a3.maxY - a3.minY);
}
function enlargedArea(a3, b) {
return (Math.max(b.maxX, a3.maxX) - Math.min(b.minX, a3.minX)) * (Math.max(b.maxY, a3.maxY) - Math.min(b.minY, a3.minY));
}
function intersectionArea(a3, b) {
const minX = Math.max(a3.minX, b.minX);
const minY = Math.max(a3.minY, b.minY);
const maxX = Math.min(a3.maxX, b.maxX);
const maxY = Math.min(a3.maxY, b.maxY);
return Math.max(0, maxX - minX) * Math.max(0, maxY - minY);
}
function contains(a3, b) {
return a3.minX <= b.minX && a3.minY <= b.minY && b.maxX <= a3.maxX && b.maxY <= a3.maxY;
}
function intersects(a3, b) {
return b.minX <= a3.maxX && b.minY <= a3.maxY && b.maxX >= a3.minX && b.maxY >= a3.minY;
}
function createNode(children) {
return {
children,
height: 1,
leaf: true,
minX: Infinity,
minY: Infinity,
maxX: -Infinity,
maxY: -Infinity
};
}
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);
}
}
// node_modules/@cesium/engine/Source/Core/RectangleCollisionChecker.js
function RectangleCollisionChecker() {
this._tree = new RBush();
}
function RectangleWithId() {
this.minX = 0;
this.minY = 0;
this.maxX = 0;
this.maxY = 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;
};
RectangleCollisionChecker.prototype.insert = function(id, rectangle) {
Check_default.typeOf.string("id", id);
Check_default.typeOf.object("rectangle", rectangle);
const withId = RectangleWithId.fromRectangleAndId(
id,
rectangle,
new RectangleWithId()
);
this._tree.insert(withId);
};
function idCompare(a3, b) {
return a3.id === b.id;
}
var removalScratch = new RectangleWithId();
RectangleCollisionChecker.prototype.remove = function(id, rectangle) {
Check_default.typeOf.string("id", id);
Check_default.typeOf.object("rectangle", rectangle);
const withId = RectangleWithId.fromRectangleAndId(
id,
rectangle,
removalScratch
);
this._tree.remove(withId, idCompare);
};
var collisionScratch = new RectangleWithId();
RectangleCollisionChecker.prototype.collides = function(rectangle) {
Check_default.typeOf.object("rectangle", rectangle);
const withId = RectangleWithId.fromRectangleAndId(
"",
rectangle,
collisionScratch
);
return this._tree.collides(withId);
};
var RectangleCollisionChecker_default = RectangleCollisionChecker;
// node_modules/@cesium/engine/Source/DataSources/StaticGroundGeometryColorBatch.js
var colorScratch4 = new Color_default();
var distanceDisplayConditionScratch4 = new DistanceDisplayCondition_default();
var defaultDistanceDisplayCondition4 = new DistanceDisplayCondition_default();
function Batch3(primitives, classificationType, color, zIndex) {
this.primitives = primitives;
this.zIndex = zIndex;
this.classificationType = classificationType;
this.color = color;
this.createPrimitive = false;
this.waitingOnCreate = false;
this.primitive = void 0;
this.oldPrimitive = void 0;
this.geometry = new AssociativeArray_default();
this.updaters = new AssociativeArray_default();
this.updatersWithAttributes = new AssociativeArray_default();
this.attributes = new AssociativeArray_default();
this.subscriptions = new AssociativeArray_default();
this.showsUpdated = new AssociativeArray_default();
this.itemsToRemove = [];
this.isDirty = false;
this.rectangleCollisionCheck = new RectangleCollisionChecker_default();
}
Batch3.prototype.overlapping = function(rectangle) {
return this.rectangleCollisionCheck.collides(rectangle);
};
Batch3.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_default.isConstant(updater.distanceDisplayConditionProperty)) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(function(entity, propertyName, newValue, oldValue2) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
})
);
}
};
Batch3.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 unsubscribe2 = this.subscriptions.get(id);
if (defined_default(unsubscribe2)) {
unsubscribe2();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
Batch3.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_default(primitive)) {
if (!defined_default(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
primitive = new GroundPrimitive_default({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
classificationType: this.classificationType
});
primitives.add(primitive, this.zIndex);
isUpdated = false;
} else {
if (defined_default(primitive)) {
primitives.remove(primitive);
primitive = void 0;
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
this.waitingOnCreate = true;
} else if (defined_default(primitive) && primitive.ready) {
primitive.show = true;
if (defined_default(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = void 0;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length3 = updatersWithAttributes.length;
const waitingOnCreate = this.waitingOnCreate;
for (i = 0; i < length3; i++) {
const updater = updatersWithAttributes[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined_default(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_default.getValueOrDefault(
colorProperty,
time,
Color_default.WHITE,
colorScratch4
);
if (!Color_default.equals(attributes._lastColor, fillColor)) {
attributes._lastColor = Color_default.clone(fillColor, attributes._lastColor);
attributes.color = ColorGeometryInstanceAttribute_default.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_default.toValue(
show,
attributes.show
);
}
const distanceDisplayConditionProperty = updater.distanceDisplayConditionProperty;
if (!Property_default.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property_default.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition4,
distanceDisplayConditionScratch4
);
if (!DistanceDisplayCondition_default.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
)) {
attributes._lastDistanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
);
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition
);
}
}
}
this.updateShows(primitive);
this.waitingOnCreate = false;
} else if (defined_default(primitive) && !primitive.ready) {
isUpdated = false;
}
this.itemsToRemove.length = removedCount;
return isUpdated;
};
Batch3.prototype.updateShows = function(primitive) {
const showsUpdated = this.showsUpdated.values;
const length3 = showsUpdated.length;
for (let i = 0; i < length3; i++) {
const updater = showsUpdated[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined_default(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_default.toValue(
show,
attributes.show
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch3.prototype.contains = function(updater) {
return this.updaters.contains(updater.id);
};
Batch3.prototype.getBoundingSphere = function(updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState_default.PENDING;
}
const bs = primitive.getBoundingSphere(updater.entity);
if (!defined_default(bs)) {
return BoundingSphereState_default.FAILED;
}
bs.clone(result);
return BoundingSphereState_default.DONE;
};
Batch3.prototype.removeAllPrimitives = function() {
const primitives = this.primitives;
const primitive = this.primitive;
if (defined_default(primitive)) {
primitives.remove(primitive);
this.primitive = void 0;
this.geometry.removeAll();
this.updaters.removeAll();
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
};
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_default.getValueOrDefault(updater.zIndex, 0);
let batch;
const length3 = batches.length;
for (let i = 0; i < length3; ++i) {
const item = batches[i];
if (item.zIndex === zIndex && !item.overlapping(instance.geometry.rectangle)) {
batch = item;
break;
}
}
if (!defined_default(batch)) {
batch = new Batch3(
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;
let isUpdated = true;
const batches = this._batches;
const batchCount = batches.length;
for (i = 0; i < batchCount; ++i) {
isUpdated = batches[i].update(time) && isUpdated;
}
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;
}
}
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_default.FAILED;
};
StaticGroundGeometryColorBatch.prototype.removeAllPrimitives = function() {
const batches = this._batches;
const batchCount = batches.length;
for (let i = 0; i < batchCount; ++i) {
batches[i].removeAllPrimitives();
}
};
var StaticGroundGeometryColorBatch_default = StaticGroundGeometryColorBatch;
// node_modules/@cesium/engine/Source/DataSources/StaticGroundGeometryPerMaterialBatch.js
var distanceDisplayConditionScratch5 = new DistanceDisplayCondition_default();
var defaultDistanceDisplayCondition5 = new DistanceDisplayCondition_default();
function Batch4(primitives, classificationType, appearanceType, materialProperty, usingSphericalTextureCoordinates, zIndex) {
this.primitives = primitives;
this.classificationType = classificationType;
this.appearanceType = appearanceType;
this.materialProperty = materialProperty;
this.updaters = new AssociativeArray_default();
this.createPrimitive = true;
this.primitive = void 0;
this.oldPrimitive = void 0;
this.geometry = new AssociativeArray_default();
this.material = void 0;
this.updatersWithAttributes = new AssociativeArray_default();
this.attributes = new AssociativeArray_default();
this.invalidated = false;
this.removeMaterialSubscription = materialProperty.definitionChanged.addEventListener(
Batch4.prototype.onMaterialChanged,
this
);
this.subscriptions = new AssociativeArray_default();
this.showsUpdated = new AssociativeArray_default();
this.usingSphericalTextureCoordinates = usingSphericalTextureCoordinates;
this.zIndex = zIndex;
this.rectangleCollisionCheck = new RectangleCollisionChecker_default();
}
Batch4.prototype.onMaterialChanged = function() {
this.invalidated = true;
};
Batch4.prototype.overlapping = function(rectangle) {
return this.rectangleCollisionCheck.collides(rectangle);
};
Batch4.prototype.isMaterial = function(updater) {
const material = this.materialProperty;
const updaterMaterial = updater.fillMaterialProperty;
if (updaterMaterial === material || updaterMaterial instanceof ColorMaterialProperty_default && material instanceof ColorMaterialProperty_default) {
return true;
}
return defined_default(material) && material.equals(updaterMaterial);
};
Batch4.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);
if (!updater.hasConstantFill || !updater.fillMaterialProperty.isConstant || !Property_default.isConstant(updater.distanceDisplayConditionProperty)) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(function(entity, propertyName, newValue, oldValue2) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
})
);
}
this.createPrimitive = true;
};
Batch4.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 unsubscribe2 = this.subscriptions.get(id);
if (defined_default(unsubscribe2)) {
unsubscribe2();
this.subscriptions.remove(id);
}
return true;
}
return false;
};
Batch4.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_default(primitive)) {
if (!defined_default(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
this.material = MaterialProperty_default.getValue(
time,
this.materialProperty,
this.material
);
primitive = new GroundPrimitive_default({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new this.appearanceType({
material: this.material
}),
classificationType: this.classificationType
});
primitives.add(primitive, this.zIndex);
isUpdated = false;
} else {
if (defined_default(primitive)) {
primitives.remove(primitive);
primitive = void 0;
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
} else if (defined_default(primitive) && primitive.ready) {
primitive.show = true;
if (defined_default(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = void 0;
}
this.material = MaterialProperty_default.getValue(
time,
this.materialProperty,
this.material
);
this.primitive.appearance.material = this.material;
const updatersWithAttributes = this.updatersWithAttributes.values;
const length3 = updatersWithAttributes.length;
for (i = 0; i < length3; 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_default(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_default.toValue(
show,
attributes.show
);
}
const distanceDisplayConditionProperty = updater.distanceDisplayConditionProperty;
if (!Property_default.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property_default.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition5,
distanceDisplayConditionScratch5
);
if (!DistanceDisplayCondition_default.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
)) {
attributes._lastDistanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
);
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition
);
}
}
}
this.updateShows(primitive);
} else if (defined_default(primitive) && !primitive.ready) {
isUpdated = false;
}
return isUpdated;
};
Batch4.prototype.updateShows = function(primitive) {
const showsUpdated = this.showsUpdated.values;
const length3 = showsUpdated.length;
for (let i = 0; i < length3; 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_default(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_default.toValue(
show,
attributes.show
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch4.prototype.contains = function(updater) {
return this.updaters.contains(updater.id);
};
Batch4.prototype.getBoundingSphere = function(updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState_default.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (!defined_default(attributes) || !defined_default(attributes.boundingSphere) || defined_default(attributes.show) && attributes.show[0] === 0) {
return BoundingSphereState_default.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState_default.DONE;
};
Batch4.prototype.destroy = function() {
const primitive = this.primitive;
const primitives = this.primitives;
if (defined_default(primitive)) {
primitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
}
this.removeMaterialSubscription();
};
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 length3 = items.length;
const geometryInstance = updater.createFillGeometryInstance(time);
const usingSphericalTextureCoordinates = ShadowVolumeAppearance_default.shouldUseSphericalCoordinates(
geometryInstance.geometry.rectangle
);
const zIndex = Property_default.getValueOrDefault(updater.zIndex, 0);
for (let i = 0; i < length3; ++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;
}
}
const batch = new Batch4(
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 length3 = items.length;
for (let i = length3 - 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 length3 = items.length;
for (i = length3 - 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 length3 = items.length;
for (let i = 0; i < length3; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState_default.FAILED;
};
StaticGroundGeometryPerMaterialBatch.prototype.removeAllPrimitives = function() {
const items = this._items;
const length3 = items.length;
for (let i = 0; i < length3; i++) {
items[i].destroy();
}
this._items.length = 0;
};
var StaticGroundGeometryPerMaterialBatch_default = StaticGroundGeometryPerMaterialBatch;
// node_modules/@cesium/engine/Source/DataSources/StaticOutlineGeometryBatch.js
var colorScratch5 = new Color_default();
var distanceDisplayConditionScratch6 = new DistanceDisplayCondition_default();
var defaultDistanceDisplayCondition6 = new DistanceDisplayCondition_default();
var defaultOffset11 = Cartesian3_default.ZERO;
var offsetScratch13 = new Cartesian3_default();
function Batch5(primitives, translucent, width, shadows) {
this.translucent = translucent;
this.width = width;
this.shadows = shadows;
this.primitives = primitives;
this.createPrimitive = false;
this.waitingOnCreate = false;
this.primitive = void 0;
this.oldPrimitive = void 0;
this.geometry = new AssociativeArray_default();
this.updaters = new AssociativeArray_default();
this.updatersWithAttributes = new AssociativeArray_default();
this.attributes = new AssociativeArray_default();
this.itemsToRemove = [];
this.subscriptions = new AssociativeArray_default();
this.showsUpdated = new AssociativeArray_default();
}
Batch5.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_default.isConstant(updater.distanceDisplayConditionProperty) || !Property_default.isConstant(updater.terrainOffsetProperty)) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(function(entity, propertyName, newValue, oldValue2) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
})
);
}
};
Batch5.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 unsubscribe2 = this.subscriptions.get(id);
if (defined_default(unsubscribe2)) {
unsubscribe2();
this.subscriptions.remove(id);
this.showsUpdated.remove(id);
}
return true;
}
return false;
};
Batch5.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_default(primitive)) {
if (!defined_default(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
primitives.remove(primitive);
}
}
primitive = new Primitive_default({
show: false,
asynchronous: true,
geometryInstances: geometries.slice(),
appearance: new PerInstanceColorAppearance_default({
flat: true,
translucent: this.translucent,
renderState: {
lineWidth: this.width
}
}),
shadows: this.shadows
});
primitives.add(primitive);
isUpdated = false;
} else {
if (defined_default(primitive)) {
primitives.remove(primitive);
primitive = void 0;
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
this.waitingOnCreate = true;
} else if (defined_default(primitive) && primitive.ready) {
primitive.show = true;
if (defined_default(this.oldPrimitive)) {
primitives.remove(this.oldPrimitive);
this.oldPrimitive = void 0;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length3 = updatersWithAttributes.length;
const waitingOnCreate = this.waitingOnCreate;
for (i = 0; i < length3; i++) {
const updater = updatersWithAttributes[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined_default(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_default.getValueOrDefault(
outlineColorProperty,
time,
Color_default.WHITE,
colorScratch5
);
if (!Color_default.equals(attributes._lastColor, outlineColor)) {
attributes._lastColor = Color_default.clone(
outlineColor,
attributes._lastColor
);
attributes.color = ColorGeometryInstanceAttribute_default.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_default.toValue(
show,
attributes.show
);
}
const distanceDisplayConditionProperty = updater.distanceDisplayConditionProperty;
if (!Property_default.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property_default.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition6,
distanceDisplayConditionScratch6
);
if (!DistanceDisplayCondition_default.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
)) {
attributes._lastDistanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
);
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition
);
}
}
const offsetProperty = updater.terrainOffsetProperty;
if (!Property_default.isConstant(offsetProperty)) {
const offset2 = Property_default.getValueOrDefault(
offsetProperty,
time,
defaultOffset11,
offsetScratch13
);
if (!Cartesian3_default.equals(offset2, attributes._lastOffset)) {
attributes._lastOffset = Cartesian3_default.clone(
offset2,
attributes._lastOffset
);
attributes.offset = OffsetGeometryInstanceAttribute_default.toValue(
offset2,
attributes.offset
);
}
}
}
this.updateShows(primitive);
this.waitingOnCreate = false;
} else if (defined_default(primitive) && !primitive.ready) {
isUpdated = false;
}
this.itemsToRemove.length = removedCount;
return isUpdated;
};
Batch5.prototype.updateShows = function(primitive) {
const showsUpdated = this.showsUpdated.values;
const length3 = showsUpdated.length;
for (let i = 0; i < length3; i++) {
const updater = showsUpdated[i];
const instance = this.geometry.get(updater.id);
let attributes = this.attributes.get(instance.id.id);
if (!defined_default(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_default.toValue(
show,
attributes.show
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch5.prototype.contains = function(updater) {
return this.updaters.contains(updater.id);
};
Batch5.prototype.getBoundingSphere = function(updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState_default.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (!defined_default(attributes) || !defined_default(attributes.boundingSphere) || defined_default(attributes.show) && attributes.show[0] === 0) {
return BoundingSphereState_default.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState_default.DONE;
};
Batch5.prototype.removeAllPrimitives = function() {
const primitives = this.primitives;
const primitive = this.primitive;
if (defined_default(primitive)) {
primitives.remove(primitive);
this.primitive = void 0;
this.geometry.removeAll();
this.updaters.removeAll();
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
primitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
};
function StaticOutlineGeometryBatch(primitives, scene, shadows) {
this._primitives = primitives;
this._scene = scene;
this._shadows = shadows;
this._solidBatches = new AssociativeArray_default();
this._translucentBatches = new AssociativeArray_default();
}
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_default(batch)) {
batch = new Batch5(this._primitives, false, width, this._shadows);
batches.set(width, batch);
}
batch.add(updater, instance);
} else {
batches = this._translucentBatches;
batch = batches.get(width);
if (!defined_default(batch)) {
batch = new Batch5(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];
isUpdated = batch.update(time);
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];
isUpdated = batch.update(time);
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_default.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();
}
};
var StaticOutlineGeometryBatch_default = StaticOutlineGeometryBatch;
// node_modules/@cesium/engine/Source/Core/WallGeometryLibrary.js
var WallGeometryLibrary = {};
function latLonEquals(c0, c14) {
return Math_default.equalsEpsilon(c0.latitude, c14.latitude, Math_default.EPSILON10) && Math_default.equalsEpsilon(c0.longitude, c14.longitude, Math_default.EPSILON10);
}
var scratchCartographic13 = new Cartographic_default();
var scratchCartographic23 = new Cartographic_default();
function removeDuplicates(ellipsoid, positions, topHeights, bottomHeights) {
positions = arrayRemoveDuplicates_default(positions, Cartesian3_default.equalsEpsilon);
const length3 = positions.length;
if (length3 < 2) {
return;
}
const hasBottomHeights = defined_default(bottomHeights);
const hasTopHeights = defined_default(topHeights);
const cleanedPositions = new Array(length3);
const cleanedTopHeights = new Array(length3);
const cleanedBottomHeights = new Array(length3);
const v02 = positions[0];
cleanedPositions[0] = v02;
const c0 = ellipsoid.cartesianToCartographic(v02, scratchCartographic13);
if (hasTopHeights) {
c0.height = topHeights[0];
}
cleanedTopHeights[0] = c0.height;
if (hasBottomHeights) {
cleanedBottomHeights[0] = bottomHeights[0];
} else {
cleanedBottomHeights[0] = 0;
}
const startTopHeight = cleanedTopHeights[0];
const startBottomHeight = cleanedBottomHeights[0];
let hasAllSameHeights = startTopHeight === startBottomHeight;
let index = 1;
for (let i = 1; i < length3; ++i) {
const v13 = positions[i];
const c14 = ellipsoid.cartesianToCartographic(v13, scratchCartographic23);
if (hasTopHeights) {
c14.height = topHeights[i];
}
hasAllSameHeights = hasAllSameHeights && c14.height === 0;
if (!latLonEquals(c0, c14)) {
cleanedPositions[index] = v13;
cleanedTopHeights[index] = c14.height;
if (hasBottomHeights) {
cleanedBottomHeights[index] = bottomHeights[i];
} else {
cleanedBottomHeights[index] = 0;
}
hasAllSameHeights = hasAllSameHeights && cleanedTopHeights[index] === cleanedBottomHeights[index];
Cartographic_default.clone(c14, c0);
++index;
} else if (c0.height < c14.height) {
cleanedTopHeights[index - 1] = c14.height;
}
}
if (hasAllSameHeights || index < 2) {
return;
}
cleanedPositions.length = index;
cleanedTopHeights.length = index;
cleanedBottomHeights.length = index;
return {
positions: cleanedPositions,
topHeights: cleanedTopHeights,
bottomHeights: cleanedBottomHeights
};
}
var positionsArrayScratch = new Array(2);
var heightsArrayScratch = new Array(2);
var generateArcOptionsScratch = {
positions: void 0,
height: void 0,
granularity: void 0,
ellipsoid: void 0
};
WallGeometryLibrary.computePositions = function(ellipsoid, wallPositions, maximumHeights, minimumHeights, granularity, duplicateCorners) {
const o = removeDuplicates(
ellipsoid,
wallPositions,
maximumHeights,
minimumHeights
);
if (!defined_default(o)) {
return;
}
wallPositions = o.positions;
maximumHeights = o.topHeights;
minimumHeights = o.bottomHeights;
const length3 = wallPositions.length;
const numCorners = length3 - 2;
let topPositions;
let bottomPositions;
const minDistance = Math_default.chordLength(
granularity,
ellipsoid.maximumRadius
);
const generateArcOptions = generateArcOptionsScratch;
generateArcOptions.minDistance = minDistance;
generateArcOptions.ellipsoid = ellipsoid;
if (duplicateCorners) {
let count = 0;
let i;
for (i = 0; i < length3 - 1; i++) {
count += PolylinePipeline_default.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 offset2 = 0;
for (i = 0; i < length3 - 1; i++) {
generateArcPositions[0] = wallPositions[i];
generateArcPositions[1] = wallPositions[i + 1];
generateArcHeights[0] = maximumHeights[i];
generateArcHeights[1] = maximumHeights[i + 1];
const pos = PolylinePipeline_default.generateArc(generateArcOptions);
topPositions.set(pos, offset2);
generateArcHeights[0] = minimumHeights[i];
generateArcHeights[1] = minimumHeights[i + 1];
bottomPositions.set(
PolylinePipeline_default.generateArc(generateArcOptions),
offset2
);
offset2 += pos.length;
}
} else {
generateArcOptions.positions = wallPositions;
generateArcOptions.height = maximumHeights;
topPositions = new Float64Array(
PolylinePipeline_default.generateArc(generateArcOptions)
);
generateArcOptions.height = minimumHeights;
bottomPositions = new Float64Array(
PolylinePipeline_default.generateArc(generateArcOptions)
);
}
return {
bottomPositions,
topPositions,
numCorners
};
};
var WallGeometryLibrary_default = WallGeometryLibrary;
// node_modules/@cesium/engine/Source/Core/WallGeometry.js
var scratchCartesian3Position1 = new Cartesian3_default();
var scratchCartesian3Position2 = new Cartesian3_default();
var scratchCartesian3Position4 = new Cartesian3_default();
var scratchCartesian3Position5 = new Cartesian3_default();
var scratchBitangent5 = new Cartesian3_default();
var scratchTangent5 = new Cartesian3_default();
var scratchNormal7 = new Cartesian3_default();
function WallGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const wallPositions = options.positions;
const maximumHeights = options.maximumHeights;
const minimumHeights = options.minimumHeights;
if (!defined_default(wallPositions)) {
throw new DeveloperError_default("options.positions is required.");
}
if (defined_default(maximumHeights) && maximumHeights.length !== wallPositions.length) {
throw new DeveloperError_default(
"options.positions and options.maximumHeights must have the same length."
);
}
if (defined_default(minimumHeights) && minimumHeights.length !== wallPositions.length) {
throw new DeveloperError_default(
"options.positions and options.minimumHeights must have the same length."
);
}
const vertexFormat = defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT);
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._positions = wallPositions;
this._minimumHeights = minimumHeights;
this._maximumHeights = maximumHeights;
this._vertexFormat = VertexFormat_default.clone(vertexFormat);
this._granularity = granularity;
this._ellipsoid = Ellipsoid_default.clone(ellipsoid);
this._workerName = "createWallGeometry";
let numComponents = 1 + wallPositions.length * Cartesian3_default.packedLength + 2;
if (defined_default(minimumHeights)) {
numComponents += minimumHeights.length;
}
if (defined_default(maximumHeights)) {
numComponents += maximumHeights.length;
}
this.packedLength = numComponents + Ellipsoid_default.packedLength + VertexFormat_default.packedLength + 1;
}
WallGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
const positions = value._positions;
let length3 = positions.length;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
Cartesian3_default.pack(positions[i], array, startingIndex);
}
const minimumHeights = value._minimumHeights;
length3 = defined_default(minimumHeights) ? minimumHeights.length : 0;
array[startingIndex++] = length3;
if (defined_default(minimumHeights)) {
for (i = 0; i < length3; ++i) {
array[startingIndex++] = minimumHeights[i];
}
}
const maximumHeights = value._maximumHeights;
length3 = defined_default(maximumHeights) ? maximumHeights.length : 0;
array[startingIndex++] = length3;
if (defined_default(maximumHeights)) {
for (i = 0; i < length3; ++i) {
array[startingIndex++] = maximumHeights[i];
}
}
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.packedLength;
array[startingIndex] = value._granularity;
return array;
};
var scratchEllipsoid12 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchVertexFormat11 = new VertexFormat_default();
var scratchOptions19 = {
positions: void 0,
minimumHeights: void 0,
maximumHeights: void 0,
ellipsoid: scratchEllipsoid12,
vertexFormat: scratchVertexFormat11,
granularity: void 0
};
WallGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
let length3 = array[startingIndex++];
const positions = new Array(length3);
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
positions[i] = Cartesian3_default.unpack(array, startingIndex);
}
length3 = array[startingIndex++];
let minimumHeights;
if (length3 > 0) {
minimumHeights = new Array(length3);
for (i = 0; i < length3; ++i) {
minimumHeights[i] = array[startingIndex++];
}
}
length3 = array[startingIndex++];
let maximumHeights;
if (length3 > 0) {
maximumHeights = new Array(length3);
for (i = 0; i < length3; ++i) {
maximumHeights[i] = array[startingIndex++];
}
}
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid12);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat11
);
startingIndex += VertexFormat_default.packedLength;
const granularity = array[startingIndex];
if (!defined_default(result)) {
scratchOptions19.positions = positions;
scratchOptions19.minimumHeights = minimumHeights;
scratchOptions19.maximumHeights = maximumHeights;
scratchOptions19.granularity = granularity;
return new WallGeometry(scratchOptions19);
}
result._positions = positions;
result._minimumHeights = minimumHeights;
result._maximumHeights = maximumHeights;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
result._granularity = granularity;
return result;
};
WallGeometry.fromConstantHeights = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.positions;
if (!defined_default(positions)) {
throw new DeveloperError_default("options.positions is required.");
}
let minHeights;
let maxHeights;
const min3 = options.minimumHeight;
const max3 = options.maximumHeight;
const doMin = defined_default(min3);
const doMax = defined_default(max3);
if (doMin || doMax) {
const length3 = positions.length;
minHeights = doMin ? new Array(length3) : void 0;
maxHeights = doMax ? new Array(length3) : void 0;
for (let i = 0; i < length3; ++i) {
if (doMin) {
minHeights[i] = min3;
}
if (doMax) {
maxHeights[i] = max3;
}
}
}
const newOptions2 = {
positions,
maximumHeights: maxHeights,
minimumHeights: minHeights,
ellipsoid: options.ellipsoid,
vertexFormat: options.vertexFormat
};
return new WallGeometry(newOptions2);
};
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_default.computePositions(
ellipsoid,
wallPositions,
maximumHeights,
minimumHeights,
granularity,
true
);
if (!defined_default(pos)) {
return;
}
const bottomPositions = pos.bottomPositions;
const topPositions = pos.topPositions;
const numCorners = pos.numCorners;
let length3 = topPositions.length;
let size = length3 * 2;
const positions = vertexFormat.position ? new Float64Array(size) : void 0;
const normals = vertexFormat.normal ? new Float32Array(size) : void 0;
const tangents = vertexFormat.tangent ? new Float32Array(size) : void 0;
const bitangents = vertexFormat.bitangent ? new Float32Array(size) : void 0;
const textureCoordinates = vertexFormat.st ? new Float32Array(size / 3 * 2) : void 0;
let positionIndex = 0;
let normalIndex = 0;
let bitangentIndex = 0;
let tangentIndex = 0;
let stIndex = 0;
let normal2 = scratchNormal7;
let tangent = scratchTangent5;
let bitangent = scratchBitangent5;
let recomputeNormal = true;
length3 /= 3;
let i;
let s = 0;
const ds = 1 / (length3 - numCorners - 1);
for (i = 0; i < length3; ++i) {
const i3 = i * 3;
const topPosition = Cartesian3_default.fromArray(
topPositions,
i3,
scratchCartesian3Position1
);
const bottomPosition = Cartesian3_default.fromArray(
bottomPositions,
i3,
scratchCartesian3Position2
);
if (vertexFormat.position) {
positions[positionIndex++] = bottomPosition.x;
positions[positionIndex++] = bottomPosition.y;
positions[positionIndex++] = bottomPosition.z;
positions[positionIndex++] = topPosition.x;
positions[positionIndex++] = topPosition.y;
positions[positionIndex++] = topPosition.z;
}
if (vertexFormat.st) {
textureCoordinates[stIndex++] = s;
textureCoordinates[stIndex++] = 0;
textureCoordinates[stIndex++] = s;
textureCoordinates[stIndex++] = 1;
}
if (vertexFormat.normal || vertexFormat.tangent || vertexFormat.bitangent) {
let nextTop = Cartesian3_default.clone(
Cartesian3_default.ZERO,
scratchCartesian3Position5
);
const groundPosition = Cartesian3_default.subtract(
topPosition,
ellipsoid.geodeticSurfaceNormal(
topPosition,
scratchCartesian3Position2
),
scratchCartesian3Position2
);
if (i + 1 < length3) {
nextTop = Cartesian3_default.fromArray(
topPositions,
i3 + 3,
scratchCartesian3Position5
);
}
if (recomputeNormal) {
const scalednextPosition = Cartesian3_default.subtract(
nextTop,
topPosition,
scratchCartesian3Position4
);
const scaledGroundPosition = Cartesian3_default.subtract(
groundPosition,
topPosition,
scratchCartesian3Position1
);
normal2 = Cartesian3_default.normalize(
Cartesian3_default.cross(scaledGroundPosition, scalednextPosition, normal2),
normal2
);
recomputeNormal = false;
}
if (Cartesian3_default.equalsEpsilon(topPosition, nextTop, Math_default.EPSILON10)) {
recomputeNormal = true;
} else {
s += ds;
if (vertexFormat.tangent) {
tangent = Cartesian3_default.normalize(
Cartesian3_default.subtract(nextTop, topPosition, tangent),
tangent
);
}
if (vertexFormat.bitangent) {
bitangent = Cartesian3_default.normalize(
Cartesian3_default.cross(normal2, tangent, bitangent),
bitangent
);
}
}
if (vertexFormat.normal) {
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.z;
normals[normalIndex++] = normal2.x;
normals[normalIndex++] = normal2.y;
normals[normalIndex++] = normal2.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_default();
if (vertexFormat.position) {
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
});
}
if (vertexFormat.normal) {
attributes.normal = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: normals
});
}
if (vertexFormat.tangent) {
attributes.tangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: tangents
});
}
if (vertexFormat.bitangent) {
attributes.bitangent = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 3,
values: bitangents
});
}
if (vertexFormat.st) {
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: textureCoordinates
});
}
const numVertices = size / 3;
size -= 6 * (numCorners + 1);
const indices2 = IndexDatatype_default.createTypedArray(numVertices, size);
let edgeIndex = 0;
for (i = 0; i < numVertices - 2; i += 2) {
const LL = i;
const LR = i + 2;
const pl = Cartesian3_default.fromArray(
positions,
LL * 3,
scratchCartesian3Position1
);
const pr = Cartesian3_default.fromArray(
positions,
LR * 3,
scratchCartesian3Position2
);
if (Cartesian3_default.equalsEpsilon(pl, pr, Math_default.EPSILON10)) {
continue;
}
const UL = i + 1;
const UR = i + 3;
indices2[edgeIndex++] = UL;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = UR;
indices2[edgeIndex++] = UR;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = LR;
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere: new BoundingSphere_default.fromVertices(positions)
});
};
var WallGeometry_default = WallGeometry;
// node_modules/@cesium/engine/Source/Core/WallOutlineGeometry.js
var scratchCartesian3Position12 = new Cartesian3_default();
var scratchCartesian3Position22 = new Cartesian3_default();
function WallOutlineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const wallPositions = options.positions;
const maximumHeights = options.maximumHeights;
const minimumHeights = options.minimumHeights;
if (!defined_default(wallPositions)) {
throw new DeveloperError_default("options.positions is required.");
}
if (defined_default(maximumHeights) && maximumHeights.length !== wallPositions.length) {
throw new DeveloperError_default(
"options.positions and options.maximumHeights must have the same length."
);
}
if (defined_default(minimumHeights) && minimumHeights.length !== wallPositions.length) {
throw new DeveloperError_default(
"options.positions and options.minimumHeights must have the same length."
);
}
const granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._positions = wallPositions;
this._minimumHeights = minimumHeights;
this._maximumHeights = maximumHeights;
this._granularity = granularity;
this._ellipsoid = Ellipsoid_default.clone(ellipsoid);
this._workerName = "createWallOutlineGeometry";
let numComponents = 1 + wallPositions.length * Cartesian3_default.packedLength + 2;
if (defined_default(minimumHeights)) {
numComponents += minimumHeights.length;
}
if (defined_default(maximumHeights)) {
numComponents += maximumHeights.length;
}
this.packedLength = numComponents + Ellipsoid_default.packedLength + 1;
}
WallOutlineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
const positions = value._positions;
let length3 = positions.length;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
Cartesian3_default.pack(positions[i], array, startingIndex);
}
const minimumHeights = value._minimumHeights;
length3 = defined_default(minimumHeights) ? minimumHeights.length : 0;
array[startingIndex++] = length3;
if (defined_default(minimumHeights)) {
for (i = 0; i < length3; ++i) {
array[startingIndex++] = minimumHeights[i];
}
}
const maximumHeights = value._maximumHeights;
length3 = defined_default(maximumHeights) ? maximumHeights.length : 0;
array[startingIndex++] = length3;
if (defined_default(maximumHeights)) {
for (i = 0; i < length3; ++i) {
array[startingIndex++] = maximumHeights[i];
}
}
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
array[startingIndex] = value._granularity;
return array;
};
var scratchEllipsoid13 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchOptions20 = {
positions: void 0,
minimumHeights: void 0,
maximumHeights: void 0,
ellipsoid: scratchEllipsoid13,
granularity: void 0
};
WallOutlineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
let length3 = array[startingIndex++];
const positions = new Array(length3);
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
positions[i] = Cartesian3_default.unpack(array, startingIndex);
}
length3 = array[startingIndex++];
let minimumHeights;
if (length3 > 0) {
minimumHeights = new Array(length3);
for (i = 0; i < length3; ++i) {
minimumHeights[i] = array[startingIndex++];
}
}
length3 = array[startingIndex++];
let maximumHeights;
if (length3 > 0) {
maximumHeights = new Array(length3);
for (i = 0; i < length3; ++i) {
maximumHeights[i] = array[startingIndex++];
}
}
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid13);
startingIndex += Ellipsoid_default.packedLength;
const granularity = array[startingIndex];
if (!defined_default(result)) {
scratchOptions20.positions = positions;
scratchOptions20.minimumHeights = minimumHeights;
scratchOptions20.maximumHeights = maximumHeights;
scratchOptions20.granularity = granularity;
return new WallOutlineGeometry(scratchOptions20);
}
result._positions = positions;
result._minimumHeights = minimumHeights;
result._maximumHeights = maximumHeights;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._granularity = granularity;
return result;
};
WallOutlineGeometry.fromConstantHeights = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.positions;
if (!defined_default(positions)) {
throw new DeveloperError_default("options.positions is required.");
}
let minHeights;
let maxHeights;
const min3 = options.minimumHeight;
const max3 = options.maximumHeight;
const doMin = defined_default(min3);
const doMax = defined_default(max3);
if (doMin || doMax) {
const length3 = positions.length;
minHeights = doMin ? new Array(length3) : void 0;
maxHeights = doMax ? new Array(length3) : void 0;
for (let i = 0; i < length3; ++i) {
if (doMin) {
minHeights[i] = min3;
}
if (doMax) {
maxHeights[i] = max3;
}
}
}
const newOptions2 = {
positions,
maximumHeights: maxHeights,
minimumHeights: minHeights,
ellipsoid: options.ellipsoid
};
return new WallOutlineGeometry(newOptions2);
};
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_default.computePositions(
ellipsoid,
wallPositions,
maximumHeights,
minimumHeights,
granularity,
false
);
if (!defined_default(pos)) {
return;
}
const bottomPositions = pos.bottomPositions;
const topPositions = pos.topPositions;
let length3 = topPositions.length;
let size = length3 * 2;
const positions = new Float64Array(size);
let positionIndex = 0;
length3 /= 3;
let i;
for (i = 0; i < length3; ++i) {
const i3 = i * 3;
const topPosition = Cartesian3_default.fromArray(
topPositions,
i3,
scratchCartesian3Position12
);
const bottomPosition = Cartesian3_default.fromArray(
bottomPositions,
i3,
scratchCartesian3Position22
);
positions[positionIndex++] = bottomPosition.x;
positions[positionIndex++] = bottomPosition.y;
positions[positionIndex++] = bottomPosition.z;
positions[positionIndex++] = topPosition.x;
positions[positionIndex++] = topPosition.y;
positions[positionIndex++] = topPosition.z;
}
const attributes = new GeometryAttributes_default({
position: new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: positions
})
});
const numVertices = size / 3;
size = 2 * numVertices - 4 + numVertices;
const indices2 = IndexDatatype_default.createTypedArray(numVertices, size);
let edgeIndex = 0;
for (i = 0; i < numVertices - 2; i += 2) {
const LL = i;
const LR = i + 2;
const pl = Cartesian3_default.fromArray(
positions,
LL * 3,
scratchCartesian3Position12
);
const pr = Cartesian3_default.fromArray(
positions,
LR * 3,
scratchCartesian3Position22
);
if (Cartesian3_default.equalsEpsilon(pl, pr, Math_default.EPSILON10)) {
continue;
}
const UL = i + 1;
const UR = i + 3;
indices2[edgeIndex++] = UL;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = UL;
indices2[edgeIndex++] = UR;
indices2[edgeIndex++] = LL;
indices2[edgeIndex++] = LR;
}
indices2[edgeIndex++] = numVertices - 2;
indices2[edgeIndex++] = numVertices - 1;
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.LINES,
boundingSphere: new BoundingSphere_default.fromVertices(positions)
});
};
var WallOutlineGeometry_default = WallOutlineGeometry;
// node_modules/@cesium/engine/Source/DataSources/WallGeometryUpdater.js
var scratchColor19 = new Color_default();
function WallGeometryOptions(entity) {
this.id = entity;
this.vertexFormat = void 0;
this.positions = void 0;
this.minimumHeights = void 0;
this.maximumHeights = void 0;
this.granularity = void 0;
}
function WallGeometryUpdater(entity, scene) {
GeometryUpdater_default.call(this, {
entity,
scene,
geometryOptions: new WallGeometryOptions(entity),
geometryPropertyName: "wall",
observedPropertyNames: ["availability", "wall"]
});
this._onEntityPropertyChanged(entity, "wall", entity.wall, void 0);
}
if (defined_default(Object.create)) {
WallGeometryUpdater.prototype = Object.create(GeometryUpdater_default.prototype);
WallGeometryUpdater.prototype.constructor = WallGeometryUpdater;
}
WallGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
let attributes;
let color;
const show = new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._fillProperty.getValue(time)
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
);
if (this._materialProperty instanceof ColorMaterialProperty_default) {
let currentColor;
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor19);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute,
color
};
} else {
attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute
};
}
return new GeometryInstance_default({
id: entity,
geometry: new WallGeometry_default(this._options),
attributes
});
};
WallGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
Check_default.defined("time", time);
if (!this._outlineEnabled) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const outlineColor = Property_default.getValueOrDefault(
this._outlineColorProperty,
time,
Color_default.BLACK,
scratchColor19
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
return new GeometryInstance_default({
id: entity,
geometry: new WallOutlineGeometry_default(this._options),
attributes: {
show: new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time) && this._showOutlineProperty.getValue(time)
),
color: ColorGeometryInstanceAttribute_default.fromColor(outlineColor),
distanceDisplayCondition: DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
)
}
});
};
WallGeometryUpdater.prototype._isHidden = function(entity, wall) {
return !defined_default(wall.positions) || GeometryUpdater_default.prototype._isHidden.call(this, entity, wall);
};
WallGeometryUpdater.prototype._getIsClosed = function(options) {
return false;
};
WallGeometryUpdater.prototype._isDynamic = function(entity, wall) {
return !wall.positions.isConstant || !Property_default.isConstant(wall.minimumHeights) || !Property_default.isConstant(wall.maximumHeights) || !Property_default.isConstant(wall.outlineWidth) || !Property_default.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_default;
const options = this._options;
options.vertexFormat = isColorMaterial ? PerInstanceColorAppearance_default.VERTEX_FORMAT : MaterialAppearance_default.MaterialSupport.TEXTURED.vertexFormat;
options.positions = wall.positions.getValue(
Iso8601_default.MINIMUM_VALUE,
options.positions
);
options.minimumHeights = defined_default(minimumHeights) ? minimumHeights.getValue(Iso8601_default.MINIMUM_VALUE, options.minimumHeights) : void 0;
options.maximumHeights = defined_default(maximumHeights) ? maximumHeights.getValue(Iso8601_default.MINIMUM_VALUE, options.maximumHeights) : void 0;
options.granularity = defined_default(granularity) ? granularity.getValue(Iso8601_default.MINIMUM_VALUE) : void 0;
};
WallGeometryUpdater.DynamicGeometryUpdater = DynamicWallGeometryUpdater;
function DynamicWallGeometryUpdater(geometryUpdater, primitives, groundPrimitives) {
DynamicGeometryUpdater_default.call(
this,
geometryUpdater,
primitives,
groundPrimitives
);
}
if (defined_default(Object.create)) {
DynamicWallGeometryUpdater.prototype = Object.create(
DynamicGeometryUpdater_default.prototype
);
DynamicWallGeometryUpdater.prototype.constructor = DynamicWallGeometryUpdater;
}
DynamicWallGeometryUpdater.prototype._isHidden = function(entity, wall, time) {
return !defined_default(this._options.positions) || DynamicGeometryUpdater_default.prototype._isHidden.call(this, entity, wall, time);
};
DynamicWallGeometryUpdater.prototype._setOptions = function(entity, wall, time) {
const options = this._options;
options.positions = Property_default.getValueOrUndefined(
wall.positions,
time,
options.positions
);
options.minimumHeights = Property_default.getValueOrUndefined(
wall.minimumHeights,
time,
options.minimumHeights
);
options.maximumHeights = Property_default.getValueOrUndefined(
wall.maximumHeights,
time,
options.maximumHeights
);
options.granularity = Property_default.getValueOrUndefined(wall.granularity, time);
};
var WallGeometryUpdater_default = WallGeometryUpdater;
// node_modules/@cesium/engine/Source/DataSources/GeometryVisualizer.js
var emptyArray = [];
var geometryUpdaters = [
BoxGeometryUpdater_default,
CylinderGeometryUpdater_default,
CorridorGeometryUpdater_default,
EllipseGeometryUpdater_default,
EllipsoidGeometryUpdater_default,
PlaneGeometryUpdater_default,
PolygonGeometryUpdater_default,
PolylineVolumeGeometryUpdater_default,
RectangleGeometryUpdater_default,
WallGeometryUpdater_default
];
function GeometryUpdaterSet(entity, scene) {
this.entity = entity;
this.scene = scene;
const updaters = new Array(geometryUpdaters.length);
const geometryChanged = new Event_default();
function raiseEvent(geometry) {
geometryChanged.raiseEvent(geometry);
}
const eventHelper = new EventHelper_default();
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, oldValue2) {
const updaters = this.updaters;
for (let i = 0; i < updaters.length; i++) {
updaters[i]._onEntityPropertyChanged(
entity,
propertyName,
newValue,
oldValue2
);
}
};
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_default(this);
};
function GeometryVisualizer(scene, entityCollection, primitives, groundPrimitives) {
Check_default.defined("scene", scene);
Check_default.defined("entityCollection", entityCollection);
primitives = defaultValue_default(primitives, scene.primitives);
groundPrimitives = defaultValue_default(groundPrimitives, scene.groundPrimitives);
this._scene = scene;
this._primitives = primitives;
this._groundPrimitives = groundPrimitives;
this._entityCollection = void 0;
this._addedObjects = new AssociativeArray_default();
this._removedObjects = new AssociativeArray_default();
this._changedObjects = new AssociativeArray_default();
const numberOfShadowModes = ShadowMode_default.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_default.supportsMaterialsforEntitiesOnTerrain(
scene
);
this._supportsMaterialsforEntitiesOnTerrain = supportsMaterialsforEntitiesOnTerrain;
let i;
for (i = 0; i < numberOfShadowModes; ++i) {
this._outlineBatches[i] = new StaticOutlineGeometryBatch_default(
primitives,
scene,
i,
false
);
this._outlineBatches[numberOfShadowModes + i] = new StaticOutlineGeometryBatch_default(primitives, scene, i, true);
this._closedColorBatches[i] = new StaticGeometryColorBatch_default(
primitives,
PerInstanceColorAppearance_default,
void 0,
true,
i,
true
);
this._closedColorBatches[numberOfShadowModes + i] = new StaticGeometryColorBatch_default(
primitives,
PerInstanceColorAppearance_default,
void 0,
true,
i,
false
);
this._closedMaterialBatches[i] = new StaticGeometryPerMaterialBatch_default(
primitives,
MaterialAppearance_default,
void 0,
true,
i,
true
);
this._closedMaterialBatches[numberOfShadowModes + i] = new StaticGeometryPerMaterialBatch_default(
primitives,
MaterialAppearance_default,
void 0,
true,
i,
false
);
this._openColorBatches[i] = new StaticGeometryColorBatch_default(
primitives,
PerInstanceColorAppearance_default,
void 0,
false,
i,
true
);
this._openColorBatches[numberOfShadowModes + i] = new StaticGeometryColorBatch_default(
primitives,
PerInstanceColorAppearance_default,
void 0,
false,
i,
false
);
this._openMaterialBatches[i] = new StaticGeometryPerMaterialBatch_default(
primitives,
MaterialAppearance_default,
void 0,
false,
i,
true
);
this._openMaterialBatches[numberOfShadowModes + i] = new StaticGeometryPerMaterialBatch_default(
primitives,
MaterialAppearance_default,
void 0,
false,
i,
false
);
}
const numberOfClassificationTypes = ClassificationType_default.NUMBER_OF_CLASSIFICATION_TYPES;
const groundColorBatches = new Array(numberOfClassificationTypes);
const groundMaterialBatches = [];
if (supportsMaterialsforEntitiesOnTerrain) {
for (i = 0; i < numberOfClassificationTypes; ++i) {
groundMaterialBatches.push(
new StaticGroundGeometryPerMaterialBatch_default(
groundPrimitives,
i,
MaterialAppearance_default
)
);
groundColorBatches[i] = new StaticGroundGeometryColorBatch_default(
groundPrimitives,
i
);
}
} else {
for (i = 0; i < numberOfClassificationTypes; ++i) {
groundColorBatches[i] = new StaticGroundGeometryColorBatch_default(
groundPrimitives,
i
);
}
}
this._groundColorBatches = groundColorBatches;
this._groundMaterialBatches = groundMaterialBatches;
this._dynamicBatch = new DynamicGeometryBatch_default(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_default();
this._updaterSets = new AssociativeArray_default();
this._entityCollection = entityCollection;
entityCollection.collectionChanged.addEventListener(
GeometryVisualizer.prototype._onCollectionChanged,
this
);
this._onCollectionChanged(
entityCollection,
entityCollection.values,
emptyArray
);
}
GeometryVisualizer.prototype.update = function(time) {
Check_default.defined("time", time);
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 (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 length3 = batches.length;
for (i = 0; i < length3; i++) {
isUpdated = batches[i].update(time) && isUpdated;
}
return isUpdated;
};
var getBoundingSphereArrayScratch = [];
var getBoundingSphereBoundingSphereScratch = new BoundingSphere_default();
GeometryVisualizer.prototype.getBoundingSphere = function(entity, result) {
Check_default.defined("entity", entity);
Check_default.defined("result", result);
const boundingSpheres = getBoundingSphereArrayScratch;
const tmp2 = getBoundingSphereBoundingSphereScratch;
let count = 0;
let state = BoundingSphereState_default.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, tmp2);
if (state === BoundingSphereState_default.PENDING) {
return BoundingSphereState_default.PENDING;
} else if (state === BoundingSphereState_default.DONE) {
boundingSpheres[count] = BoundingSphere_default.clone(
tmp2,
boundingSpheres[count]
);
count++;
}
}
}
if (count === 0) {
return BoundingSphereState_default.FAILED;
}
boundingSpheres.length = count;
BoundingSphere_default.fromBoundingSpheres(boundingSpheres, result);
return BoundingSphereState_default.DONE;
};
GeometryVisualizer.prototype.isDestroyed = function() {
return false;
};
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 length3 = batches.length;
for (i = 0; i < length3; i++) {
batches[i].removeAllPrimitives();
}
const subscriptions = this._subscriptions.values;
length3 = subscriptions.length;
for (i = 0; i < length3; i++) {
subscriptions[i]();
}
this._subscriptions.removeAll();
const updaterSets = this._updaterSets.values;
length3 = updaterSets.length;
for (i = 0; i < length3; i++) {
updaterSets[i].destroy();
}
this._updaterSets.removeAll();
return destroyObject_default(this);
};
GeometryVisualizer.prototype._removeUpdater = function(updater) {
const batches = this._batches;
const length3 = batches.length;
for (let i = 0; i < length3; i++) {
batches[i].remove(updater);
}
};
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_default.NUMBER_OF_SHADOW_MODES;
if (updater.outlineEnabled) {
if (defined_default(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_default) {
this._groundColorBatches[classificationType].add(time, updater);
} else {
this._groundMaterialBatches[classificationType].add(time, updater);
}
} else if (updater.isClosed) {
if (updater.fillMaterialProperty instanceof ColorMaterialProperty_default) {
if (defined_default(updater.terrainOffsetProperty)) {
this._closedColorBatches[numberOfShadowModes + shadows].add(
time,
updater
);
} else {
this._closedColorBatches[shadows].add(time, updater);
}
} else if (defined_default(updater.terrainOffsetProperty)) {
this._closedMaterialBatches[numberOfShadowModes + shadows].add(
time,
updater
);
} else {
this._closedMaterialBatches[shadows].add(time, updater);
}
} else if (updater.fillMaterialProperty instanceof ColorMaterialProperty_default) {
if (defined_default(updater.terrainOffsetProperty)) {
this._openColorBatches[numberOfShadowModes + shadows].add(
time,
updater
);
} else {
this._openColorBatches[shadows].add(time, updater);
}
} else if (defined_default(updater.terrainOffsetProperty)) {
this._openMaterialBatches[numberOfShadowModes + shadows].add(
time,
updater
);
} else {
this._openMaterialBatches[shadows].add(time, updater);
}
}
};
GeometryVisualizer._onGeometryChanged = function(updater) {
const removedObjects = this._removedObjects;
const changedObjects = this._changedObjects;
const entity = updater.entity;
const id = entity.id;
if (!defined_default(removedObjects.get(id)) && !defined_default(changedObjects.get(id))) {
changedObjects.set(id, entity);
}
};
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);
}
}
};
var GeometryVisualizer_default = GeometryVisualizer;
// node_modules/@cesium/engine/Source/DataSources/LabelVisualizer.js
var defaultScale4 = 1;
var defaultFont = "30px sans-serif";
var defaultStyle = LabelStyle_default.FILL;
var defaultFillColor = Color_default.WHITE;
var defaultOutlineColor3 = Color_default.BLACK;
var defaultOutlineWidth2 = 1;
var defaultShowBackground = false;
var defaultBackgroundColor2 = new Color_default(0.165, 0.165, 0.165, 0.8);
var defaultBackgroundPadding2 = new Cartesian2_default(7, 5);
var defaultPixelOffset2 = Cartesian2_default.ZERO;
var defaultEyeOffset2 = Cartesian3_default.ZERO;
var defaultHeightReference2 = HeightReference_default.NONE;
var defaultHorizontalOrigin2 = HorizontalOrigin_default.CENTER;
var defaultVerticalOrigin2 = VerticalOrigin_default.CENTER;
var positionScratch13 = new Cartesian3_default();
var fillColorScratch = new Color_default();
var outlineColorScratch = new Color_default();
var backgroundColorScratch = new Color_default();
var backgroundPaddingScratch = new Cartesian2_default();
var eyeOffsetScratch2 = new Cartesian3_default();
var pixelOffsetScratch2 = new Cartesian2_default();
var translucencyByDistanceScratch2 = new NearFarScalar_default();
var pixelOffsetScaleByDistanceScratch2 = new NearFarScalar_default();
var scaleByDistanceScratch2 = new NearFarScalar_default();
var distanceDisplayConditionScratch7 = new DistanceDisplayCondition_default();
function EntityData2(entity) {
this.entity = entity;
this.label = void 0;
this.index = void 0;
}
function LabelVisualizer(entityCluster, entityCollection) {
if (!defined_default(entityCluster)) {
throw new DeveloperError_default("entityCluster is required.");
}
if (!defined_default(entityCollection)) {
throw new DeveloperError_default("entityCollection is required.");
}
entityCollection.collectionChanged.addEventListener(
LabelVisualizer.prototype._onCollectionChanged,
this
);
this._cluster = entityCluster;
this._entityCollection = entityCollection;
this._items = new AssociativeArray_default();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
LabelVisualizer.prototype.update = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
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 text2;
let label = item.label;
let show = entity.isShowing && entity.isAvailable(time) && Property_default.getValueOrDefault(labelGraphics._show, time, true);
let position;
if (show) {
position = Property_default.getValueOrUndefined(
entity._position,
time,
positionScratch13
);
text2 = Property_default.getValueOrUndefined(labelGraphics._text, time);
show = defined_default(position) && defined_default(text2);
}
if (!show) {
returnPrimitive2(item, entity, cluster);
continue;
}
if (!Property_default.isConstant(entity._position)) {
cluster._clusterDirty = true;
}
let updateClamping2 = false;
const heightReference = Property_default.getValueOrDefault(
labelGraphics._heightReference,
time,
defaultHeightReference2
);
if (!defined_default(label)) {
label = cluster.getLabel(entity);
label.id = entity;
item.label = label;
updateClamping2 = Cartesian3_default.equals(label.position, position) && label.heightReference === heightReference;
}
label.show = true;
label.position = position;
label.text = text2;
label.scale = Property_default.getValueOrDefault(
labelGraphics._scale,
time,
defaultScale4
);
label.font = Property_default.getValueOrDefault(
labelGraphics._font,
time,
defaultFont
);
label.style = Property_default.getValueOrDefault(
labelGraphics._style,
time,
defaultStyle
);
label.fillColor = Property_default.getValueOrDefault(
labelGraphics._fillColor,
time,
defaultFillColor,
fillColorScratch
);
label.outlineColor = Property_default.getValueOrDefault(
labelGraphics._outlineColor,
time,
defaultOutlineColor3,
outlineColorScratch
);
label.outlineWidth = Property_default.getValueOrDefault(
labelGraphics._outlineWidth,
time,
defaultOutlineWidth2
);
label.showBackground = Property_default.getValueOrDefault(
labelGraphics._showBackground,
time,
defaultShowBackground
);
label.backgroundColor = Property_default.getValueOrDefault(
labelGraphics._backgroundColor,
time,
defaultBackgroundColor2,
backgroundColorScratch
);
label.backgroundPadding = Property_default.getValueOrDefault(
labelGraphics._backgroundPadding,
time,
defaultBackgroundPadding2,
backgroundPaddingScratch
);
label.pixelOffset = Property_default.getValueOrDefault(
labelGraphics._pixelOffset,
time,
defaultPixelOffset2,
pixelOffsetScratch2
);
label.eyeOffset = Property_default.getValueOrDefault(
labelGraphics._eyeOffset,
time,
defaultEyeOffset2,
eyeOffsetScratch2
);
label.heightReference = heightReference;
label.horizontalOrigin = Property_default.getValueOrDefault(
labelGraphics._horizontalOrigin,
time,
defaultHorizontalOrigin2
);
label.verticalOrigin = Property_default.getValueOrDefault(
labelGraphics._verticalOrigin,
time,
defaultVerticalOrigin2
);
label.translucencyByDistance = Property_default.getValueOrUndefined(
labelGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch2
);
label.pixelOffsetScaleByDistance = Property_default.getValueOrUndefined(
labelGraphics._pixelOffsetScaleByDistance,
time,
pixelOffsetScaleByDistanceScratch2
);
label.scaleByDistance = Property_default.getValueOrUndefined(
labelGraphics._scaleByDistance,
time,
scaleByDistanceScratch2
);
label.distanceDisplayCondition = Property_default.getValueOrUndefined(
labelGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch7
);
label.disableDepthTestDistance = Property_default.getValueOrUndefined(
labelGraphics._disableDepthTestDistance,
time
);
if (updateClamping2) {
label._updateClamping();
}
}
return true;
};
LabelVisualizer.prototype.getBoundingSphere = function(entity, result) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const item = this._items.get(entity.id);
if (!defined_default(item) || !defined_default(item.label)) {
return BoundingSphereState_default.FAILED;
}
const label = item.label;
result.center = Cartesian3_default.clone(
defaultValue_default(label._clampedPosition, label.position),
result.center
);
result.radius = 0;
return BoundingSphereState_default.DONE;
};
LabelVisualizer.prototype.isDestroyed = function() {
return false;
};
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_default(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_default(entity._label) && defined_default(entity._position)) {
items.set(entity.id, new EntityData2(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined_default(entity._label) && defined_default(entity._position)) {
if (!items.contains(entity.id)) {
items.set(entity.id, new EntityData2(entity));
}
} else {
returnPrimitive2(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
returnPrimitive2(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
};
function returnPrimitive2(item, entity, cluster) {
if (defined_default(item)) {
item.label = void 0;
cluster.removeLabel(entity);
}
}
var LabelVisualizer_default = LabelVisualizer;
// node_modules/@cesium/engine/Source/Core/sampleTerrain.js
async function sampleTerrain(terrainProvider, level, positions) {
Check_default.typeOf.object("terrainProvider", terrainProvider);
Check_default.typeOf.number("level", level);
Check_default.defined("positions", positions);
await terrainProvider._readyPromise;
return doSampling(terrainProvider, level, positions);
}
function attemptConsumeNextQueueItem(tileRequests, results) {
const tileRequest = tileRequests[0];
const requestPromise = tileRequest.terrainProvider.requestTileGeometry(
tileRequest.x,
tileRequest.y,
tileRequest.level
);
if (!requestPromise) {
return false;
}
const promise = requestPromise.then(createInterpolateFunction(tileRequest)).catch(createMarkFailedFunction(tileRequest));
tileRequests.shift();
results.push(promise);
return true;
}
function delay(ms) {
return new Promise(function(res) {
setTimeout(res, ms);
});
}
function drainTileRequestQueue(tileRequests, results) {
if (!tileRequests.length) {
return Promise.resolve();
}
const success = attemptConsumeNextQueueItem(tileRequests, results);
if (success) {
return drainTileRequestQueue(tileRequests, results);
}
return delay(100).then(() => {
return drainTileRequestQueue(tileRequests, results);
});
}
function doSampling(terrainProvider, level, positions) {
const tilingScheme2 = terrainProvider.tilingScheme;
let i;
const tileRequests = [];
const tileRequestSet = {};
for (i = 0; i < positions.length; ++i) {
const xy = tilingScheme2.positionToTileXY(positions[i], level);
if (!defined_default(xy)) {
continue;
}
const key = xy.toString();
if (!tileRequestSet.hasOwnProperty(key)) {
const value = {
x: xy.x,
y: xy.y,
level,
tilingScheme: tilingScheme2,
terrainProvider,
positions: []
};
tileRequestSet[key] = value;
tileRequests.push(value);
}
tileRequestSet[key].positions.push(positions[i]);
}
const tilePromises = [];
return drainTileRequestQueue(tileRequests, tilePromises).then(function() {
return Promise.all(tilePromises).then(function() {
return positions;
});
});
}
function interpolateAndAssignHeight(position, terrainData, rectangle) {
const height = terrainData.interpolateHeight(
rectangle,
position.longitude,
position.latitude
);
if (height === void 0) {
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
);
if (!isHeightAssigned) {
isMeshRequired = true;
break;
}
}
if (!isMeshRequired) {
return Promise.resolve();
}
return terrainData.createMesh({
tilingScheme: tileRequest.tilingScheme,
x: tileRequest.x,
y: tileRequest.y,
level: tileRequest.level,
throttle: false
}).then(function() {
for (let i = 0; i < tilePositions.length; ++i) {
const position = tilePositions[i];
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 = void 0;
}
};
}
var sampleTerrain_default = sampleTerrain;
// node_modules/@cesium/engine/Source/Core/sampleTerrainMostDetailed.js
var scratchCartesian29 = new Cartesian2_default();
async function sampleTerrainMostDetailed(terrainProvider, positions) {
if (!defined_default(terrainProvider)) {
throw new DeveloperError_default("terrainProvider is required.");
}
if (!defined_default(positions)) {
throw new DeveloperError_default("positions is required.");
}
const byLevel = [];
const maxLevels = [];
await terrainProvider._readyPromise;
const availability = terrainProvider.availability;
if (!defined_default(availability)) {
throw new DeveloperError_default(
"sampleTerrainMostDetailed requires a terrain provider that has tile availability."
);
}
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) {
terrainProvider.tilingScheme.positionToTileXY(
position,
1,
scratchCartesian29
);
const promise = terrainProvider.loadTileDataAvailability(
scratchCartesian29.x,
scratchCartesian29.y,
1
);
if (defined_default(promise)) {
promises.push(promise);
}
}
let atLevel = byLevel[maxLevel];
if (!defined_default(atLevel)) {
byLevel[maxLevel] = atLevel = [];
}
atLevel.push(position);
}
await Promise.all(promises);
await Promise.all(
byLevel.map(function(positionsAtLevel, index) {
if (defined_default(positionsAtLevel)) {
return sampleTerrain_default(terrainProvider, index, positionsAtLevel);
}
})
);
const changedPositions = [];
for (let i = 0; i < positions.length; ++i) {
const position = positions[i];
const maxLevel = availability.computeMaximumLevelAtPosition(position);
if (maxLevel !== maxLevels[i]) {
changedPositions.push(position);
}
}
if (changedPositions.length > 0) {
await sampleTerrainMostDetailed(terrainProvider, changedPositions);
}
return positions;
}
var sampleTerrainMostDetailed_default = sampleTerrainMostDetailed;
// node_modules/@cesium/engine/Source/DataSources/ModelVisualizer.js
var defaultScale5 = 1;
var defaultMinimumPixelSize = 0;
var defaultIncrementallyLoadTextures = true;
var defaultClampAnimations = true;
var defaultShadows2 = ShadowMode_default.ENABLED;
var defaultHeightReference3 = HeightReference_default.NONE;
var defaultSilhouetteColor = Color_default.RED;
var defaultSilhouetteSize = 0;
var defaultColor7 = Color_default.WHITE;
var defaultColorBlendMode = ColorBlendMode_default.HIGHLIGHT;
var defaultColorBlendAmount = 0.5;
var defaultImageBasedLightingFactor = new Cartesian2_default(1, 1);
var modelMatrixScratch3 = new Matrix4_default();
var nodeMatrixScratch = new Matrix4_default();
var scratchColor20 = new Color_default();
var scratchArray = new Array(4);
var scratchCartesian19 = new Cartesian3_default();
function ModelVisualizer(scene, entityCollection) {
Check_default.typeOf.object("scene", scene);
Check_default.typeOf.object("entityCollection", entityCollection);
entityCollection.collectionChanged.addEventListener(
ModelVisualizer.prototype._onCollectionChanged,
this
);
this._scene = scene;
this._primitives = scene.primitives;
this._entityCollection = entityCollection;
this._modelHash = {};
this._entitiesToVisualize = new AssociativeArray_default();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
async function createModelPrimitive(visualizer, entity, resource, incrementallyLoadTextures) {
const primitives = visualizer._primitives;
const modelHash = visualizer._modelHash;
try {
const model = await Model_default.fromGltfAsync({
url: resource,
incrementallyLoadTextures,
scene: visualizer._scene
});
if (visualizer.isDestroyed() || !defined_default(modelHash[entity.id])) {
return;
}
model.id = entity;
primitives.add(model);
modelHash[entity.id].modelPrimitive = model;
model.errorEvent.addEventListener((error) => {
if (!defined_default(modelHash[entity.id])) {
return;
}
console.log(error);
if (error.name !== "TextureError" && model.incrementallyLoadTextures) {
modelHash[entity.id].loadFailed = true;
}
});
} catch (error) {
if (visualizer.isDestroyed() || !defined_default(modelHash[entity.id])) {
return;
}
console.log(error);
modelHash[entity.id].loadFailed = true;
}
}
ModelVisualizer.prototype.update = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
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_default.getValueOrDefault(modelGraphics._show, time, true);
let modelMatrix;
if (show) {
modelMatrix = entity.computeModelMatrix(time, modelMatrixScratch3);
resource = Resource_default.createIfNeeded(
Property_default.getValueOrUndefined(modelGraphics._uri, time)
);
show = defined_default(modelMatrix) && defined_default(resource);
}
if (!show) {
if (defined_default(modelData) && modelData.modelPrimitive) {
modelData.modelPrimitive.show = false;
}
continue;
}
if (!defined_default(modelData) || resource.url !== modelData.url) {
if (defined_default(modelData == null ? void 0 : modelData.modelPrimitive)) {
primitives.removeAndDestroy(modelData.modelPrimitive);
delete modelHash[entity.id];
}
modelData = {
modelPrimitive: void 0,
url: resource.url,
animationsRunning: false,
nodeTransformationsScratch: {},
articulationsScratch: {},
loadFailed: false,
modelUpdated: false,
awaitingSampleTerrain: false,
clampedBoundingSphere: void 0,
sampleTerrainFailed: false
};
modelHash[entity.id] = modelData;
const incrementallyLoadTextures = Property_default.getValueOrDefault(
modelGraphics._incrementallyLoadTextures,
time,
defaultIncrementallyLoadTextures
);
createModelPrimitive(this, entity, resource, incrementallyLoadTextures);
}
const model = modelData.modelPrimitive;
if (!defined_default(model)) {
continue;
}
model.show = true;
model.scale = Property_default.getValueOrDefault(
modelGraphics._scale,
time,
defaultScale5
);
model.minimumPixelSize = Property_default.getValueOrDefault(
modelGraphics._minimumPixelSize,
time,
defaultMinimumPixelSize
);
model.maximumScale = Property_default.getValueOrUndefined(
modelGraphics._maximumScale,
time
);
model.modelMatrix = Matrix4_default.clone(modelMatrix, model.modelMatrix);
model.shadows = Property_default.getValueOrDefault(
modelGraphics._shadows,
time,
defaultShadows2
);
model.heightReference = Property_default.getValueOrDefault(
modelGraphics._heightReference,
time,
defaultHeightReference3
);
model.distanceDisplayCondition = Property_default.getValueOrUndefined(
modelGraphics._distanceDisplayCondition,
time
);
model.silhouetteColor = Property_default.getValueOrDefault(
modelGraphics._silhouetteColor,
time,
defaultSilhouetteColor,
scratchColor20
);
model.silhouetteSize = Property_default.getValueOrDefault(
modelGraphics._silhouetteSize,
time,
defaultSilhouetteSize
);
model.color = Property_default.getValueOrDefault(
modelGraphics._color,
time,
defaultColor7,
scratchColor20
);
model.colorBlendMode = Property_default.getValueOrDefault(
modelGraphics._colorBlendMode,
time,
defaultColorBlendMode
);
model.colorBlendAmount = Property_default.getValueOrDefault(
modelGraphics._colorBlendAmount,
time,
defaultColorBlendAmount
);
model.clippingPlanes = Property_default.getValueOrUndefined(
modelGraphics._clippingPlanes,
time
);
model.clampAnimations = Property_default.getValueOrDefault(
modelGraphics._clampAnimations,
time,
defaultClampAnimations
);
model.imageBasedLighting.imageBasedLightingFactor = Property_default.getValueOrDefault(
modelGraphics._imageBasedLightingFactor,
time,
defaultImageBasedLightingFactor
);
let lightColor = Property_default.getValueOrUndefined(
modelGraphics._lightColor,
time
);
if (defined_default(lightColor)) {
Color_default.pack(lightColor, scratchArray, 0);
lightColor = Cartesian3_default.unpack(scratchArray, 0, scratchCartesian19);
}
model.lightColor = lightColor;
model.customShader = Property_default.getValueOrUndefined(
modelGraphics._customShader,
time
);
modelHash[entity.id].modelUpdated = true;
if (model.ready) {
const runAnimations = Property_default.getValueOrDefault(
modelGraphics._runAnimations,
time,
true
);
if (modelData.animationsRunning !== runAnimations) {
if (runAnimations) {
model.activeAnimations.addAll({
loop: ModelAnimationLoop_default.REPEAT
});
} else {
model.activeAnimations.removeAll();
}
modelData.animationsRunning = runAnimations;
}
const nodeTransformations = Property_default.getValueOrUndefined(
modelGraphics._nodeTransformations,
time,
modelData.nodeTransformationsScratch
);
if (defined_default(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_default(nodeTransformation)) {
continue;
}
const modelNode = model.getNode(nodeName);
if (!defined_default(modelNode)) {
continue;
}
const transformationMatrix = Matrix4_default.fromTranslationRotationScale(
nodeTransformation,
nodeMatrixScratch
);
modelNode.matrix = Matrix4_default.multiply(
modelNode.originalMatrix,
transformationMatrix,
transformationMatrix
);
}
}
let anyArticulationUpdated = false;
const articulations = Property_default.getValueOrUndefined(
modelGraphics._articulations,
time,
modelData.articulationsScratch
);
if (defined_default(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_default(articulationStageValue)) {
continue;
}
anyArticulationUpdated = true;
model.setArticulationStage(key, articulationStageValue);
}
}
if (anyArticulationUpdated) {
model.applyArticulations();
}
}
}
return true;
};
ModelVisualizer.prototype.isDestroyed = function() {
return false;
};
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_default(this);
};
ModelVisualizer._sampleTerrainMostDetailed = sampleTerrainMostDetailed_default;
var scratchPosition11 = new Cartesian3_default();
var scratchCartographic11 = new Cartographic_default();
ModelVisualizer.prototype.getBoundingSphere = function(entity, result) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const modelData = this._modelHash[entity.id];
if (!defined_default(modelData)) {
return BoundingSphereState_default.FAILED;
}
if (modelData.loadFailed) {
return BoundingSphereState_default.FAILED;
}
const model = modelData.modelPrimitive;
if (!defined_default(model) || !model.show) {
return BoundingSphereState_default.PENDING;
}
if (!model.ready || !modelData.modelUpdated) {
return BoundingSphereState_default.PENDING;
}
const scene = this._scene;
const globe = scene.globe;
const terrainProvider = defined_default(globe) ? globe.terrainProvider : void 0;
const hasHeightReference = model.heightReference !== HeightReference_default.NONE;
if (defined_default(globe) && hasHeightReference) {
const ellipsoid = globe.ellipsoid;
if (!terrainProvider._ready) {
return BoundingSphereState_default.PENDING;
}
const modelMatrix = model.modelMatrix;
scratchPosition11.x = modelMatrix[12];
scratchPosition11.y = modelMatrix[13];
scratchPosition11.z = modelMatrix[14];
const cartoPosition = ellipsoid.cartesianToCartographic(scratchPosition11);
if (!defined_default(terrainProvider.availability)) {
if (model.heightReference === HeightReference_default.CLAMP_TO_GROUND) {
cartoPosition.height = 0;
}
const scratchPosition17 = ellipsoid.cartographicToCartesian(cartoPosition);
BoundingSphere_default.clone(model.boundingSphere, result);
result.center = scratchPosition17;
return BoundingSphereState_default.DONE;
}
let clampedBoundingSphere = this._modelHash[entity.id].clampedBoundingSphere;
const sampleTerrainFailed = this._modelHash[entity.id].sampleTerrainFailed;
if (sampleTerrainFailed) {
this._modelHash[entity.id].sampleTerrainFailed = false;
return BoundingSphereState_default.FAILED;
}
if (!defined_default(clampedBoundingSphere)) {
clampedBoundingSphere = new BoundingSphere_default();
const awaitingSampleTerrain = this._modelHash[entity.id].awaitingSampleTerrain;
if (!awaitingSampleTerrain) {
Cartographic_default.clone(cartoPosition, scratchCartographic11);
this._modelHash[entity.id].awaitingSampleTerrain = true;
ModelVisualizer._sampleTerrainMostDetailed(terrainProvider, [
scratchCartographic11
]).then((result2) => {
if (this.isDestroyed()) {
return;
}
this._modelHash[entity.id].awaitingSampleTerrain = false;
const updatedCartographic = result2[0];
if (model.heightReference === HeightReference_default.RELATIVE_TO_GROUND) {
updatedCartographic.height += cartoPosition.height;
}
ellipsoid.cartographicToCartesian(
updatedCartographic,
scratchPosition11
);
BoundingSphere_default.clone(model.boundingSphere, clampedBoundingSphere);
clampedBoundingSphere.center = scratchPosition11;
this._modelHash[entity.id].clampedBoundingSphere = BoundingSphere_default.clone(
clampedBoundingSphere
);
}).catch((e) => {
if (this.isDestroyed()) {
return;
}
this._modelHash[entity.id].sampleTerrainFailed = true;
this._modelHash[entity.id].awaitingSampleTerrain = false;
});
}
return BoundingSphereState_default.PENDING;
}
BoundingSphere_default.clone(clampedBoundingSphere, result);
this._modelHash[entity.id].clampedBoundingSphere = void 0;
return BoundingSphereState_default.DONE;
}
BoundingSphere_default.clone(model.boundingSphere, result);
return BoundingSphereState_default.DONE;
};
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_default(entity._model) && defined_default(entity._position)) {
entities.set(entity.id, entity);
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined_default(entity._model) && defined_default(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_default(modelData)) {
primitives.removeAndDestroy(modelData.modelPrimitive);
delete modelHash[entity.id];
}
}
function clearNodeTransformationsArticulationsScratch(entity, modelHash) {
const modelData = modelHash[entity.id];
if (defined_default(modelData)) {
modelData.nodeTransformationsScratch = {};
modelData.articulationsScratch = {};
}
}
var ModelVisualizer_default = ModelVisualizer;
// node_modules/@cesium/engine/Source/DataSources/ScaledPositionProperty.js
function ScaledPositionProperty(value) {
this._definitionChanged = new Event_default();
this._value = void 0;
this._removeSubscription = void 0;
this.setValue(value);
}
Object.defineProperties(ScaledPositionProperty.prototype, {
isConstant: {
get: function() {
return Property_default.isConstant(this._value);
}
},
definitionChanged: {
get: function() {
return this._definitionChanged;
}
},
referenceFrame: {
get: function() {
return defined_default(this._value) ? this._value.referenceFrame : ReferenceFrame_default.FIXED;
}
}
});
ScaledPositionProperty.prototype.getValue = function(time, result) {
return this.getValueInReferenceFrame(time, ReferenceFrame_default.FIXED, result);
};
ScaledPositionProperty.prototype.setValue = function(value) {
if (this._value !== value) {
this._value = value;
if (defined_default(this._removeSubscription)) {
this._removeSubscription();
this._removeSubscription = void 0;
}
if (defined_default(value)) {
this._removeSubscription = value.definitionChanged.addEventListener(
this._raiseDefinitionChanged,
this
);
}
this._definitionChanged.raiseEvent(this);
}
};
ScaledPositionProperty.prototype.getValueInReferenceFrame = function(time, referenceFrame, result) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!defined_default(referenceFrame)) {
throw new DeveloperError_default("referenceFrame is required.");
}
if (!defined_default(this._value)) {
return void 0;
}
result = this._value.getValueInReferenceFrame(time, referenceFrame, result);
return defined_default(result) ? Ellipsoid_default.WGS84.scaleToGeodeticSurface(result, result) : void 0;
};
ScaledPositionProperty.prototype.equals = function(other) {
return this === other || other instanceof ScaledPositionProperty && this._value === other._value;
};
ScaledPositionProperty.prototype._raiseDefinitionChanged = function() {
this._definitionChanged.raiseEvent(this);
};
var ScaledPositionProperty_default = ScaledPositionProperty;
// node_modules/@cesium/engine/Source/DataSources/PathVisualizer.js
var defaultResolution = 60;
var defaultWidth = 1;
var scratchTimeInterval2 = new TimeInterval_default();
var subSampleCompositePropertyScratch = new TimeInterval_default();
var subSampleIntervalPropertyScratch = new TimeInterval_default();
function EntityData3(entity) {
this.entity = entity;
this.polyline = void 0;
this.index = void 0;
this.updater = void 0;
}
function subSampleSampledProperty(property, start, stop2, times, updateTime, referenceFrame, maximumStep, startingIndex, result) {
let r = startingIndex;
let tmp2;
tmp2 = property.getValueInReferenceFrame(start, referenceFrame, result[r]);
if (defined_default(tmp2)) {
result[r++] = tmp2;
}
let steppedOnNow = !defined_default(updateTime) || JulianDate_default.lessThanOrEquals(updateTime, start) || JulianDate_default.greaterThanOrEquals(updateTime, stop2);
let t = 0;
const len = times.length;
let current = times[t];
const loopStop = stop2;
let sampling = false;
let sampleStepsToTake;
let sampleStepsTaken;
let sampleStepSize;
while (t < len) {
if (!steppedOnNow && JulianDate_default.greaterThanOrEquals(current, updateTime)) {
tmp2 = property.getValueInReferenceFrame(
updateTime,
referenceFrame,
result[r]
);
if (defined_default(tmp2)) {
result[r++] = tmp2;
}
steppedOnNow = true;
}
if (JulianDate_default.greaterThan(current, start) && JulianDate_default.lessThan(current, loopStop) && !current.equals(updateTime)) {
tmp2 = property.getValueInReferenceFrame(
current,
referenceFrame,
result[r]
);
if (defined_default(tmp2)) {
result[r++] = tmp2;
}
}
if (t < len - 1) {
if (maximumStep > 0 && !sampling) {
const next = times[t + 1];
const secondsUntilNext = JulianDate_default.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_default.addSeconds(
current,
sampleStepSize,
new JulianDate_default()
);
sampleStepsTaken++;
continue;
}
}
sampling = false;
t++;
current = times[t];
}
tmp2 = property.getValueInReferenceFrame(stop2, referenceFrame, result[r]);
if (defined_default(tmp2)) {
result[r++] = tmp2;
}
return r;
}
function subSampleGenericProperty(property, start, stop2, updateTime, referenceFrame, maximumStep, startingIndex, result) {
let tmp2;
let i = 0;
let index = startingIndex;
let time = start;
const stepSize = Math.max(maximumStep, 60);
let steppedOnNow = !defined_default(updateTime) || JulianDate_default.lessThanOrEquals(updateTime, start) || JulianDate_default.greaterThanOrEquals(updateTime, stop2);
while (JulianDate_default.lessThan(time, stop2)) {
if (!steppedOnNow && JulianDate_default.greaterThanOrEquals(time, updateTime)) {
steppedOnNow = true;
tmp2 = property.getValueInReferenceFrame(
updateTime,
referenceFrame,
result[index]
);
if (defined_default(tmp2)) {
result[index] = tmp2;
index++;
}
}
tmp2 = property.getValueInReferenceFrame(
time,
referenceFrame,
result[index]
);
if (defined_default(tmp2)) {
result[index] = tmp2;
index++;
}
i++;
time = JulianDate_default.addSeconds(start, stepSize * i, new JulianDate_default());
}
tmp2 = property.getValueInReferenceFrame(stop2, referenceFrame, result[index]);
if (defined_default(tmp2)) {
result[index] = tmp2;
index++;
}
return index;
}
function subSampleIntervalProperty(property, start, stop2, updateTime, referenceFrame, maximumStep, startingIndex, result) {
subSampleIntervalPropertyScratch.start = start;
subSampleIntervalPropertyScratch.stop = stop2;
let index = startingIndex;
const intervals = property.intervals;
for (let i = 0; i < intervals.length; i++) {
const interval = intervals.get(i);
if (!TimeInterval_default.intersect(
interval,
subSampleIntervalPropertyScratch,
scratchTimeInterval2
).isEmpty) {
let time = interval.start;
if (!interval.isStartIncluded) {
if (interval.isStopIncluded) {
time = interval.stop;
} else {
time = JulianDate_default.addSeconds(
interval.start,
JulianDate_default.secondsDifference(interval.stop, interval.start) / 2,
new JulianDate_default()
);
}
}
const tmp2 = property.getValueInReferenceFrame(
time,
referenceFrame,
result[index]
);
if (defined_default(tmp2)) {
result[index] = tmp2;
index++;
}
}
}
return index;
}
function subSampleConstantProperty(property, start, stop2, updateTime, referenceFrame, maximumStep, startingIndex, result) {
const tmp2 = property.getValueInReferenceFrame(
start,
referenceFrame,
result[startingIndex]
);
if (defined_default(tmp2)) {
result[startingIndex++] = tmp2;
}
return startingIndex;
}
function subSampleCompositeProperty(property, start, stop2, updateTime, referenceFrame, maximumStep, startingIndex, result) {
subSampleCompositePropertyScratch.start = start;
subSampleCompositePropertyScratch.stop = stop2;
let index = startingIndex;
const intervals = property.intervals;
for (let i = 0; i < intervals.length; i++) {
const interval = intervals.get(i);
if (!TimeInterval_default.intersect(
interval,
subSampleCompositePropertyScratch,
scratchTimeInterval2
).isEmpty) {
const intervalStart = interval.start;
const intervalStop = interval.stop;
let sampleStart = start;
if (JulianDate_default.greaterThan(intervalStart, sampleStart)) {
sampleStart = intervalStart;
}
let sampleStop = stop2;
if (JulianDate_default.lessThan(intervalStop, sampleStop)) {
sampleStop = intervalStop;
}
index = reallySubSample(
interval.data,
sampleStart,
sampleStop,
updateTime,
referenceFrame,
maximumStep,
index,
result
);
}
}
return index;
}
function reallySubSample(property, start, stop2, updateTime, referenceFrame, maximumStep, index, result) {
while (property instanceof ReferenceProperty_default) {
property = property.resolvedProperty;
}
if (property instanceof SampledPositionProperty_default) {
const times = property._property._times;
index = subSampleSampledProperty(
property,
start,
stop2,
times,
updateTime,
referenceFrame,
maximumStep,
index,
result
);
} else if (property instanceof CompositePositionProperty_default) {
index = subSampleCompositeProperty(
property,
start,
stop2,
updateTime,
referenceFrame,
maximumStep,
index,
result
);
} else if (property instanceof TimeIntervalCollectionPositionProperty_default) {
index = subSampleIntervalProperty(
property,
start,
stop2,
updateTime,
referenceFrame,
maximumStep,
index,
result
);
} else if (property instanceof ConstantPositionProperty_default || property instanceof ScaledPositionProperty_default && Property_default.isConstant(property)) {
index = subSampleConstantProperty(
property,
start,
stop2,
updateTime,
referenceFrame,
maximumStep,
index,
result
);
} else {
index = subSampleGenericProperty(
property,
start,
stop2,
updateTime,
referenceFrame,
maximumStep,
index,
result
);
}
return index;
}
function subSample(property, start, stop2, updateTime, referenceFrame, maximumStep, result) {
if (!defined_default(result)) {
result = [];
}
const length3 = reallySubSample(
property,
start,
stop2,
updateTime,
referenceFrame,
maximumStep,
0,
result
);
result.length = length3;
return result;
}
var toFixedScratch = new Matrix3_default();
function PolylineUpdater(scene, referenceFrame) {
this._unusedIndexes = [];
this._polylineCollection = new PolylineCollection_default();
this._scene = scene;
this._referenceFrame = referenceFrame;
scene.primitives.add(this._polylineCollection);
}
PolylineUpdater.prototype.update = function(time) {
if (this._referenceFrame === ReferenceFrame_default.INERTIAL) {
let toFixed = Transforms_default.computeIcrfToFixedMatrix(time, toFixedScratch);
if (!defined_default(toFixed)) {
toFixed = Transforms_default.computeTemeToPseudoFixedMatrix(time, toFixedScratch);
}
Matrix4_default.fromRotationTranslation(
toFixed,
Cartesian3_default.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_default(showProperty) || showProperty.getValue(time));
if (show) {
const leadTime = Property_default.getValueOrUndefined(pathGraphics._leadTime, time);
const trailTime = Property_default.getValueOrUndefined(
pathGraphics._trailTime,
time
);
const availability = entity._availability;
const hasAvailability = defined_default(availability);
const hasLeadTime = defined_default(leadTime);
const hasTrailTime = defined_default(trailTime);
show = hasAvailability || hasLeadTime && hasTrailTime;
if (show) {
if (hasTrailTime) {
sampleStart = JulianDate_default.addSeconds(time, -trailTime, new JulianDate_default());
}
if (hasLeadTime) {
sampleStop = JulianDate_default.addSeconds(time, leadTime, new JulianDate_default());
}
if (hasAvailability) {
const start = availability.start;
const stop2 = availability.stop;
if (!hasTrailTime || JulianDate_default.greaterThan(start, sampleStart)) {
sampleStart = start;
}
if (!hasLeadTime || JulianDate_default.lessThan(stop2, sampleStop)) {
sampleStop = stop2;
}
}
show = JulianDate_default.lessThan(sampleStart, sampleStop);
}
}
if (!show) {
if (defined_default(polyline)) {
this._unusedIndexes.push(item.index);
item.polyline = void 0;
polyline.show = false;
item.index = void 0;
}
return;
}
if (!defined_default(polyline)) {
const unusedIndexes = this._unusedIndexes;
const length3 = unusedIndexes.length;
if (length3 > 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_default.getValueOrDefault(
pathGraphics._resolution,
time,
defaultResolution
);
polyline.show = true;
polyline.positions = subSample(
positionProperty,
sampleStart,
sampleStop,
time,
this._referenceFrame,
resolution,
polyline.positions.slice()
);
polyline.material = MaterialProperty_default.getValue(
time,
pathGraphics._material,
polyline.material
);
polyline.width = Property_default.getValueOrDefault(
pathGraphics._width,
time,
defaultWidth
);
polyline.distanceDisplayCondition = Property_default.getValueOrUndefined(
pathGraphics._distanceDisplayCondition,
time,
polyline.distanceDisplayCondition
);
};
PolylineUpdater.prototype.removeObject = function(item) {
const polyline = item.polyline;
if (defined_default(polyline)) {
this._unusedIndexes.push(item.index);
item.polyline = void 0;
polyline.show = false;
polyline.id = void 0;
item.index = void 0;
}
};
PolylineUpdater.prototype.destroy = function() {
this._scene.primitives.remove(this._polylineCollection);
return destroyObject_default(this);
};
function PathVisualizer(scene, entityCollection) {
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required.");
}
if (!defined_default(entityCollection)) {
throw new DeveloperError_default("entityCollection is required.");
}
entityCollection.collectionChanged.addEventListener(
PathVisualizer.prototype._onCollectionChanged,
this
);
this._scene = scene;
this._updaters = {};
this._entityCollection = entityCollection;
this._items = new AssociativeArray_default();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
PathVisualizer.prototype.update = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
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_default(this._updaters) && Object.keys(this._updaters).length > 0) {
for (const u3 in updaters) {
if (updaters.hasOwnProperty(u3)) {
updaters[u3].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_default.FIXED;
if (this._scene.mode === SceneMode_default.SCENE3D) {
frameToVisualize = positionProperty.referenceFrame;
}
let currentUpdater = this._updaters[frameToVisualize];
if (lastUpdater === currentUpdater && defined_default(currentUpdater)) {
currentUpdater.updateObject(time, item);
continue;
}
if (defined_default(lastUpdater)) {
lastUpdater.removeObject(item);
}
if (!defined_default(currentUpdater)) {
currentUpdater = new PolylineUpdater(this._scene, frameToVisualize);
currentUpdater.update(time);
this._updaters[frameToVisualize] = currentUpdater;
}
item.updater = currentUpdater;
if (defined_default(currentUpdater)) {
currentUpdater.updateObject(time, item);
}
}
return true;
};
PathVisualizer.prototype.isDestroyed = function() {
return false;
};
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_default(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_default(entity._path) && defined_default(entity._position)) {
items.set(entity.id, new EntityData3(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined_default(entity._path) && defined_default(entity._position)) {
if (!items.contains(entity.id)) {
items.set(entity.id, new EntityData3(entity));
}
} else {
item = items.get(entity.id);
if (defined_default(item)) {
if (defined_default(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_default(item)) {
if (defined_default(item.updater)) {
item.updater.removeObject(item);
}
items.remove(entity.id);
}
}
};
PathVisualizer._subSample = subSample;
var PathVisualizer_default = PathVisualizer;
// node_modules/@cesium/engine/Source/DataSources/PointVisualizer.js
var defaultColor8 = Color_default.WHITE;
var defaultOutlineColor4 = Color_default.BLACK;
var defaultOutlineWidth3 = 0;
var defaultPixelSize = 1;
var defaultDisableDepthTestDistance = 0;
var colorScratch6 = new Color_default();
var positionScratch14 = new Cartesian3_default();
var outlineColorScratch2 = new Color_default();
var scaleByDistanceScratch3 = new NearFarScalar_default();
var translucencyByDistanceScratch3 = new NearFarScalar_default();
var distanceDisplayConditionScratch8 = new DistanceDisplayCondition_default();
function EntityData4(entity) {
this.entity = entity;
this.pointPrimitive = void 0;
this.billboard = void 0;
this.color = void 0;
this.outlineColor = void 0;
this.pixelSize = void 0;
this.outlineWidth = void 0;
}
function PointVisualizer(entityCluster, entityCollection) {
if (!defined_default(entityCluster)) {
throw new DeveloperError_default("entityCluster is required.");
}
if (!defined_default(entityCollection)) {
throw new DeveloperError_default("entityCollection is required.");
}
entityCollection.collectionChanged.addEventListener(
PointVisualizer.prototype._onCollectionChanged,
this
);
this._cluster = entityCluster;
this._entityCollection = entityCollection;
this._items = new AssociativeArray_default();
this._onCollectionChanged(entityCollection, entityCollection.values, [], []);
}
PointVisualizer.prototype.update = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
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_default.getValueOrDefault(
pointGraphics._heightReference,
time,
HeightReference_default.NONE
);
let show = entity.isShowing && entity.isAvailable(time) && Property_default.getValueOrDefault(pointGraphics._show, time, true);
let position;
if (show) {
position = Property_default.getValueOrUndefined(
entity._position,
time,
positionScratch14
);
show = defined_default(position);
}
if (!show) {
returnPrimitive3(item, entity, cluster);
continue;
}
if (!Property_default.isConstant(entity._position)) {
cluster._clusterDirty = true;
}
let needsRedraw = false;
let updateClamping2 = false;
if (heightReference !== HeightReference_default.NONE && !defined_default(billboard)) {
if (defined_default(pointPrimitive)) {
returnPrimitive3(item, entity, cluster);
pointPrimitive = void 0;
}
billboard = cluster.getBillboard(entity);
billboard.id = entity;
billboard.image = void 0;
item.billboard = billboard;
needsRedraw = true;
updateClamping2 = Cartesian3_default.equals(billboard.position, position) && billboard.heightReference === heightReference;
} else if (heightReference === HeightReference_default.NONE && !defined_default(pointPrimitive)) {
if (defined_default(billboard)) {
returnPrimitive3(item, entity, cluster);
billboard = void 0;
}
pointPrimitive = cluster.getPoint(entity);
pointPrimitive.id = entity;
item.pointPrimitive = pointPrimitive;
}
if (defined_default(pointPrimitive)) {
pointPrimitive.show = true;
pointPrimitive.position = position;
pointPrimitive.scaleByDistance = Property_default.getValueOrUndefined(
pointGraphics._scaleByDistance,
time,
scaleByDistanceScratch3
);
pointPrimitive.translucencyByDistance = Property_default.getValueOrUndefined(
pointGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch3
);
pointPrimitive.color = Property_default.getValueOrDefault(
pointGraphics._color,
time,
defaultColor8,
colorScratch6
);
pointPrimitive.outlineColor = Property_default.getValueOrDefault(
pointGraphics._outlineColor,
time,
defaultOutlineColor4,
outlineColorScratch2
);
pointPrimitive.outlineWidth = Property_default.getValueOrDefault(
pointGraphics._outlineWidth,
time,
defaultOutlineWidth3
);
pointPrimitive.pixelSize = Property_default.getValueOrDefault(
pointGraphics._pixelSize,
time,
defaultPixelSize
);
pointPrimitive.distanceDisplayCondition = Property_default.getValueOrUndefined(
pointGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch8
);
pointPrimitive.disableDepthTestDistance = Property_default.getValueOrDefault(
pointGraphics._disableDepthTestDistance,
time,
defaultDisableDepthTestDistance
);
} else if (defined_default(billboard)) {
billboard.show = true;
billboard.position = position;
billboard.scaleByDistance = Property_default.getValueOrUndefined(
pointGraphics._scaleByDistance,
time,
scaleByDistanceScratch3
);
billboard.translucencyByDistance = Property_default.getValueOrUndefined(
pointGraphics._translucencyByDistance,
time,
translucencyByDistanceScratch3
);
billboard.distanceDisplayCondition = Property_default.getValueOrUndefined(
pointGraphics._distanceDisplayCondition,
time,
distanceDisplayConditionScratch8
);
billboard.disableDepthTestDistance = Property_default.getValueOrDefault(
pointGraphics._disableDepthTestDistance,
time,
defaultDisableDepthTestDistance
);
billboard.heightReference = heightReference;
const newColor = Property_default.getValueOrDefault(
pointGraphics._color,
time,
defaultColor8,
colorScratch6
);
const newOutlineColor = Property_default.getValueOrDefault(
pointGraphics._outlineColor,
time,
defaultOutlineColor4,
outlineColorScratch2
);
const newOutlineWidth = Math.round(
Property_default.getValueOrDefault(
pointGraphics._outlineWidth,
time,
defaultOutlineWidth3
)
);
let newPixelSize = Math.max(
1,
Math.round(
Property_default.getValueOrDefault(
pointGraphics._pixelSize,
time,
defaultPixelSize
)
)
);
if (newOutlineWidth > 0) {
billboard.scale = 1;
needsRedraw = needsRedraw || newOutlineWidth !== item.outlineWidth || newPixelSize !== item.pixelSize || !Color_default.equals(newColor, item.color) || !Color_default.equals(newOutlineColor, item.outlineColor);
} else {
billboard.scale = newPixelSize / 50;
newPixelSize = 50;
needsRedraw = needsRedraw || newOutlineWidth !== item.outlineWidth || !Color_default.equals(newColor, item.color) || !Color_default.equals(newOutlineColor, item.outlineColor);
}
if (needsRedraw) {
item.color = Color_default.clone(newColor, item.color);
item.outlineColor = Color_default.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_default(
centerAlpha,
cssColor,
cssOutlineColor,
newOutlineWidth,
newPixelSize
)
);
}
if (updateClamping2) {
billboard._updateClamping();
}
}
}
return true;
};
PointVisualizer.prototype.getBoundingSphere = function(entity, result) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required.");
}
if (!defined_default(result)) {
throw new DeveloperError_default("result is required.");
}
const item = this._items.get(entity.id);
if (!defined_default(item) || !(defined_default(item.pointPrimitive) || defined_default(item.billboard))) {
return BoundingSphereState_default.FAILED;
}
if (defined_default(item.pointPrimitive)) {
result.center = Cartesian3_default.clone(
item.pointPrimitive.position,
result.center
);
} else {
const billboard = item.billboard;
if (!defined_default(billboard._clampedPosition)) {
return BoundingSphereState_default.PENDING;
}
result.center = Cartesian3_default.clone(billboard._clampedPosition, result.center);
}
result.radius = 0;
return BoundingSphereState_default.DONE;
};
PointVisualizer.prototype.isDestroyed = function() {
return false;
};
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_default(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_default(entity._point) && defined_default(entity._position)) {
items.set(entity.id, new EntityData4(entity));
}
}
for (i = changed.length - 1; i > -1; i--) {
entity = changed[i];
if (defined_default(entity._point) && defined_default(entity._position)) {
if (!items.contains(entity.id)) {
items.set(entity.id, new EntityData4(entity));
}
} else {
returnPrimitive3(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
}
for (i = removed.length - 1; i > -1; i--) {
entity = removed[i];
returnPrimitive3(items.get(entity.id), entity, cluster);
items.remove(entity.id);
}
};
function returnPrimitive3(item, entity, cluster) {
if (defined_default(item)) {
const pointPrimitive = item.pointPrimitive;
if (defined_default(pointPrimitive)) {
item.pointPrimitive = void 0;
cluster.removePoint(entity);
return;
}
const billboard = item.billboard;
if (defined_default(billboard)) {
item.billboard = void 0;
cluster.removeBillboard(entity);
}
}
}
var PointVisualizer_default = PointVisualizer;
// node_modules/@cesium/engine/Source/Core/PolylineGeometry.js
var scratchInterpolateColorsArray = [];
function interpolateColors(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_default.equals(color0, color1)) {
for (i = 0; i < numPoints; i++) {
colors[i] = Color_default.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_default(
r0 + i * redPerVertex,
g0 + i * greenPerVertex,
b0 + i * bluePerVertex,
a0 + i * alphaPerVertex
);
}
return colors;
}
function PolylineGeometry(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const positions = options.positions;
const colors = options.colors;
const width = defaultValue_default(options.width, 1);
const colorsPerVertex = defaultValue_default(options.colorsPerVertex, false);
if (!defined_default(positions) || positions.length < 2) {
throw new DeveloperError_default("At least two positions are required.");
}
if (typeof width !== "number") {
throw new DeveloperError_default("width must be a number");
}
if (defined_default(colors) && (colorsPerVertex && colors.length < positions.length || !colorsPerVertex && colors.length < positions.length - 1)) {
throw new DeveloperError_default("colors has an invalid length.");
}
this._positions = positions;
this._colors = colors;
this._width = width;
this._colorsPerVertex = colorsPerVertex;
this._vertexFormat = VertexFormat_default.clone(
defaultValue_default(options.vertexFormat, VertexFormat_default.DEFAULT)
);
this._arcType = defaultValue_default(options.arcType, ArcType_default.GEODESIC);
this._granularity = defaultValue_default(
options.granularity,
Math_default.RADIANS_PER_DEGREE
);
this._ellipsoid = Ellipsoid_default.clone(
defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
);
this._workerName = "createPolylineGeometry";
let numComponents = 1 + positions.length * Cartesian3_default.packedLength;
numComponents += defined_default(colors) ? 1 + colors.length * Color_default.packedLength : 1;
this.packedLength = numComponents + Ellipsoid_default.packedLength + VertexFormat_default.packedLength + 4;
}
PolylineGeometry.pack = function(value, array, startingIndex) {
if (!defined_default(value)) {
throw new DeveloperError_default("value is required");
}
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
const positions = value._positions;
let length3 = positions.length;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
Cartesian3_default.pack(positions[i], array, startingIndex);
}
const colors = value._colors;
length3 = defined_default(colors) ? colors.length : 0;
array[startingIndex++] = length3;
for (i = 0; i < length3; ++i, startingIndex += Color_default.packedLength) {
Color_default.pack(colors[i], array, startingIndex);
}
Ellipsoid_default.pack(value._ellipsoid, array, startingIndex);
startingIndex += Ellipsoid_default.packedLength;
VertexFormat_default.pack(value._vertexFormat, array, startingIndex);
startingIndex += VertexFormat_default.packedLength;
array[startingIndex++] = value._width;
array[startingIndex++] = value._colorsPerVertex ? 1 : 0;
array[startingIndex++] = value._arcType;
array[startingIndex] = value._granularity;
return array;
};
var scratchEllipsoid14 = Ellipsoid_default.clone(Ellipsoid_default.UNIT_SPHERE);
var scratchVertexFormat12 = new VertexFormat_default();
var scratchOptions21 = {
positions: void 0,
colors: void 0,
ellipsoid: scratchEllipsoid14,
vertexFormat: scratchVertexFormat12,
width: void 0,
colorsPerVertex: void 0,
arcType: void 0,
granularity: void 0
};
PolylineGeometry.unpack = function(array, startingIndex, result) {
if (!defined_default(array)) {
throw new DeveloperError_default("array is required");
}
startingIndex = defaultValue_default(startingIndex, 0);
let i;
let length3 = array[startingIndex++];
const positions = new Array(length3);
for (i = 0; i < length3; ++i, startingIndex += Cartesian3_default.packedLength) {
positions[i] = Cartesian3_default.unpack(array, startingIndex);
}
length3 = array[startingIndex++];
const colors = length3 > 0 ? new Array(length3) : void 0;
for (i = 0; i < length3; ++i, startingIndex += Color_default.packedLength) {
colors[i] = Color_default.unpack(array, startingIndex);
}
const ellipsoid = Ellipsoid_default.unpack(array, startingIndex, scratchEllipsoid14);
startingIndex += Ellipsoid_default.packedLength;
const vertexFormat = VertexFormat_default.unpack(
array,
startingIndex,
scratchVertexFormat12
);
startingIndex += VertexFormat_default.packedLength;
const width = array[startingIndex++];
const colorsPerVertex = array[startingIndex++] === 1;
const arcType = array[startingIndex++];
const granularity = array[startingIndex];
if (!defined_default(result)) {
scratchOptions21.positions = positions;
scratchOptions21.colors = colors;
scratchOptions21.width = width;
scratchOptions21.colorsPerVertex = colorsPerVertex;
scratchOptions21.arcType = arcType;
scratchOptions21.granularity = granularity;
return new PolylineGeometry(scratchOptions21);
}
result._positions = positions;
result._colors = colors;
result._ellipsoid = Ellipsoid_default.clone(ellipsoid, result._ellipsoid);
result._vertexFormat = VertexFormat_default.clone(vertexFormat, result._vertexFormat);
result._width = width;
result._colorsPerVertex = colorsPerVertex;
result._arcType = arcType;
result._granularity = granularity;
return result;
};
var scratchCartesian39 = new Cartesian3_default();
var scratchPosition12 = new Cartesian3_default();
var scratchPrevPosition = new Cartesian3_default();
var scratchNextPosition = new Cartesian3_default();
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_default(
polylineGeometry._positions,
Cartesian3_default.equalsEpsilon,
false,
removedIndices
);
if (defined_default(colors) && removedIndices.length > 0) {
let removedArrayIndex = 0;
let nextRemovedIndex = removedIndices[0];
colors = colors.filter(function(color, index2) {
let remove5 = false;
if (colorsPerVertex) {
remove5 = index2 === nextRemovedIndex || index2 === 0 && nextRemovedIndex === 1;
} else {
remove5 = index2 + 1 === nextRemovedIndex;
}
if (remove5) {
removedArrayIndex++;
nextRemovedIndex = removedIndices[removedArrayIndex];
return false;
}
return true;
});
}
let positionsLength = positions.length;
if (positionsLength < 2 || width <= 0) {
return void 0;
}
if (arcType === ArcType_default.GEODESIC || arcType === ArcType_default.RHUMB) {
let subdivisionSize;
let numberOfPointsFunction;
if (arcType === ArcType_default.GEODESIC) {
subdivisionSize = Math_default.chordLength(
granularity,
ellipsoid.maximumRadius
);
numberOfPointsFunction = PolylinePipeline_default.numberOfPoints;
} else {
subdivisionSize = granularity;
numberOfPointsFunction = PolylinePipeline_default.numberOfPointsRhumbLine;
}
const heights = PolylinePipeline_default.extractHeights(positions, ellipsoid);
if (defined_default(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 c14 = colors[i + 1];
const interpolatedColors = interpolateColors(
p0,
p1,
c0,
c14,
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_default.clone(c0);
}
}
}
newColors[newColorIndex] = Color_default.clone(colors[colors.length - 1]);
colors = newColors;
scratchInterpolateColorsArray.length = 0;
}
if (arcType === ArcType_default.GEODESIC) {
positions = PolylinePipeline_default.generateCartesianArc({
positions,
minDistance: subdivisionSize,
ellipsoid,
height: heights
});
} else {
positions = PolylinePipeline_default.generateCartesianRhumbArc({
positions,
granularity: subdivisionSize,
ellipsoid,
height: heights
});
}
}
positionsLength = positions.length;
const size = positionsLength * 4 - 4;
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) : void 0;
const finalColors = defined_default(colors) ? new Uint8Array(size * 4) : void 0;
let positionIndex = 0;
let expandAndWidthIndex = 0;
let stIndex = 0;
let colorIndex = 0;
let position;
for (j = 0; j < positionsLength; ++j) {
if (j === 0) {
position = scratchCartesian39;
Cartesian3_default.subtract(positions[0], positions[1], position);
Cartesian3_default.add(positions[0], position, position);
} else {
position = positions[j - 1];
}
Cartesian3_default.clone(position, scratchPrevPosition);
Cartesian3_default.clone(positions[j], scratchPosition12);
if (j === positionsLength - 1) {
position = scratchCartesian39;
Cartesian3_default.subtract(
positions[positionsLength - 1],
positions[positionsLength - 2],
position
);
Cartesian3_default.add(positions[positionsLength - 1], position, position);
} else {
position = positions[j + 1];
}
Cartesian3_default.clone(position, scratchNextPosition);
let color0, color1;
if (defined_default(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_default.pack(scratchPosition12, finalPositions, positionIndex);
Cartesian3_default.pack(scratchPrevPosition, prevPositions, positionIndex);
Cartesian3_default.pack(scratchNextPosition, nextPositions, positionIndex);
positionIndex += 3;
const direction2 = k - 2 < 0 ? -1 : 1;
expandAndWidth[expandAndWidthIndex++] = 2 * (k % 2) - 1;
expandAndWidth[expandAndWidthIndex++] = direction2 * width;
if (vertexFormat.st) {
st[stIndex++] = j / (positionsLength - 1);
st[stIndex++] = Math.max(expandAndWidth[expandAndWidthIndex - 2], 0);
}
if (defined_default(finalColors)) {
const color = k < 2 ? color0 : color1;
finalColors[colorIndex++] = Color_default.floatToByte(color.red);
finalColors[colorIndex++] = Color_default.floatToByte(color.green);
finalColors[colorIndex++] = Color_default.floatToByte(color.blue);
finalColors[colorIndex++] = Color_default.floatToByte(color.alpha);
}
}
}
const attributes = new GeometryAttributes_default();
attributes.position = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: finalPositions
});
attributes.prevPosition = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: prevPositions
});
attributes.nextPosition = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.DOUBLE,
componentsPerAttribute: 3,
values: nextPositions
});
attributes.expandAndWidth = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: expandAndWidth
});
if (vertexFormat.st) {
attributes.st = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.FLOAT,
componentsPerAttribute: 2,
values: st
});
}
if (defined_default(finalColors)) {
attributes.color = new GeometryAttribute_default({
componentDatatype: ComponentDatatype_default.UNSIGNED_BYTE,
componentsPerAttribute: 4,
values: finalColors,
normalize: true
});
}
const indices2 = IndexDatatype_default.createTypedArray(size, positionsLength * 6 - 6);
let index = 0;
let indicesIndex = 0;
const length3 = positionsLength - 1;
for (j = 0; j < length3; ++j) {
indices2[indicesIndex++] = index;
indices2[indicesIndex++] = index + 2;
indices2[indicesIndex++] = index + 1;
indices2[indicesIndex++] = index + 1;
indices2[indicesIndex++] = index + 2;
indices2[indicesIndex++] = index + 3;
index += 4;
}
return new Geometry_default({
attributes,
indices: indices2,
primitiveType: PrimitiveType_default.TRIANGLES,
boundingSphere: BoundingSphere_default.fromPoints(positions),
geometryType: GeometryType_default.POLYLINES
});
};
var PolylineGeometry_default = PolylineGeometry;
// node_modules/@cesium/engine/Source/DataSources/PolylineGeometryUpdater.js
var defaultZIndex2 = new ConstantProperty_default(0);
var polylineCollections = {};
var scratchColor21 = new Color_default();
var defaultMaterial3 = new ColorMaterialProperty_default(Color_default.WHITE);
var defaultShow2 = new ConstantProperty_default(true);
var defaultShadows3 = new ConstantProperty_default(ShadowMode_default.DISABLED);
var defaultDistanceDisplayCondition7 = new ConstantProperty_default(
new DistanceDisplayCondition_default()
);
var defaultClassificationType2 = new ConstantProperty_default(ClassificationType_default.BOTH);
function GeometryOptions() {
this.vertexFormat = void 0;
this.positions = void 0;
this.width = void 0;
this.arcType = void 0;
this.granularity = void 0;
}
function GroundGeometryOptions() {
this.positions = void 0;
this.width = void 0;
this.arcType = void 0;
this.granularity = void 0;
}
function PolylineGeometryUpdater(entity, scene) {
if (!defined_default(entity)) {
throw new DeveloperError_default("entity is required");
}
if (!defined_default(scene)) {
throw new DeveloperError_default("scene is required");
}
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_default();
this._showProperty = void 0;
this._materialProperty = void 0;
this._shadowsProperty = void 0;
this._distanceDisplayConditionProperty = void 0;
this._classificationTypeProperty = void 0;
this._depthFailMaterialProperty = void 0;
this._geometryOptions = new GeometryOptions();
this._groundGeometryOptions = new GroundGeometryOptions();
this._id = `polyline-${entity.id}`;
this._clampToGround = false;
this._supportsPolylinesOnTerrain = Entity_default.supportsPolylinesOnTerrain(scene);
this._zIndex = 0;
this._onEntityPropertyChanged(entity, "polyline", entity.polyline, void 0);
}
Object.defineProperties(PolylineGeometryUpdater.prototype, {
id: {
get: function() {
return this._id;
}
},
entity: {
get: function() {
return this._entity;
}
},
fillEnabled: {
get: function() {
return this._fillEnabled;
}
},
hasConstantFill: {
get: function() {
return !this._fillEnabled || !defined_default(this._entity.availability) && Property_default.isConstant(this._showProperty);
}
},
fillMaterialProperty: {
get: function() {
return this._materialProperty;
}
},
depthFailMaterialProperty: {
get: function() {
return this._depthFailMaterialProperty;
}
},
outlineEnabled: {
value: false
},
hasConstantOutline: {
value: true
},
outlineColorProperty: {
value: void 0
},
shadowsProperty: {
get: function() {
return this._shadowsProperty;
}
},
distanceDisplayConditionProperty: {
get: function() {
return this._distanceDisplayConditionProperty;
}
},
classificationTypeProperty: {
get: function() {
return this._classificationTypeProperty;
}
},
isDynamic: {
get: function() {
return this._dynamic;
}
},
isClosed: {
value: false
},
geometryChanged: {
get: function() {
return this._geometryChanged;
}
},
arcType: {
get: function() {
return this._arcType;
}
},
clampToGround: {
get: function() {
return this._clampToGround && this._supportsPolylinesOnTerrain;
}
},
zIndex: {
get: function() {
return this._zIndex;
}
}
});
PolylineGeometryUpdater.prototype.isOutlineVisible = function(time) {
return false;
};
PolylineGeometryUpdater.prototype.isFilled = function(time) {
const entity = this._entity;
const visible = this._fillEnabled && entity.isAvailable(time) && this._showProperty.getValue(time);
return defaultValue_default(visible, false);
};
PolylineGeometryUpdater.prototype.createFillGeometryInstance = function(time) {
if (!defined_default(time)) {
throw new DeveloperError_default("time is required.");
}
if (!this._fillEnabled) {
throw new DeveloperError_default(
"This instance does not represent a filled geometry."
);
}
const entity = this._entity;
const isAvailable = entity.isAvailable(time);
const show = new ShowGeometryInstanceAttribute_default(
isAvailable && entity.isShowing && this._showProperty.getValue(time)
);
const distanceDisplayCondition = this._distanceDisplayConditionProperty.getValue(
time
);
const distanceDisplayConditionAttribute = DistanceDisplayConditionGeometryInstanceAttribute_default.fromDistanceDisplayCondition(
distanceDisplayCondition
);
const attributes = {
show,
distanceDisplayCondition: distanceDisplayConditionAttribute
};
let currentColor;
if (this._materialProperty instanceof ColorMaterialProperty_default) {
if (defined_default(this._materialProperty.color) && (this._materialProperty.color.isConstant || isAvailable)) {
currentColor = this._materialProperty.color.getValue(time, scratchColor21);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.color = ColorGeometryInstanceAttribute_default.fromColor(currentColor);
}
if (this.clampToGround) {
return new GeometryInstance_default({
id: entity,
geometry: new GroundPolylineGeometry_default(this._groundGeometryOptions),
attributes
});
}
if (defined_default(this._depthFailMaterialProperty) && this._depthFailMaterialProperty instanceof ColorMaterialProperty_default) {
if (defined_default(this._depthFailMaterialProperty.color) && (this._depthFailMaterialProperty.color.isConstant || isAvailable)) {
currentColor = this._depthFailMaterialProperty.color.getValue(
time,
scratchColor21
);
}
if (!defined_default(currentColor)) {
currentColor = Color_default.WHITE;
}
attributes.depthFailColor = ColorGeometryInstanceAttribute_default.fromColor(
currentColor
);
}
return new GeometryInstance_default({
id: entity,
geometry: new PolylineGeometry_default(this._geometryOptions),
attributes
});
};
PolylineGeometryUpdater.prototype.createOutlineGeometryInstance = function(time) {
throw new DeveloperError_default(
"This instance does not represent an outlined geometry."
);
};
PolylineGeometryUpdater.prototype.isDestroyed = function() {
return false;
};
PolylineGeometryUpdater.prototype.destroy = function() {
this._entitySubscription();
destroyObject_default(this);
};
PolylineGeometryUpdater.prototype._onEntityPropertyChanged = function(entity, propertyName, newValue, oldValue2) {
if (!(propertyName === "availability" || propertyName === "polyline")) {
return;
}
const polyline = this._entity.polyline;
if (!defined_default(polyline)) {
if (this._fillEnabled) {
this._fillEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
const positionsProperty = polyline.positions;
const show = polyline.show;
if (defined_default(show) && show.isConstant && !show.getValue(Iso8601_default.MINIMUM_VALUE) || !defined_default(positionsProperty)) {
if (this._fillEnabled) {
this._fillEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
const zIndex = polyline.zIndex;
const material = defaultValue_default(polyline.material, defaultMaterial3);
const isColorMaterial = material instanceof ColorMaterialProperty_default;
this._materialProperty = material;
this._depthFailMaterialProperty = polyline.depthFailMaterial;
this._showProperty = defaultValue_default(show, defaultShow2);
this._shadowsProperty = defaultValue_default(polyline.shadows, defaultShadows3);
this._distanceDisplayConditionProperty = defaultValue_default(
polyline.distanceDisplayCondition,
defaultDistanceDisplayCondition7
);
this._classificationTypeProperty = defaultValue_default(
polyline.classificationType,
defaultClassificationType2
);
this._fillEnabled = true;
this._zIndex = defaultValue_default(zIndex, defaultZIndex2);
const width = polyline.width;
const arcType = polyline.arcType;
const clampToGround = polyline.clampToGround;
const granularity = polyline.granularity;
if (!positionsProperty.isConstant || !Property_default.isConstant(width) || !Property_default.isConstant(arcType) || !Property_default.isConstant(granularity) || !Property_default.isConstant(clampToGround) || !Property_default.isConstant(zIndex)) {
if (!this._dynamic) {
this._dynamic = true;
this._geometryChanged.raiseEvent(this);
}
} else {
const geometryOptions = this._geometryOptions;
const positions = positionsProperty.getValue(
Iso8601_default.MINIMUM_VALUE,
geometryOptions.positions
);
if (!defined_default(positions) || positions.length < 2) {
if (this._fillEnabled) {
this._fillEnabled = false;
this._geometryChanged.raiseEvent(this);
}
return;
}
let vertexFormat;
if (isColorMaterial && (!defined_default(this._depthFailMaterialProperty) || this._depthFailMaterialProperty instanceof ColorMaterialProperty_default)) {
vertexFormat = PolylineColorAppearance_default.VERTEX_FORMAT;
} else {
vertexFormat = PolylineMaterialAppearance_default.VERTEX_FORMAT;
}
geometryOptions.vertexFormat = vertexFormat;
geometryOptions.positions = positions;
geometryOptions.width = defined_default(width) ? width.getValue(Iso8601_default.MINIMUM_VALUE) : void 0;
geometryOptions.arcType = defined_default(arcType) ? arcType.getValue(Iso8601_default.MINIMUM_VALUE) : void 0;
geometryOptions.granularity = defined_default(granularity) ? granularity.getValue(Iso8601_default.MINIMUM_VALUE) : void 0;
const groundGeometryOptions = this._groundGeometryOptions;
groundGeometryOptions.positions = positions;
groundGeometryOptions.width = geometryOptions.width;
groundGeometryOptions.arcType = geometryOptions.arcType;
groundGeometryOptions.granularity = geometryOptions.granularity;
this._clampToGround = defined_default(clampToGround) ? clampToGround.getValue(Iso8601_default.MINIMUM_VALUE) : false;
if (!this._clampToGround && defined_default(zIndex)) {
oneTimeWarning_default(
"Entity polylines must have clampToGround: true when using zIndex. zIndex will be ignored."
);
}
this._dynamic = false;
this._geometryChanged.raiseEvent(this);
}
};
PolylineGeometryUpdater.prototype.createDynamicUpdater = function(primitives, groundPrimitives) {
Check_default.defined("primitives", primitives);
Check_default.defined("groundPrimitives", groundPrimitives);
if (!this._dynamic) {
throw new DeveloperError_default(
"This instance does not represent dynamic geometry."
);
}
return new DynamicGeometryUpdater2(primitives, groundPrimitives, this);
};
var generateCartesianArcOptions = {
positions: void 0,
granularity: void 0,
height: void 0,
ellipsoid: void 0
};
function DynamicGeometryUpdater2(primitives, groundPrimitives, geometryUpdater) {
this._line = void 0;
this._primitives = primitives;
this._groundPrimitives = groundPrimitives;
this._groundPolylinePrimitive = void 0;
this._material = void 0;
this._geometryUpdater = geometryUpdater;
this._positions = [];
}
function getLine(dynamicGeometryUpdater) {
if (defined_default(dynamicGeometryUpdater._line)) {
return dynamicGeometryUpdater._line;
}
const sceneId = dynamicGeometryUpdater._geometryUpdater._scene.id;
let polylineCollection = polylineCollections[sceneId];
const primitives = dynamicGeometryUpdater._primitives;
if (!defined_default(polylineCollection) || polylineCollection.isDestroyed()) {
polylineCollection = new PolylineCollection_default();
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;
}
DynamicGeometryUpdater2.prototype.update = function(time) {
const geometryUpdater = this._geometryUpdater;
const entity = geometryUpdater._entity;
const polyline = entity.polyline;
const positionsProperty = polyline.positions;
let positions = Property_default.getValueOrUndefined(
positionsProperty,
time,
this._positions
);
geometryUpdater._clampToGround = Property_default.getValueOrDefault(
polyline._clampToGround,
time,
false
);
geometryUpdater._groundGeometryOptions.positions = positions;
geometryUpdater._groundGeometryOptions.width = Property_default.getValueOrDefault(
polyline._width,
time,
1
);
geometryUpdater._groundGeometryOptions.arcType = Property_default.getValueOrDefault(
polyline._arcType,
time,
ArcType_default.GEODESIC
);
geometryUpdater._groundGeometryOptions.granularity = Property_default.getValueOrDefault(
polyline._granularity,
time,
9999
);
const groundPrimitives = this._groundPrimitives;
if (defined_default(this._groundPolylinePrimitive)) {
groundPrimitives.remove(this._groundPolylinePrimitive);
this._groundPolylinePrimitive = void 0;
}
if (geometryUpdater.clampToGround) {
if (!entity.isShowing || !entity.isAvailable(time) || !Property_default.getValueOrDefault(polyline._show, time, true)) {
return;
}
if (!defined_default(positions) || positions.length < 2) {
return;
}
const fillMaterialProperty = geometryUpdater.fillMaterialProperty;
let appearance;
if (fillMaterialProperty instanceof ColorMaterialProperty_default) {
appearance = new PolylineColorAppearance_default();
} else {
const material = MaterialProperty_default.getValue(
time,
fillMaterialProperty,
this._material
);
appearance = new PolylineMaterialAppearance_default({
material,
translucent: material.isTranslucent()
});
this._material = material;
}
this._groundPolylinePrimitive = groundPrimitives.add(
new GroundPolylinePrimitive_default({
geometryInstances: geometryUpdater.createFillGeometryInstance(time),
appearance,
classificationType: geometryUpdater.classificationTypeProperty.getValue(
time
),
asynchronous: false
}),
Property_default.getValueOrUndefined(geometryUpdater.zIndex, time)
);
if (defined_default(this._line)) {
this._line.show = false;
}
return;
}
const line = getLine(this);
if (!entity.isShowing || !entity.isAvailable(time) || !Property_default.getValueOrDefault(polyline._show, time, true)) {
line.show = false;
return;
}
if (!defined_default(positions) || positions.length < 2) {
line.show = false;
return;
}
let arcType = ArcType_default.GEODESIC;
arcType = Property_default.getValueOrDefault(polyline._arcType, time, arcType);
const globe = geometryUpdater._scene.globe;
if (arcType !== ArcType_default.NONE && defined_default(globe)) {
generateCartesianArcOptions.ellipsoid = globe.ellipsoid;
generateCartesianArcOptions.positions = positions;
generateCartesianArcOptions.granularity = Property_default.getValueOrUndefined(
polyline._granularity,
time
);
generateCartesianArcOptions.height = PolylinePipeline_default.extractHeights(
positions,
globe.ellipsoid
);
if (arcType === ArcType_default.GEODESIC) {
positions = PolylinePipeline_default.generateCartesianArc(
generateCartesianArcOptions
);
} else {
positions = PolylinePipeline_default.generateCartesianRhumbArc(
generateCartesianArcOptions
);
}
}
line.show = true;
line.positions = positions.slice();
line.material = MaterialProperty_default.getValue(
time,
geometryUpdater.fillMaterialProperty,
line.material
);
line.width = Property_default.getValueOrDefault(polyline._width, time, 1);
line.distanceDisplayCondition = Property_default.getValueOrUndefined(
polyline._distanceDisplayCondition,
time,
line.distanceDisplayCondition
);
};
DynamicGeometryUpdater2.prototype.getBoundingSphere = function(result) {
Check_default.defined("result", result);
if (!this._geometryUpdater.clampToGround) {
const line = getLine(this);
if (line.show && line.positions.length > 0) {
BoundingSphere_default.fromPoints(line.positions, result);
return BoundingSphereState_default.DONE;
}
} else {
const groundPolylinePrimitive = this._groundPolylinePrimitive;
if (defined_default(groundPolylinePrimitive) && groundPolylinePrimitive.show && groundPolylinePrimitive.ready) {
const attributes = groundPolylinePrimitive.getGeometryInstanceAttributes(
this._geometryUpdater._entity
);
if (defined_default(attributes) && defined_default(attributes.boundingSphere)) {
BoundingSphere_default.clone(attributes.boundingSphere, result);
return BoundingSphereState_default.DONE;
}
}
if (defined_default(groundPolylinePrimitive) && !groundPolylinePrimitive.ready) {
return BoundingSphereState_default.PENDING;
}
return BoundingSphereState_default.DONE;
}
return BoundingSphereState_default.FAILED;
};
DynamicGeometryUpdater2.prototype.isDestroyed = function() {
return false;
};
DynamicGeometryUpdater2.prototype.destroy = function() {
const geometryUpdater = this._geometryUpdater;
const sceneId = geometryUpdater._scene.id;
const polylineCollection = polylineCollections[sceneId];
if (defined_default(polylineCollection)) {
polylineCollection.remove(this._line);
if (polylineCollection.length === 0) {
this._primitives.removeAndDestroy(polylineCollection);
delete polylineCollections[sceneId];
}
}
if (defined_default(this._groundPolylinePrimitive)) {
this._groundPrimitives.remove(this._groundPolylinePrimitive);
}
destroyObject_default(this);
};
var PolylineGeometryUpdater_default = PolylineGeometryUpdater;
// node_modules/@cesium/engine/Source/DataSources/StaticGroundPolylinePerMaterialBatch.js
var scratchColor23 = new Color_default();
var distanceDisplayConditionScratch9 = new DistanceDisplayCondition_default();
var defaultDistanceDisplayCondition8 = new DistanceDisplayCondition_default();
function Batch6(orderedGroundPrimitives, classificationType, materialProperty, zIndex, asynchronous) {
let appearanceType;
if (materialProperty instanceof ColorMaterialProperty_default) {
appearanceType = PolylineColorAppearance_default;
} else {
appearanceType = PolylineMaterialAppearance_default;
}
this.orderedGroundPrimitives = orderedGroundPrimitives;
this.classificationType = classificationType;
this.appearanceType = appearanceType;
this.materialProperty = materialProperty;
this.updaters = new AssociativeArray_default();
this.createPrimitive = true;
this.primitive = void 0;
this.oldPrimitive = void 0;
this.geometry = new AssociativeArray_default();
this.material = void 0;
this.updatersWithAttributes = new AssociativeArray_default();
this.attributes = new AssociativeArray_default();
this.invalidated = false;
this.removeMaterialSubscription = materialProperty.definitionChanged.addEventListener(
Batch6.prototype.onMaterialChanged,
this
);
this.subscriptions = new AssociativeArray_default();
this.showsUpdated = new AssociativeArray_default();
this.zIndex = zIndex;
this._asynchronous = asynchronous;
}
Batch6.prototype.onMaterialChanged = function() {
this.invalidated = true;
};
Batch6.prototype.isMaterial = function(updater) {
const material = this.materialProperty;
const updaterMaterial = updater.fillMaterialProperty;
if (updaterMaterial === material || updaterMaterial instanceof ColorMaterialProperty_default && material instanceof ColorMaterialProperty_default) {
return true;
}
return defined_default(material) && material.equals(updaterMaterial);
};
Batch6.prototype.add = function(time, updater, geometryInstance) {
const id = updater.id;
this.updaters.set(id, updater);
this.geometry.set(id, geometryInstance);
if (!updater.hasConstantFill || !updater.fillMaterialProperty.isConstant || !Property_default.isConstant(updater.distanceDisplayConditionProperty)) {
this.updatersWithAttributes.set(id, updater);
} else {
const that = this;
this.subscriptions.set(
id,
updater.entity.definitionChanged.addEventListener(function(entity, propertyName, newValue, oldValue2) {
if (propertyName === "isShowing") {
that.showsUpdated.set(updater.id, updater);
}
})
);
}
this.createPrimitive = true;
};
Batch6.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 unsubscribe2 = this.subscriptions.get(id);
if (defined_default(unsubscribe2)) {
unsubscribe2();
this.subscriptions.remove(id);
}
return true;
}
return false;
};
Batch6.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_default(primitive)) {
if (!defined_default(this.oldPrimitive)) {
this.oldPrimitive = primitive;
} else {
orderedGroundPrimitives.remove(primitive);
}
}
primitive = new GroundPolylinePrimitive_default({
show: false,
asynchronous: this._asynchronous,
geometryInstances: geometries.slice(),
appearance: new this.appearanceType(),
classificationType: this.classificationType
});
if (this.appearanceType === PolylineMaterialAppearance_default) {
this.material = MaterialProperty_default.getValue(
time,
this.materialProperty,
this.material
);
primitive.appearance.material = this.material;
}
orderedGroundPrimitives.add(primitive, this.zIndex);
isUpdated = false;
} else {
if (defined_default(primitive)) {
orderedGroundPrimitives.remove(primitive);
primitive = void 0;
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
orderedGroundPrimitives.remove(oldPrimitive);
this.oldPrimitive = void 0;
}
}
this.attributes.removeAll();
this.primitive = primitive;
this.createPrimitive = false;
} else if (defined_default(primitive) && primitive.ready) {
primitive.show = true;
if (defined_default(this.oldPrimitive)) {
orderedGroundPrimitives.remove(this.oldPrimitive);
this.oldPrimitive = void 0;
}
if (this.appearanceType === PolylineMaterialAppearance_default) {
this.material = MaterialProperty_default.getValue(
time,
this.materialProperty,
this.material
);
this.primitive.appearance.material = this.material;
}
const updatersWithAttributes = this.updatersWithAttributes.values;
const length3 = updatersWithAttributes.length;
for (i = 0; i < length3; 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_default(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_default.getValueOrDefault(
colorProperty,
time,
Color_default.WHITE,
scratchColor23
);
if (!Color_default.equals(attributes._lastColor, resultColor)) {
attributes._lastColor = Color_default.clone(
resultColor,
attributes._lastColor
);
attributes.color = ColorGeometryInstanceAttribute_default.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_default.toValue(
show,
attributes.show
);
}
const distanceDisplayConditionProperty = updater.distanceDisplayConditionProperty;
if (!Property_default.isConstant(distanceDisplayConditionProperty)) {
const distanceDisplayCondition = Property_default.getValueOrDefault(
distanceDisplayConditionProperty,
time,
defaultDistanceDisplayCondition8,
distanceDisplayConditionScratch9
);
if (!DistanceDisplayCondition_default.equals(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
)) {
attributes._lastDistanceDisplayCondition = DistanceDisplayCondition_default.clone(
distanceDisplayCondition,
attributes._lastDistanceDisplayCondition
);
attributes.distanceDisplayCondition = DistanceDisplayConditionGeometryInstanceAttribute_default.toValue(
distanceDisplayCondition,
attributes.distanceDisplayCondition
);
}
}
}
this.updateShows(primitive);
} else if (defined_default(primitive) && !primitive.ready) {
isUpdated = false;
}
return isUpdated;
};
Batch6.prototype.updateShows = function(primitive) {
const showsUpdated = this.showsUpdated.values;
const length3 = showsUpdated.length;
for (let i = 0; i < length3; 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_default(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_default.toValue(
show,
attributes.show
);
instance.attributes.show.value[0] = attributes.show[0];
}
}
this.showsUpdated.removeAll();
};
Batch6.prototype.contains = function(updater) {
return this.updaters.contains(updater.id);
};
Batch6.prototype.getBoundingSphere = function(updater, result) {
const primitive = this.primitive;
if (!primitive.ready) {
return BoundingSphereState_default.PENDING;
}
const attributes = primitive.getGeometryInstanceAttributes(updater.entity);
if (!defined_default(attributes) || !defined_default(attributes.boundingSphere) || defined_default(attributes.show) && attributes.show[0] === 0) {
return BoundingSphereState_default.FAILED;
}
attributes.boundingSphere.clone(result);
return BoundingSphereState_default.DONE;
};
Batch6.prototype.destroy = function() {
const primitive = this.primitive;
const orderedGroundPrimitives = this.orderedGroundPrimitives;
if (defined_default(primitive)) {
orderedGroundPrimitives.remove(primitive);
}
const oldPrimitive = this.oldPrimitive;
if (defined_default(oldPrimitive)) {
orderedGroundPrimitives.remove(oldPrimitive);
}
this.removeMaterialSubscription();
};
function StaticGroundPolylinePerMaterialBatch(orderedGroundPrimitives, classificationType, asynchronous) {
this._items = [];
this._orderedGroundPrimitives = orderedGroundPrimitives;
this._classificationType = classificationType;
this._asynchronous = defaultValue_default(asynchronous, true);
}
StaticGroundPolylinePerMaterialBatch.prototype.add = function(time, updater) {
const items = this._items;
const length3 = items.length;
const geometryInstance = updater.createFillGeometryInstance(time);
const zIndex = Property_default.getValueOrDefault(updater.zIndex, 0);
for (let i = 0; i < length3; ++i) {
const item = items[i];
if (item.isMaterial(updater) && item.zIndex === zIndex) {
item.add(time, updater, geometryInstance);
return;
}
}
const batch = new Batch6(
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 length3 = items.length;
for (let i = length3 - 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 length3 = items.length;
for (i = length3 - 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 length3 = items.length;
for (let i = 0; i < length3; i++) {
const item = items[i];
if (item.contains(updater)) {
return item.getBoundingSphere(updater, result);
}
}
return BoundingSphereState_default.FAILED;
};
StaticGroundPolylinePerMaterialBatch.prototype.removeAllPrimitives = function() {
const items = this._items;
const length3 = items.length;
for (let i = 0; i < length3; i++) {
items[i].destroy();
}
this._items.length = 0;
};
var StaticGroundPolylinePerMaterialBatch_default = StaticGroundPolylinePerMaterialBatch;
// node_modules/@cesium/engine/Source/DataSources/PolylineVisualizer.js
var emptyArray2 = [];
function removeUpdater(that, updater) {
const batches = that._batches;
const length3 = batches.length;
for (let i = 0; i < length3; i++) {
batches[i].remove(updater);
}
}
function insertUpdaterIntoBatch(that, time, updater) {
if (updater.isDynamic) {
that._dynamicBatch.add(time, updater);
return;
}
if (updater.clampToGround && updater.fillEnabled) {
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_default(updater.depthFailMaterialProperty)) {
multiplier = updater.depthFailMaterialProperty instanceof ColorMaterialProperty_default ? 1 : 2;
}
let index;
if (defined_default(shadows)) {
index = shadows + multiplier * ShadowMode_default.NUMBER_OF_SHADOW_MODES;
}
if (updater.fillEnabled) {
if (updater.fillMaterialProperty instanceof ColorMaterialProperty_default) {
that._colorBatches[index].add(time, updater);
} else {
that._materialBatches[index].add(time, updater);
}
}
}
function PolylineVisualizer(scene, entityCollection, primitives, groundPrimitives) {
Check_default.defined("scene", scene);
Check_default.defined("entityCollection", entityCollection);
groundPrimitives = defaultValue_default(groundPrimitives, scene.groundPrimitives);
primitives = defaultValue_default(primitives, scene.primitives);
this._scene = scene;
this._primitives = primitives;
this._entityCollection = void 0;
this._addedObjects = new AssociativeArray_default();
this._removedObjects = new AssociativeArray_default();
this._changedObjects = new AssociativeArray_default();
let i;
const numberOfShadowModes = ShadowMode_default.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_default(
primitives,
PolylineColorAppearance_default,
void 0,
false,
i
);
this._materialBatches[i] = new StaticGeometryPerMaterialBatch_default(
primitives,
PolylineMaterialAppearance_default,
void 0,
false,
i
);
this._colorBatches[i + numberOfShadowModes] = new StaticGeometryColorBatch_default(
primitives,
PolylineColorAppearance_default,
PolylineColorAppearance_default,
false,
i
);
this._materialBatches[i + numberOfShadowModes] = new StaticGeometryPerMaterialBatch_default(
primitives,
PolylineMaterialAppearance_default,
PolylineColorAppearance_default,
false,
i
);
this._colorBatches[i + numberOfShadowModes * 2] = new StaticGeometryColorBatch_default(
primitives,
PolylineColorAppearance_default,
PolylineMaterialAppearance_default,
false,
i
);
this._materialBatches[i + numberOfShadowModes * 2] = new StaticGeometryPerMaterialBatch_default(
primitives,
PolylineMaterialAppearance_default,
PolylineMaterialAppearance_default,
false,
i
);
}
this._dynamicBatch = new DynamicGeometryBatch_default(primitives, groundPrimitives);
const numberOfClassificationTypes = ClassificationType_default.NUMBER_OF_CLASSIFICATION_TYPES;
this._groundBatches = new Array(numberOfClassificationTypes);
for (i = 0; i < numberOfClassificationTypes; ++i) {
this._groundBatches[i] = new StaticGroundPolylinePerMaterialBatch_default(
groundPrimitives,
i
);
}
this._batches = this._colorBatches.concat(
this._materialBatches,
this._dynamicBatch,
this._groundBatches
);
this._subscriptions = new AssociativeArray_default();
this._updaters = new AssociativeArray_default();
this._entityCollection = entityCollection;
entityCollection.collectionChanged.addEventListener(
PolylineVisualizer.prototype._onCollectionChanged,
this
);
this._onCollectionChanged(
entityCollection,
entityCollection.values,
emptyArray2
);
}
PolylineVisualizer.prototype.update = function(time) {
Check_default.defined("time", time);
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 (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_default(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 length3 = batches.length;
for (i = 0; i < length3; i++) {
isUpdated = batches[i].update(time) && isUpdated;
}
return isUpdated;
};
var getBoundingSphereArrayScratch2 = [];
var getBoundingSphereBoundingSphereScratch2 = new BoundingSphere_default();
PolylineVisualizer.prototype.getBoundingSphere = function(entity, result) {
Check_default.defined("entity", entity);
Check_default.defined("result", result);
const boundingSpheres = getBoundingSphereArrayScratch2;
const tmp2 = getBoundingSphereBoundingSphereScratch2;
let count = 0;
let state = BoundingSphereState_default.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, tmp2);
if (state === BoundingSphereState_default.PENDING) {
return BoundingSphereState_default.PENDING;
} else if (state === BoundingSphereState_default.DONE) {
boundingSpheres[count] = BoundingSphere_default.clone(
tmp2,
boundingSpheres[count]
);
count++;
}
}
if (count === 0) {
return BoundingSphereState_default.FAILED;
}
boundingSpheres.length = count;
BoundingSphere_default.fromBoundingSpheres(boundingSpheres, result);
return BoundingSphereState_default.DONE;
};
PolylineVisualizer.prototype.isDestroyed = function() {
return false;
};
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 length3 = batches.length;
for (i = 0; i < length3; i++) {
batches[i].removeAllPrimitives();
}
const subscriptions = this._subscriptions.values;
length3 = subscriptions.length;
for (i = 0; i < length3; i++) {
subscriptions[i]();
}
this._subscriptions.removeAll();
return destroyObject_default(this);
};
PolylineVisualizer._onGeometryChanged = function(updater) {
const removedObjects = this._removedObjects;
const changedObjects = this._changedObjects;
const entity = updater.entity;
const id = entity.id;
if (!defined_default(removedObjects.get(id)) && !defined_default(changedObjects.get(id))) {
changedObjects.set(id, entity);
}
};
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);
}
}
};
var PolylineVisualizer_default = PolylineVisualizer;
// node_modules/@cesium/engine/Source/DataSources/DataSourceDisplay.js
function DataSourceDisplay(options) {
Check_default.typeOf.object("options", options);
Check_default.typeOf.object("options.scene", options.scene);
Check_default.typeOf.object(
"options.dataSourceCollection",
options.dataSourceCollection
);
GroundPrimitive_default.initializeTerrainHeights();
GroundPolylinePrimitive_default.initializeTerrainHeights();
const scene = options.scene;
const dataSourceCollection = options.dataSourceCollection;
this._eventHelper = new EventHelper_default();
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_default(
options.visualizersCallback,
DataSourceDisplay.defaultVisualizersCallback
);
let primitivesAdded = false;
const primitives = new PrimitiveCollection_default();
const groundPrimitives = new PrimitiveCollection_default();
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_default();
this._onDataSourceAdded(void 0, 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 = void 0;
that._removeDataSourceCollectionListener = void 0;
};
removeDefaultDataSourceListener = defaultDataSource.entities.collectionChanged.addEventListener(
addPrimitives
);
removeDataSourceCollectionListener = dataSourceCollection.dataSourceAdded.addEventListener(
addPrimitives
);
}
this._removeDefaultDataSourceListener = removeDefaultDataSourceListener;
this._removeDataSourceCollectionListener = removeDataSourceCollectionListener;
this._ready = false;
}
DataSourceDisplay.defaultVisualizersCallback = function(scene, entityCluster, dataSource) {
const entities = dataSource.entities;
return [
new BillboardVisualizer_default(entityCluster, entities),
new GeometryVisualizer_default(
scene,
entities,
dataSource._primitives,
dataSource._groundPrimitives
),
new LabelVisualizer_default(entityCluster, entities),
new ModelVisualizer_default(scene, entities),
new Cesium3DTilesetVisualizer_default(scene, entities),
new PointVisualizer_default(entityCluster, entities),
new PathVisualizer_default(scene, entities),
new PolylineVisualizer_default(
scene,
entities,
dataSource._primitives,
dataSource._groundPrimitives
)
];
};
Object.defineProperties(DataSourceDisplay.prototype, {
scene: {
get: function() {
return this._scene;
}
},
dataSources: {
get: function() {
return this._dataSourceCollection;
}
},
defaultDataSource: {
get: function() {
return this._defaultDataSource;
}
},
ready: {
get: function() {
return this._ready;
}
}
});
DataSourceDisplay.prototype.isDestroyed = function() {
return false;
};
DataSourceDisplay.prototype.destroy = function() {
this._eventHelper.removeAll();
const dataSourceCollection = this._dataSourceCollection;
for (let i = 0, length3 = dataSourceCollection.length; i < length3; ++i) {
this._onDataSourceRemoved(
this._dataSourceCollection,
dataSourceCollection.get(i)
);
}
this._onDataSourceRemoved(void 0, this._defaultDataSource);
if (defined_default(this._removeDefaultDataSourceListener)) {
this._removeDefaultDataSourceListener();
this._removeDataSourceCollectionListener();
} else {
this._scene.primitives.remove(this._primitives);
this._scene.groundPrimitives.remove(this._groundPrimitives);
}
return destroyObject_default(this);
};
DataSourceDisplay.prototype.update = function(time) {
Check_default.defined("time", time);
if (!ApproximateTerrainHeights_default.initialized) {
this._ready = false;
return false;
}
let result = true;
let i;
let x;
let visualizers;
let vLength;
const dataSources = this._dataSourceCollection;
const length3 = dataSources.length;
for (i = 0; i < length3; i++) {
const dataSource = dataSources.get(i);
if (defined_default(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() {
const frameState = this._scene.frameState;
const dataSources = this._dataSourceCollection;
const length3 = dataSources.length;
for (let i = 0; i < length3; i++) {
const dataSource = dataSources.get(i);
const credit = dataSource.credit;
if (defined_default(credit)) {
frameState.creditDisplay.addCreditToNextFrame(credit);
}
const credits = dataSource._resourceCredits;
if (defined_default(credits)) {
const creditCount = credits.length;
for (let c = 0; c < creditCount; c++) {
frameState.creditDisplay.addCreditToNextFrame(credits[c]);
}
}
}
};
var getBoundingSphereArrayScratch3 = [];
var getBoundingSphereBoundingSphereScratch3 = new BoundingSphere_default();
DataSourceDisplay.prototype.getBoundingSphere = function(entity, allowPartial, result) {
Check_default.defined("entity", entity);
Check_default.typeOf.bool("allowPartial", allowPartial);
Check_default.defined("result", result);
if (!this._ready) {
return BoundingSphereState_default.PENDING;
}
let i;
let length3;
let dataSource = this._defaultDataSource;
if (!dataSource.entities.contains(entity)) {
dataSource = void 0;
const dataSources = this._dataSourceCollection;
length3 = dataSources.length;
for (i = 0; i < length3; i++) {
const d = dataSources.get(i);
if (d.entities.contains(entity)) {
dataSource = d;
break;
}
}
}
if (!defined_default(dataSource)) {
return BoundingSphereState_default.FAILED;
}
const boundingSpheres = getBoundingSphereArrayScratch3;
const tmp2 = getBoundingSphereBoundingSphereScratch3;
let count = 0;
let state = BoundingSphereState_default.DONE;
const visualizers = dataSource._visualizers;
const visualizersLength = visualizers.length;
for (i = 0; i < visualizersLength; i++) {
const visualizer = visualizers[i];
if (defined_default(visualizer.getBoundingSphere)) {
state = visualizers[i].getBoundingSphere(entity, tmp2);
if (!allowPartial && state === BoundingSphereState_default.PENDING) {
return BoundingSphereState_default.PENDING;
} else if (state === BoundingSphereState_default.DONE) {
boundingSpheres[count] = BoundingSphere_default.clone(
tmp2,
boundingSpheres[count]
);
count++;
}
}
}
if (count === 0) {
return BoundingSphereState_default.FAILED;
}
boundingSpheres.length = count;
BoundingSphere_default.fromBoundingSpheres(boundingSpheres, result);
return BoundingSphereState_default.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_default());
const groundPrimitives = displayGroundPrimitives.add(
new OrderedGroundPrimitiveCollection_default()
);
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 length3 = visualizers.length;
for (let i = 0; i < length3; i++) {
visualizers[i].destroy();
}
displayPrimitives.remove(primitives);
displayGroundPrimitives.remove(groundPrimitives);
dataSource._visualizers = void 0;
};
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);
displayGroundPrimitives.raise(groundPrimitives);
} else {
displayPrimitives.raiseToTop(primitives);
displayGroundPrimitives.raiseToTop(groundPrimitives);
}
};
var DataSourceDisplay_default = DataSourceDisplay;
// node_modules/@cesium/engine/Source/Core/HeadingPitchRange.js
function HeadingPitchRange(heading, pitch, range) {
this.heading = defaultValue_default(heading, 0);
this.pitch = defaultValue_default(pitch, 0);
this.range = defaultValue_default(range, 0);
}
HeadingPitchRange.clone = function(hpr, result) {
if (!defined_default(hpr)) {
return void 0;
}
if (!defined_default(result)) {
result = new HeadingPitchRange();
}
result.heading = hpr.heading;
result.pitch = hpr.pitch;
result.range = hpr.range;
return result;
};
var HeadingPitchRange_default = HeadingPitchRange;
// node_modules/@cesium/engine/Source/DataSources/EntityView.js
var updateTransformMatrix3Scratch1 = new Matrix3_default();
var updateTransformMatrix3Scratch2 = new Matrix3_default();
var updateTransformMatrix3Scratch3 = new Matrix3_default();
var updateTransformMatrix4Scratch = new Matrix4_default();
var updateTransformCartesian3Scratch1 = new Cartesian3_default();
var updateTransformCartesian3Scratch2 = new Cartesian3_default();
var updateTransformCartesian3Scratch3 = new Cartesian3_default();
var updateTransformCartesian3Scratch4 = new Cartesian3_default();
var updateTransformCartesian3Scratch5 = new Cartesian3_default();
var updateTransformCartesian3Scratch6 = new Cartesian3_default();
var deltaTime = new JulianDate_default();
var northUpAxisFactor = 1.25;
function updateTransform(that, camera, updateLookAt, saveCamera, positionProperty, time, ellipsoid) {
const mode2 = that.scene.mode;
let cartesian11 = positionProperty.getValue(time, that._lastCartesian);
if (defined_default(cartesian11)) {
let hasBasis = false;
let invertVelocity = false;
let xBasis;
let yBasis;
let zBasis;
if (mode2 === SceneMode_default.SCENE3D) {
JulianDate_default.addSeconds(time, 1e-3, deltaTime);
let deltaCartesian = positionProperty.getValue(
deltaTime,
updateTransformCartesian3Scratch1
);
if (!defined_default(deltaCartesian)) {
JulianDate_default.addSeconds(time, -1e-3, deltaTime);
deltaCartesian = positionProperty.getValue(
deltaTime,
updateTransformCartesian3Scratch1
);
invertVelocity = true;
}
if (defined_default(deltaCartesian)) {
let toInertial = Transforms_default.computeFixedToIcrfMatrix(
time,
updateTransformMatrix3Scratch1
);
let toInertialDelta = Transforms_default.computeFixedToIcrfMatrix(
deltaTime,
updateTransformMatrix3Scratch2
);
let toFixed;
if (!defined_default(toInertial) || !defined_default(toInertialDelta)) {
toFixed = Transforms_default.computeTemeToPseudoFixedMatrix(
time,
updateTransformMatrix3Scratch3
);
toInertial = Matrix3_default.transpose(
toFixed,
updateTransformMatrix3Scratch1
);
toInertialDelta = Transforms_default.computeTemeToPseudoFixedMatrix(
deltaTime,
updateTransformMatrix3Scratch2
);
Matrix3_default.transpose(toInertialDelta, toInertialDelta);
} else {
toFixed = Matrix3_default.transpose(
toInertial,
updateTransformMatrix3Scratch3
);
}
const inertialCartesian = Matrix3_default.multiplyByVector(
toInertial,
cartesian11,
updateTransformCartesian3Scratch5
);
const inertialDeltaCartesian = Matrix3_default.multiplyByVector(
toInertialDelta,
deltaCartesian,
updateTransformCartesian3Scratch6
);
Cartesian3_default.subtract(
inertialCartesian,
inertialDeltaCartesian,
updateTransformCartesian3Scratch4
);
const inertialVelocity = Cartesian3_default.magnitude(updateTransformCartesian3Scratch4) * 1e3;
const mu = Math_default.GRAVITATIONALPARAMETER;
const semiMajorAxis = -mu / (inertialVelocity * inertialVelocity - 2 * mu / Cartesian3_default.magnitude(inertialCartesian));
if (semiMajorAxis < 0 || semiMajorAxis > northUpAxisFactor * ellipsoid.maximumRadius) {
xBasis = updateTransformCartesian3Scratch2;
Cartesian3_default.normalize(cartesian11, xBasis);
Cartesian3_default.negate(xBasis, xBasis);
zBasis = Cartesian3_default.clone(
Cartesian3_default.UNIT_Z,
updateTransformCartesian3Scratch3
);
yBasis = Cartesian3_default.cross(
zBasis,
xBasis,
updateTransformCartesian3Scratch1
);
if (Cartesian3_default.magnitude(yBasis) > Math_default.EPSILON7) {
Cartesian3_default.normalize(xBasis, xBasis);
Cartesian3_default.normalize(yBasis, yBasis);
zBasis = Cartesian3_default.cross(
xBasis,
yBasis,
updateTransformCartesian3Scratch3
);
Cartesian3_default.normalize(zBasis, zBasis);
hasBasis = true;
}
} else if (!Cartesian3_default.equalsEpsilon(
cartesian11,
deltaCartesian,
Math_default.EPSILON7
)) {
zBasis = updateTransformCartesian3Scratch2;
Cartesian3_default.normalize(inertialCartesian, zBasis);
Cartesian3_default.normalize(inertialDeltaCartesian, inertialDeltaCartesian);
yBasis = Cartesian3_default.cross(
zBasis,
inertialDeltaCartesian,
updateTransformCartesian3Scratch3
);
if (invertVelocity) {
yBasis = Cartesian3_default.multiplyByScalar(yBasis, -1, yBasis);
}
if (!Cartesian3_default.equalsEpsilon(
yBasis,
Cartesian3_default.ZERO,
Math_default.EPSILON7
)) {
xBasis = Cartesian3_default.cross(
yBasis,
zBasis,
updateTransformCartesian3Scratch1
);
Matrix3_default.multiplyByVector(toFixed, xBasis, xBasis);
Matrix3_default.multiplyByVector(toFixed, yBasis, yBasis);
Matrix3_default.multiplyByVector(toFixed, zBasis, zBasis);
Cartesian3_default.normalize(xBasis, xBasis);
Cartesian3_default.normalize(yBasis, yBasis);
Cartesian3_default.normalize(zBasis, zBasis);
hasBasis = true;
}
}
}
}
if (defined_default(that.boundingSphere)) {
cartesian11 = that.boundingSphere.center;
}
let position;
let direction2;
let up;
if (saveCamera) {
position = Cartesian3_default.clone(
camera.position,
updateTransformCartesian3Scratch4
);
direction2 = Cartesian3_default.clone(
camera.direction,
updateTransformCartesian3Scratch5
);
up = Cartesian3_default.clone(camera.up, updateTransformCartesian3Scratch6);
}
const transform3 = updateTransformMatrix4Scratch;
if (hasBasis) {
transform3[0] = xBasis.x;
transform3[1] = xBasis.y;
transform3[2] = xBasis.z;
transform3[3] = 0;
transform3[4] = yBasis.x;
transform3[5] = yBasis.y;
transform3[6] = yBasis.z;
transform3[7] = 0;
transform3[8] = zBasis.x;
transform3[9] = zBasis.y;
transform3[10] = zBasis.z;
transform3[11] = 0;
transform3[12] = cartesian11.x;
transform3[13] = cartesian11.y;
transform3[14] = cartesian11.z;
transform3[15] = 0;
} else {
Transforms_default.eastNorthUpToFixedFrame(cartesian11, ellipsoid, transform3);
}
camera._setTransform(transform3);
if (saveCamera) {
Cartesian3_default.clone(position, camera.position);
Cartesian3_default.clone(direction2, camera.direction);
Cartesian3_default.clone(up, camera.up);
Cartesian3_default.cross(direction2, up, camera.right);
}
}
if (updateLookAt) {
const offset2 = mode2 === SceneMode_default.SCENE2D || Cartesian3_default.equals(that._offset3D, Cartesian3_default.ZERO) ? void 0 : that._offset3D;
camera.lookAtTransform(camera.transform, offset2);
}
}
function EntityView(entity, scene, ellipsoid) {
Check_default.defined("entity", entity);
Check_default.defined("scene", scene);
this.entity = entity;
this.scene = scene;
this.ellipsoid = defaultValue_default(ellipsoid, Ellipsoid_default.WGS84);
this.boundingSphere = void 0;
this._lastEntity = void 0;
this._mode = void 0;
this._lastCartesian = new Cartesian3_default();
this._defaultOffset3D = void 0;
this._offset3D = new Cartesian3_default();
}
Object.defineProperties(EntityView, {
defaultOffset3D: {
get: function() {
return this._defaultOffset3D;
},
set: function(vector) {
this._defaultOffset3D = Cartesian3_default.clone(vector, new Cartesian3_default());
}
}
});
EntityView.defaultOffset3D = new Cartesian3_default(-14e3, 3500, 3500);
var scratchHeadingPitchRange = new HeadingPitchRange_default();
var scratchCartesian20 = new Cartesian3_default();
EntityView.prototype.update = function(time, boundingSphere) {
Check_default.defined("time", time);
const scene = this.scene;
const ellipsoid = this.ellipsoid;
const sceneMode = scene.mode;
if (sceneMode === SceneMode_default.MORPHING) {
return;
}
const entity = this.entity;
const positionProperty = entity.position;
if (!defined_default(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_default(viewFromProperty);
if (!hasViewFrom && defined_default(boundingSphere)) {
scratchHeadingPitchRange.pitch = -Math_default.PI_OVER_FOUR;
scratchHeadingPitchRange.range = 0;
const position = positionProperty.getValue(time, scratchCartesian20);
if (defined_default(position)) {
const factor2 = 2 - 1 / Math.max(
1,
Cartesian3_default.magnitude(position) / ellipsoid.maximumRadius
);
scratchHeadingPitchRange.pitch *= factor2;
}
camera.viewBoundingSphere(boundingSphere, scratchHeadingPitchRange);
this.boundingSphere = boundingSphere;
updateLookAt = false;
saveCamera = false;
} else if (!hasViewFrom || !defined_default(viewFromProperty.getValue(time, this._offset3D))) {
Cartesian3_default.clone(EntityView._defaultOffset3D, this._offset3D);
}
} else if (!sceneModeChanged && this._mode !== SceneMode_default.SCENE2D) {
Cartesian3_default.clone(camera.position, this._offset3D);
}
this._lastEntity = entity;
this._mode = sceneMode;
updateTransform(
this,
camera,
updateLookAt,
saveCamera,
positionProperty,
time,
ellipsoid
);
};
var EntityView_default = EntityView;
// node_modules/@cesium/engine/Source/Core/PinBuilder.js
function PinBuilder() {
this._cache = {};
}
PinBuilder.prototype.fromColor = function(color, size) {
if (!defined_default(color)) {
throw new DeveloperError_default("color is required");
}
if (!defined_default(size)) {
throw new DeveloperError_default("size is required");
}
return createPin(void 0, void 0, color, size, this._cache);
};
PinBuilder.prototype.fromUrl = function(url2, color, size) {
if (!defined_default(url2)) {
throw new DeveloperError_default("url is required");
}
if (!defined_default(color)) {
throw new DeveloperError_default("color is required");
}
if (!defined_default(size)) {
throw new DeveloperError_default("size is required");
}
return createPin(url2, void 0, color, size, this._cache);
};
PinBuilder.prototype.fromMakiIconId = function(id, color, size) {
if (!defined_default(id)) {
throw new DeveloperError_default("id is required");
}
if (!defined_default(color)) {
throw new DeveloperError_default("color is required");
}
if (!defined_default(size)) {
throw new DeveloperError_default("size is required");
}
return createPin(
buildModuleUrl_default(`Assets/Textures/maki/${encodeURIComponent(id)}.png`),
void 0,
color,
size,
this._cache
);
};
PinBuilder.prototype.fromText = function(text2, color, size) {
if (!defined_default(text2)) {
throw new DeveloperError_default("text is required");
}
if (!defined_default(color)) {
throw new DeveloperError_default("color is required");
}
if (!defined_default(size)) {
throw new DeveloperError_default("size is required");
}
return createPin(void 0, text2, color, size, this._cache);
};
var colorScratch7 = new Color_default();
function drawPin(context2D, color, size) {
context2D.save();
context2D.scale(size / 24, size / 24);
context2D.fillStyle = color.toCssColorString();
context2D.strokeStyle = color.brighten(0.6, colorScratch7).toCssColorString();
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();
}
function drawIcon(context2D, image, size) {
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);
}
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_default.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_default.WHITE.toCssColorString();
context2D.fillRect(x - 1, y - 2, sizeX + 2, sizeY + 2);
}
var stringifyScratch = new Array(4);
function createPin(url2, label, color, size, cache) {
stringifyScratch[0] = url2;
stringifyScratch[1] = label;
stringifyScratch[2] = color;
stringifyScratch[3] = size;
const id = JSON.stringify(stringifyScratch);
const item = cache[id];
if (defined_default(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_default(url2)) {
const resource = Resource_default.createIfNeeded(url2);
const promise = resource.fetchImage().then(function(image) {
drawIcon(context2D, image, size);
cache[id] = canvas;
return canvas;
});
cache[id] = promise;
return promise;
} else if (defined_default(label)) {
const image = writeTextToCanvas_default(label, {
font: `bold ${size}px sans-serif`
});
drawIcon(context2D, image, size);
}
cache[id] = canvas;
return canvas;
}
var PinBuilder_default = PinBuilder;
// node_modules/@cesium/engine/Source/DataSources/GeoJsonDataSource.js
function defaultCrsFunction(coordinates) {
return Cartesian3_default.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
}
var crsNames = {
"urn:ogc:def:crs:OGC:1.3:CRS84": defaultCrsFunction,
"EPSG:4326": defaultCrsFunction,
"urn:ogc:def:crs:EPSG::4326": defaultCrsFunction
};
var crsLinkHrefs = {};
var crsLinkTypes = {};
var defaultMarkerSize = 48;
var defaultMarkerSymbol;
var defaultMarkerColor = Color_default.ROYALBLUE;
var defaultStroke = Color_default.YELLOW;
var defaultStrokeWidth = 2;
var defaultFill2 = Color_default.fromBytes(255, 255, 0, 100);
var defaultClampToGround = false;
var sizes = {
small: 24,
medium: 48,
large: 64
};
var simpleStyleIdentifiers = [
"title",
"description",
"marker-size",
"marker-symbol",
"marker-color",
"stroke",
"stroke-opacity",
"stroke-width",
"fill",
"fill-opacity"
];
function defaultDescribe(properties, nameProperty) {
let html2 = "";
for (const key in properties) {
if (properties.hasOwnProperty(key)) {
if (key === nameProperty || simpleStyleIdentifiers.indexOf(key) !== -1) {
continue;
}
const value = properties[key];
if (defined_default(value)) {
if (typeof value === "object") {
html2 += `
${key}
${defaultDescribe(value)}
`;
} else {
html2 += `
${key}
${value}
`;
}
}
}
}
if (html2.length > 0) {
html2 = `
${html2}
`;
}
return html2;
}
function createDescriptionCallback(describe, properties, nameProperty) {
let description;
return function(time, result) {
if (!defined_default(description)) {
description = describe(properties, nameProperty);
}
return description;
};
}
function defaultDescribeProperty(properties, nameProperty) {
return new CallbackProperty_default(
createDescriptionCallback(defaultDescribe, properties, nameProperty),
true
);
}
function createObject(geoJson, entityCollection, describe) {
let id = geoJson.id;
if (!defined_default(id) || geoJson.type !== "Feature") {
id = createGuid_default();
} else {
let i = 2;
let finalId = id;
while (defined_default(entityCollection.getById(finalId))) {
finalId = `${id}_${i}`;
i++;
}
id = finalId;
}
const entity = entityCollection.getOrCreateEntity(id);
const properties = geoJson.properties;
if (defined_default(properties)) {
entity.properties = properties;
let nameProperty;
const name = properties.title;
if (defined_default(name)) {
entity.name = name;
nameProperty = "title";
} else {
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_default(nameProperty)) {
entity.name = properties[nameProperty];
}
}
const description = properties.description;
if (description !== null) {
entity.description = !defined_default(description) ? describe(properties, nameProperty) : new ConstantProperty_default(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;
}
var geoJsonObjectTypes2 = {
Feature: processFeature,
FeatureCollection: processFeatureCollection,
GeometryCollection: processGeometryCollection,
LineString: processLineString,
MultiLineString: processMultiLineString,
MultiPoint: processMultiPoint,
MultiPolygon: processMultiPolygon,
Point: processPoint2,
Polygon: processPolygon2,
Topology: processTopology
};
var geometryTypes2 = {
GeometryCollection: processGeometryCollection,
LineString: processLineString,
MultiLineString: processMultiLineString,
MultiPoint: processMultiPoint,
MultiPolygon: processMultiPolygon,
Point: processPoint2,
Polygon: processPolygon2,
Topology: processTopology
};
function processFeature(dataSource, feature, notUsed, crsFunction, options) {
if (feature.geometry === null) {
createObject(feature, dataSource._entityCollection, options.describe);
return;
}
if (!defined_default(feature.geometry)) {
throw new RuntimeError_default("feature.geometry is required.");
}
const geometryType = feature.geometry.type;
const geometryHandler = geometryTypes2[geometryType];
if (!defined_default(geometryHandler)) {
throw new RuntimeError_default(`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(dataSource, features[i], void 0, 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 = geometryTypes2[geometryType];
if (!defined_default(geometryHandler)) {
throw new RuntimeError_default(`Unknown geometry type: ${geometryType}`);
}
geometryHandler(dataSource, geoJson, geometry, crsFunction, options);
}
}
function createPoint(dataSource, geoJson, crsFunction, coordinates, options) {
let symbol = options.markerSymbol;
let color = options.markerColor;
let size = options.markerSize;
const properties = geoJson.properties;
if (defined_default(properties)) {
const cssColor = properties["marker-color"];
if (defined_default(cssColor)) {
color = Color_default.fromCssColorString(cssColor);
}
size = defaultValue_default(sizes[properties["marker-size"]], size);
const markerSymbol = properties["marker-symbol"];
if (defined_default(markerSymbol)) {
symbol = markerSymbol;
}
}
let canvasOrPromise;
if (defined_default(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_default();
billboard.verticalOrigin = new ConstantProperty_default(VerticalOrigin_default.BOTTOM);
if (coordinates.length === 2 && options.clampToGround) {
billboard.heightReference = HeightReference_default.CLAMP_TO_GROUND;
}
const entity = createObject(
geoJson,
dataSource._entityCollection,
options.describe
);
entity.billboard = billboard;
entity.position = new ConstantPositionProperty_default(crsFunction(coordinates));
const promise = Promise.resolve(canvasOrPromise).then(function(image) {
billboard.image = new ConstantProperty_default(image);
}).catch(function() {
billboard.image = new ConstantProperty_default(
dataSource._pinBuilder.fromColor(color, size)
);
});
dataSource._promises.push(promise);
}
function processPoint2(dataSource, geoJson, geometry, crsFunction, options) {
createPoint(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(dataSource, geoJson, crsFunction, coordinates[i], options);
}
}
function createLineString(dataSource, geoJson, crsFunction, coordinates, options) {
let material = options.strokeMaterialProperty;
let widthProperty = options.strokeWidthProperty;
const properties = geoJson.properties;
if (defined_default(properties)) {
const width = properties["stroke-width"];
if (defined_default(width)) {
widthProperty = new ConstantProperty_default(width);
}
let color;
const stroke = properties.stroke;
if (defined_default(stroke)) {
color = Color_default.fromCssColorString(stroke);
}
const opacity = properties["stroke-opacity"];
if (defined_default(opacity) && opacity !== 1) {
if (!defined_default(color)) {
color = material.color.getValue().clone();
}
color.alpha = opacity;
}
if (defined_default(color)) {
material = new ColorMaterialProperty_default(color);
}
}
const entity = createObject(
geoJson,
dataSource._entityCollection,
options.describe
);
const polylineGraphics = new PolylineGraphics_default();
entity.polyline = polylineGraphics;
polylineGraphics.clampToGround = options.clampToGround;
polylineGraphics.material = material;
polylineGraphics.width = widthProperty;
polylineGraphics.positions = new ConstantProperty_default(
coordinatesArrayToCartesianArray(coordinates, crsFunction)
);
polylineGraphics.arcType = ArcType_default.RHUMB;
}
function processLineString(dataSource, geoJson, geometry, crsFunction, options) {
createLineString(
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(dataSource, geoJson, crsFunction, lineStrings[i], options);
}
}
function createPolygon(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_default(properties)) {
const width = properties["stroke-width"];
if (defined_default(width)) {
widthProperty = new ConstantProperty_default(width);
}
let color;
const stroke = properties.stroke;
if (defined_default(stroke)) {
color = Color_default.fromCssColorString(stroke);
}
let opacity = properties["stroke-opacity"];
if (defined_default(opacity) && opacity !== 1) {
if (!defined_default(color)) {
color = outlineColorProperty.getValue().clone();
}
color.alpha = opacity;
}
if (defined_default(color)) {
outlineColorProperty = new ConstantProperty_default(color);
}
let fillColor;
const fill = properties.fill;
const materialColor = material.color.getValue();
if (defined_default(fill)) {
fillColor = Color_default.fromCssColorString(fill);
fillColor.alpha = materialColor.alpha;
}
opacity = properties["fill-opacity"];
if (defined_default(opacity) && opacity !== materialColor.alpha) {
if (!defined_default(fillColor)) {
fillColor = materialColor.clone();
}
fillColor.alpha = opacity;
}
if (defined_default(fillColor)) {
material = new ColorMaterialProperty_default(fillColor);
}
}
const polygon = new PolygonGraphics_default();
polygon.outline = new ConstantProperty_default(true);
polygon.outlineColor = outlineColorProperty;
polygon.outlineWidth = widthProperty;
polygon.material = material;
polygon.arcType = ArcType_default.RHUMB;
const holes = [];
for (let i = 1, len = coordinates.length; i < len; i++) {
holes.push(
new PolygonHierarchy_default(
coordinatesArrayToCartesianArray(coordinates[i], crsFunction)
)
);
}
const positions = coordinates[0];
polygon.hierarchy = new ConstantProperty_default(
new PolygonHierarchy_default(
coordinatesArrayToCartesianArray(positions, crsFunction),
holes
)
);
if (positions[0].length > 2) {
polygon.perPositionHeight = new ConstantProperty_default(true);
} else if (!options.clampToGround) {
polygon.height = 0;
}
const entity = createObject(
geoJson,
dataSource._entityCollection,
options.describe
);
entity.polygon = polygon;
}
function processPolygon2(dataSource, geoJson, geometry, crsFunction, options) {
createPolygon(
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(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 = feature_default(geometry, geometry.objects[property]);
const typeHandler = geoJsonObjectTypes2[feature.type];
typeHandler(dataSource, feature, feature, crsFunction, options);
}
}
}
function GeoJsonDataSource(name) {
this._name = name;
this._changed = new Event_default();
this._error = new Event_default();
this._isLoading = false;
this._loading = new Event_default();
this._entityCollection = new EntityCollection_default(this);
this._promises = [];
this._pinBuilder = new PinBuilder_default();
this._entityCluster = new EntityCluster_default();
this._credit = void 0;
this._resourceCredits = [];
}
GeoJsonDataSource.load = function(data, options) {
return new GeoJsonDataSource().load(data, options);
};
Object.defineProperties(GeoJsonDataSource, {
markerSize: {
get: function() {
return defaultMarkerSize;
},
set: function(value) {
defaultMarkerSize = value;
}
},
markerSymbol: {
get: function() {
return defaultMarkerSymbol;
},
set: function(value) {
defaultMarkerSymbol = value;
}
},
markerColor: {
get: function() {
return defaultMarkerColor;
},
set: function(value) {
defaultMarkerColor = value;
}
},
stroke: {
get: function() {
return defaultStroke;
},
set: function(value) {
defaultStroke = value;
}
},
strokeWidth: {
get: function() {
return defaultStrokeWidth;
},
set: function(value) {
defaultStrokeWidth = value;
}
},
fill: {
get: function() {
return defaultFill2;
},
set: function(value) {
defaultFill2 = value;
}
},
clampToGround: {
get: function() {
return defaultClampToGround;
},
set: function(value) {
defaultClampToGround = value;
}
},
crsNames: {
get: function() {
return crsNames;
}
},
crsLinkHrefs: {
get: function() {
return crsLinkHrefs;
}
},
crsLinkTypes: {
get: function() {
return crsLinkTypes;
}
}
});
Object.defineProperties(GeoJsonDataSource.prototype, {
name: {
get: function() {
return this._name;
},
set: function(value) {
if (this._name !== value) {
this._name = value;
this._changed.raiseEvent(this);
}
}
},
clock: {
value: void 0,
writable: false
},
entities: {
get: function() {
return this._entityCollection;
}
},
isLoading: {
get: function() {
return this._isLoading;
}
},
changedEvent: {
get: function() {
return this._changed;
}
},
errorEvent: {
get: function() {
return this._error;
}
},
loadingEvent: {
get: function() {
return this._loading;
}
},
show: {
get: function() {
return this._entityCollection.show;
},
set: function(value) {
this._entityCollection.show = value;
}
},
clustering: {
get: function() {
return this._entityCluster;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value must be defined.");
}
this._entityCluster = value;
}
},
credit: {
get: function() {
return this._credit;
}
}
});
GeoJsonDataSource.prototype.load = function(data, options) {
return preload(this, data, options, true);
};
GeoJsonDataSource.prototype.process = function(data, options) {
return preload(this, data, options, false);
};
function preload(that, data, options, clear2) {
if (!defined_default(data)) {
throw new DeveloperError_default("data is required.");
}
DataSource_default.setLoading(that, true);
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
that._credit = credit;
let promise = data;
let sourceUri = options.sourceUri;
if (typeof data === "string" || data instanceof Resource_default) {
data = Resource_default.createIfNeeded(data);
promise = data.fetchJson();
sourceUri = defaultValue_default(sourceUri, data.getUrlComponent());
const resourceCredits = that._resourceCredits;
const credits = data.credits;
if (defined_default(credits)) {
const length3 = credits.length;
for (let i = 0; i < length3; i++) {
resourceCredits.push(credits[i]);
}
}
}
options = {
describe: defaultValue_default(options.describe, defaultDescribeProperty),
markerSize: defaultValue_default(options.markerSize, defaultMarkerSize),
markerSymbol: defaultValue_default(options.markerSymbol, defaultMarkerSymbol),
markerColor: defaultValue_default(options.markerColor, defaultMarkerColor),
strokeWidthProperty: new ConstantProperty_default(
defaultValue_default(options.strokeWidth, defaultStrokeWidth)
),
strokeMaterialProperty: new ColorMaterialProperty_default(
defaultValue_default(options.stroke, defaultStroke)
),
fillMaterialProperty: new ColorMaterialProperty_default(
defaultValue_default(options.fill, defaultFill2)
),
clampToGround: defaultValue_default(options.clampToGround, defaultClampToGround)
};
return Promise.resolve(promise).then(function(geoJson) {
return load2(that, geoJson, options, sourceUri, clear2);
}).catch(function(error) {
DataSource_default.setLoading(that, false);
that._error.raiseEvent(that, error);
throw error;
});
}
GeoJsonDataSource.prototype.update = function(time) {
return true;
};
function load2(that, geoJson, options, sourceUri, clear2) {
let name;
if (defined_default(sourceUri)) {
name = getFilenameFromUri_default(sourceUri);
}
if (defined_default(name) && that._name !== name) {
that._name = name;
that._changed.raiseEvent(that);
}
const typeHandler = geoJsonObjectTypes2[geoJson.type];
if (!defined_default(typeHandler)) {
throw new RuntimeError_default(`Unsupported GeoJSON object type: ${geoJson.type}`);
}
const crs = geoJson.crs;
let crsFunction = crs !== null ? defaultCrsFunction : null;
if (defined_default(crs)) {
if (!defined_default(crs.properties)) {
throw new RuntimeError_default("crs.properties is undefined.");
}
const properties = crs.properties;
if (crs.type === "name") {
crsFunction = crsNames[properties.name];
if (!defined_default(crsFunction)) {
throw new RuntimeError_default(`Unknown crs name: ${properties.name}`);
}
} else if (crs.type === "link") {
let handler = crsLinkHrefs[properties.href];
if (!defined_default(handler)) {
handler = crsLinkTypes[properties.type];
}
if (!defined_default(handler)) {
throw new RuntimeError_default(
`Unable to resolve crs link: ${JSON.stringify(properties)}`
);
}
crsFunction = handler(properties);
} else if (crs.type === "EPSG") {
crsFunction = crsNames[`EPSG:${properties.code}`];
if (!defined_default(crsFunction)) {
throw new RuntimeError_default(`Unknown crs EPSG code: ${properties.code}`);
}
} else {
throw new RuntimeError_default(`Unknown crs type: ${crs.type}`);
}
}
return Promise.resolve(crsFunction).then(function(crsFunction2) {
if (clear2) {
that._entityCollection.removeAll();
}
if (crsFunction2 !== null) {
typeHandler(that, geoJson, geoJson, crsFunction2, options);
}
return Promise.all(that._promises).then(function() {
that._promises.length = 0;
DataSource_default.setLoading(that, false);
return that;
});
});
}
var GeoJsonDataSource_default = GeoJsonDataSource;
// node_modules/autolinker/dist/es2015/version.js
var version = "4.0.0";
// node_modules/autolinker/dist/es2015/utils.js
function isUndefined(value) {
return value === void 0;
}
function isBoolean(value) {
return typeof value === "boolean";
}
function defaults(dest, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop) && isUndefined(dest[prop])) {
dest[prop] = src[prop];
}
}
return dest;
}
function ellipsis(str, truncateLen, ellipsisChars) {
var ellipsisLength;
if (str.length > truncateLen) {
if (ellipsisChars == null) {
ellipsisChars = "…";
ellipsisLength = 3;
} else {
ellipsisLength = ellipsisChars.length;
}
str = str.substring(0, truncateLen - ellipsisLength) + ellipsisChars;
}
return str;
}
function remove2(arr, item) {
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] === item) {
arr.splice(i, 1);
}
}
}
function removeWithPredicate(arr, fn) {
for (var i = arr.length - 1; i >= 0; i--) {
if (fn(arr[i]) === true) {
arr.splice(i, 1);
}
}
}
function assertNever(theValue) {
throw new Error("Unhandled case for value: '".concat(theValue, "'"));
}
// node_modules/autolinker/dist/es2015/regex-lib.js
var letterRe = /[A-Za-z]/;
var digitRe = /[\d]/;
var whitespaceRe = /\s/;
var quoteRe = /['"]/;
var controlCharsRe = /[\x00-\x1F\x7F]/;
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;
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;
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;
var alphaCharsAndMarksStr = alphaCharsStr + emojiStr + marksStr;
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;
var alphaNumericCharsRe = new RegExp("[".concat(alphaCharsStr + decimalNumbersStr, "]"));
var alphaNumericAndMarksCharsStr = alphaCharsAndMarksStr + decimalNumbersStr;
var alphaNumericAndMarksRe = new RegExp("[".concat(alphaNumericAndMarksCharsStr, "]"));
// node_modules/autolinker/dist/es2015/html-tag.js
var HtmlTag = function() {
function HtmlTag2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.tagName = "";
this.attrs = {};
this.innerHTML = "";
this.tagName = cfg.tagName || "";
this.attrs = cfg.attrs || {};
this.innerHTML = cfg.innerHtml || cfg.innerHTML || "";
}
HtmlTag2.prototype.setTagName = function(tagName) {
this.tagName = tagName;
return this;
};
HtmlTag2.prototype.getTagName = function() {
return this.tagName || "";
};
HtmlTag2.prototype.setAttr = function(attrName, attrValue) {
var tagAttrs = this.getAttrs();
tagAttrs[attrName] = attrValue;
return this;
};
HtmlTag2.prototype.getAttr = function(attrName) {
return this.getAttrs()[attrName];
};
HtmlTag2.prototype.setAttrs = function(attrs) {
Object.assign(this.getAttrs(), attrs);
return this;
};
HtmlTag2.prototype.getAttrs = function() {
return this.attrs || (this.attrs = {});
};
HtmlTag2.prototype.setClass = function(cssClass) {
return this.setAttr("class", cssClass);
};
HtmlTag2.prototype.addClass = function(cssClass) {
var classAttr = this.getClass(), classes = !classAttr ? [] : classAttr.split(whitespaceRe), newClasses = cssClass.split(whitespaceRe), newClass;
while (newClass = newClasses.shift()) {
if (classes.indexOf(newClass) === -1) {
classes.push(newClass);
}
}
this.getAttrs()["class"] = classes.join(" ");
return this;
};
HtmlTag2.prototype.removeClass = function(cssClass) {
var classAttr = this.getClass(), classes = !classAttr ? [] : classAttr.split(whitespaceRe), removeClasses = cssClass.split(whitespaceRe), removeClass;
while (classes.length && (removeClass = removeClasses.shift())) {
var idx = classes.indexOf(removeClass);
if (idx !== -1) {
classes.splice(idx, 1);
}
}
this.getAttrs()["class"] = classes.join(" ");
return this;
};
HtmlTag2.prototype.getClass = function() {
return this.getAttrs()["class"] || "";
};
HtmlTag2.prototype.hasClass = function(cssClass) {
return (" " + this.getClass() + " ").indexOf(" " + cssClass + " ") !== -1;
};
HtmlTag2.prototype.setInnerHTML = function(html2) {
this.innerHTML = html2;
return this;
};
HtmlTag2.prototype.setInnerHtml = function(html2) {
return this.setInnerHTML(html2);
};
HtmlTag2.prototype.getInnerHTML = function() {
return this.innerHTML || "";
};
HtmlTag2.prototype.getInnerHtml = function() {
return this.getInnerHTML();
};
HtmlTag2.prototype.toAnchorString = function() {
var tagName = this.getTagName(), attrsStr = this.buildAttrsStr();
attrsStr = attrsStr ? " " + attrsStr : "";
return ["<", tagName, attrsStr, ">", this.getInnerHtml(), "", tagName, ">"].join("");
};
HtmlTag2.prototype.buildAttrsStr = function() {
if (!this.attrs)
return "";
var attrs = this.getAttrs(), attrsArr = [];
for (var prop in attrs) {
if (attrs.hasOwnProperty(prop)) {
attrsArr.push(prop + '="' + attrs[prop] + '"');
}
}
return attrsArr.join(" ");
};
return HtmlTag2;
}();
// node_modules/autolinker/dist/es2015/truncate/truncate-smart.js
function truncateSmart(url2, truncateLen, ellipsisChars) {
var ellipsisLengthBeforeParsing;
var ellipsisLength;
if (ellipsisChars == null) {
ellipsisChars = "…";
ellipsisLength = 3;
ellipsisLengthBeforeParsing = 8;
} else {
ellipsisLength = ellipsisChars.length;
ellipsisLengthBeforeParsing = ellipsisChars.length;
}
var parse_url = function(url3) {
var urlObj2 = {};
var urlSub = url3;
var match = urlSub.match(/^([a-z]+):\/\//i);
if (match) {
urlObj2.scheme = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^(.*?)(?=(\?|#|\/|$))/i);
if (match) {
urlObj2.host = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^\/(.*?)(?=(\?|#|$))/i);
if (match) {
urlObj2.path = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^\?(.*?)(?=(#|$))/i);
if (match) {
urlObj2.query = match[1];
urlSub = urlSub.substr(match[0].length);
}
match = urlSub.match(/^#(.*?)$/i);
if (match) {
urlObj2.fragment = match[1];
}
return urlObj2;
};
var buildUrl = function(urlObj2) {
var url3 = "";
if (urlObj2.scheme && urlObj2.host) {
url3 += urlObj2.scheme + "://";
}
if (urlObj2.host) {
url3 += urlObj2.host;
}
if (urlObj2.path) {
url3 += "/" + urlObj2.path;
}
if (urlObj2.query) {
url3 += "?" + urlObj2.query;
}
if (urlObj2.fragment) {
url3 += "#" + urlObj2.fragment;
}
return url3;
};
var buildSegment = function(segment, remainingAvailableLength3) {
var remainingAvailableLengthHalf = remainingAvailableLength3 / 2, startOffset = Math.ceil(remainingAvailableLengthHalf), endOffset = -1 * Math.floor(remainingAvailableLengthHalf), end2 = "";
if (endOffset < 0) {
end2 = segment.substr(endOffset);
}
return segment.substr(0, startOffset) + ellipsisChars + end2;
};
if (url2.length <= truncateLen) {
return url2;
}
var availableLength = truncateLen - ellipsisLength;
var urlObj = parse_url(url2);
if (urlObj.query) {
var matchQuery = urlObj.query.match(/^(.*?)(?=(\?|\#))(.*?)$/i);
if (matchQuery) {
urlObj.query = urlObj.query.substr(0, matchQuery[1].length);
url2 = buildUrl(urlObj);
}
}
if (url2.length <= truncateLen) {
return url2;
}
if (urlObj.host) {
urlObj.host = urlObj.host.replace(/^www\./, "");
url2 = buildUrl(urlObj);
}
if (url2.length <= truncateLen) {
return url2;
}
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);
}
// node_modules/autolinker/dist/es2015/truncate/truncate-middle.js
function truncateMiddle(url2, truncateLen, ellipsisChars) {
if (url2.length <= truncateLen) {
return url2;
}
var ellipsisLengthBeforeParsing;
var ellipsisLength;
if (ellipsisChars == null) {
ellipsisChars = "…";
ellipsisLengthBeforeParsing = 8;
ellipsisLength = 3;
} else {
ellipsisLengthBeforeParsing = ellipsisChars.length;
ellipsisLength = ellipsisChars.length;
}
var availableLength = truncateLen - ellipsisLength;
var end = "";
if (availableLength > 0) {
end = url2.substr(-1 * Math.floor(availableLength / 2));
}
return (url2.substr(0, Math.ceil(availableLength / 2)) + ellipsisChars + end).substr(0, availableLength + ellipsisLengthBeforeParsing);
}
// node_modules/autolinker/dist/es2015/truncate/truncate-end.js
function truncateEnd(anchorText, truncateLen, ellipsisChars) {
return ellipsis(anchorText, truncateLen, ellipsisChars);
}
// node_modules/autolinker/dist/es2015/anchor-tag-builder.js
var AnchorTagBuilder = function() {
function AnchorTagBuilder2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.newWindow = false;
this.truncate = {};
this.className = "";
this.newWindow = cfg.newWindow || false;
this.truncate = cfg.truncate || {};
this.className = cfg.className || "";
}
AnchorTagBuilder2.prototype.build = function(match) {
return new HtmlTag({
tagName: "a",
attrs: this.createAttrs(match),
innerHtml: this.processAnchorText(match.getAnchorText())
});
};
AnchorTagBuilder2.prototype.createAttrs = function(match) {
var attrs = {
href: match.getAnchorHref()
};
var cssClass = this.createCssClass(match);
if (cssClass) {
attrs["class"] = cssClass;
}
if (this.newWindow) {
attrs["target"] = "_blank";
attrs["rel"] = "noopener noreferrer";
}
if (this.truncate) {
if (this.truncate.length && this.truncate.length < match.getAnchorText().length) {
attrs["title"] = match.getAnchorHref();
}
}
return attrs;
};
AnchorTagBuilder2.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(" ");
}
};
AnchorTagBuilder2.prototype.processAnchorText = function(anchorText) {
anchorText = this.doTruncate(anchorText);
return anchorText;
};
AnchorTagBuilder2.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 AnchorTagBuilder2;
}();
// node_modules/tslib/tslib.es6.js
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
d2.__proto__ = b2;
} || function(d2, b2) {
for (var p in b2)
if (Object.prototype.hasOwnProperty.call(b2, p))
d2[p] = b2[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 __assign2(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);
};
// node_modules/autolinker/dist/es2015/match/abstract-match.js
var AbstractMatch = function() {
function AbstractMatch2(cfg) {
this._ = null;
this.matchedText = "";
this.offset = 0;
this.tagBuilder = cfg.tagBuilder;
this.matchedText = cfg.matchedText;
this.offset = cfg.offset;
}
AbstractMatch2.prototype.getMatchedText = function() {
return this.matchedText;
};
AbstractMatch2.prototype.setOffset = function(offset2) {
this.offset = offset2;
};
AbstractMatch2.prototype.getOffset = function() {
return this.offset;
};
AbstractMatch2.prototype.getCssClassSuffixes = function() {
return [this.type];
};
AbstractMatch2.prototype.buildTag = function() {
return this.tagBuilder.build(this);
};
return AbstractMatch2;
}();
// node_modules/autolinker/dist/es2015/parser/tld-regex.js
var tldRegexStr = "(?:xn--vermgensberatung-pwb|xn--vermgensberater-ctb|xn--clchc0ea0b2g2a9gcd|xn--w4r85el8fhu5dnra|northwesternmutual|travelersinsurance|verm\xF6gensberatung|xn--5su34j936bgsg|xn--bck1b9a5dre4c|xn--mgbah1a3hjkrd|xn--mgbai9azgqp6j|xn--mgberp4a5d4ar|xn--xkc2dl3a5ee0h|verm\xF6gensberater|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|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|\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD|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|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|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|\u0645\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u0627|abudhabi|airforce|allstate|attorney|barclays|barefoot|bargains|baseball|boutique|bradesco|broadway|brussels|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|\u0627\u0644\u0633\u0639\u0648\u062F\u064A\u0629|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|\u043A\u0430\u0442\u043E\u043B\u0438\u043A|\u0627\u062A\u0635\u0627\u0644\u0627\u062A|\u0627\u0644\u0628\u062D\u0631\u064A\u0646|\u0627\u0644\u062C\u0632\u0627\u0626\u0631|\u0627\u0644\u0639\u0644\u064A\u0627\u0646|\u067E\u0627\u06A9\u0633\u062A\u0627\u0646|\u0643\u0627\u062B\u0648\u0644\u064A\u0643|\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE|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|\u043C\u043E\u0441\u043A\u0432\u0430|\u043E\u043D\u043B\u0430\u0439\u043D|\u0627\u0628\u0648\u0638\u0628\u064A|\u0627\u0631\u0627\u0645\u0643\u0648|\u0627\u0644\u0627\u0631\u062F\u0646|\u0627\u0644\u0645\u063A\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062A|\u0641\u0644\u0633\u0637\u064A\u0646|\u0645\u0644\u064A\u0633\u064A\u0627|\u092D\u093E\u0930\u0924\u092E\u094D|\u0B87\u0BB2\u0B99\u0BCD\u0B95\u0BC8|\u30D5\u30A1\u30C3\u30B7\u30E7\u30F3|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|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|loans|locus|lotte|lotto|macys|mango|media|miami|money|movie|music|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|\u05D9\u05E9\u05E8\u05D0\u05DC|\u0627\u06CC\u0631\u0627\u0646|\u0628\u0627\u0632\u0627\u0631|\u0628\u06BE\u0627\u0631\u062A|\u0633\u0648\u062F\u0627\u0646|\u0633\u0648\u0631\u064A\u0629|\u0647\u0645\u0631\u0627\u0647|\u092D\u093E\u0930\u094B\u0924|\u0938\u0902\u0917\u0920\u0928|\u09AC\u09BE\u0982\u09B2\u09BE|\u0C2D\u0C3E\u0C30\u0C24\u0C4D|\u0D2D\u0D3E\u0D30\u0D24\u0D02|\u5609\u91CC\u5927\u9152\u5E97|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|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|kids|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|read|reit|rent|rest|rich|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|\u0434\u0435\u0442\u0438|\u0441\u0430\u0439\u0442|\u0628\u0627\u0631\u062A|\u0628\u064A\u062A\u0643|\u0680\u0627\u0631\u062A|\u062A\u0648\u0646\u0633|\u0634\u0628\u0643\u0629|\u0639\u0631\u0627\u0642|\u0639\u0645\u0627\u0646|\u0645\u0648\u0642\u0639|\u092D\u093E\u0930\u0924|\u09AD\u09BE\u09B0\u09A4|\u09AD\u09BE\u09F0\u09A4|\u0A2D\u0A3E\u0A30\u0A24|\u0AAD\u0ABE\u0AB0\u0AA4|\u0B2D\u0B3E\u0B30\u0B24|\u0CAD\u0CBE\u0CB0\u0CA4|\u0DBD\u0D82\u0D9A\u0DCF|\u30A2\u30DE\u30BE\u30F3|\u30B0\u30FC\u30B0\u30EB|\u30AF\u30E9\u30A6\u30C9|\u30DD\u30A4\u30F3\u30C8|\u7EC4\u7EC7\u673A\u6784|\u96FB\u8A0A\u76C8\u79D1|\u9999\u683C\u91CC\u62C9|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|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|one|ong|onl|ooo|org|ott|ovh|pay|pet|phd|pid|pin|pnc|pro|pru|pub|pwc|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|\u0431\u0435\u043B|\u043A\u043E\u043C|\u049B\u0430\u0437|\u043C\u043A\u0434|\u043C\u043E\u043D|\u043E\u0440\u0433|\u0440\u0443\u0441|\u0441\u0440\u0431|\u0443\u043A\u0440|\u0570\u0561\u0575|\u05E7\u05D5\u05DD|\u0639\u0631\u0628|\u0642\u0637\u0631|\u0643\u0648\u0645|\u0645\u0635\u0631|\u0915\u0949\u092E|\u0928\u0947\u091F|\u0E04\u0E2D\u0E21|\u0E44\u0E17\u0E22|\u0EA5\u0EB2\u0EA7|\u30B9\u30C8\u30A2|\u30BB\u30FC\u30EB|\u307F\u3093\u306A|\u4E2D\u6587\u7F51|\u4E9A\u9A6C\u900A|\u5929\u4E3B\u6559|\u6211\u7231\u4F60|\u65B0\u52A0\u5761|\u6DE1\u9A6C\u9521|\u8BFA\u57FA\u4E9A|\u98DE\u5229\u6D66|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|\u03B5\u03BB|\u03B5\u03C5|\u0431\u0433|\u0435\u044E|\u0440\u0444|\u10D2\u10D4|\uB2F7\uB137|\uB2F7\uCEF4|\uC0BC\uC131|\uD55C\uAD6D|\u30B3\u30E0|\u4E16\u754C|\u4E2D\u4FE1|\u4E2D\u56FD|\u4E2D\u570B|\u4F01\u4E1A|\u4F5B\u5C71|\u4FE1\u606F|\u5065\u5EB7|\u516B\u5366|\u516C\u53F8|\u516C\u76CA|\u53F0\u6E7E|\u53F0\u7063|\u5546\u57CE|\u5546\u5E97|\u5546\u6807|\u5609\u91CC|\u5728\u7EBF|\u5927\u62FF|\u5A31\u4E50|\u5BB6\u96FB|\u5E7F\u4E1C|\u5FAE\u535A|\u6148\u5584|\u624B\u673A|\u62DB\u8058|\u653F\u52A1|\u653F\u5E9C|\u65B0\u95FB|\u65F6\u5C1A|\u66F8\u7C4D|\u673A\u6784|\u6E38\u620F|\u6FB3\u9580|\u70B9\u770B|\u79FB\u52A8|\u7F51\u5740|\u7F51\u5E97|\u7F51\u7AD9|\u7F51\u7EDC|\u8054\u901A|\u8C37\u6B4C|\u8D2D\u7269|\u901A\u8CA9|\u96C6\u56E2|\u98DF\u54C1|\u9910\u5385|\u9999\u6E2F)";
var tldRegex = new RegExp("^" + tldRegexStr + "$");
// node_modules/autolinker/dist/es2015/parser/uri-utils.js
var urlSuffixStartCharsRe = /[\/?#]/;
var urlSuffixAllowedSpecialCharsRe = /[-+&@#/%=~_()|'$*\[\]{}\u2713]/;
var urlSuffixNotAllowedAsLastCharRe = /[?!:,.;^]/;
var httpSchemeRe = /https?:\/\//i;
var httpSchemePrefixRe = new RegExp("^" + httpSchemeRe.source, "i");
var urlSuffixedCharsNotAllowedAtEndRe = new RegExp(urlSuffixNotAllowedAsLastCharRe.source + "$");
var invalidSchemeRe = /^(javascript|vbscript):/i;
var schemeUrlRe = /^[A-Za-z][-.+A-Za-z0-9]*:(\/\/)?([^:/]*)/;
var tldUrlHostRe = /^(?:\/\/)?([^/#?:]+)/;
function isSchemeStartChar(char) {
return letterRe.test(char);
}
function isSchemeChar(char) {
return letterRe.test(char) || digitRe.test(char) || char === "+" || char === "-" || char === ".";
}
function isDomainLabelStartChar(char) {
return alphaNumericAndMarksRe.test(char);
}
function isDomainLabelChar(char) {
return char === "_" || isDomainLabelStartChar(char);
}
function isPathChar(char) {
return alphaNumericAndMarksRe.test(char) || urlSuffixAllowedSpecialCharsRe.test(char) || urlSuffixNotAllowedAsLastCharRe.test(char);
}
function isUrlSuffixStartChar(char) {
return urlSuffixStartCharsRe.test(char);
}
function isKnownTld(tld) {
return tldRegex.test(tld.toLowerCase());
}
function isValidSchemeUrl(url2) {
if (invalidSchemeRe.test(url2)) {
return false;
}
var schemeMatch = url2.match(schemeUrlRe);
if (!schemeMatch) {
return false;
}
var isAuthorityMatch = !!schemeMatch[1];
var host = schemeMatch[2];
if (isAuthorityMatch) {
return true;
}
if (host.indexOf(".") === -1 || !letterRe.test(host)) {
return false;
}
return true;
}
function isValidTldMatch(url2) {
var tldUrlHostMatch = url2.match(tldUrlHostRe);
if (!tldUrlHostMatch) {
return false;
}
var host = tldUrlHostMatch[0];
var hostLabels = host.split(".");
if (hostLabels.length < 2) {
return false;
}
var tld = hostLabels[hostLabels.length - 1];
if (!isKnownTld(tld)) {
return false;
}
return true;
}
var ipV4Re = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var ipV4PartRe = /[:/?#]/;
function isValidIpV4Address(url2) {
var ipV4Part = url2.split(ipV4PartRe, 1)[0];
return ipV4Re.test(ipV4Part);
}
// node_modules/autolinker/dist/es2015/match/url-match.js
var wwwPrefixRegex = /^(https?:\/\/)?(www\.)?/i;
var protocolRelativeRegex = /^\/\//;
var UrlMatch = function(_super) {
__extends(UrlMatch2, _super);
function UrlMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "url";
_this.url = "";
_this.urlMatchType = "scheme";
_this.protocolRelativeMatch = false;
_this.stripPrefix = {
scheme: true,
www: true
};
_this.stripTrailingSlash = true;
_this.decodePercentEncoding = true;
_this.protocolPrepended = false;
_this.urlMatchType = cfg.urlMatchType;
_this.url = cfg.url;
_this.protocolRelativeMatch = cfg.protocolRelativeMatch;
_this.stripPrefix = cfg.stripPrefix;
_this.stripTrailingSlash = cfg.stripTrailingSlash;
_this.decodePercentEncoding = cfg.decodePercentEncoding;
return _this;
}
UrlMatch2.prototype.getType = function() {
return "url";
};
UrlMatch2.prototype.getUrlMatchType = function() {
return this.urlMatchType;
};
UrlMatch2.prototype.getUrl = function() {
var url2 = this.url;
if (!this.protocolRelativeMatch && this.urlMatchType !== "scheme" && !this.protocolPrepended) {
url2 = this.url = "http://" + url2;
this.protocolPrepended = true;
}
return url2;
};
UrlMatch2.prototype.getAnchorHref = function() {
var url2 = this.getUrl();
return url2.replace(/&/g, "&");
};
UrlMatch2.prototype.getAnchorText = function() {
var anchorText = this.getMatchedText();
if (this.protocolRelativeMatch) {
anchorText = stripProtocolRelativePrefix(anchorText);
}
if (this.stripPrefix.scheme) {
anchorText = stripSchemePrefix(anchorText);
}
if (this.stripPrefix.www) {
anchorText = stripWwwPrefix(anchorText);
}
if (this.stripTrailingSlash) {
anchorText = removeTrailingSlash(anchorText);
}
if (this.decodePercentEncoding) {
anchorText = removePercentEncoding(anchorText);
}
return anchorText;
};
return UrlMatch2;
}(AbstractMatch);
function stripSchemePrefix(url2) {
return url2.replace(httpSchemePrefixRe, "");
}
function stripWwwPrefix(url2) {
return url2.replace(wwwPrefixRegex, "$1");
}
function stripProtocolRelativePrefix(text2) {
return text2.replace(protocolRelativeRegex, "");
}
function removeTrailingSlash(anchorText) {
if (anchorText.charAt(anchorText.length - 1) === "/") {
anchorText = anchorText.slice(0, -1);
}
return anchorText;
}
function removePercentEncoding(anchorText) {
var preProcessedEntityAnchorText = anchorText.replace(/%22/gi, """).replace(/%26/gi, "&").replace(/%27/gi, "'").replace(/%3C/gi, "<").replace(/%3E/gi, ">");
try {
return decodeURIComponent(preProcessedEntityAnchorText);
} catch (e) {
return preProcessedEntityAnchorText;
}
}
// node_modules/autolinker/dist/es2015/parser/email-utils.js
var mailtoSchemePrefixRe = /^mailto:/i;
var emailLocalPartCharRegex = new RegExp("[".concat(alphaNumericAndMarksCharsStr, "!#$%&'*+/=?^_`{|}~-]"));
function isEmailLocalPartStartChar(char) {
return alphaNumericAndMarksRe.test(char);
}
function isEmailLocalPartChar(char) {
return emailLocalPartCharRegex.test(char);
}
function isValidEmail(emailAddress) {
var emailAddressTld = emailAddress.split(".").pop() || "";
return isKnownTld(emailAddressTld);
}
// node_modules/autolinker/dist/es2015/match/email-match.js
var EmailMatch = function(_super) {
__extends(EmailMatch2, _super);
function EmailMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "email";
_this.email = "";
_this.email = cfg.email;
return _this;
}
EmailMatch2.prototype.getType = function() {
return "email";
};
EmailMatch2.prototype.getEmail = function() {
return this.email;
};
EmailMatch2.prototype.getAnchorHref = function() {
return "mailto:" + this.email;
};
EmailMatch2.prototype.getAnchorText = function() {
return this.email;
};
return EmailMatch2;
}(AbstractMatch);
// node_modules/autolinker/dist/es2015/parser/hashtag-utils.js
function isHashtagTextChar(char) {
return char === "_" || alphaNumericAndMarksRe.test(char);
}
function isValidHashtag(hashtag) {
return hashtag.length <= 140;
}
var hashtagServices = ["twitter", "facebook", "instagram", "tiktok"];
// node_modules/autolinker/dist/es2015/match/hashtag-match.js
var HashtagMatch = function(_super) {
__extends(HashtagMatch2, _super);
function HashtagMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "hashtag";
_this.serviceName = "twitter";
_this.hashtag = "";
_this.serviceName = cfg.serviceName;
_this.hashtag = cfg.hashtag;
return _this;
}
HashtagMatch2.prototype.getType = function() {
return "hashtag";
};
HashtagMatch2.prototype.getServiceName = function() {
return this.serviceName;
};
HashtagMatch2.prototype.getHashtag = function() {
return this.hashtag;
};
HashtagMatch2.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:
assertNever(serviceName);
throw new Error("Invalid hashtag service: ".concat(serviceName));
}
};
HashtagMatch2.prototype.getAnchorText = function() {
return "#" + this.hashtag;
};
HashtagMatch2.prototype.getCssClassSuffixes = function() {
var cssClassSuffixes = _super.prototype.getCssClassSuffixes.call(this), serviceName = this.getServiceName();
if (serviceName) {
cssClassSuffixes.push(serviceName);
}
return cssClassSuffixes;
};
return HashtagMatch2;
}(AbstractMatch);
// node_modules/autolinker/dist/es2015/parser/mention-utils.js
var mentionRegexes = {
twitter: /^@\w{1,15}$/,
instagram: /^@[_\w]{1,30}$/,
soundcloud: /^@[-a-z0-9_]{3,25}$/,
tiktok: /^@[.\w]{1,23}[\w]$/
};
var mentionTextCharRe = /[-\w.]/;
function isMentionTextChar(char) {
return mentionTextCharRe.test(char);
}
function isValidMention(mention, serviceName) {
var re = mentionRegexes[serviceName];
return re.test(mention);
}
var mentionServices = ["twitter", "instagram", "soundcloud", "tiktok"];
// node_modules/autolinker/dist/es2015/match/mention-match.js
var MentionMatch = function(_super) {
__extends(MentionMatch2, _super);
function MentionMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "mention";
_this.serviceName = "twitter";
_this.mention = "";
_this.mention = cfg.mention;
_this.serviceName = cfg.serviceName;
return _this;
}
MentionMatch2.prototype.getType = function() {
return "mention";
};
MentionMatch2.prototype.getMention = function() {
return this.mention;
};
MentionMatch2.prototype.getServiceName = function() {
return this.serviceName;
};
MentionMatch2.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:
throw new Error("Unknown service name to point mention to: " + this.serviceName);
}
};
MentionMatch2.prototype.getAnchorText = function() {
return "@" + this.mention;
};
MentionMatch2.prototype.getCssClassSuffixes = function() {
var cssClassSuffixes = _super.prototype.getCssClassSuffixes.call(this), serviceName = this.getServiceName();
if (serviceName) {
cssClassSuffixes.push(serviceName);
}
return cssClassSuffixes;
};
return MentionMatch2;
}(AbstractMatch);
// node_modules/autolinker/dist/es2015/parser/phone-number-utils.js
var separatorCharRe = /[-. ]/;
var hasDelimCharsRe = /[-. ()]/;
var controlCharRe = /[,;]/;
var mostPhoneNumbers = /(?:(?:(?:(\+)?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\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)[-. ]?(?:\d[-. ]?){6,12}\d+))([,;]+[0-9]+#?)*/;
var japanesePhoneRe = /(0([1-9]-?[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})/;
var validPhoneNumberRe = new RegExp("^".concat(mostPhoneNumbers.source, "|").concat(japanesePhoneRe.source, "$"));
function isPhoneNumberSeparatorChar(char) {
return separatorCharRe.test(char);
}
function isPhoneNumberControlChar(char) {
return controlCharRe.test(char);
}
function isValidPhoneNumber(phoneNumberText) {
var hasDelimiters = phoneNumberText.charAt(0) === "+" || hasDelimCharsRe.test(phoneNumberText);
return hasDelimiters && validPhoneNumberRe.test(phoneNumberText);
}
// node_modules/autolinker/dist/es2015/match/phone-match.js
var PhoneMatch = function(_super) {
__extends(PhoneMatch2, _super);
function PhoneMatch2(cfg) {
var _this = _super.call(this, cfg) || this;
_this.type = "phone";
_this.number = "";
_this.plusSign = false;
_this.number = cfg.number;
_this.plusSign = cfg.plusSign;
return _this;
}
PhoneMatch2.prototype.getType = function() {
return "phone";
};
PhoneMatch2.prototype.getPhoneNumber = function() {
return this.number;
};
PhoneMatch2.prototype.getNumber = function() {
return this.getPhoneNumber();
};
PhoneMatch2.prototype.getAnchorHref = function() {
return "tel:" + (this.plusSign ? "+" : "") + this.number;
};
PhoneMatch2.prototype.getAnchorText = function() {
return this.matchedText;
};
return PhoneMatch2;
}(AbstractMatch);
// node_modules/autolinker/dist/es2015/parser/parse-matches.js
function parseMatches(text2, args) {
var tagBuilder = args.tagBuilder;
var stripPrefix = args.stripPrefix;
var stripTrailingSlash = args.stripTrailingSlash;
var decodePercentEncoding = args.decodePercentEncoding;
var hashtagServiceName = args.hashtagServiceName;
var mentionServiceName = args.mentionServiceName;
var matches = [];
var textLen = text2.length;
var stateMachines = [];
var charIdx = 0;
for (; charIdx < textLen; charIdx++) {
var char = text2.charAt(charIdx);
if (stateMachines.length === 0) {
stateNoMatch(char);
} else {
for (var stateIdx = stateMachines.length - 1; stateIdx >= 0; stateIdx--) {
var stateMachine = stateMachines[stateIdx];
switch (stateMachine.state) {
case 11:
stateProtocolRelativeSlash1(stateMachine, char);
break;
case 12:
stateProtocolRelativeSlash2(stateMachine, char);
break;
case 0:
stateSchemeChar(stateMachine, char);
break;
case 1:
stateSchemeHyphen(stateMachine, char);
break;
case 2:
stateSchemeColon(stateMachine, char);
break;
case 3:
stateSchemeSlash1(stateMachine, char);
break;
case 4:
stateSchemeSlash2(stateMachine, char);
break;
case 5:
stateDomainLabelChar(stateMachine, char);
break;
case 6:
stateDomainHyphen(stateMachine, char);
break;
case 7:
stateDomainDot(stateMachine, char);
break;
case 13:
stateIpV4Digit(stateMachine, char);
break;
case 14:
stateIPv4Dot(stateMachine, char);
break;
case 8:
statePortColon(stateMachine, char);
break;
case 9:
statePortNumber(stateMachine, char);
break;
case 10:
statePath(stateMachine, char);
break;
case 15:
stateEmailMailto_M(stateMachine, char);
break;
case 16:
stateEmailMailto_A(stateMachine, char);
break;
case 17:
stateEmailMailto_I(stateMachine, char);
break;
case 18:
stateEmailMailto_L(stateMachine, char);
break;
case 19:
stateEmailMailto_T(stateMachine, char);
break;
case 20:
stateEmailMailto_O(stateMachine, char);
break;
case 21:
stateEmailMailtoColon(stateMachine, char);
break;
case 22:
stateEmailLocalPart(stateMachine, char);
break;
case 23:
stateEmailLocalPartDot(stateMachine, char);
break;
case 24:
stateEmailAtSign(stateMachine, char);
break;
case 25:
stateEmailDomainChar(stateMachine, char);
break;
case 26:
stateEmailDomainHyphen(stateMachine, char);
break;
case 27:
stateEmailDomainDot(stateMachine, char);
break;
case 28:
stateHashtagHashChar(stateMachine, char);
break;
case 29:
stateHashtagTextChar(stateMachine, char);
break;
case 30:
stateMentionAtChar(stateMachine, char);
break;
case 31:
stateMentionTextChar(stateMachine, char);
break;
case 32:
statePhoneNumberOpenParen(stateMachine, char);
break;
case 33:
statePhoneNumberAreaCodeDigit1(stateMachine, char);
break;
case 34:
statePhoneNumberAreaCodeDigit2(stateMachine, char);
break;
case 35:
statePhoneNumberAreaCodeDigit3(stateMachine, char);
break;
case 36:
statePhoneNumberCloseParen(stateMachine, char);
break;
case 37:
statePhoneNumberPlus(stateMachine, char);
break;
case 38:
statePhoneNumberDigit(stateMachine, char);
break;
case 39:
statePhoneNumberSeparator(stateMachine, char);
break;
case 40:
statePhoneNumberControlChar(stateMachine, char);
break;
case 41:
statePhoneNumberPoundChar(stateMachine, char);
break;
default:
assertNever(stateMachine.state);
}
}
}
}
for (var i = stateMachines.length - 1; i >= 0; i--) {
stateMachines.forEach(function(stateMachine2) {
return captureMatchIfValidAndRemove(stateMachine2);
});
}
return matches;
function stateNoMatch(char2) {
if (char2 === "#") {
stateMachines.push(createHashtagStateMachine(charIdx, 28));
} else if (char2 === "@") {
stateMachines.push(createMentionStateMachine(charIdx, 30));
} else if (char2 === "/") {
stateMachines.push(createTldUrlStateMachine(charIdx, 11));
} else if (char2 === "+") {
stateMachines.push(createPhoneNumberStateMachine(charIdx, 37));
} else if (char2 === "(") {
stateMachines.push(createPhoneNumberStateMachine(charIdx, 32));
} else {
if (digitRe.test(char2)) {
stateMachines.push(createPhoneNumberStateMachine(charIdx, 38));
stateMachines.push(createIpV4UrlStateMachine(charIdx, 13));
}
if (isEmailLocalPartStartChar(char2)) {
var startState = char2.toLowerCase() === "m" ? 15 : 22;
stateMachines.push(createEmailStateMachine(charIdx, startState));
}
if (isSchemeStartChar(char2)) {
stateMachines.push(createSchemeUrlStateMachine(charIdx, 0));
}
if (alphaNumericAndMarksRe.test(char2)) {
stateMachines.push(createTldUrlStateMachine(charIdx, 5));
}
}
}
function stateSchemeChar(stateMachine2, char2) {
if (char2 === ":") {
stateMachine2.state = 2;
} else if (char2 === "-") {
stateMachine2.state = 1;
} else if (isSchemeChar(char2)) {
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateSchemeHyphen(stateMachine2, char2) {
if (char2 === "-") {
} else if (char2 === "/") {
remove2(stateMachines, stateMachine2);
stateMachines.push(createTldUrlStateMachine(charIdx, 11));
} else if (isSchemeChar(char2)) {
stateMachine2.state = 0;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateSchemeColon(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 3;
} else if (char2 === ".") {
remove2(stateMachines, stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
if (isSchemeStartChar(char2)) {
stateMachines.push(createSchemeUrlStateMachine(charIdx, 0));
}
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateSchemeSlash1(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 4;
} else if (isPathChar(char2)) {
stateMachine2.state = 10;
stateMachine2.acceptStateReached = true;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateSchemeSlash2(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 10;
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
stateMachine2.acceptStateReached = true;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateProtocolRelativeSlash1(stateMachine2, char2) {
if (char2 === "/") {
stateMachine2.state = 12;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateProtocolRelativeSlash2(stateMachine2, char2) {
if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateDomainLabelChar(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 7;
} else if (char2 === "-") {
stateMachine2.state = 6;
} else if (char2 === ":") {
stateMachine2.state = 8;
} else if (isUrlSuffixStartChar(char2)) {
stateMachine2.state = 10;
} else if (isDomainLabelChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateDomainHyphen(stateMachine2, char2) {
if (char2 === "-") {
} else if (char2 === ".") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateDomainDot(stateMachine2, char2) {
if (char2 === ".") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 5;
stateMachine2.acceptStateReached = true;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateIpV4Digit(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 14;
} else if (char2 === ":") {
stateMachine2.state = 8;
} else if (digitRe.test(char2)) {
} else if (isUrlSuffixStartChar(char2)) {
stateMachine2.state = 10;
} else if (alphaNumericAndMarksRe.test(char2)) {
remove2(stateMachines, stateMachine2);
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateIPv4Dot(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.octetsEncountered++;
if (stateMachine2.octetsEncountered === 4) {
stateMachine2.acceptStateReached = true;
}
stateMachine2.state = 13;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePortColon(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 9;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePortNumber(stateMachine2, char2) {
if (digitRe.test(char2)) {
} else if (isUrlSuffixStartChar(char2)) {
stateMachine2.state = 10;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePath(stateMachine2, char2) {
if (isPathChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateEmailMailto_M(stateMachine2, char2) {
if (char2.toLowerCase() === "a") {
stateMachine2.state = 16;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_A(stateMachine2, char2) {
if (char2.toLowerCase() === "i") {
stateMachine2.state = 17;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_I(stateMachine2, char2) {
if (char2.toLowerCase() === "l") {
stateMachine2.state = 18;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_L(stateMachine2, char2) {
if (char2.toLowerCase() === "t") {
stateMachine2.state = 19;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_T(stateMachine2, char2) {
if (char2.toLowerCase() === "o") {
stateMachine2.state = 20;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailto_O(stateMachine2, char2) {
if (char2.toLowerCase() === ":") {
stateMachine2.state = 21;
} else {
stateEmailLocalPart(stateMachine2, char2);
}
}
function stateEmailMailtoColon(stateMachine2, char2) {
if (isEmailLocalPartChar(char2)) {
stateMachine2.state = 22;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailLocalPart(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 23;
} else if (char2 === "@") {
stateMachine2.state = 24;
} else if (isEmailLocalPartChar(char2)) {
stateMachine2.state = 22;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailLocalPartDot(stateMachine2, char2) {
if (char2 === ".") {
remove2(stateMachines, stateMachine2);
} else if (char2 === "@") {
remove2(stateMachines, stateMachine2);
} else if (isEmailLocalPartChar(char2)) {
stateMachine2.state = 22;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailAtSign(stateMachine2, char2) {
if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 25;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateEmailDomainChar(stateMachine2, char2) {
if (char2 === ".") {
stateMachine2.state = 27;
} else if (char2 === "-") {
stateMachine2.state = 26;
} else if (isDomainLabelChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateEmailDomainHyphen(stateMachine2, char2) {
if (char2 === "-" || char2 === ".") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelChar(char2)) {
stateMachine2.state = 25;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateEmailDomainDot(stateMachine2, char2) {
if (char2 === "." || char2 === "-") {
captureMatchIfValidAndRemove(stateMachine2);
} else if (isDomainLabelStartChar(char2)) {
stateMachine2.state = 25;
stateMachine2.acceptStateReached = true;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateHashtagHashChar(stateMachine2, char2) {
if (isHashtagTextChar(char2)) {
stateMachine2.state = 29;
stateMachine2.acceptStateReached = true;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateHashtagTextChar(stateMachine2, char2) {
if (isHashtagTextChar(char2)) {
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function stateMentionAtChar(stateMachine2, char2) {
if (isMentionTextChar(char2)) {
stateMachine2.state = 31;
stateMachine2.acceptStateReached = true;
} else {
remove2(stateMachines, stateMachine2);
}
}
function stateMentionTextChar(stateMachine2, char2) {
if (isMentionTextChar(char2)) {
} else if (alphaNumericAndMarksRe.test(char2)) {
remove2(stateMachines, stateMachine2);
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePhoneNumberPlus(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else {
remove2(stateMachines, stateMachine2);
stateNoMatch(char2);
}
}
function statePhoneNumberOpenParen(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 33;
} else {
remove2(stateMachines, stateMachine2);
}
stateNoMatch(char2);
}
function statePhoneNumberAreaCodeDigit1(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 34;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberAreaCodeDigit2(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 35;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberAreaCodeDigit3(stateMachine2, char2) {
if (char2 === ")") {
stateMachine2.state = 36;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberCloseParen(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else if (isPhoneNumberSeparatorChar(char2)) {
stateMachine2.state = 39;
} else {
remove2(stateMachines, stateMachine2);
}
}
function statePhoneNumberDigit(stateMachine2, char2) {
stateMachine2.acceptStateReached = true;
if (isPhoneNumberControlChar(char2)) {
stateMachine2.state = 40;
} else if (char2 === "#") {
stateMachine2.state = 41;
} else if (digitRe.test(char2)) {
} else if (char2 === "(") {
stateMachine2.state = 32;
} else if (isPhoneNumberSeparatorChar(char2)) {
stateMachine2.state = 39;
} else {
captureMatchIfValidAndRemove(stateMachine2);
if (isSchemeStartChar(char2)) {
stateMachines.push(createSchemeUrlStateMachine(charIdx, 0));
}
}
}
function statePhoneNumberSeparator(stateMachine2, char2) {
if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else if (char2 === "(") {
stateMachine2.state = 32;
} else {
captureMatchIfValidAndRemove(stateMachine2);
stateNoMatch(char2);
}
}
function statePhoneNumberControlChar(stateMachine2, char2) {
if (isPhoneNumberControlChar(char2)) {
} else if (char2 === "#") {
stateMachine2.state = 41;
} else if (digitRe.test(char2)) {
stateMachine2.state = 38;
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function statePhoneNumberPoundChar(stateMachine2, char2) {
if (isPhoneNumberControlChar(char2)) {
stateMachine2.state = 40;
} else if (digitRe.test(char2)) {
remove2(stateMachines, stateMachine2);
} else {
captureMatchIfValidAndRemove(stateMachine2);
}
}
function captureMatchIfValidAndRemove(stateMachine2) {
remove2(stateMachines, stateMachine2);
if (!stateMachine2.acceptStateReached) {
return;
}
var startIdx = stateMachine2.startIdx;
var matchedText = text2.slice(stateMachine2.startIdx, charIdx);
matchedText = excludeUnbalancedTrailingBracesAndPunctuation(matchedText);
if (stateMachine2.type === "url") {
var charBeforeUrlMatch = text2.charAt(stateMachine2.startIdx - 1);
if (charBeforeUrlMatch === "@") {
return;
}
var urlMatchType = stateMachine2.matchType;
if (urlMatchType === "scheme") {
var httpSchemeMatch = httpSchemeRe.exec(matchedText);
if (httpSchemeMatch) {
startIdx = startIdx + httpSchemeMatch.index;
matchedText = matchedText.slice(httpSchemeMatch.index);
}
if (!isValidSchemeUrl(matchedText)) {
return;
}
} else if (urlMatchType === "tld") {
if (!isValidTldMatch(matchedText)) {
return;
}
} else if (urlMatchType === "ipV4") {
if (!isValidIpV4Address(matchedText)) {
return;
}
} else {
assertNever(urlMatchType);
}
matches.push(new UrlMatch({
tagBuilder,
matchedText,
offset: startIdx,
urlMatchType,
url: matchedText,
protocolRelativeMatch: matchedText.slice(0, 2) === "//",
stripPrefix,
stripTrailingSlash,
decodePercentEncoding
}));
} else if (stateMachine2.type === "email") {
if (isValidEmail(matchedText)) {
matches.push(new EmailMatch({
tagBuilder,
matchedText,
offset: startIdx,
email: matchedText.replace(mailtoSchemePrefixRe, "")
}));
}
} else if (stateMachine2.type === "hashtag") {
if (isValidHashtag(matchedText)) {
matches.push(new HashtagMatch({
tagBuilder,
matchedText,
offset: startIdx,
serviceName: hashtagServiceName,
hashtag: matchedText.slice(1)
}));
}
} else if (stateMachine2.type === "mention") {
if (isValidMention(matchedText, mentionServiceName)) {
matches.push(new MentionMatch({
tagBuilder,
matchedText,
offset: startIdx,
serviceName: mentionServiceName,
mention: matchedText.slice(1)
}));
}
} else if (stateMachine2.type === "phone") {
matchedText = matchedText.replace(/ +$/g, "");
if (isValidPhoneNumber(matchedText)) {
var cleanNumber = matchedText.replace(/[^0-9,;#]/g, "");
matches.push(new PhoneMatch({
tagBuilder,
matchedText,
offset: startIdx,
number: cleanNumber,
plusSign: matchedText.charAt(0) === "+"
}));
}
} else {
assertNever(stateMachine2);
}
}
}
var openBraceRe = /[\(\{\[]/;
var closeBraceRe = /[\)\}\]]/;
var oppositeBrace = {
")": "(",
"}": "{",
"]": "["
};
function excludeUnbalancedTrailingBracesAndPunctuation(matchedText) {
var braceCounts = {
"(": 0,
"{": 0,
"[": 0
};
for (var i = 0; i < matchedText.length; i++) {
var char_1 = matchedText.charAt(i);
if (openBraceRe.test(char_1)) {
braceCounts[char_1]++;
} else if (closeBraceRe.test(char_1)) {
braceCounts[oppositeBrace[char_1]]--;
}
}
var endIdx = matchedText.length - 1;
var char;
while (endIdx >= 0) {
char = matchedText.charAt(endIdx);
if (closeBraceRe.test(char)) {
var oppositeBraceChar = oppositeBrace[char];
if (braceCounts[oppositeBraceChar] < 0) {
braceCounts[oppositeBraceChar]++;
endIdx--;
} else {
break;
}
} else if (urlSuffixedCharsNotAllowedAtEndRe.test(char)) {
endIdx--;
} else {
break;
}
}
return matchedText.slice(0, endIdx + 1);
}
function createSchemeUrlStateMachine(startIdx, state) {
return {
type: "url",
startIdx,
state,
acceptStateReached: false,
matchType: "scheme"
};
}
function createTldUrlStateMachine(startIdx, state) {
return {
type: "url",
startIdx,
state,
acceptStateReached: false,
matchType: "tld"
};
}
function createIpV4UrlStateMachine(startIdx, state) {
return {
type: "url",
startIdx,
state,
acceptStateReached: false,
matchType: "ipV4",
octetsEncountered: 1
};
}
function createEmailStateMachine(startIdx, state) {
return {
type: "email",
startIdx,
state,
acceptStateReached: false
};
}
function createHashtagStateMachine(startIdx, state) {
return {
type: "hashtag",
startIdx,
state,
acceptStateReached: false
};
}
function createMentionStateMachine(startIdx, state) {
return {
type: "mention",
startIdx,
state,
acceptStateReached: false
};
}
function createPhoneNumberStateMachine(startIdx, state) {
return {
type: "phone",
startIdx,
state,
acceptStateReached: false
};
}
// node_modules/autolinker/dist/es2015/htmlParser/parse-html.js
function parseHtml(html2, _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 = html2.length, state = 0, currentDataIdx = 0, currentTag = noCurrentTag;
while (charIdx < len) {
var char = html2.charAt(charIdx);
switch (state) {
case 0:
stateData(char);
break;
case 1:
stateTagOpen(char);
break;
case 2:
stateEndTagOpen(char);
break;
case 3:
stateTagName(char);
break;
case 4:
stateBeforeAttributeName(char);
break;
case 5:
stateAttributeName(char);
break;
case 6:
stateAfterAttributeName(char);
break;
case 7:
stateBeforeAttributeValue(char);
break;
case 8:
stateAttributeValueDoubleQuoted(char);
break;
case 9:
stateAttributeValueSingleQuoted(char);
break;
case 10:
stateAttributeValueUnquoted(char);
break;
case 11:
stateAfterAttributeValueQuoted(char);
break;
case 12:
stateSelfClosingStartTag(char);
break;
case 13:
stateMarkupDeclarationOpen(char);
break;
case 14:
stateCommentStart(char);
break;
case 15:
stateCommentStartDash(char);
break;
case 16:
stateComment(char);
break;
case 17:
stateCommentEndDash(char);
break;
case 18:
stateCommentEnd(char);
break;
case 19:
stateCommentEndBang(char);
break;
case 20:
stateDoctype(char);
break;
default:
assertNever(state);
}
charIdx++;
}
if (currentDataIdx < charIdx) {
emitText();
}
function stateData(char2) {
if (char2 === "<") {
startNewTag();
}
}
function stateTagOpen(char2) {
if (char2 === "!") {
state = 13;
} else if (char2 === "/") {
state = 2;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isClosing: true }));
} else if (char2 === "<") {
startNewTag();
} else if (letterRe.test(char2)) {
state = 3;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isOpening: true }));
} else {
state = 0;
currentTag = noCurrentTag;
}
}
function stateTagName(char2) {
if (whitespaceRe.test(char2)) {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
state = 4;
} else if (char2 === "<") {
startNewTag();
} else if (char2 === "/") {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
state = 12;
} else if (char2 === ">") {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { name: captureTagName() }));
emitTagAndPreviousTextNode();
} else if (!letterRe.test(char2) && !digitRe.test(char2) && char2 !== ":") {
resetToDataState();
} else {
}
}
function stateEndTagOpen(char2) {
if (char2 === ">") {
resetToDataState();
} else if (letterRe.test(char2)) {
state = 3;
} else {
resetToDataState();
}
}
function stateBeforeAttributeName(char2) {
if (whitespaceRe.test(char2)) {
} else if (char2 === "/") {
state = 12;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else if (char2 === "=" || quoteRe.test(char2) || controlCharsRe.test(char2)) {
resetToDataState();
} else {
state = 5;
}
}
function stateAttributeName(char2) {
if (whitespaceRe.test(char2)) {
state = 6;
} else if (char2 === "/") {
state = 12;
} else if (char2 === "=") {
state = 7;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else if (quoteRe.test(char2)) {
resetToDataState();
} else {
}
}
function stateAfterAttributeName(char2) {
if (whitespaceRe.test(char2)) {
} else if (char2 === "/") {
state = 12;
} else if (char2 === "=") {
state = 7;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else if (quoteRe.test(char2)) {
resetToDataState();
} else {
state = 5;
}
}
function stateBeforeAttributeValue(char2) {
if (whitespaceRe.test(char2)) {
} else if (char2 === '"') {
state = 8;
} else if (char2 === "'") {
state = 9;
} else if (/[>=`]/.test(char2)) {
resetToDataState();
} else if (char2 === "<") {
startNewTag();
} else {
state = 10;
}
}
function stateAttributeValueDoubleQuoted(char2) {
if (char2 === '"') {
state = 11;
} else {
}
}
function stateAttributeValueSingleQuoted(char2) {
if (char2 === "'") {
state = 11;
} else {
}
}
function stateAttributeValueUnquoted(char2) {
if (whitespaceRe.test(char2)) {
state = 4;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else {
}
}
function stateAfterAttributeValueQuoted(char2) {
if (whitespaceRe.test(char2)) {
state = 4;
} else if (char2 === "/") {
state = 12;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else {
state = 4;
reconsumeCurrentCharacter();
}
}
function stateSelfClosingStartTag(char2) {
if (char2 === ">") {
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { isClosing: true }));
emitTagAndPreviousTextNode();
} else {
state = 4;
}
}
function stateMarkupDeclarationOpen(char2) {
if (html2.substr(charIdx, 2) === "--") {
charIdx += 2;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { type: "comment" }));
state = 14;
} else if (html2.substr(charIdx, 7).toUpperCase() === "DOCTYPE") {
charIdx += 7;
currentTag = new CurrentTag(__assign(__assign({}, currentTag), { type: "doctype" }));
state = 20;
} else {
resetToDataState();
}
}
function stateCommentStart(char2) {
if (char2 === "-") {
state = 15;
} else if (char2 === ">") {
resetToDataState();
} else {
state = 16;
}
}
function stateCommentStartDash(char2) {
if (char2 === "-") {
state = 18;
} else if (char2 === ">") {
resetToDataState();
} else {
state = 16;
}
}
function stateComment(char2) {
if (char2 === "-") {
state = 17;
} else {
}
}
function stateCommentEndDash(char2) {
if (char2 === "-") {
state = 18;
} else {
state = 16;
}
}
function stateCommentEnd(char2) {
if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "!") {
state = 19;
} else if (char2 === "-") {
} else {
state = 16;
}
}
function stateCommentEndBang(char2) {
if (char2 === "-") {
state = 17;
} else if (char2 === ">") {
emitTagAndPreviousTextNode();
} else {
state = 16;
}
}
function stateDoctype(char2) {
if (char2 === ">") {
emitTagAndPreviousTextNode();
} else if (char2 === "<") {
startNewTag();
} else {
}
}
function resetToDataState() {
state = 0;
currentTag = noCurrentTag;
}
function startNewTag() {
state = 1;
currentTag = new CurrentTag({ idx: charIdx });
}
function emitTagAndPreviousTextNode() {
var textBeforeTag = html2.slice(currentDataIdx, currentTag.idx);
if (textBeforeTag) {
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) {
onCloseTag(currentTag.name, currentTag.idx);
}
}
resetToDataState();
currentDataIdx = charIdx + 1;
}
function emitText() {
var text2 = html2.slice(currentDataIdx, charIdx);
onText(text2, currentDataIdx);
currentDataIdx = charIdx + 1;
}
function captureTagName() {
var startIdx = currentTag.idx + (currentTag.isClosing ? 2 : 1);
return html2.slice(startIdx, charIdx).toLowerCase();
}
function reconsumeCurrentCharacter() {
charIdx--;
}
}
var CurrentTag = function() {
function CurrentTag2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.idx = cfg.idx !== void 0 ? cfg.idx : -1;
this.type = cfg.type || "tag";
this.name = cfg.name || "";
this.isOpening = !!cfg.isOpening;
this.isClosing = !!cfg.isClosing;
}
return CurrentTag2;
}();
// node_modules/autolinker/dist/es2015/autolinker.js
var Autolinker = function() {
function Autolinker2(cfg) {
if (cfg === void 0) {
cfg = {};
}
this.version = Autolinker2.version;
this.urls = {};
this.email = true;
this.phone = true;
this.hashtag = false;
this.mention = false;
this.newWindow = true;
this.stripPrefix = {
scheme: true,
www: true
};
this.stripTrailingSlash = true;
this.decodePercentEncoding = true;
this.truncate = {
length: 0,
location: "end"
};
this.className = "";
this.replaceFn = null;
this.context = void 0;
this.sanitizeHtml = false;
this.tagBuilder = null;
this.urls = normalizeUrlsCfg(cfg.urls);
this.email = isBoolean(cfg.email) ? cfg.email : this.email;
this.phone = isBoolean(cfg.phone) ? cfg.phone : this.phone;
this.hashtag = cfg.hashtag || this.hashtag;
this.mention = cfg.mention || this.mention;
this.newWindow = isBoolean(cfg.newWindow) ? cfg.newWindow : this.newWindow;
this.stripPrefix = normalizeStripPrefixCfg(cfg.stripPrefix);
this.stripTrailingSlash = isBoolean(cfg.stripTrailingSlash) ? cfg.stripTrailingSlash : this.stripTrailingSlash;
this.decodePercentEncoding = isBoolean(cfg.decodePercentEncoding) ? cfg.decodePercentEncoding : this.decodePercentEncoding;
this.sanitizeHtml = cfg.sanitizeHtml || false;
var mention = this.mention;
if (mention !== false && mentionServices.indexOf(mention) === -1) {
throw new Error("invalid `mention` cfg '".concat(mention, "' - see docs"));
}
var hashtag = this.hashtag;
if (hashtag !== false && hashtagServices.indexOf(hashtag) === -1) {
throw new Error("invalid `hashtag` cfg '".concat(hashtag, "' - see docs"));
}
this.truncate = normalizeTruncateCfg(cfg.truncate);
this.className = cfg.className || this.className;
this.replaceFn = cfg.replaceFn || this.replaceFn;
this.context = cfg.context || this;
}
Autolinker2.link = function(textOrHtml, options) {
var autolinker3 = new Autolinker2(options);
return autolinker3.link(textOrHtml);
};
Autolinker2.parse = function(textOrHtml, options) {
var autolinker3 = new Autolinker2(options);
return autolinker3.parse(textOrHtml);
};
Autolinker2.prototype.parse = function(textOrHtml) {
var _this = this;
var skipTagNames = ["a", "style", "script"], skipTagsStackCount = 0, matches = [];
parseHtml(textOrHtml, {
onOpenTag: function(tagName) {
if (skipTagNames.indexOf(tagName) >= 0) {
skipTagsStackCount++;
}
},
onText: function(text2, offset2) {
if (skipTagsStackCount === 0) {
var htmlCharacterEntitiesRegex = /( | |<|<|>|>|"|"|')/gi;
var textSplit = text2.split(htmlCharacterEntitiesRegex);
var currentOffset_1 = offset2;
textSplit.forEach(function(splitText, i) {
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);
}
},
onComment: function(_offset) {
},
onDoctype: function(_offset) {
}
});
matches = this.compactMatches(matches);
matches = this.removeUnwantedMatches(matches);
return matches;
};
Autolinker2.prototype.compactMatches = function(matches) {
matches.sort(function(a3, b) {
return a3.getOffset() - b.getOffset();
});
var i = 0;
while (i < matches.length - 1) {
var match = matches[i], offset2 = match.getOffset(), matchedTextLength = match.getMatchedText().length, endIdx = offset2 + matchedTextLength;
if (i + 1 < matches.length) {
if (matches[i + 1].getOffset() === offset2) {
var removeIdx = matches[i + 1].getMatchedText().length > matchedTextLength ? i : i + 1;
matches.splice(removeIdx, 1);
continue;
}
if (matches[i + 1].getOffset() < endIdx) {
matches.splice(i + 1, 1);
continue;
}
}
i++;
}
return matches;
};
Autolinker2.prototype.removeUnwantedMatches = function(matches) {
if (!this.hashtag)
removeWithPredicate(matches, function(match) {
return match.getType() === "hashtag";
});
if (!this.email)
removeWithPredicate(matches, function(match) {
return match.getType() === "email";
});
if (!this.phone)
removeWithPredicate(matches, function(match) {
return match.getType() === "phone";
});
if (!this.mention)
removeWithPredicate(matches, function(match) {
return match.getType() === "mention";
});
if (!this.urls.schemeMatches) {
removeWithPredicate(matches, function(m) {
return m.getType() === "url" && m.getUrlMatchType() === "scheme";
});
}
if (!this.urls.tldMatches) {
removeWithPredicate(matches, function(m) {
return m.getType() === "url" && m.getUrlMatchType() === "tld";
});
}
if (!this.urls.ipV4Matches) {
removeWithPredicate(matches, function(m) {
return m.getType() === "url" && m.getUrlMatchType() === "ipV4";
});
}
return matches;
};
Autolinker2.prototype.parseText = function(text2, offset2) {
if (offset2 === void 0) {
offset2 = 0;
}
offset2 = offset2 || 0;
var matches = parseMatches(text2, {
tagBuilder: this.getTagBuilder(),
stripPrefix: this.stripPrefix,
stripTrailingSlash: this.stripTrailingSlash,
decodePercentEncoding: this.decodePercentEncoding,
hashtagServiceName: this.hashtag,
mentionServiceName: this.mention || "twitter"
});
for (var i = 0, numTextMatches = matches.length; i < numTextMatches; i++) {
matches[i].setOffset(offset2 + matches[i].getOffset());
}
return matches;
};
Autolinker2.prototype.link = function(textOrHtml) {
if (!textOrHtml) {
return "";
}
if (this.sanitizeHtml) {
textOrHtml = textOrHtml.replace(//g, ">");
}
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));
return newHtml.join("");
};
Autolinker2.prototype.createMatchReturnVal = function(match) {
var replaceFnResult;
if (this.replaceFn) {
replaceFnResult = this.replaceFn.call(this.context, match);
}
if (typeof replaceFnResult === "string") {
return replaceFnResult;
} else if (replaceFnResult === false) {
return match.getMatchedText();
} else if (replaceFnResult instanceof HtmlTag) {
return replaceFnResult.toAnchorString();
} else {
var anchorTag = match.buildTag();
return anchorTag.toAnchorString();
}
};
Autolinker2.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;
};
Autolinker2.version = version;
return Autolinker2;
}();
var autolinker_default = Autolinker;
function normalizeUrlsCfg(urls) {
if (urls == null)
urls = true;
if (isBoolean(urls)) {
return { schemeMatches: urls, tldMatches: urls, ipV4Matches: urls };
} else {
return {
schemeMatches: isBoolean(urls.schemeMatches) ? urls.schemeMatches : true,
tldMatches: isBoolean(urls.tldMatches) ? urls.tldMatches : true,
ipV4Matches: isBoolean(urls.ipV4Matches) ? urls.ipV4Matches : true
};
}
}
function normalizeStripPrefixCfg(stripPrefix) {
if (stripPrefix == null)
stripPrefix = true;
if (isBoolean(stripPrefix)) {
return { scheme: stripPrefix, www: stripPrefix };
} else {
return {
scheme: isBoolean(stripPrefix.scheme) ? stripPrefix.scheme : true,
www: isBoolean(stripPrefix.www) ? stripPrefix.www : true
};
}
}
function normalizeTruncateCfg(truncate) {
if (typeof truncate === "number") {
return { length: truncate, location: "end" };
} else {
return defaults(truncate || {}, {
length: Number.POSITIVE_INFINITY,
location: "end"
});
}
}
// node_modules/autolinker/dist/es2015/index.js
var es2015_default = autolinker_default;
// node_modules/@cesium/engine/Source/DataSources/GpxDataSource.js
var parser;
if (typeof DOMParser !== "undefined") {
parser = new DOMParser();
}
var autolinker = new es2015_default({
stripPrefix: false,
email: false,
replaceFn: function(linker, match) {
return match.urlMatchType === "scheme" || match.urlMatchType === "www";
}
});
var BILLBOARD_SIZE = 32;
var BILLBOARD_NEAR_DISTANCE = 2414016;
var BILLBOARD_NEAR_RATIO = 1;
var BILLBOARD_FAR_DISTANCE = 16093e3;
var BILLBOARD_FAR_RATIO = 0.1;
var gpxNamespaces = [null, void 0, "http://www.topografix.com/GPX/1/1"];
var namespaces = {
gpx: gpxNamespaces
};
function readBlobAsText(blob) {
return new Promise((resolve2, reject) => {
const reader = new FileReader();
reader.addEventListener("load", function() {
resolve2(reader.result);
});
reader.addEventListener("error", function() {
reject(reader.error);
});
reader.readAsText(blob);
});
}
function getOrCreateEntity(node, entityCollection) {
let id = queryStringAttribute(node, "id");
id = defined_default(id) ? id : createGuid_default();
const entity = entityCollection.getOrCreateEntity(id);
return entity;
}
function readCoordinateFromNode(node) {
const longitude = queryNumericAttribute(node, "lon");
const latitude = queryNumericAttribute(node, "lat");
const elevation = queryNumericValue(node, "ele", namespaces.gpx);
return Cartesian3_default.fromDegrees(longitude, latitude, elevation);
}
function queryNumericAttribute(node, attributeName) {
if (!defined_default(node)) {
return void 0;
}
const value = node.getAttribute(attributeName);
if (value !== null) {
const result = parseFloat(value);
return !isNaN(result) ? result : void 0;
}
return void 0;
}
function queryStringAttribute(node, attributeName) {
if (!defined_default(node)) {
return void 0;
}
const value = node.getAttribute(attributeName);
return value !== null ? value : void 0;
}
function queryFirstNode(node, tagName, namespace) {
if (!defined_default(node)) {
return void 0;
}
const childNodes = node.childNodes;
const length3 = childNodes.length;
for (let q = 0; q < length3; q++) {
const child = childNodes[q];
if (child.localName === tagName && namespace.indexOf(child.namespaceURI) !== -1) {
return child;
}
}
return void 0;
}
function queryNodes(node, tagName, namespace) {
if (!defined_default(node)) {
return void 0;
}
const result = [];
const childNodes = node.getElementsByTagName(tagName);
const length3 = childNodes.length;
for (let q = 0; q < length3; 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_default(resultNode)) {
const result = parseFloat(resultNode.textContent);
return !isNaN(result) ? result : void 0;
}
return void 0;
}
function queryStringValue(node, tagName, namespace) {
const result = queryFirstNode(node, tagName, namespace);
if (defined_default(result)) {
return result.textContent.trim();
}
return void 0;
}
function createDefaultBillboard(image) {
const billboard = new BillboardGraphics_default();
billboard.width = BILLBOARD_SIZE;
billboard.height = BILLBOARD_SIZE;
billboard.scaleByDistance = new NearFarScalar_default(
BILLBOARD_NEAR_DISTANCE,
BILLBOARD_NEAR_RATIO,
BILLBOARD_FAR_DISTANCE,
BILLBOARD_FAR_RATIO
);
billboard.pixelOffsetScaleByDistance = new NearFarScalar_default(
BILLBOARD_NEAR_DISTANCE,
BILLBOARD_NEAR_RATIO,
BILLBOARD_FAR_DISTANCE,
BILLBOARD_FAR_RATIO
);
billboard.verticalOrigin = new ConstantProperty_default(VerticalOrigin_default.BOTTOM);
billboard.image = image;
return billboard;
}
function createDefaultLabel() {
const label = new LabelGraphics_default();
label.translucencyByDistance = new NearFarScalar_default(3e6, 1, 5e6, 0);
label.pixelOffset = new Cartesian2_default(17, 0);
label.horizontalOrigin = HorizontalOrigin_default.LEFT;
label.font = "16px sans-serif";
label.style = LabelStyle_default.FILL_AND_OUTLINE;
return label;
}
function createDefaultPolyline(color) {
const polyline = new PolylineGraphics_default();
polyline.width = 4;
polyline.material = new PolylineOutlineMaterialProperty_default();
polyline.material.color = defined_default(color) ? color : Color_default.RED;
polyline.material.outlineWidth = 2;
polyline.material.outlineColor = Color_default.BLACK;
return polyline;
}
var 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"
}
};
var scratchDiv;
if (typeof document !== "undefined") {
scratchDiv = document.createElement("div");
}
function processDescription2(node, entity) {
let i;
let text2 = "";
const infoTypeNames = Object.keys(descriptiveInfoTypes);
const length3 = infoTypeNames.length;
for (i = 0; i < length3; i++) {
const infoTypeName = infoTypeNames[i];
const infoType = descriptiveInfoTypes[infoTypeName];
infoType.value = defaultValue_default(
queryStringValue(node, infoType.tag, namespaces.gpx),
""
);
if (defined_default(infoType.value) && infoType.value !== "") {
text2 = `${text2}
${infoType.text}: ${infoType.value}
`;
}
}
if (!defined_default(text2) || text2 === "") {
return;
}
text2 = autolinker.link(text2);
scratchDiv.innerHTML = text2;
const links = scratchDiv.querySelectorAll("a");
for (i = 0; i < links.length; i++) {
links[i].setAttribute("target", "_blank");
}
const background = Color_default.WHITE;
const foreground = Color_default.BLACK;
let tmp2 = '
';
tmp2 += `${scratchDiv.innerHTML}
`;
scratchDiv.innerHTML = "";
return tmp2;
}
function processWpt(dataSource, geometryNode, entityCollection, options) {
const position = readCoordinateFromNode(geometryNode);
const entity = getOrCreateEntity(geometryNode, entityCollection);
entity.position = position;
const image = defined_default(options.waypointImage) ? options.waypointImage : dataSource._pinBuilder.fromMakiIconId(
"marker",
Color_default.RED,
BILLBOARD_SIZE
);
entity.billboard = createDefaultBillboard(image);
const name = queryStringValue(geometryNode, "name", namespaces.gpx);
entity.name = name;
entity.label = createDefaultLabel();
entity.label.text = name;
entity.description = processDescription2(geometryNode, entity);
if (options.clampToGround) {
entity.billboard.heightReference = HeightReference_default.CLAMP_TO_GROUND;
entity.label.heightReference = HeightReference_default.CLAMP_TO_GROUND;
}
}
function processRte(dataSource, geometryNode, entityCollection, options) {
const entity = getOrCreateEntity(geometryNode, entityCollection);
entity.description = processDescription2(geometryNode, entity);
const routePoints = queryNodes(geometryNode, "rtept", namespaces.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;
}
function processTrk(dataSource, geometryNode, entityCollection, options) {
const entity = getOrCreateEntity(geometryNode, entityCollection);
entity.description = processDescription2(geometryNode, entity);
const trackSegs = queryNodes(geometryNode, "trkseg", namespaces.gpx);
let positions = [];
let times = [];
let trackSegInfo;
let isTimeDynamic = true;
const property = new SampledPositionProperty_default();
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);
isTimeDynamic = isTimeDynamic && true;
} else {
isTimeDynamic = false;
}
}
if (isTimeDynamic) {
const image = defined_default(options.waypointImage) ? options.waypointImage : dataSource._pinBuilder.fromMakiIconId(
"marker",
Color_default.RED,
BILLBOARD_SIZE
);
entity.billboard = createDefaultBillboard(image);
entity.position = property;
if (options.clampToGround) {
entity.billboard.heightReference = HeightReference_default.CLAMP_TO_GROUND;
}
entity.availability = new TimeIntervalCollection_default();
entity.availability.addInterval(
new TimeInterval_default({
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(node, "trkpt", namespaces.gpx);
let time;
for (let i = 0; i < trackPoints.length; i++) {
const position = readCoordinateFromNode(trackPoints[i]);
result.positions.push(position);
time = queryStringValue(trackPoints[i], "time", namespaces.gpx);
if (defined_default(time)) {
result.times.push(JulianDate_default.fromIso8601(time));
}
}
return result;
}
function processMetadata(node) {
const metadataNode = queryFirstNode(node, "metadata", namespaces.gpx);
if (defined_default(metadataNode)) {
const metadata = {
name: queryStringValue(metadataNode, "name", namespaces.gpx),
desc: queryStringValue(metadataNode, "desc", namespaces.gpx),
author: getPerson(metadataNode),
copyright: getCopyright(metadataNode),
link: getLink(metadataNode),
time: queryStringValue(metadataNode, "time", namespaces.gpx),
keywords: queryStringValue(metadataNode, "keywords", namespaces.gpx),
bounds: getBounds(metadataNode)
};
if (defined_default(metadata.name) || defined_default(metadata.desc) || defined_default(metadata.author) || defined_default(metadata.copyright) || defined_default(metadata.link) || defined_default(metadata.time) || defined_default(metadata.keywords) || defined_default(metadata.bounds)) {
return metadata;
}
}
return void 0;
}
function getPerson(node) {
const personNode = queryFirstNode(node, "author", namespaces.gpx);
if (defined_default(personNode)) {
const person = {
name: queryStringValue(personNode, "name", namespaces.gpx),
email: getEmail(personNode),
link: getLink(personNode)
};
if (defined_default(person.name) || defined_default(person.email) || defined_default(person.link)) {
return person;
}
}
return void 0;
}
function getEmail(node) {
const emailNode = queryFirstNode(node, "email", namespaces.gpx);
if (defined_default(emailNode)) {
const id = queryStringValue(emailNode, "id", namespaces.gpx);
const domain = queryStringValue(emailNode, "domain", namespaces.gpx);
return `${id}@${domain}`;
}
return void 0;
}
function getLink(node) {
const linkNode = queryFirstNode(node, "link", namespaces.gpx);
if (defined_default(linkNode)) {
const link = {
href: queryStringAttribute(linkNode, "href"),
text: queryStringValue(linkNode, "text", namespaces.gpx),
mimeType: queryStringValue(linkNode, "type", namespaces.gpx)
};
if (defined_default(link.href) || defined_default(link.text) || defined_default(link.mimeType)) {
return link;
}
}
return void 0;
}
function getCopyright(node) {
const copyrightNode = queryFirstNode(node, "copyright", namespaces.gpx);
if (defined_default(copyrightNode)) {
const copyright = {
author: queryStringAttribute(copyrightNode, "author"),
year: queryStringValue(copyrightNode, "year", namespaces.gpx),
license: queryStringValue(copyrightNode, "license", namespaces.gpx)
};
if (defined_default(copyright.author) || defined_default(copyright.year) || defined_default(copyright.license)) {
return copyright;
}
}
return void 0;
}
function getBounds(node) {
const boundsNode = queryFirstNode(node, "bounds", namespaces.gpx);
if (defined_default(boundsNode)) {
const bounds = {
minLat: queryNumericValue(boundsNode, "minlat", namespaces.gpx),
maxLat: queryNumericValue(boundsNode, "maxlat", namespaces.gpx),
minLon: queryNumericValue(boundsNode, "minlon", namespaces.gpx),
maxLon: queryNumericValue(boundsNode, "maxlon", namespaces.gpx)
};
if (defined_default(bounds.minLat) || defined_default(bounds.maxLat) || defined_default(bounds.minLon) || defined_default(bounds.maxLon)) {
return bounds;
}
}
return void 0;
}
var 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 length3 = childNodes.length;
for (let q = 0; q < length3; q++) {
const child = childNodes[q];
if (child.localName === typeName && namespaces.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 version2 = queryStringAttribute(element, "version");
const creator = queryStringAttribute(element, "creator");
let name;
const metadata = processMetadata(element);
if (defined_default(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 stop2 = availability.stop;
const isMinStart = JulianDate_default.equals(start, Iso8601_default.MINIMUM_VALUE);
const isMaxStop = JulianDate_default.equals(stop2, Iso8601_default.MAXIMUM_VALUE);
if (!isMinStart || !isMaxStop) {
let date;
if (isMinStart) {
date = new Date();
date.setHours(0, 0, 0, 0);
start = JulianDate_default.fromDate(date);
}
if (isMaxStop) {
date = new Date();
date.setHours(24, 0, 0, 0);
stop2 = JulianDate_default.fromDate(date);
}
clock = new DataSourceClock_default();
clock.startTime = start;
clock.stopTime = stop2;
clock.currentTime = JulianDate_default.clone(start);
clock.clockRange = ClockRange_default.LOOP_STOP;
clock.clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
clock.multiplier = Math.round(
Math.min(
Math.max(JulianDate_default.secondsDifference(stop2, start) / 60, 1),
31556900
)
);
}
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 !== version2) {
dataSource._version = version2;
changed = true;
}
if (clock !== dataSource._clock) {
changed = true;
dataSource._clock = clock;
}
if (changed) {
dataSource._changed.raiseEvent(dataSource);
}
DataSource_default.setLoading(dataSource, false);
return dataSource;
}
function metadataChanged(old, current) {
if (!defined_default(old) && !defined_default(current)) {
return false;
} else if (defined_default(old) && defined_default(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 load3(dataSource, entityCollection, data, options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
let promise = data;
if (typeof data === "string" || data instanceof Resource_default) {
data = Resource_default.createIfNeeded(data);
promise = data.fetchBlob();
const resourceCredits = dataSource._resourceCredits;
const credits = data.credits;
if (defined_default(credits)) {
const length3 = credits.length;
for (let i = 0; i < length3; i++) {
resourceCredits.push(credits[i]);
}
}
}
return Promise.resolve(promise).then(function(dataToLoad) {
if (dataToLoad instanceof Blob) {
return readBlobAsText(dataToLoad).then(function(text2) {
let gpx;
let error;
try {
gpx = parser.parseFromString(text2, "application/xml");
} catch (e) {
error = e.toString();
}
if (defined_default(error) || gpx.body || gpx.documentElement.tagName === "parsererror") {
let msg = defined_default(error) ? error : gpx.documentElement.firstChild.nodeValue;
if (!msg) {
msg = gpx.body.innerText;
}
throw new RuntimeError_default(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);
});
}
function GpxDataSource() {
this._changed = new Event_default();
this._error = new Event_default();
this._loading = new Event_default();
this._clock = void 0;
this._entityCollection = new EntityCollection_default(this);
this._entityCluster = new EntityCluster_default();
this._name = void 0;
this._version = void 0;
this._creator = void 0;
this._metadata = void 0;
this._isLoading = false;
this._pinBuilder = new PinBuilder_default();
}
GpxDataSource.load = function(data, options) {
return new GpxDataSource().load(data, options);
};
Object.defineProperties(GpxDataSource.prototype, {
name: {
get: function() {
return this._name;
}
},
version: {
get: function() {
return this._version;
}
},
creator: {
get: function() {
return this._creator;
}
},
metadata: {
get: function() {
return this._metadata;
}
},
clock: {
get: function() {
return this._clock;
}
},
entities: {
get: function() {
return this._entityCollection;
}
},
isLoading: {
get: function() {
return this._isLoading;
}
},
changedEvent: {
get: function() {
return this._changed;
}
},
errorEvent: {
get: function() {
return this._error;
}
},
loadingEvent: {
get: function() {
return this._loading;
}
},
show: {
get: function() {
return this._entityCollection.show;
},
set: function(value) {
this._entityCollection.show = value;
}
},
clustering: {
get: function() {
return this._entityCluster;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value must be defined.");
}
this._entityCluster = value;
}
}
});
GpxDataSource.prototype.update = function(time) {
return true;
};
GpxDataSource.prototype.load = function(data, options) {
if (!defined_default(data)) {
throw new DeveloperError_default("data is required.");
}
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
DataSource_default.setLoading(this, true);
const oldName = this._name;
const that = this;
return load3(this, this._entityCollection, data, options).then(function() {
let clock;
const availability = that._entityCollection.computeAvailability();
let start = availability.start;
let stop2 = availability.stop;
const isMinStart = JulianDate_default.equals(start, Iso8601_default.MINIMUM_VALUE);
const isMaxStop = JulianDate_default.equals(stop2, Iso8601_default.MAXIMUM_VALUE);
if (!isMinStart || !isMaxStop) {
let date;
if (isMinStart) {
date = new Date();
date.setHours(0, 0, 0, 0);
start = JulianDate_default.fromDate(date);
}
if (isMaxStop) {
date = new Date();
date.setHours(24, 0, 0, 0);
stop2 = JulianDate_default.fromDate(date);
}
clock = new DataSourceClock_default();
clock.startTime = start;
clock.stopTime = stop2;
clock.currentTime = JulianDate_default.clone(start);
clock.clockRange = ClockRange_default.LOOP_STOP;
clock.clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
clock.multiplier = Math.round(
Math.min(
Math.max(JulianDate_default.secondsDifference(stop2, start) / 60, 1),
31556900
)
);
}
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_default.setLoading(that, false);
return that;
}).catch(function(error) {
DataSource_default.setLoading(that, false);
that._error.raiseEvent(that, error);
console.log(error);
return Promise.reject(error);
});
};
var GpxDataSource_default = GpxDataSource;
// node_modules/@cesium/engine/Source/DataSources/KmlCamera.js
function KmlCamera(position, headingPitchRoll) {
this.position = position;
this.headingPitchRoll = headingPitchRoll;
}
var KmlCamera_default = KmlCamera;
// node_modules/@cesium/engine/Source/DataSources/KmlDataSource.js
var import_urijs11 = __toESM(require_URI(), 1);
// node_modules/@zip.js/zip.js/lib/core/codecs/deflate.js
var MAX_BITS = 15;
var D_CODES = 30;
var BL_CODES = 19;
var LENGTH_CODES = 29;
var LITERALS = 256;
var L_CODES = LITERALS + 1 + LENGTH_CODES;
var HEAP_SIZE = 2 * L_CODES + 1;
var END_BLOCK = 256;
var MAX_BL_BITS = 7;
var REP_3_6 = 16;
var REPZ_3_10 = 17;
var REPZ_11_138 = 18;
var Buf_size = 8 * 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_DEFAULT_STRATEGY = 0;
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_BUF_ERROR = -5;
function extractArray(array) {
return flatArray(array.map(([length3, value]) => new Array(length3).fill(value, 0, length3)));
}
function flatArray(array) {
return array.reduce((a3, b) => a3.concat(Array.isArray(b) ? flatArray(b) : b), []);
}
var _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;
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;
let n, m;
let bits;
let xbits;
let f;
let overflow = 0;
for (bits = 0; bits <= MAX_BITS; bits++)
s.bl_count[bits] = 0;
tree[s.heap[s.heap_max] * 2 + 1] = 0;
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;
if (n > that.max_code)
continue;
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;
do {
bits = max_length - 1;
while (s.bl_count[bits] === 0)
bits--;
s.bl_count[bits]--;
s.bl_count[bits + 1] += 2;
s.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--;
}
}
}
function bi_reverse(code, len) {
let res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
function gen_codes(tree, max_code, bl_count) {
const next_code = [];
let code = 0;
let bits;
let n;
let len;
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = code + bl_count[bits - 1] << 1;
}
for (n = 0; n <= max_code; n++) {
len = tree[n * 2 + 1];
if (len === 0)
continue;
tree[n * 2] = bi_reverse(next_code[len]++, len);
}
}
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;
let max_code = -1;
let node;
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;
}
}
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];
}
that.max_code = max_code;
for (n = Math.floor(s.heap_len / 2); n >= 1; n--)
s.pqdownheap(tree, n);
node = elems;
do {
n = s.heap[1];
s.heap[1] = s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m = s.heap[1];
s.heap[--s.heap_max] = n;
s.heap[--s.heap_max] = 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;
s.heap[1] = node++;
s.pqdownheap(tree, 1);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1];
gen_bitlen(s);
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
];
Tree.d_code = function(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
};
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];
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];
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];
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;
}
var 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
];
var 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]]));
var 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];
var 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);
StaticTree.static_d_desc = new StaticTree(StaticTree.static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS);
StaticTree.static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
var MAX_MEM_LEVEL = 9;
var 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;
}
var STORED = 0;
var FAST = 1;
var SLOW = 2;
var config_table = [
new Config(0, 0, 0, 0, STORED),
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)
];
var z_errmsg = [
"need dictionary",
"stream end",
"",
"",
"stream error",
"data error",
"",
"buffer error",
"",
""
];
var NeedMore = 0;
var BlockDone = 1;
var FinishStarted = 2;
var FinishDone = 3;
var PRESET_DICT = 32;
var INIT_STATE = 42;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var Z_DEFLATED = 8;
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var 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() {
const that = this;
let strm;
let status;
let pending_buf_size;
let last_flush;
let w_size;
let w_bits;
let w_mask;
let win;
let window_size;
let prev;
let head;
let ins_h;
let hash_size;
let hash_bits;
let hash_mask;
let hash_shift;
let block_start;
let match_length;
let prev_match;
let match_available;
let strstart;
let match_start;
let lookahead;
let prev_length;
let max_chain_length;
let max_lazy_match;
let level;
let strategy;
let good_match;
let nice_match;
let dyn_ltree;
let dyn_dtree;
let bl_tree;
const l_desc = new Tree();
const d_desc = new Tree();
const bl_desc = new Tree();
that.depth = [];
let lit_bufsize;
let last_lit;
let matches;
let last_eob_len;
let bi_buf;
let bi_valid;
that.bl_count = [];
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;
}
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;
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;
}
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;
init_block();
}
that.pqdownheap = function(tree, k) {
const heap = that.heap;
const v7 = heap[k];
let j = k << 1;
while (j <= that.heap_len) {
if (j < that.heap_len && smaller(tree, heap[j + 1], heap[j], that.depth)) {
j++;
}
if (smaller(tree, v7, heap[j], that.depth))
break;
heap[k] = heap[j];
k = j;
j <<= 1;
}
heap[k] = v7;
};
function scan_tree(tree, max_code) {
let prevlen = -1;
let curlen;
let nextlen = tree[0 * 2 + 1];
let count = 0;
let max_count = 7;
let min_count = 4;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1] = 65535;
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;
}
}
}
function build_bl_tree() {
let max_blindex;
scan_tree(dyn_ltree, l_desc.max_code);
scan_tree(dyn_dtree, d_desc.max_code);
bl_desc.build_tree(that);
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] !== 0)
break;
}
that.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
return max_blindex;
}
function put_byte(p) {
that.pending_buf[that.pending++] = p;
}
function put_short(w) {
put_byte(w & 255);
put_byte(w >>> 8 & 255);
}
function putShortMSB(b) {
put_byte(b >> 8 & 255);
put_byte(b & 255 & 255);
}
function send_bits(value, length3) {
let val;
const len = length3;
if (bi_valid > Buf_size - len) {
val = value;
bi_buf |= val << bi_valid & 65535;
put_short(bi_buf);
bi_buf = val >>> Buf_size - bi_valid;
bi_valid += len - Buf_size;
} else {
bi_buf |= value << bi_valid & 65535;
bi_valid += len;
}
}
function send_code(c, tree) {
const c22 = c * 2;
send_bits(tree[c22] & 65535, tree[c22 + 1] & 65535);
}
function send_tree(tree, max_code) {
let n;
let prevlen = -1;
let curlen;
let nextlen = tree[0 * 2 + 1];
let count = 0;
let max_count = 7;
let min_count = 4;
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;
}
}
}
function send_all_trees(lcodes, dcodes, blcodes) {
let rank;
send_bits(lcodes - 257, 5);
send_bits(dcodes - 1, 5);
send_bits(blcodes - 4, 4);
for (rank = 0; rank < blcodes; rank++) {
send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
}
send_tree(dyn_ltree, lcodes - 1);
send_tree(dyn_dtree, dcodes - 1);
}
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 & 255);
bi_buf >>>= 8;
bi_valid -= 8;
}
}
function _tr_align() {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
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;
}
function _tr_tally(dist, lc) {
let out_length, in_length, dcode;
that.dist_buf[last_lit] = dist;
that.lc_buf[last_lit] = lc & 255;
last_lit++;
if (dist === 0) {
dyn_ltree[lc * 2]++;
} else {
matches++;
dist--;
dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
dyn_dtree[Tree.d_code(dist) * 2]++;
}
if ((last_lit & 8191) === 0 && level > 2) {
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;
}
function compress_block(ltree, dtree) {
let dist;
let lc;
let lx = 0;
let code;
let extra;
if (last_lit !== 0) {
do {
dist = that.dist_buf[lx];
lc = that.lc_buf[lx];
lx++;
if (dist === 0) {
send_code(lc, ltree);
} else {
code = Tree._length_code[lc];
send_code(code + LITERALS + 1, ltree);
extra = Tree.extra_lbits[code];
if (extra !== 0) {
lc -= Tree.base_length[code];
send_bits(lc, extra);
}
dist--;
code = Tree.d_code(dist);
send_code(code, dtree);
extra = Tree.extra_dbits[code];
if (extra !== 0) {
dist -= Tree.base_dist[code];
send_bits(dist, extra);
}
}
} while (lx < last_lit);
}
send_code(END_BLOCK, ltree);
last_eob_len = ltree[END_BLOCK * 2 + 1];
}
function bi_windup() {
if (bi_valid > 8) {
put_short(bi_buf);
} else if (bi_valid > 0) {
put_byte(bi_buf & 255);
}
bi_buf = 0;
bi_valid = 0;
}
function copy_block(buf, len, header) {
bi_windup();
last_eob_len = 8;
if (header) {
put_short(len);
put_short(~len);
}
that.pending_buf.set(win.subarray(buf, buf + len), that.pending);
that.pending += len;
}
function _tr_stored_block(buf, stored_len, eof) {
send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3);
copy_block(buf, stored_len, true);
}
function _tr_flush_block(buf, stored_len, eof) {
let opt_lenb, static_lenb;
let max_blindex = 0;
if (level > 0) {
l_desc.build_tree(that);
d_desc.build_tree(that);
max_blindex = build_bl_tree();
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;
}
if (stored_len + 4 <= opt_lenb && buf != -1) {
_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);
}
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();
}
function fill_window() {
let n, m;
let p;
let more;
do {
more = window_size - lookahead - strstart;
if (more === 0 && strstart === 0 && lookahead === 0) {
more = w_size;
} else if (more == -1) {
more--;
} 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;
block_start -= w_size;
n = hash_size;
p = n;
do {
m = head[--p] & 65535;
head[p] = m >= w_size ? m - w_size : 0;
} while (--n !== 0);
n = w_size;
p = n;
do {
m = prev[--p] & 65535;
prev[p] = m >= w_size ? m - w_size : 0;
} while (--n !== 0);
more += w_size;
}
if (strm.avail_in === 0)
return;
n = strm.read_buf(win, strstart + lookahead, more);
lookahead += n;
if (lookahead >= MIN_MATCH) {
ins_h = win[strstart] & 255;
ins_h = (ins_h << hash_shift ^ win[strstart + 1] & 255) & hash_mask;
}
} while (lookahead < MIN_LOOKAHEAD && strm.avail_in !== 0);
}
function deflate_stored(flush) {
let max_block_size = 65535;
let max_start;
if (max_block_size > pending_buf_size - 5) {
max_block_size = pending_buf_size - 5;
}
while (true) {
if (lookahead <= 1) {
fill_window();
if (lookahead === 0 && flush == Z_NO_FLUSH)
return NeedMore;
if (lookahead === 0)
break;
}
strstart += lookahead;
lookahead = 0;
max_start = block_start + max_block_size;
if (strstart === 0 || strstart >= max_start) {
lookahead = strstart - max_start;
strstart = max_start;
flush_block_only(false);
if (strm.avail_out === 0)
return NeedMore;
}
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);
if (strm.avail_out === 0)
return flush == Z_FINISH ? FinishStarted : NeedMore;
return flush == Z_FINISH ? FinishDone : BlockDone;
}
function longest_match(cur_match) {
let chain_length = max_chain_length;
let scan = strstart;
let match;
let len;
let best_len = prev_length;
const limit = strstart > w_size - MIN_LOOKAHEAD ? strstart - (w_size - MIN_LOOKAHEAD) : 0;
let _nice_match = nice_match;
const wmask = w_mask;
const strend = strstart + MAX_MATCH;
let scan_end1 = win[scan + best_len - 1];
let scan_end = win[scan + best_len];
if (prev_length >= good_match) {
chain_length >>= 2;
}
if (_nice_match > lookahead)
_nice_match = lookahead;
do {
match = cur_match;
if (win[match + best_len] != scan_end || win[match + best_len - 1] != scan_end1 || win[match] != win[scan] || win[++match] != win[scan + 1])
continue;
scan += 2;
match++;
do {
} 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] & 65535) > limit && --chain_length !== 0);
if (best_len <= lookahead)
return best_len;
return lookahead;
}
function deflate_fast(flush) {
let hash_head = 0;
let bflush;
while (true) {
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead === 0)
break;
}
if (lookahead >= MIN_MATCH) {
ins_h = (ins_h << hash_shift ^ win[strstart + (MIN_MATCH - 1)] & 255) & hash_mask;
hash_head = head[ins_h] & 65535;
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = strstart;
}
if (hash_head !== 0 && (strstart - hash_head & 65535) <= w_size - MIN_LOOKAHEAD) {
if (strategy != Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
}
if (match_length >= MIN_MATCH) {
bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
lookahead -= match_length;
if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
match_length--;
do {
strstart++;
ins_h = (ins_h << hash_shift ^ win[strstart + (MIN_MATCH - 1)] & 255) & hash_mask;
hash_head = head[ins_h] & 65535;
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = strstart;
} while (--match_length !== 0);
strstart++;
} else {
strstart += match_length;
match_length = 0;
ins_h = win[strstart] & 255;
ins_h = (ins_h << hash_shift ^ win[strstart + 1] & 255) & hash_mask;
}
} else {
bflush = _tr_tally(0, win[strstart] & 255);
lookahead--;
strstart++;
}
if (bflush) {
flush_block_only(false);
if (strm.avail_out === 0)
return NeedMore;
}
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out === 0) {
if (flush == Z_FINISH)
return FinishStarted;
else
return NeedMore;
}
return flush == Z_FINISH ? FinishDone : BlockDone;
}
function deflate_slow(flush) {
let hash_head = 0;
let bflush;
let max_insert;
while (true) {
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead === 0)
break;
}
if (lookahead >= MIN_MATCH) {
ins_h = (ins_h << hash_shift ^ win[strstart + (MIN_MATCH - 1)] & 255) & hash_mask;
hash_head = head[ins_h] & 65535;
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = strstart;
}
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 & 65535) <= w_size - MIN_LOOKAHEAD) {
if (strategy != Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
if (match_length <= 5 && (strategy == Z_FILTERED || match_length == MIN_MATCH && strstart - match_start > 4096)) {
match_length = MIN_MATCH - 1;
}
}
if (prev_length >= MIN_MATCH && match_length <= prev_length) {
max_insert = strstart + lookahead - MIN_MATCH;
bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH);
lookahead -= prev_length - 1;
prev_length -= 2;
do {
if (++strstart <= max_insert) {
ins_h = (ins_h << hash_shift ^ win[strstart + (MIN_MATCH - 1)] & 255) & hash_mask;
hash_head = head[ins_h] & 65535;
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) {
bflush = _tr_tally(0, win[strstart - 1] & 255);
if (bflush) {
flush_block_only(false);
}
strstart++;
lookahead--;
if (strm.avail_out === 0)
return NeedMore;
} else {
match_available = 1;
strstart++;
lookahead--;
}
}
if (match_available !== 0) {
bflush = _tr_tally(0, win[strstart - 1] & 255);
match_available = 0;
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out === 0) {
if (flush == Z_FINISH)
return FinishStarted;
else
return NeedMore;
}
return flush == Z_FINISH ? FinishDone : BlockDone;
}
function deflateReset(strm2) {
strm2.total_in = strm2.total_out = 0;
strm2.msg = null;
that.pending = 0;
that.pending_out = 0;
status = BUSY_STATE;
last_flush = Z_NO_FLUSH;
tr_init();
lm_init();
return Z_OK;
}
that.deflateInit = function(strm2, _level, bits, _method, memLevel, _strategy) {
if (!_method)
_method = Z_DEFLATED;
if (!memLevel)
memLevel = DEF_MEM_LEVEL;
if (!_strategy)
_strategy = Z_DEFAULT_STRATEGY;
strm2.msg = null;
if (_level == Z_DEFAULT_COMPRESSION)
_level = 6;
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || _method != Z_DEFLATED || bits < 9 || bits > 15 || _level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
strm2.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;
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(strm2);
};
that.deflateEnd = function() {
if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) {
return Z_STREAM_ERROR;
}
that.lc_buf = null;
that.dist_buf = null;
that.pending_buf = null;
head = null;
prev = null;
win = null;
that.dstate = null;
return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
};
that.deflateParams = function(strm2, _level, _strategy) {
let err = Z_OK;
if (_level == Z_DEFAULT_COMPRESSION) {
_level = 6;
}
if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
if (config_table[level].func != config_table[_level].func && strm2.total_in !== 0) {
err = strm2.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 length3 = dictLength;
let n, index = 0;
if (!dictionary || status != INIT_STATE)
return Z_STREAM_ERROR;
if (length3 < MIN_MATCH)
return Z_OK;
if (length3 > w_size - MIN_LOOKAHEAD) {
length3 = w_size - MIN_LOOKAHEAD;
index = dictLength - length3;
}
win.set(dictionary.subarray(index, index + length3), 0);
strstart = length3;
block_start = length3;
ins_h = win[0] & 255;
ins_h = (ins_h << hash_shift ^ win[1] & 255) & hash_mask;
for (n = 0; n <= length3 - MIN_MATCH; n++) {
ins_h = (ins_h << hash_shift ^ win[n + (MIN_MATCH - 1)] & 255) & hash_mask;
prev[n & w_mask] = head[ins_h];
head[ins_h] = n;
}
return Z_OK;
};
that.deflate = function(_strm, flush) {
let i, header, level_flags, old_flush, bstate;
if (flush > Z_FINISH || flush < 0) {
return Z_STREAM_ERROR;
}
if (!_strm.next_out || !_strm.next_in && _strm.avail_in !== 0 || status == FINISH_STATE && flush != Z_FINISH) {
_strm.msg = z_errmsg[Z_NEED_DICT - Z_STREAM_ERROR];
return Z_STREAM_ERROR;
}
if (_strm.avail_out === 0) {
_strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
return Z_BUF_ERROR;
}
strm = _strm;
old_flush = last_flush;
last_flush = flush;
if (status == INIT_STATE) {
header = Z_DEFLATED + (w_bits - 8 << 4) << 8;
level_flags = (level - 1 & 255) >> 1;
if (level_flags > 3)
level_flags = 3;
header |= level_flags << 6;
if (strstart !== 0)
header |= PRESET_DICT;
header += 31 - header % 31;
status = BUSY_STATE;
putShortMSB(header);
}
if (that.pending !== 0) {
strm.flush_pending();
if (strm.avail_out === 0) {
last_flush = -1;
return Z_OK;
}
} else if (strm.avail_in === 0 && flush <= old_flush && flush != Z_FINISH) {
strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
return Z_BUF_ERROR;
}
if (status == FINISH_STATE && strm.avail_in !== 0) {
_strm.msg = z_errmsg[Z_NEED_DICT - Z_BUF_ERROR];
return Z_BUF_ERROR;
}
if (strm.avail_in !== 0 || lookahead !== 0 || flush != Z_NO_FLUSH && status != FINISH_STATE) {
bstate = -1;
switch (config_table[level].func) {
case STORED:
bstate = deflate_stored(flush);
break;
case FAST:
bstate = deflate_fast(flush);
break;
case SLOW:
bstate = deflate_slow(flush);
break;
default:
}
if (bstate == FinishStarted || bstate == FinishDone) {
status = FINISH_STATE;
}
if (bstate == NeedMore || bstate == FinishStarted) {
if (strm.avail_out === 0) {
last_flush = -1;
}
return Z_OK;
}
if (bstate == BlockDone) {
if (flush == Z_PARTIAL_FLUSH) {
_tr_align();
} else {
_tr_stored_block(0, 0, false);
if (flush == Z_FULL_FLUSH) {
for (i = 0; i < hash_size; i++)
head[i] = 0;
}
}
strm.flush_pending();
if (strm.avail_out === 0) {
last_flush = -1;
return Z_OK;
}
}
}
if (flush != Z_FINISH)
return Z_OK;
return Z_STREAM_END;
};
}
function ZStream() {
const that = this;
that.next_in_index = 0;
that.next_out_index = 0;
that.avail_in = 0;
that.total_in = 0;
that.avail_out = 0;
that.total_out = 0;
}
ZStream.prototype = {
deflateInit: function(level, bits) {
const that = this;
that.dstate = new Deflate();
if (!bits)
bits = MAX_BITS;
return that.dstate.deflateInit(that, level, bits);
},
deflate: function(flush) {
const that = this;
if (!that.dstate) {
return Z_STREAM_ERROR;
}
return that.dstate.deflate(that, flush);
},
deflateEnd: function() {
const that = this;
if (!that.dstate)
return Z_STREAM_ERROR;
const ret = that.dstate.deflateEnd();
that.dstate = null;
return ret;
},
deflateParams: function(level, strategy) {
const that = this;
if (!that.dstate)
return Z_STREAM_ERROR;
return that.dstate.deflateParams(that, level, strategy);
},
deflateSetDictionary: function(dictionary, dictLength) {
const that = this;
if (!that.dstate)
return Z_STREAM_ERROR;
return that.dstate.deflateSetDictionary(that, dictionary, dictLength);
},
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_pending: function() {
const that = this;
let len = that.dstate.pending;
if (len > that.avail_out)
len = that.avail_out;
if (len === 0)
return;
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;
}
}
};
function ZipDeflate(options) {
const that = this;
const z = new ZStream();
const bufsize = getMaximumCompressedSize(options && options.chunkSize ? options.chunkSize : 64 * 1024);
const flush = Z_NO_FLUSH;
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)
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);
if (err != Z_STREAM_END && err != Z_OK)
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(uncompressedSize) {
return uncompressedSize + 5 * (Math.floor(uncompressedSize / 16383) + 1);
}
var deflate_default = ZipDeflate;
// node_modules/@zip.js/zip.js/lib/core/codecs/inflate.js
var MAX_BITS2 = 15;
var Z_OK2 = 0;
var Z_STREAM_END2 = 1;
var Z_NEED_DICT2 = 2;
var Z_STREAM_ERROR2 = -2;
var Z_DATA_ERROR2 = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR2 = -5;
var inflate_mask = [
0,
1,
3,
7,
15,
31,
63,
127,
255,
511,
1023,
2047,
4095,
8191,
16383,
32767,
65535
];
var MANY = 1440;
var Z_NO_FLUSH2 = 0;
var Z_FINISH2 = 4;
var fixed_bl = 9;
var fixed_bd = 5;
var 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
];
var 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
];
var cplens = [
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 cplext = [
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
];
var cpdist = [
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
];
var cpdext = [
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
];
var BMAX = 15;
function InfTree() {
const that = this;
let hn;
let v7;
let c;
let r;
let u3;
let x;
function huft_build(b, bindex, n, s, d, e, t, m, hp, hn2, v8) {
let a3;
let f;
let g;
let h;
let i;
let j;
let k;
let l;
let mask;
let p;
let q;
let w;
let xp;
let y;
let z;
p = 0;
i = n;
do {
c[b[bindex + p]]++;
p++;
i--;
} while (i !== 0);
if (c[0] == n) {
t[0] = -1;
m[0] = 0;
return Z_OK2;
}
l = m[0];
for (j = 1; j <= BMAX; j++)
if (c[j] !== 0)
break;
k = j;
if (l < j) {
l = j;
}
for (i = BMAX; i !== 0; i--) {
if (c[i] !== 0)
break;
}
g = i;
if (l > i) {
l = i;
}
m[0] = l;
for (y = 1 << j; j < i; j++, y <<= 1) {
if ((y -= c[j]) < 0) {
return Z_DATA_ERROR2;
}
}
if ((y -= c[i]) < 0) {
return Z_DATA_ERROR2;
}
c[i] += y;
x[1] = j = 0;
p = 1;
xp = 2;
while (--i !== 0) {
x[xp] = j += c[p];
xp++;
p++;
}
i = 0;
p = 0;
do {
if ((j = b[bindex + p]) !== 0) {
v8[x[j]++] = i;
}
p++;
} while (++i < n);
n = x[g];
x[0] = i = 0;
p = 0;
h = -1;
w = -l;
u3[0] = 0;
q = 0;
z = 0;
for (; k <= g; k++) {
a3 = c[k];
while (a3-- !== 0) {
while (k > w + l) {
h++;
w += l;
z = g - w;
z = z > l ? l : z;
if ((f = 1 << (j = k - w)) > a3 + 1) {
f -= a3 + 1;
xp = k;
if (j < z) {
while (++j < z) {
if ((f <<= 1) <= c[++xp])
break;
f -= c[xp];
}
}
}
z = 1 << j;
if (hn2[0] + z > MANY) {
return Z_DATA_ERROR2;
}
u3[h] = q = hn2[0];
hn2[0] += z;
if (h !== 0) {
x[h] = i;
r[0] = j;
r[1] = l;
j = i >>> w - l;
r[2] = q - u3[h - 1] - j;
hp.set(r, (u3[h - 1] + j) * 3);
} else {
t[0] = q;
}
}
r[1] = k - w;
if (p >= n) {
r[0] = 128 + 64;
} else if (v8[p] < s) {
r[0] = v8[p] < 256 ? 0 : 32 + 64;
r[2] = v8[p++];
} else {
r[0] = e[v8[p] - s] + 16 + 64;
r[2] = d[v8[p++] - s];
}
f = 1 << k - w;
for (j = i >>> w; j < z; j += f) {
hp.set(r, (q + j) * 3);
}
for (j = 1 << k - 1; (i & j) !== 0; j >>>= 1) {
i ^= j;
}
i ^= j;
mask = (1 << w) - 1;
while ((i & mask) != x[h]) {
h--;
w -= l;
mask = (1 << w) - 1;
}
}
}
return y !== 0 && g != 1 ? Z_BUF_ERROR2 : Z_OK2;
}
function initWorkArea(vsize) {
let i;
if (!hn) {
hn = [];
v7 = [];
c = new Int32Array(BMAX + 1);
r = [];
u3 = new Int32Array(BMAX);
x = new Int32Array(BMAX + 1);
}
if (v7.length < vsize) {
v7 = [];
}
for (i = 0; i < vsize; i++) {
v7[i] = 0;
}
for (i = 0; i < BMAX + 1; i++) {
c[i] = 0;
}
for (i = 0; i < 3; i++) {
r[i] = 0;
}
u3.set(c.subarray(0, BMAX), 0);
x.set(c.subarray(0, BMAX + 1), 0);
}
that.inflate_trees_bits = function(c14, bb, tb, hp, z) {
let result;
initWorkArea(19);
hn[0] = 0;
result = huft_build(c14, 0, 19, 19, null, null, tb, bb, hp, hn, v7);
if (result == Z_DATA_ERROR2) {
z.msg = "oversubscribed dynamic bit lengths tree";
} else if (result == Z_BUF_ERROR2 || bb[0] === 0) {
z.msg = "incomplete dynamic bit lengths tree";
result = Z_DATA_ERROR2;
}
return result;
};
that.inflate_trees_dynamic = function(nl, nd, c14, bl, bd, tl, td, hp, z) {
let result;
initWorkArea(288);
hn[0] = 0;
result = huft_build(c14, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v7);
if (result != Z_OK2 || bl[0] === 0) {
if (result == Z_DATA_ERROR2) {
z.msg = "oversubscribed literal/length tree";
} else if (result != Z_MEM_ERROR) {
z.msg = "incomplete literal/length tree";
result = Z_DATA_ERROR2;
}
return result;
}
initWorkArea(288);
result = huft_build(c14, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v7);
if (result != Z_OK2 || bd[0] === 0 && nl > 257) {
if (result == Z_DATA_ERROR2) {
z.msg = "oversubscribed distance tree";
} else if (result == Z_BUF_ERROR2) {
z.msg = "incomplete distance tree";
result = Z_DATA_ERROR2;
} else if (result != Z_MEM_ERROR) {
z.msg = "empty distance tree with lengths";
result = Z_DATA_ERROR2;
}
return result;
}
return Z_OK2;
};
}
InfTree.inflate_trees_fixed = function(bl, bd, tl, td) {
bl[0] = fixed_bl;
bd[0] = fixed_bd;
tl[0] = fixed_tl;
td[0] = fixed_td;
return Z_OK2;
};
var START = 0;
var LEN = 1;
var LENEXT = 2;
var DIST = 3;
var DISTEXT = 4;
var COPY = 5;
var LIT = 6;
var WASH = 7;
var END = 8;
var BADCODE = 9;
function InfCodes() {
const that = this;
let mode2;
let len = 0;
let tree;
let tree_index = 0;
let need = 0;
let lit = 0;
let get2 = 0;
let dist = 0;
let lbits = 0;
let dbits = 0;
let ltree;
let ltree_index = 0;
let dtree;
let dtree_index = 0;
function inflate_fast(bl, bd, tl, tl_index, td, td_index, s, z) {
let t;
let tp;
let tp_index;
let e;
let b;
let k;
let p;
let n;
let q;
let m;
let ml;
let md;
let c;
let d;
let r;
let tp_index_t_3;
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;
ml = inflate_mask[bl];
md = inflate_mask[bd];
do {
while (k < 20) {
n--;
b |= (z.read_byte(p++) & 255) << 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++] = 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] + (b & inflate_mask[e]);
b >>= e;
k -= e;
while (k < 15) {
n--;
b |= (z.read_byte(p++) & 255) << 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) {
e &= 15;
while (k < e) {
n--;
b |= (z.read_byte(p++) & 255) << k;
k += 8;
}
d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]);
b >>= e;
k -= e;
m -= c;
if (q >= d) {
r = q - d;
if (q - r > 0 && 2 > q - r) {
s.win[q++] = s.win[r++];
s.win[q++] = s.win[r++];
c -= 2;
} else {
s.win.set(s.win.subarray(r, r + 2), q);
q += 2;
r += 2;
c -= 2;
}
} else {
r = q - d;
do {
r += s.end;
} while (r < 0);
e = s.end - r;
if (c > e) {
c -= e;
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;
}
}
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_ERROR2;
}
} 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++] = 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_END2;
} 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_ERROR2;
}
} while (true);
} while (m >= 258 && n >= 10);
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_OK2;
}
that.init = function(bl, bd, tl, tl_index, td, td_index) {
mode2 = START;
lbits = bl;
dbits = bd;
ltree = tl;
ltree_index = tl_index;
dtree = td;
dtree_index = td_index;
tree = null;
};
that.proc = function(s, z, r) {
let j;
let tindex;
let e;
let b = 0;
let k = 0;
let p = 0;
let n;
let q;
let m;
let f;
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;
while (true) {
switch (mode2) {
case START:
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_OK2) {
mode2 = r == Z_STREAM_END2 ? WASH : BADCODE;
break;
}
}
need = lbits;
tree = ltree;
tree_index = ltree_index;
mode2 = LEN;
case LEN:
j = need;
while (k < j) {
if (n !== 0)
r = Z_OK2;
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++) & 255) << 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) {
lit = tree[tindex + 2];
mode2 = LIT;
break;
}
if ((e & 16) !== 0) {
get2 = e & 15;
len = tree[tindex + 2];
mode2 = LENEXT;
break;
}
if ((e & 64) === 0) {
need = e;
tree_index = tindex / 3 + tree[tindex + 2];
break;
}
if ((e & 32) !== 0) {
mode2 = WASH;
break;
}
mode2 = BADCODE;
z.msg = "invalid literal/length code";
r = Z_DATA_ERROR2;
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:
j = get2;
while (k < j) {
if (n !== 0)
r = Z_OK2;
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++) & 255) << k;
k += 8;
}
len += b & inflate_mask[j];
b >>= j;
k -= j;
need = dbits;
tree = dtree;
tree_index = dtree_index;
mode2 = DIST;
case DIST:
j = need;
while (k < j) {
if (n !== 0)
r = Z_OK2;
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++) & 255) << 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) {
get2 = e & 15;
dist = tree[tindex + 2];
mode2 = DISTEXT;
break;
}
if ((e & 64) === 0) {
need = e;
tree_index = tindex / 3 + tree[tindex + 2];
break;
}
mode2 = BADCODE;
z.msg = "invalid distance code";
r = Z_DATA_ERROR2;
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:
j = get2;
while (k < j) {
if (n !== 0)
r = Z_OK2;
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++) & 255) << k;
k += 8;
}
dist += b & inflate_mask[j];
b >>= j;
k -= j;
mode2 = COPY;
case COPY:
f = q - dist;
while (f < 0) {
f += s.end;
}
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--;
}
mode2 = START;
break;
case LIT:
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_OK2;
s.win[q++] = lit;
m--;
mode2 = START;
break;
case WASH:
if (k > 7) {
k -= 8;
n++;
p--;
}
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);
}
mode2 = END;
case END:
r = Z_STREAM_END2;
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:
r = Z_DATA_ERROR2;
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_ERROR2;
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() {
};
}
var border = [
16,
17,
18,
0,
8,
7,
9,
6,
10,
5,
11,
4,
12,
3,
13,
2,
14,
1,
15
];
var TYPE = 0;
var LENS = 1;
var STORED2 = 2;
var TABLE = 3;
var BTREE = 4;
var DTREE = 5;
var CODES = 6;
var DRY = 7;
var DONELOCKS = 8;
var BADBLOCKS = 9;
function InfBlocks(z, w) {
const that = this;
let mode2 = TYPE;
let left = 0;
let table2 = 0;
let index = 0;
let blens;
const bb = [0];
const tb = [0];
const codes = new InfCodes();
let last = 0;
let hufts = new Int32Array(MANY * 3);
const check = 0;
const inftree = new InfTree();
that.bitk = 0;
that.bitb = 0;
that.win = new Uint8Array(w);
that.end = w;
that.read = 0;
that.write = 0;
that.reset = function(z2, c) {
if (c)
c[0] = check;
if (mode2 == CODES) {
codes.free(z2);
}
mode2 = TYPE;
that.bitk = 0;
that.bitb = 0;
that.read = that.write = 0;
};
that.reset(z, null);
that.inflate_flush = function(z2, r) {
let n;
let p;
let q;
p = z2.next_out_index;
q = that.read;
n = (q <= that.write ? that.write : that.end) - q;
if (n > z2.avail_out)
n = z2.avail_out;
if (n !== 0 && r == Z_BUF_ERROR2)
r = Z_OK2;
z2.avail_out -= n;
z2.total_out += n;
z2.next_out.set(that.win.subarray(q, q + n), p);
p += n;
q += n;
if (q == that.end) {
q = 0;
if (that.write == that.end)
that.write = 0;
n = that.write - q;
if (n > z2.avail_out)
n = z2.avail_out;
if (n !== 0 && r == Z_BUF_ERROR2)
r = Z_OK2;
z2.avail_out -= n;
z2.total_out += n;
z2.next_out.set(that.win.subarray(q, q + n), p);
p += n;
q += n;
}
z2.next_out_index = p;
that.read = q;
return r;
};
that.proc = function(z2, r) {
let t;
let b;
let k;
let p;
let n;
let q;
let m;
let i;
p = z2.next_in_index;
n = z2.avail_in;
b = that.bitb;
k = that.bitk;
q = that.write;
m = q < that.read ? that.read - q - 1 : that.end - q;
while (true) {
let bl, bd, tl, td, bl_, bd_, tl_, td_;
switch (mode2) {
case TYPE:
while (k < 3) {
if (n !== 0) {
r = Z_OK2;
} else {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
n--;
b |= (z2.read_byte(p++) & 255) << k;
k += 8;
}
t = b & 7;
last = t & 1;
switch (t >>> 1) {
case 0:
b >>>= 3;
k -= 3;
t = k & 7;
b >>>= t;
k -= t;
mode2 = LENS;
break;
case 1:
bl = [];
bd = [];
tl = [[]];
td = [[]];
InfTree.inflate_trees_fixed(bl, bd, tl, td);
codes.init(bl[0], bd[0], tl[0], 0, td[0], 0);
b >>>= 3;
k -= 3;
mode2 = CODES;
break;
case 2:
b >>>= 3;
k -= 3;
mode2 = TABLE;
break;
case 3:
b >>>= 3;
k -= 3;
mode2 = BADBLOCKS;
z2.msg = "invalid block type";
r = Z_DATA_ERROR2;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
break;
case LENS:
while (k < 32) {
if (n !== 0) {
r = Z_OK2;
} else {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
n--;
b |= (z2.read_byte(p++) & 255) << k;
k += 8;
}
if ((~b >>> 16 & 65535) != (b & 65535)) {
mode2 = BADBLOCKS;
z2.msg = "invalid stored block lengths";
r = Z_DATA_ERROR2;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
left = b & 65535;
b = k = 0;
mode2 = left !== 0 ? STORED2 : last !== 0 ? DRY : TYPE;
break;
case STORED2:
if (n === 0) {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
if (m === 0) {
if (q == that.end && that.read !== 0) {
q = 0;
m = q < that.read ? that.read - q - 1 : that.end - q;
}
if (m === 0) {
that.write = q;
r = that.inflate_flush(z2, r);
q = that.write;
m = q < that.read ? that.read - q - 1 : that.end - q;
if (q == that.end && that.read !== 0) {
q = 0;
m = q < that.read ? that.read - q - 1 : that.end - q;
}
if (m === 0) {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
}
}
r = Z_OK2;
t = left;
if (t > n)
t = n;
if (t > m)
t = m;
that.win.set(z2.read_buf(p, t), q);
p += t;
n -= t;
q += t;
m -= t;
if ((left -= t) !== 0)
break;
mode2 = last !== 0 ? DRY : TYPE;
break;
case TABLE:
while (k < 14) {
if (n !== 0) {
r = Z_OK2;
} else {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
n--;
b |= (z2.read_byte(p++) & 255) << k;
k += 8;
}
table2 = t = b & 16383;
if ((t & 31) > 29 || (t >> 5 & 31) > 29) {
mode2 = BADBLOCKS;
z2.msg = "too many length or distance symbols";
r = Z_DATA_ERROR2;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
t = 258 + (t & 31) + (t >> 5 & 31);
if (!blens || blens.length < t) {
blens = [];
} else {
for (i = 0; i < t; i++) {
blens[i] = 0;
}
}
b >>>= 14;
k -= 14;
index = 0;
mode2 = BTREE;
case BTREE:
while (index < 4 + (table2 >>> 10)) {
while (k < 3) {
if (n !== 0) {
r = Z_OK2;
} else {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
n--;
b |= (z2.read_byte(p++) & 255) << 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, z2);
if (t != Z_OK2) {
r = t;
if (r == Z_DATA_ERROR2) {
blens = null;
mode2 = BADBLOCKS;
}
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
index = 0;
mode2 = DTREE;
case DTREE:
while (true) {
t = table2;
if (index >= 258 + (t & 31) + (t >> 5 & 31)) {
break;
}
let j, c;
t = bb[0];
while (k < t) {
if (n !== 0) {
r = Z_OK2;
} else {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
n--;
b |= (z2.read_byte(p++) & 255) << k;
k += 8;
}
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 {
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
while (k < t + i) {
if (n !== 0) {
r = Z_OK2;
} else {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
n--;
b |= (z2.read_byte(p++) & 255) << k;
k += 8;
}
b >>>= t;
k -= t;
j += b & inflate_mask[i];
b >>>= i;
k -= i;
i = index;
t = table2;
if (i + j > 258 + (t & 31) + (t >> 5 & 31) || c == 16 && i < 1) {
blens = null;
mode2 = BADBLOCKS;
z2.msg = "invalid bit length repeat";
r = Z_DATA_ERROR2;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
c = c == 16 ? blens[i - 1] : 0;
do {
blens[i++] = c;
} while (--j !== 0);
index = i;
}
}
tb[0] = -1;
bl_ = [];
bd_ = [];
tl_ = [];
td_ = [];
bl_[0] = 9;
bd_[0] = 6;
t = table2;
t = inftree.inflate_trees_dynamic(257 + (t & 31), 1 + (t >> 5 & 31), blens, bl_, bd_, tl_, td_, hufts, z2);
if (t != Z_OK2) {
if (t == Z_DATA_ERROR2) {
blens = null;
mode2 = BADBLOCKS;
}
r = t;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
codes.init(bl_[0], bd_[0], hufts, tl_[0], hufts, td_[0]);
mode2 = CODES;
case CODES:
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
if ((r = codes.proc(that, z2, r)) != Z_STREAM_END2) {
return that.inflate_flush(z2, r);
}
r = Z_OK2;
codes.free(z2);
p = z2.next_in_index;
n = z2.avail_in;
b = that.bitb;
k = that.bitk;
q = that.write;
m = q < that.read ? that.read - q - 1 : that.end - q;
if (last === 0) {
mode2 = TYPE;
break;
}
mode2 = DRY;
case DRY:
that.write = q;
r = that.inflate_flush(z2, r);
q = that.write;
m = q < that.read ? that.read - q - 1 : that.end - q;
if (that.read != that.write) {
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
mode2 = DONELOCKS;
case DONELOCKS:
r = Z_STREAM_END2;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
case BADBLOCKS:
r = Z_DATA_ERROR2;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
default:
r = Z_STREAM_ERROR2;
that.bitb = b;
that.bitk = k;
z2.avail_in = n;
z2.total_in += p - z2.next_in_index;
z2.next_in_index = p;
that.write = q;
return that.inflate_flush(z2, r);
}
}
};
that.free = function(z2) {
that.reset(z2, null);
that.win = null;
hufts = null;
};
that.set_dictionary = function(d, start, n) {
that.win.set(d.subarray(start, start + n), 0);
that.read = that.write = n;
};
that.sync_point = function() {
return mode2 == LENS ? 1 : 0;
};
}
var PRESET_DICT2 = 32;
var Z_DEFLATED2 = 8;
var METHOD = 0;
var FLAG = 1;
var DICT4 = 2;
var DICT3 = 3;
var DICT2 = 4;
var DICT1 = 5;
var DICT0 = 6;
var BLOCKS = 7;
var DONE = 12;
var BAD = 13;
var mark = [0, 0, 255, 255];
function Inflate() {
const that = this;
that.mode = 0;
that.method = 0;
that.was = [0];
that.need = 0;
that.marker = 0;
that.wbits = 0;
function inflateReset(z) {
if (!z || !z.istate)
return Z_STREAM_ERROR2;
z.total_in = z.total_out = 0;
z.msg = null;
z.istate.mode = BLOCKS;
z.istate.blocks.reset(z, null);
return Z_OK2;
}
that.inflateEnd = function(z) {
if (that.blocks)
that.blocks.free(z);
that.blocks = null;
return Z_OK2;
};
that.inflateInit = function(z, w) {
z.msg = null;
that.blocks = null;
if (w < 8 || w > 15) {
that.inflateEnd(z);
return Z_STREAM_ERROR2;
}
that.wbits = w;
z.istate.blocks = new InfBlocks(z, 1 << w);
inflateReset(z);
return Z_OK2;
};
that.inflate = function(z, f) {
let r;
let b;
if (!z || !z.istate || !z.next_in)
return Z_STREAM_ERROR2;
const istate = z.istate;
f = f == Z_FINISH2 ? Z_BUF_ERROR2 : Z_OK2;
r = Z_BUF_ERROR2;
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++)) & 15) != Z_DEFLATED2) {
istate.mode = BAD;
z.msg = "unknown compression method";
istate.marker = 5;
break;
}
if ((istate.method >> 4) + 8 > istate.wbits) {
istate.mode = BAD;
z.msg = "invalid win size";
istate.marker = 5;
break;
}
istate.mode = FLAG;
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++) & 255;
if (((istate.method << 8) + b) % 31 !== 0) {
istate.mode = BAD;
z.msg = "incorrect header check";
istate.marker = 5;
break;
}
if ((b & PRESET_DICT2) === 0) {
istate.mode = BLOCKS;
break;
}
istate.mode = DICT4;
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++) & 255) << 24 & 4278190080;
istate.mode = DICT3;
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++) & 255) << 16 & 16711680;
istate.mode = DICT2;
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++) & 255) << 8 & 65280;
istate.mode = DICT1;
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++) & 255;
istate.mode = DICT0;
return Z_NEED_DICT2;
case DICT0:
istate.mode = BAD;
z.msg = "need dictionary";
istate.marker = 0;
return Z_STREAM_ERROR2;
case BLOCKS:
r = istate.blocks.proc(z, r);
if (r == Z_DATA_ERROR2) {
istate.mode = BAD;
istate.marker = 0;
break;
}
if (r == Z_OK2) {
r = f;
}
if (r != Z_STREAM_END2) {
return r;
}
r = f;
istate.blocks.reset(z, istate.was);
istate.mode = DONE;
case DONE:
z.avail_in = 0;
return Z_STREAM_END2;
case BAD:
return Z_DATA_ERROR2;
default:
return Z_STREAM_ERROR2;
}
}
};
that.inflateSetDictionary = function(z, dictionary, dictLength) {
let index = 0, length3 = dictLength;
if (!z || !z.istate || z.istate.mode != DICT0)
return Z_STREAM_ERROR2;
const istate = z.istate;
if (length3 >= 1 << istate.wbits) {
length3 = (1 << istate.wbits) - 1;
index = dictLength - length3;
}
istate.blocks.set_dictionary(dictionary, index, length3);
istate.mode = BLOCKS;
return Z_OK2;
};
that.inflateSync = function(z) {
let n;
let p;
let m;
let r, w;
if (!z || !z.istate)
return Z_STREAM_ERROR2;
const istate = z.istate;
if (istate.mode != BAD) {
istate.mode = BAD;
istate.marker = 0;
}
if ((n = z.avail_in) === 0)
return Z_BUF_ERROR2;
p = z.next_in_index;
m = istate.marker;
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--;
}
z.total_in += p - z.next_in_index;
z.next_in_index = p;
z.avail_in = n;
istate.marker = m;
if (m != 4) {
return Z_DATA_ERROR2;
}
r = z.total_in;
w = z.total_out;
inflateReset(z);
z.total_in = r;
z.total_out = w;
istate.mode = BLOCKS;
return Z_OK2;
};
that.inflateSyncPoint = function(z) {
if (!z || !z.istate || !z.istate.blocks)
return Z_STREAM_ERROR2;
return z.istate.blocks.sync_point();
};
}
function ZStream2() {
}
ZStream2.prototype = {
inflateInit: function(bits) {
const that = this;
that.istate = new Inflate();
if (!bits)
bits = MAX_BITS2;
return that.istate.inflateInit(that, bits);
},
inflate: function(f) {
const that = this;
if (!that.istate)
return Z_STREAM_ERROR2;
return that.istate.inflate(that, f);
},
inflateEnd: function() {
const that = this;
if (!that.istate)
return Z_STREAM_ERROR2;
const ret = that.istate.inflateEnd(that);
that.istate = null;
return ret;
},
inflateSync: function() {
const that = this;
if (!that.istate)
return Z_STREAM_ERROR2;
return that.istate.inflateSync(that);
},
inflateSetDictionary: function(dictionary, dictLength) {
const that = this;
if (!that.istate)
return Z_STREAM_ERROR2;
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);
}
};
function ZipInflate(options) {
const that = this;
const z = new ZStream2();
const bufsize = options && options.chunkSize ? Math.floor(options.chunkSize * 2) : 128 * 1024;
const flush = Z_NO_FLUSH2;
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) {
z.next_in_index = 0;
nomoreinput = true;
}
err = z.inflate(flush);
if (nomoreinput && err === Z_BUF_ERROR2) {
if (z.avail_in !== 0)
throw new Error("inflating: bad input");
} else if (err !== Z_OK2 && err !== Z_STREAM_END2)
throw new Error("inflating: " + z.msg);
if ((nomoreinput || err === Z_STREAM_END2) && 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();
};
}
var inflate_default = ZipInflate;
// node_modules/@zip.js/zip.js/lib/core/configuration.js
var DEFAULT_CONFIGURATION = {
chunkSize: 512 * 1024,
maxWorkers: typeof navigator != "undefined" && navigator.hardwareConcurrency || 2,
terminateWorkerTimeout: 5e3,
useWebWorkers: true,
workerScripts: void 0
};
var config = Object.assign({}, DEFAULT_CONFIGURATION);
function getConfiguration() {
return config;
}
function configure(configuration) {
if (configuration.baseURL !== void 0) {
config.baseURL = configuration.baseURL;
}
if (configuration.chunkSize !== void 0) {
config.chunkSize = configuration.chunkSize;
}
if (configuration.maxWorkers !== void 0) {
config.maxWorkers = configuration.maxWorkers;
}
if (configuration.terminateWorkerTimeout !== void 0) {
config.terminateWorkerTimeout = configuration.terminateWorkerTimeout;
}
if (configuration.useWebWorkers !== void 0) {
config.useWebWorkers = configuration.useWebWorkers;
}
if (configuration.Deflate !== void 0) {
config.Deflate = configuration.Deflate;
}
if (configuration.Inflate !== void 0) {
config.Inflate = configuration.Inflate;
}
if (configuration.workerScripts !== void 0) {
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;
}
}
}
// node_modules/@zip.js/zip.js/lib/core/codecs/crc32.js
var table = [];
for (let i = 0; i < 256; i++) {
let t = i;
for (let j = 0; j < 8; j++) {
if (t & 1) {
t = t >>> 1 ^ 3988292384;
} else {
t = t >>> 1;
}
}
table[i] = t;
}
var Crc32 = class {
constructor(crc) {
this.crc = crc || -1;
}
append(data) {
let crc = this.crc | 0;
for (let offset2 = 0, length3 = data.length | 0; offset2 < length3; offset2++) {
crc = crc >>> 8 ^ table[(crc ^ data[offset2]) & 255];
}
this.crc = crc;
}
get() {
return ~this.crc;
}
};
var crc32_default = Crc32;
// node_modules/@zip.js/zip.js/lib/core/util/encode-text.js
var encode_text_default = encodeText;
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);
}
}
// node_modules/@zip.js/zip.js/lib/core/codecs/sjcl.js
var bitArray = {
concat(a1, a22) {
if (a1.length === 0 || a22.length === 0) {
return a1.concat(a22);
}
const last = a1[a1.length - 1], shift = bitArray.getPartial(last);
if (shift === 32) {
return a1.concat(a22);
} else {
return bitArray._shiftRight(a22, shift, last | 0, a1.slice(0, a1.length - 1));
}
},
bitLength(a3) {
const l = a3.length;
if (l === 0) {
return 0;
}
const x = a3[l - 1];
return (l - 1) * 32 + bitArray.getPartial(x);
},
clamp(a3, len) {
if (a3.length * 32 < len) {
return a3;
}
a3 = a3.slice(0, Math.ceil(len / 32));
const l = a3.length;
len = len & 31;
if (l > 0 && len) {
a3[l - 1] = bitArray.partial(len, a3[l - 1] & 2147483648 >> len - 1, 1);
}
return a3;
},
partial(len, x, _end) {
if (len === 32) {
return x;
}
return (_end ? x | 0 : x << 32 - len) + len * 1099511627776;
},
getPartial(x) {
return Math.round(x / 1099511627776) || 32;
},
_shiftRight(a3, shift, carry, out) {
if (out === void 0) {
out = [];
}
for (; shift >= 32; shift -= 32) {
out.push(carry);
carry = 0;
}
if (shift === 0) {
return out.concat(a3);
}
for (let i = 0; i < a3.length; i++) {
out.push(carry | a3[i] >>> shift);
carry = a3[i] << 32 - shift;
}
const last2 = a3.length ? a3[a3.length - 1] : 0;
const shift2 = bitArray.getPartial(last2);
out.push(bitArray.partial(shift + shift2 & 31, shift + shift2 > 32 ? carry : out.pop(), 1));
return out;
}
};
var codec = {
bytes: {
fromBits(arr) {
const bl = bitArray.bitLength(arr);
const byteLength = bl / 8;
const out = new Uint8Array(byteLength);
let tmp2;
for (let i = 0; i < byteLength; i++) {
if ((i & 3) === 0) {
tmp2 = arr[i / 4];
}
out[i] = tmp2 >>> 24;
tmp2 <<= 8;
}
return out;
},
toBits(bytes) {
const out = [];
let i;
let tmp2 = 0;
for (i = 0; i < bytes.length; i++) {
tmp2 = tmp2 << 8 | bytes[i];
if ((i & 3) === 3) {
out.push(tmp2);
tmp2 = 0;
}
}
if (i & 3) {
out.push(bitArray.partial(8 * (i & 3), tmp2));
}
return out;
}
}
};
var hash = {};
hash.sha1 = function(hash2) {
if (hash2) {
this._h = hash2._h.slice(0);
this._buffer = hash2._buffer.slice(0);
this._length = hash2._length;
} else {
this.reset();
}
};
hash.sha1.prototype = {
blockSize: 512,
reset: function() {
const sha1 = this;
sha1._h = this._init.slice(0);
sha1._buffer = [];
sha1._length = 0;
return sha1;
},
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;
},
finalize: function() {
const sha1 = this;
let b = sha1._buffer;
const h = sha1._h;
b = bitArray.concat(b, [bitArray.partial(1, 1)]);
for (let i = b.length + 2; i & 15; i++) {
b.push(0);
}
b.push(Math.floor(sha1._length / 4294967296));
b.push(sha1._length | 0);
while (b.length) {
sha1._block(b.splice(0, 16));
}
sha1.reset();
return h;
},
_init: [1732584193, 4023233417, 2562383102, 271733878, 3285377520],
_key: [1518500249, 1859775393, 2400959708, 3395469782],
_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;
}
},
_S: function(n, x) {
return x << n | x >>> 32 - n;
},
_block: function(words) {
const sha1 = this;
const h = sha1._h;
const w = Array(80);
for (let j = 0; j < 16; j++) {
w[j] = words[j];
}
let a3 = 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 tmp2 = sha1._S(5, a3) + 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 = a3;
a3 = tmp2;
}
h[0] = h[0] + a3 | 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;
}
};
var cipher = {};
cipher.aes = class {
constructor(key) {
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 = []];
for (i = keyLen; i < 4 * keyLen + 28; i++) {
let tmp2 = encKey[i - 1];
if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
tmp2 = sbox[tmp2 >>> 24] << 24 ^ sbox[tmp2 >> 16 & 255] << 16 ^ sbox[tmp2 >> 8 & 255] << 8 ^ sbox[tmp2 & 255];
if (i % keyLen === 0) {
tmp2 = tmp2 << 8 ^ tmp2 >>> 24 ^ rcon << 24;
rcon = rcon << 1 ^ (rcon >> 7) * 283;
}
}
encKey[i] = encKey[i - keyLen] ^ tmp2;
}
for (let j = 0; i; j++, i--) {
const tmp2 = encKey[j & 3 ? i : i - 4];
if (i <= 4 || j < 4) {
decKey[j] = tmp2;
} else {
decKey[j] = decTable[0][sbox[tmp2 >>> 24]] ^ decTable[1][sbox[tmp2 >> 16 & 255]] ^ decTable[2][sbox[tmp2 >> 8 & 255]] ^ decTable[3][sbox[tmp2 & 255]];
}
}
}
encrypt(data) {
return this._crypt(data, 0);
}
decrypt(data) {
return this._crypt(data, 1);
}
_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;
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) {
let s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
s = s >> 8 ^ s & 255 ^ 99;
sbox[x] = s;
sboxInv[s] = x;
x8 = d[x4 = d[x2 = d[x]]];
let tDec = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008;
let tEnc = d[s] * 257 ^ s * 16843008;
for (let i = 0; i < 4; i++) {
encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
}
}
for (let i = 0; i < 5; i++) {
encTable[i] = encTable[i].slice(0);
decTable[i] = decTable[i].slice(0);
}
}
_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 table2 = this._tables[dir];
const t0 = table2[0];
const t1 = table2[1];
const t2 = table2[2];
const t3 = table2[3];
const sbox = table2[4];
let a3 = 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 a22, b2, c22;
for (let i = 0; i < nInnerRounds; i++) {
a22 = t0[a3 >>> 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[a3 & 255] ^ key[kIndex + 1];
c22 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a3 >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
d = t0[d >>> 24] ^ t1[a3 >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
kIndex += 4;
a3 = a22;
b = b2;
c = c22;
}
for (let i = 0; i < 4; i++) {
out[dir ? 3 & -i : i] = sbox[a3 >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
a22 = a3;
a3 = b;
b = c;
c = d;
d = a22;
}
return out;
}
};
var random = {
getRandomValues(typedArray) {
const words = new Uint32Array(typedArray.buffer);
const r = (m_w) => {
let m_z = 987654321;
const mask = 4294967295;
return function() {
m_z = 36969 * (m_z & 65535) + (m_z >> 16) & mask;
m_w = 18e3 * (m_w & 65535) + (m_w >> 16) & mask;
const result = ((m_z << 16) + m_w & mask) / 4294967296 + 0.5;
return result * (Math.random() > 0.5 ? 1 : -1);
};
};
for (let i = 0, rcache; i < typedArray.length; i += 4) {
const _r = r((rcache || Math.random()) * 4294967296);
rcache = _r() * 987654071;
words[i / 4] = _r() * 4294967296 | 0;
}
return typedArray;
}
};
var mode = {};
mode.ctrGladman = class {
constructor(prf, iv) {
this._prf = prf;
this._initIv = iv;
this._iv = iv;
}
reset() {
this._iv = this._initIv;
}
update(data) {
return this.calculate(this._prf, data, this._iv);
}
incWord(word) {
if ((word >> 24 & 255) === 255) {
let b1 = word >> 16 & 255;
let b2 = word >> 8 & 255;
let b3 = word & 255;
if (b1 === 255) {
b1 = 0;
if (b2 === 255) {
b2 = 0;
if (b3 === 255) {
b3 = 0;
} else {
++b3;
}
} else {
++b2;
}
} else {
++b1;
}
word = 0;
word += b1 << 16;
word += b2 << 8;
word += b3;
} else {
word += 1 << 24;
}
return word;
}
incCounter(counter) {
if ((counter[0] = this.incWord(counter[0])) === 0) {
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);
}
};
var misc = {
importKey(password) {
return new misc.hmacSha1(codec.bytes.toBits(password));
},
pbkdf2(prf, salt, count, length3) {
count = count || 1e4;
if (length3 < 0 || count < 0) {
throw new Error("invalid params to pbkdf2");
}
const byteLength = (length3 >> 5) + 1 << 2;
let u3, 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++) {
u3 = ui = prf.encrypt(b.concat(salt, [k]));
for (i = 1; i < count; i++) {
ui = prf.encrypt(ui);
for (j = 0; j < ui.length; j++) {
u3[j] ^= ui[j];
}
}
for (i = 0; outLength < (byteLength || 1) && i < u3.length; i++) {
out.setInt32(outLength, u3[i]);
outLength += 4;
}
}
return arrayBuffer.slice(0, length3 / 8);
}
};
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] ^ 909522486;
exKey[1][i] = key[i] ^ 1549556828;
}
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!");
}
}
};
// node_modules/@zip.js/zip.js/lib/core/codecs/aes-crypto.js
var ERR_INVALID_PASSWORD = "Invalid pasword";
var BLOCK_LENGTH = 16;
var RAW_FORMAT = "raw";
var PBKDF2_ALGORITHM = { name: "PBKDF2" };
var HASH_ALGORITHM = { name: "HMAC" };
var HASH_FUNCTION = "SHA-1";
var BASE_KEY_ALGORITHM = Object.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM);
var DERIVED_BITS_ALGORITHM = Object.assign({ iterations: 1e3, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM);
var DERIVED_BITS_USAGE = ["deriveBits"];
var SALT_LENGTH = [8, 12, 16];
var KEY_LENGTH = [16, 24, 32];
var SIGNATURE_LENGTH = 10;
var COUNTER_DEFAULT_VALUE = [0, 0, 0, 0];
var CRYPTO_API_SUPPORTED = typeof crypto != "undefined";
var SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof crypto.subtle != "undefined";
var codecBytes = codec.bytes;
var Aes = cipher.aes;
var CtrGladman = mode.ctrGladman;
var HmacSha1 = misc.hmacSha1;
var AESDecrypt = class {
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
};
}
};
var AESEncrypt = class {
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 offset2;
for (offset2 = 0; offset2 <= inputLength - BLOCK_LENGTH; offset2 += BLOCK_LENGTH) {
const inputChunk = codecBytes.toBits(subarray(input, offset2, offset2 + 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), offset2 + paddingStart);
}
aesCrypto.pendingInput = subarray(input, offset2);
return output;
}
async function createDecryptionKeys(decrypt2, preambleArray, password) {
await createKeys(decrypt2, password, subarray(preambleArray, 0, SALT_LENGTH[decrypt2.strength]));
const passwordVerification = subarray(preambleArray, SALT_LENGTH[decrypt2.strength]);
const passwordVerificationKey = decrypt2.keys.passwordVerification;
if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) {
throw new Error(ERR_INVALID_PASSWORD);
}
}
async function createEncryptionKeys(encrypt2, password) {
const salt = getRandomValues2(new Uint8Array(SALT_LENGTH[encrypt2.strength]));
await createKeys(encrypt2, password, salt);
return concat(salt, encrypt2.keys.passwordVerification);
}
async function createKeys(target, password, salt) {
const encodedPassword = encode_text_default(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 getRandomValues2(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, length3) {
if (CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof crypto.subtle.deriveBits == "function") {
return await crypto.subtle.deriveBits(algorithm, baseKey, length3);
} else {
return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length3);
}
}
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, length3) {
if (length3 && length3 > inputArray.length) {
const array = inputArray;
inputArray = new Uint8Array(length3);
inputArray.set(array, 0);
}
return inputArray;
}
function subarray(array, begin, end) {
return array.subarray(begin, end);
}
// node_modules/@zip.js/zip.js/lib/core/codecs/zip-crypto.js
var HEADER_LENGTH = 12;
var ZipCryptoDecrypt = class {
constructor(password, passwordVerification) {
const zipCrypto = this;
Object.assign(zipCrypto, {
password,
passwordVerification
});
createKeys2(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)
};
}
};
var ZipCryptoEncrypt = class {
constructor(password, passwordVerification) {
const zipCrypto = this;
Object.assign(zipCrypto, {
password,
passwordVerification
});
createKeys2(zipCrypto, password);
}
append(input) {
const zipCrypto = this;
let output;
let offset2;
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);
offset2 = HEADER_LENGTH;
} else {
output = new Uint8Array(input.length);
offset2 = 0;
}
output.set(encrypt(zipCrypto, input), offset2);
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 createKeys2(target, password) {
target.keys = [305419896, 591751049, 878082192];
target.crcKey0 = new crc32_default(target.keys[0]);
target.crcKey2 = new crc32_default(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 & 255;
}
function getInt32(number) {
return number & 4294967295;
}
// node_modules/@zip.js/zip.js/lib/core/codecs/codec.js
var CODEC_DEFLATE = "deflate";
var CODEC_INFLATE = "inflate";
var ERR_INVALID_SIGNATURE = "Invalid signature";
var Inflate2 = class {
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_default(),
zipCrypto,
decrypt: encrypted && zipCrypto ? new ZipCryptoDecrypt(password, passwordVerification) : new AESDecrypt(password, signed, encryptionStrength)
});
}
async append(data) {
const codec2 = this;
if (codec2.encrypted && data.length) {
data = await codec2.decrypt.append(data);
}
if (codec2.compressed && data.length) {
data = await codec2.inflate.append(data);
}
if ((!codec2.encrypted || codec2.zipCrypto) && codec2.signed && data.length) {
codec2.crc32.append(data);
}
return data;
}
async flush() {
const codec2 = this;
let signature;
let data = new Uint8Array(0);
if (codec2.encrypted) {
const result = codec2.decrypt.flush();
if (!result.valid) {
throw new Error(ERR_INVALID_SIGNATURE);
}
data = result.data;
}
if ((!codec2.encrypted || codec2.zipCrypto) && codec2.signed) {
const dataViewSignature = new DataView(new Uint8Array(4).buffer);
signature = codec2.crc32.get();
dataViewSignature.setUint32(0, signature);
if (codec2.signature != dataViewSignature.getUint32(0, false)) {
throw new Error(ERR_INVALID_SIGNATURE);
}
}
if (codec2.compressed) {
data = await codec2.inflate.append(data) || new Uint8Array(0);
await codec2.inflate.flush();
}
return { data, signature };
}
};
var Deflate2 = class {
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_default(),
zipCrypto,
encrypt: encrypted && zipCrypto ? new ZipCryptoEncrypt(password, passwordVerification) : new AESEncrypt(password, encryptionStrength)
});
}
async append(inputData) {
const codec2 = this;
let data = inputData;
if (codec2.compressed && inputData.length) {
data = await codec2.deflate.append(inputData);
}
if (codec2.encrypted && data.length) {
data = await codec2.encrypt.append(data);
}
if ((!codec2.encrypted || codec2.zipCrypto) && codec2.signed && inputData.length) {
codec2.crc32.append(inputData);
}
return data;
}
async flush() {
const codec2 = this;
let signature;
let data = new Uint8Array(0);
if (codec2.compressed) {
data = await codec2.deflate.flush() || new Uint8Array(0);
}
if (codec2.encrypted) {
data = await codec2.encrypt.append(data);
const result = codec2.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 ((!codec2.encrypted || codec2.zipCrypto) && codec2.signed) {
signature = codec2.crc32.get();
}
return { data, signature };
}
};
function createCodec(codecConstructor, options, config2) {
if (options.codecType.startsWith(CODEC_DEFLATE)) {
return new Deflate2(codecConstructor, options, config2);
} else if (options.codecType.startsWith(CODEC_INFLATE)) {
return new Inflate2(codecConstructor, options, config2);
}
}
// node_modules/@zip.js/zip.js/lib/core/codecs/codec-pool-worker.js
var MESSAGE_INIT = "init";
var MESSAGE_APPEND = "append";
var MESSAGE_FLUSH = "flush";
var MESSAGE_EVENT_TYPE = "message";
var classicWorkersSupported = true;
var codec_pool_worker_default = (workerData, codecConstructor, options, config2, 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, config2) : createWorkerInterface(workerData, config2);
};
function createWorkerInterface(workerData, config2) {
const interfaceCodec = createCodec(workerData.codecConstructor, workerData.options, config2);
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, config2) {
let messageTask;
const workerOptions = { type: "module" };
if (!workerData.interface) {
if (!classicWorkersSupported) {
workerData.worker = getWorker(workerOptions, config2.baseURL);
} else {
try {
workerData.worker = getWorker({}, config2.baseURL);
} catch (_error) {
classicWorkersSupported = false;
workerData.worker = getWorker(workerOptions, config2.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 url2, scriptUrl;
url2 = workerData.scripts[0];
if (typeof url2 == "function") {
url2 = url2();
}
try {
scriptUrl = new URL(url2, baseURL);
} catch (_error) {
scriptUrl = url2;
}
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: config2.chunkSize } });
}
return sendMessage(message);
}
function sendMessage(message) {
const worker = workerData.worker;
const result = new Promise((resolve2, reject) => messageTask = { resolve: resolve2, 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));
}
}
}
}
}
// node_modules/@zip.js/zip.js/lib/core/codecs/codec-pool.js
var pool = [];
var pendingRequests = [];
function createCodec2(codecConstructor, options, config2) {
const streamCopy = !options.compressed && !options.signed && !options.encrypted;
const webWorker = !streamCopy && (options.useWebWorkers || options.useWebWorkers === void 0 && config2.useWebWorkers);
const scripts = webWorker && config2.workerScripts ? config2.workerScripts[options.codecType] : [];
if (pool.length < config2.maxWorkers) {
const workerData = {};
pool.push(workerData);
return codec_pool_worker_default(workerData, codecConstructor, options, config2, onTaskFinished, webWorker, scripts);
} else {
const workerData = pool.find((workerData2) => !workerData2.busy);
if (workerData) {
clearTerminateTimeout(workerData);
return codec_pool_worker_default(workerData, codecConstructor, options, config2, onTaskFinished, webWorker, scripts);
} else {
return new Promise((resolve2) => pendingRequests.push({ resolve: resolve2, codecConstructor, options, webWorker, scripts }));
}
}
function onTaskFinished(workerData) {
if (pendingRequests.length) {
const [{ resolve: resolve2, codecConstructor: codecConstructor2, options: options2, webWorker: webWorker2, scripts: scripts2 }] = pendingRequests.splice(0, 1);
resolve2(codec_pool_worker_default(workerData, codecConstructor2, options2, config2, onTaskFinished, webWorker2, scripts2));
} else if (workerData.worker) {
clearTerminateTimeout(workerData);
if (Number.isFinite(config2.terminateWorkerTimeout) && config2.terminateWorkerTimeout >= 0) {
workerData.terminateTimeout = setTimeout(() => {
pool = pool.filter((data) => data != workerData);
workerData.terminate();
}, config2.terminateWorkerTimeout);
}
} else {
pool = pool.filter((data) => data != workerData);
}
}
}
function clearTerminateTimeout(workerData) {
if (workerData.terminateTimeout) {
clearTimeout(workerData.terminateTimeout);
workerData.terminateTimeout = null;
}
}
// node_modules/@zip.js/zip.js/lib/core/engine.js
var MINIMUM_CHUNK_SIZE = 64;
var ERR_ABORT = "Abort error";
async function processData(codec2, reader, writer, offset2, inputLengthGetter, config2, options) {
const chunkSize = Math.max(config2.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, codec2);
const inputData = await reader.readUint8Array(chunkOffset + offset2, Math.min(chunkSize, inputLength - chunkOffset));
const chunkLength = inputData.length;
testAborted(signal, codec2);
const data = await codec2.append(inputData);
testAborted(signal, codec2);
outputLength += await writeData(writer, data);
if (options.onprogress) {
try {
options.onprogress(chunkOffset + chunkLength, inputLength);
} catch (error) {
}
}
return processChunk(chunkOffset + chunkSize, outputLength);
} else {
const result = await codec2.flush();
outputLength += await writeData(writer, result.data);
return { signature: result.signature, length: outputLength };
}
}
}
function testAborted(signal, codec2) {
if (signal && signal.aborted) {
codec2.abort();
throw new Error(ERR_ABORT);
}
}
async function writeData(writer, data) {
if (data.length) {
await writer.writeUint8Array(data);
}
return data.length;
}
// node_modules/@zip.js/zip.js/lib/core/io.js
var CONTENT_TYPE_TEXT_PLAIN = "text/plain";
var Stream = class {
constructor() {
this.size = 0;
}
init() {
this.initialized = true;
}
};
var Reader = class extends Stream {
};
var Writer = class extends Stream {
writeUint8Array(array) {
this.size += array.length;
}
};
var TextReader = class extends Reader {
constructor(text2) {
super();
this.blobReader = new BlobReader(new Blob([text2], { type: CONTENT_TYPE_TEXT_PLAIN }));
}
init() {
super.init();
this.blobReader.init();
this.size = this.blobReader.size;
}
readUint8Array(offset2, length3) {
return this.blobReader.readUint8Array(offset2, length3);
}
};
var TextWriter = class 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((resolve2, reject) => {
reader.onload = (event) => resolve2(event.target.result);
reader.onerror = () => reject(reader.error);
reader.readAsText(this.blob, this.encoding);
});
}
}
};
var Data64URIWriter = class 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);
}
};
var BlobReader = class extends Reader {
constructor(blob) {
super();
this.blob = blob;
this.size = blob.size;
}
async readUint8Array(offset2, length3) {
if (this.blob.arrayBuffer) {
return new Uint8Array(await this.blob.slice(offset2, offset2 + length3).arrayBuffer());
} else {
const reader = new FileReader();
return new Promise((resolve2, reject) => {
reader.onload = (event) => resolve2(new Uint8Array(event.target.result));
reader.onerror = () => reject(reader.error);
reader.readAsArrayBuffer(this.blob.slice(offset2, offset2 + length3));
});
}
}
};
var BlobWriter = class 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 = [];
}
// node_modules/@zip.js/zip.js/lib/core/constants.js
var MAX_32_BITS = 4294967295;
var MAX_16_BITS = 65535;
var COMPRESSION_METHOD_DEFLATE = 8;
var COMPRESSION_METHOD_STORE = 0;
var COMPRESSION_METHOD_AES = 99;
var LOCAL_FILE_HEADER_SIGNATURE = 67324752;
var DATA_DESCRIPTOR_RECORD_SIGNATURE = 134695760;
var CENTRAL_FILE_HEADER_SIGNATURE = 33639248;
var END_OF_CENTRAL_DIR_SIGNATURE = 101010256;
var ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = 101075792;
var ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = 117853008;
var END_OF_CENTRAL_DIR_LENGTH = 22;
var ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH = 20;
var ZIP64_END_OF_CENTRAL_DIR_LENGTH = 56;
var 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;
var ZIP64_TOTAL_NUMBER_OF_DISKS = 1;
var EXTRAFIELD_TYPE_ZIP64 = 1;
var EXTRAFIELD_TYPE_AES = 39169;
var EXTRAFIELD_TYPE_NTFS = 10;
var EXTRAFIELD_TYPE_NTFS_TAG1 = 1;
var EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP = 21589;
var EXTRAFIELD_TYPE_UNICODE_PATH = 28789;
var EXTRAFIELD_TYPE_UNICODE_COMMENT = 25461;
var BITFLAG_ENCRYPTED = 1;
var BITFLAG_LEVEL = 6;
var BITFLAG_DATA_DESCRIPTOR = 8;
var BITFLAG_LANG_ENCODING_FLAG = 2048;
var FILE_ATTR_MSDOS_DIR_MASK = 16;
var VERSION_DEFLATE = 20;
var VERSION_ZIP64 = 45;
var VERSION_AES = 51;
var DIRECTORY_SIGNATURE = "/";
var MAX_DATE = new Date(2107, 11, 31);
var MIN_DATE = new Date(1980, 0, 1);
// node_modules/@zip.js/zip.js/lib/core/util/cp437-decode.js
var CP437 = "\0\u263A\u263B\u2665\u2666\u2663\u2660\u2022\u25D8\u25CB\u25D9\u2642\u2640\u266A\u266B\u263C\u25BA\u25C4\u2195\u203C\xB6\xA7\u25AC\u21A8\u2191\u2193\u2192\u2190\u221F\u2194\u25B2\u25BC !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u2302\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0 ".split("");
var cp437_decode_default = (stringValue) => {
let result = "";
for (let indexCharacter = 0; indexCharacter < stringValue.length; indexCharacter++) {
result += CP437[stringValue[indexCharacter]];
}
return result;
};
// node_modules/@zip.js/zip.js/lib/core/util/decode-text.js
var decode_text_default = decodeText;
function decodeText(value, encoding) {
if (encoding && encoding.trim().toLowerCase() == "cp437") {
return cp437_decode_default(value);
} else if (typeof TextDecoder == "undefined") {
const fileReader = new FileReader();
return new Promise((resolve2, reject) => {
fileReader.onload = (event) => resolve2(event.target.result);
fileReader.onerror = () => reject(fileReader.error);
fileReader.readAsText(new Blob([value]));
});
} else {
return new TextDecoder(encoding).decode(value);
}
}
// node_modules/@zip.js/zip.js/lib/core/zip-entry.js
var 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"
];
var Entry = class {
constructor(data) {
PROPERTY_NAMES.forEach((name) => this[name] = data[name]);
}
};
// node_modules/@zip.js/zip.js/lib/core/zip-reader.js
var ERR_BAD_FORMAT = "File format is not recognized";
var ERR_EOCDR_NOT_FOUND = "End of central directory not found";
var ERR_EOCDR_ZIP64_NOT_FOUND = "End of Zip64 central directory not found";
var ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND = "End of Zip64 central directory locator not found";
var ERR_CENTRAL_DIRECTORY_NOT_FOUND = "Central directory header not found";
var ERR_LOCAL_FILE_HEADER_NOT_FOUND = "Local file header not found";
var ERR_EXTRAFIELD_ZIP64_NOT_FOUND = "Zip64 extra field not found";
var ERR_ENCRYPTED = "File contains encrypted entry";
var ERR_UNSUPPORTED_ENCRYPTION = "Encryption method not supported";
var ERR_UNSUPPORTED_COMPRESSION = "Compression method not supported";
var CHARSET_UTF8 = "utf-8";
var CHARSET_CP437 = "cp437";
var ZIP64_PROPERTIES = ["uncompressedSize", "compressedSize", "offset"];
var ZipReader = class {
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(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(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 endOfDirectoryView2 = getDataView(endOfDirectoryArray);
const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH - ZIP64_END_OF_CENTRAL_DIR_LENGTH;
if (getUint32(endOfDirectoryView2, 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);
endOfDirectoryView2 = getDataView(endOfDirectoryArray);
}
if (getUint32(endOfDirectoryView2, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE) {
throw new Error(ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND);
}
filesLength = getBigUint64(endOfDirectoryView2, 32);
directoryDataLength = getBigUint64(endOfDirectoryView2, 40);
directoryDataOffset -= directoryDataLength;
}
if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
throw new Error(ERR_BAD_FORMAT);
}
let offset2 = 0;
let directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength);
let directoryView = getDataView(directoryArray);
if (directoryDataLength) {
const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - directoryDataLength;
if (getUint32(directoryView, offset2) != CENTRAL_FILE_HEADER_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
const originalDirectoryDataOffset = directoryDataOffset;
directoryDataOffset = expectedDirectoryDataOffset;
prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength);
directoryView = getDataView(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, offset2) != CENTRAL_FILE_HEADER_SIGNATURE) {
throw new Error(ERR_CENTRAL_DIRECTORY_NOT_FOUND);
}
readCommonHeader(fileEntry, directoryView, offset2 + 6);
const languageEncodingFlag = Boolean(fileEntry.bitFlag.languageEncodingFlag);
const filenameOffset = offset2 + 46;
const extraFieldOffset = filenameOffset + fileEntry.filenameLength;
const commentOffset = extraFieldOffset + fileEntry.extraFieldLength;
const versionMadeBy = getUint16(directoryView, offset2 + 4);
const msDosCompatible = (versionMadeBy & 0) == 0;
Object.assign(fileEntry, {
versionMadeBy,
msDosCompatible,
compressedSize: 0,
uncompressedSize: 0,
commentLength: getUint16(directoryView, offset2 + 32),
directory: msDosCompatible && (getUint8(directoryView, offset2 + 38) & FILE_ATTR_MSDOS_DIR_MASK) == FILE_ATTR_MSDOS_DIR_MASK,
offset: getUint32(directoryView, offset2 + 42) + prependedDataLength,
internalFileAttribute: getUint32(directoryView, offset2 + 34),
externalFileAttribute: getUint32(directoryView, offset2 + 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(zipReader, options, "filenameEncoding");
const commentEncoding = getOptionValue(zipReader, options, "commentEncoding");
const [filename, comment] = await Promise.all([
decode_text_default(fileEntry.rawFilename, fileEntry.filenameUTF8 ? CHARSET_UTF8 : filenameEncoding || CHARSET_CP437),
decode_text_default(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, offset2 + 6);
const entry = new Entry(fileEntry);
entry.getData = (writer, options2) => fileEntry.getData(writer, entry, options2);
offset2 = endOffset;
if (options.onprogress) {
try {
options.onprogress(indexFile + 1, filesLength, new Entry(fileEntry));
} catch (_error) {
}
}
yield entry;
}
return true;
}
async getEntries(options = {}) {
const entries2 = [];
const iter = this.getEntriesGenerator(options);
let curr = iter.next();
while (!(await curr).done) {
entries2.push((await curr).value);
curr = iter.next();
}
return entries2;
}
async close() {
}
};
var ZipEntry = class {
constructor(reader, config2, options) {
Object.assign(this, {
reader,
config: config2,
options
});
}
async getData(writer, fileEntry, options = {}) {
const zipEntry = this;
const {
reader,
offset: offset2,
extraFieldAES,
compressionMethod,
config: config2,
bitFlag,
signature,
rawLastModDate,
compressedSize
} = zipEntry;
const localDirectory = zipEntry.localDirectory = {};
if (!reader.initialized) {
await reader.init();
}
let dataArray = await readUint8Array(reader, offset2, 30);
const dataView = getDataView(dataArray);
let password = getOptionValue(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, offset2, 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 === void 0) {
throw new Error(ERR_UNSUPPORTED_ENCRYPTION);
} else if (!password) {
throw new Error(ERR_ENCRYPTED);
}
}
const codec2 = await createCodec2(config2.Inflate, {
codecType: CODEC_INFLATE,
password,
zipCrypto,
encryptionStrength: extraFieldAES && extraFieldAES.strength,
signed: getOptionValue(zipEntry, options, "checkSignature"),
passwordVerification: zipCrypto && (bitFlag.dataDescriptor ? rawLastModDate >>> 8 & 255 : signature >>> 24 & 255),
signature,
compressed: compressionMethod != 0,
encrypted,
useWebWorkers: getOptionValue(zipEntry, options, "useWebWorkers")
}, config2);
if (!writer.initialized) {
await writer.init();
}
const signal = getOptionValue(zipEntry, options, "signal");
const dataOffset = offset2 + 30 + localDirectory.filenameLength + localDirectory.extraFieldLength;
await processData(codec2, reader, writer, dataOffset, () => compressedSize, config2, { onprogress: options.onprogress, signal });
return writer.getData();
}
};
function readCommonHeader(directory, dataView, offset2) {
const rawBitFlag = directory.rawBitFlag = getUint16(dataView, offset2 + 2);
const encrypted = (rawBitFlag & BITFLAG_ENCRYPTED) == BITFLAG_ENCRYPTED;
const rawLastModDate = getUint32(dataView, offset2 + 6);
Object.assign(directory, {
encrypted,
version: getUint16(dataView, offset2),
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, offset2 + 22),
extraFieldLength: getUint16(dataView, offset2 + 24)
});
}
async function readCommonFooter(fileEntry, directory, dataView, offset2) {
const rawExtraField = directory.rawExtraField;
const extraField = directory.extraField = /* @__PURE__ */ new Map();
const rawExtraFieldView = getDataView(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) {
}
const compressionMethod = getUint16(dataView, offset2 + 4);
directory.signature = getUint32(dataView, offset2 + 10);
directory.uncompressedSize = getUint32(dataView, offset2 + 18);
directory.compressedSize = getUint32(dataView, offset2 + 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(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] !== void 0) {
directory[propertyName] = extraFieldZip64[propertyName];
} else {
throw new Error(ERR_EXTRAFIELD_ZIP64_NOT_FOUND);
}
}
});
}
async function readExtraFieldUnicode(extraFieldUnicode, propertyName, rawPropertyName, directory, fileEntry) {
const extraFieldView = getDataView(extraFieldUnicode.data);
extraFieldUnicode.version = getUint8(extraFieldView, 0);
extraFieldUnicode.signature = getUint32(extraFieldView, 1);
const crc32 = new crc32_default();
crc32.append(fileEntry[rawPropertyName]);
const dataViewSignature = getDataView(new Uint8Array(4));
dataViewSignature.setUint32(0, crc32.get(), true);
extraFieldUnicode[propertyName] = await decode_text_default(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(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(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) {
}
try {
if (tag1Data && tag1Data.length == 24) {
const tag1View = getDataView(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) {
}
}
function readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory) {
const extraFieldView = getDataView(extraFieldExtendedTimestamp.data);
const flags = getUint8(extraFieldView, 0);
const timeProperties = [];
const timeRawProperties = [];
if ((flags & 1) == 1) {
timeProperties.push("lastModDate");
timeRawProperties.push("rawLastModDate");
}
if ((flags & 2) == 2) {
timeProperties.push("lastAccessDate");
timeRawProperties.push("rawLastAccessDate");
}
if ((flags & 4) == 4) {
timeProperties.push("creationDate");
timeRawProperties.push("rawCreationDate");
}
let offset2 = 1;
timeProperties.forEach((propertyName, indexProperty) => {
if (extraFieldExtendedTimestamp.data.length >= offset2 + 4) {
const time = getUint32(extraFieldView, offset2);
directory[propertyName] = extraFieldExtendedTimestamp[propertyName] = new Date(time * 1e3);
const rawPropertyName = timeRawProperties[indexProperty];
extraFieldExtendedTimestamp[rawPropertyName] = time;
}
offset2 += 4;
});
}
async function seekSignature(reader, signature, startOffset, minimumBytes, maximumLength) {
const signatureArray = new Uint8Array(4);
const signatureView = getDataView(signatureArray);
setUint32(signatureView, 0, signature);
const maximumBytes = minimumBytes + maximumLength;
return await seek(minimumBytes) || await seek(Math.min(maximumBytes, startOffset));
async function seek(length3) {
const offset2 = startOffset - length3;
const bytes = await readUint8Array(reader, offset2, length3);
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: offset2 + indexByte,
buffer: bytes.slice(indexByte, indexByte + minimumBytes).buffer
};
}
}
}
}
function getOptionValue(zipReader, options, name) {
return options[name] === void 0 ? zipReader.options[name] : options[name];
}
function getDate(timeRaw) {
const date = (timeRaw & 4294901760) >> 16, time = timeRaw & 65535;
try {
return new Date(1980 + ((date & 65024) >> 9), ((date & 480) >> 5) - 1, date & 31, (time & 63488) >> 11, (time & 2016) >> 5, (time & 31) * 2, 0);
} catch (_error) {
}
}
function getDateNTFS(timeRaw) {
return new Date(Number(timeRaw / BigInt(1e4) - BigInt(116444736e5)));
}
function getUint8(view, offset2) {
return view.getUint8(offset2);
}
function getUint16(view, offset2) {
return view.getUint16(offset2, true);
}
function getUint32(view, offset2) {
return view.getUint32(offset2, true);
}
function getBigUint64(view, offset2) {
return Number(view.getBigUint64(offset2, true));
}
function setUint32(view, offset2, value) {
view.setUint32(offset2, value, true);
}
function getDataView(array) {
return new DataView(array.buffer);
}
function readUint8Array(reader, offset2, size) {
return reader.readUint8Array(offset2, size);
}
// node_modules/@zip.js/zip.js/lib/core/zip-writer.js
var ERR_DUPLICATED_NAME = "File already exists";
var ERR_INVALID_COMMENT = "Zip file comment exceeds 64KB";
var ERR_INVALID_ENTRY_COMMENT = "File entry comment exceeds 64KB";
var ERR_INVALID_ENTRY_NAME = "File entry name exceeds 64KB";
var ERR_INVALID_VERSION = "Version exceeds 65535";
var ERR_INVALID_ENCRYPTION_STRENGTH = "The strength must equal 1, 2, or 3";
var ERR_INVALID_EXTRAFIELD_TYPE = "Extra field type exceeds 65535";
var ERR_INVALID_EXTRAFIELD_DATA = "Extra field data exceeds 64KB";
var ERR_UNSUPPORTED_FORMAT = "Zip64 is not supported";
var EXTRAFIELD_DATA_AES = new Uint8Array([7, 0, 2, 0, 65, 69, 3, 0, 0]);
var EXTRAFIELD_LENGTH_ZIP64 = 24;
var workers = 0;
var ZipWriter = class {
constructor(writer, options = {}) {
Object.assign(this, {
writer,
options,
config: getConfiguration(),
files: /* @__PURE__ */ new Map(),
offset: writer.size,
pendingCompressedSize: 0,
pendingEntries: [],
pendingAddFileCalls: /* @__PURE__ */ 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((resolve2, reject) => zipWriter.pendingEntries.push({ name, reader, options, resolve: resolve2, 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 = encode_text_default(name);
if (rawFilename.length > MAX_16_BITS) {
throw new Error(ERR_INVALID_ENTRY_NAME);
}
const comment = options.comment || "";
const rawComment = encode_text_default(comment);
if (rawComment.length > MAX_16_BITS) {
throw new Error(ERR_INVALID_ENTRY_COMMENT);
}
const version2 = zipWriter.options.version || options.version || 0;
if (version2 > 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 = getOptionValue2(zipWriter, options, "lastModDate") || new Date();
const lastAccessDate = getOptionValue2(zipWriter, options, "lastAccessDate");
const creationDate = getOptionValue2(zipWriter, options, "creationDate");
const password = getOptionValue2(zipWriter, options, "password");
const encryptionStrength = getOptionValue2(zipWriter, options, "encryptionStrength") || 3;
const zipCrypto = getOptionValue2(zipWriter, options, "zipCrypto");
if (password !== void 0 && encryptionStrength !== void 0 && (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 offset2 = 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]), offset2);
arraySet(rawExtraField, new Uint16Array([data.length]), offset2 + 2);
arraySet(rawExtraField, data, offset2 + 4);
offset2 += 4 + data.length;
});
}
let extendedTimestamp = getOptionValue2(zipWriter, options, "extendedTimestamp");
if (extendedTimestamp === void 0) {
extendedTimestamp = true;
}
let maximumCompressedSize = 0;
let keepOrder = getOptionValue2(zipWriter, options, "keepOrder");
if (keepOrder === void 0) {
keepOrder = true;
}
let uncompressedSize = 0;
let msDosCompatible = getOptionValue2(zipWriter, options, "msDosCompatible");
if (msDosCompatible === void 0) {
msDosCompatible = true;
}
const internalFileAttribute = getOptionValue2(zipWriter, options, "internalFileAttribute") || 0;
const externalFileAttribute = getOptionValue2(zipWriter, options, "externalFileAttribute") || 0;
if (reader) {
if (!reader.initialized) {
await reader.init();
}
uncompressedSize = reader.size;
maximumCompressedSize = getMaximumCompressedSize2(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 = getOptionValue2(zipWriter, options, "level");
const useWebWorkers = getOptionValue2(zipWriter, options, "useWebWorkers");
const bufferedWrite = getOptionValue2(zipWriter, options, "bufferedWrite");
let dataDescriptor = getOptionValue2(zipWriter, options, "dataDescriptor");
let dataDescriptorSignature = getOptionValue2(zipWriter, options, "dataDescriptorSignature");
const signal = getOptionValue2(zipWriter, options, "signal");
if (dataDescriptor === void 0) {
dataDescriptor = true;
}
if (dataDescriptor && dataDescriptorSignature === void 0) {
dataDescriptorSignature = false;
}
const fileEntry = await getFileEntry(zipWriter, name, reader, Object.assign({}, options, {
rawFilename,
rawComment,
version: version2,
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((resolve2) => resolveLockCurrentFileEntry = resolve2);
if (options.bufferedWrite || zipWriter.lockWrite || !options.dataDescriptor) {
fileWriter = new BlobWriter();
fileWriter.init();
bufferedWrite = true;
} else {
zipWriter.lockWrite = new Promise((resolve2) => resolveLockUnbufferedWrite = resolve2);
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((fileEntry2) => fileEntry2.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) {
setUint322(arrayBufferView, 14, fileEntry.signature);
}
if (fileEntry.zip64) {
setUint322(arrayBufferView, 18, MAX_32_BITS);
setUint322(arrayBufferView, 22, MAX_32_BITS);
} else {
setUint322(arrayBufferView, 18, fileEntry.compressedSize);
setUint322(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 = getDataView2(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, config2, options) {
const {
rawFilename,
lastAccessDate,
creationDate,
password,
level,
zip64,
zipCrypto,
dataDescriptor,
dataDescriptorSignature,
directory,
version: version2,
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 = getDataView2(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 = getDataView2(rawExtraFieldExtendedTimestamp);
setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
setUint16(extraFieldExtendedTimestampView, 2, rawExtraFieldExtendedTimestamp.length - 4);
const extraFieldExtendedTimestampFlag = 1 + (lastAccessDate ? 2 : 0) + (creationDate ? 4 : 0);
setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
setUint322(extraFieldExtendedTimestampView, 5, Math.floor(options.lastModDate.getTime() / 1e3));
if (lastAccessDate) {
setUint322(extraFieldExtendedTimestampView, 9, Math.floor(lastAccessDate.getTime() / 1e3));
}
if (creationDate) {
setUint322(extraFieldExtendedTimestampView, 13, Math.floor(creationDate.getTime() / 1e3));
}
try {
rawExtraFieldNTFS = new Uint8Array(36);
const extraFieldNTFSView = getDataView2(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: version2 || 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 = getDataView2(headerArray);
setUint16(headerView, 0, fileEntry.version);
setUint16(headerView, 2, bitFlag);
setUint16(headerView, 4, compressionMethod);
const dateArray = new Uint32Array(1);
const dateView = getDataView2(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];
setUint322(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 = getDataView2(localHeaderArray);
setUint322(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 codec2 = await createCodec2(config2.Deflate, {
codecType: CODEC_DEFLATE,
level,
password,
encryptionStrength,
zipCrypto: encrypted && zipCrypto,
passwordVerification: encrypted && zipCrypto && rawLastModDate >> 8 & 255,
signed: true,
compressed,
encrypted,
useWebWorkers
}, config2);
await writer.writeUint8Array(localHeaderArray);
fileEntry.dataWritten = true;
result = await processData(codec2, reader, writer, 0, () => reader.size, config2, { 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 = getDataView2(dataDescriptorArray);
if (dataDescriptorSignature) {
dataDescriptorOffset = 4;
setUint322(dataDescriptorView, 0, DATA_DESCRIPTOR_RECORD_SIGNATURE);
}
}
if (reader) {
const signature = result.signature;
if ((!encrypted || zipCrypto) && signature !== void 0) {
setUint322(headerView, 10, signature);
fileEntry.signature = signature;
if (dataDescriptor) {
setUint322(dataDescriptorView, dataDescriptorOffset, signature);
}
}
if (zip64) {
const rawExtraFieldZip64View = getDataView2(fileEntry.rawExtraFieldZip64);
setUint16(rawExtraFieldZip64View, 0, EXTRAFIELD_TYPE_ZIP64);
setUint16(rawExtraFieldZip64View, 2, EXTRAFIELD_LENGTH_ZIP64);
setUint322(headerView, 14, MAX_32_BITS);
setBigUint64(rawExtraFieldZip64View, 12, BigInt(compressedSize));
setUint322(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 {
setUint322(headerView, 14, compressedSize);
setUint322(headerView, 18, uncompressedSize);
if (dataDescriptor) {
setUint322(dataDescriptorView, dataDescriptorOffset + 4, compressedSize);
setUint322(dataDescriptorView, dataDescriptorOffset + 8, uncompressedSize);
}
}
}
if (dataDescriptor) {
await writer.writeUint8Array(dataDescriptorArray);
}
const length3 = localHeaderArray.length + compressedSize + dataDescriptorArray.length;
Object.assign(fileEntry, { compressedSize, lastModDate, rawLastModDate, creationDate, lastAccessDate, encrypted, length: length3 });
return fileEntry;
}
async function closeFile(zipWriter, comment, options) {
const writer = zipWriter.writer;
const files = zipWriter.files;
let offset2 = 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 = getDataView2(directoryArray);
if (comment && comment.length) {
if (comment.length <= MAX_16_BITS) {
setUint16(directoryView, offset2 + 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: zip642,
msDosCompatible,
internalFileAttribute,
externalFileAttribute
} = fileEntry;
let rawExtraFieldExtendedTimestamp;
let rawExtraFieldNTFS;
if (fileEntry.extendedTimestamp) {
rawExtraFieldNTFS = fileEntry.rawExtraFieldNTFS;
rawExtraFieldExtendedTimestamp = new Uint8Array(9);
const extraFieldExtendedTimestampView = getDataView2(rawExtraFieldExtendedTimestamp);
setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
setUint16(extraFieldExtendedTimestampView, 2, rawExtraFieldExtendedTimestamp.length - 4);
setUint8(extraFieldExtendedTimestampView, 4, 1);
setUint322(extraFieldExtendedTimestampView, 5, Math.floor(fileEntry.lastModDate.getTime() / 1e3));
} else {
rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array(0);
}
const extraFieldLength = rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length + rawExtraField.length;
setUint322(directoryView, offset2, CENTRAL_FILE_HEADER_SIGNATURE);
setUint16(directoryView, offset2 + 4, versionMadeBy);
arraySet(directoryArray, headerArray, offset2 + 6);
setUint16(directoryView, offset2 + 30, extraFieldLength);
setUint16(directoryView, offset2 + 32, rawComment.length);
setUint322(directoryView, offset2 + 34, internalFileAttribute);
if (externalFileAttribute) {
setUint322(directoryView, offset2 + 38, externalFileAttribute);
} else if (directory && msDosCompatible) {
setUint8(directoryView, offset2 + 38, FILE_ATTR_MSDOS_DIR_MASK);
}
if (zip642) {
setUint322(directoryView, offset2 + 42, MAX_32_BITS);
} else {
setUint322(directoryView, offset2 + 42, fileEntry.offset);
}
arraySet(directoryArray, rawFilename, offset2 + 46);
arraySet(directoryArray, rawExtraFieldZip64, offset2 + 46 + rawFilename.length);
arraySet(directoryArray, rawExtraFieldAES, offset2 + 46 + rawFilename.length + rawExtraFieldZip64.length);
arraySet(directoryArray, rawExtraFieldExtendedTimestamp, offset2 + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length);
arraySet(directoryArray, rawExtraFieldNTFS, offset2 + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length);
arraySet(directoryArray, rawExtraField, offset2 + 46 + rawFilename.length + rawExtraFieldZip64.length + rawExtraFieldAES.length + rawExtraFieldExtendedTimestamp.length + rawExtraFieldNTFS.length);
arraySet(directoryArray, rawComment, offset2 + 46 + rawFilename.length + extraFieldLength);
offset2 += 46 + rawFilename.length + extraFieldLength + rawComment.length;
if (options.onprogress) {
try {
options.onprogress(indexFileEntry + 1, files.size, new Entry(fileEntry));
} catch (_error) {
}
}
}
if (zip64) {
setUint322(directoryView, offset2, ZIP64_END_OF_CENTRAL_DIR_SIGNATURE);
setBigUint64(directoryView, offset2 + 4, BigInt(44));
setUint16(directoryView, offset2 + 12, 45);
setUint16(directoryView, offset2 + 14, 45);
setBigUint64(directoryView, offset2 + 24, BigInt(filesLength));
setBigUint64(directoryView, offset2 + 32, BigInt(filesLength));
setBigUint64(directoryView, offset2 + 40, BigInt(directoryDataLength));
setBigUint64(directoryView, offset2 + 48, BigInt(directoryOffset));
setUint322(directoryView, offset2 + 56, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE);
setBigUint64(directoryView, offset2 + 64, BigInt(directoryOffset) + BigInt(directoryDataLength));
setUint322(directoryView, offset2 + 72, ZIP64_TOTAL_NUMBER_OF_DISKS);
filesLength = MAX_16_BITS;
directoryOffset = MAX_32_BITS;
directoryDataLength = MAX_32_BITS;
offset2 += 76;
}
setUint322(directoryView, offset2, END_OF_CENTRAL_DIR_SIGNATURE);
setUint16(directoryView, offset2 + 8, filesLength);
setUint16(directoryView, offset2 + 10, filesLength);
setUint322(directoryView, offset2 + 12, directoryDataLength);
setUint322(directoryView, offset2 + 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((resolve2, reject) => {
fileReader.onload = (event) => resolve2(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(116444736e5)) * BigInt(1e4);
}
}
function getOptionValue2(zipWriter, options, name) {
return options[name] === void 0 ? zipWriter.options[name] : options[name];
}
function getMaximumCompressedSize2(uncompressedSize) {
return uncompressedSize + 5 * (Math.floor(uncompressedSize / 16383) + 1);
}
function setUint8(view, offset2, value) {
view.setUint8(offset2, value);
}
function setUint16(view, offset2, value) {
view.setUint16(offset2, value, true);
}
function setUint322(view, offset2, value) {
view.setUint32(offset2, value, true);
}
function setBigUint64(view, offset2, value) {
view.setBigUint64(offset2, value, true);
}
function arraySet(array, typedArray, offset2) {
array.set(typedArray, offset2);
}
function getDataView2(array) {
return new DataView(array.buffer);
}
// node_modules/@zip.js/zip.js/lib/zip-no-worker.js
configure({ Deflate: deflate_default, Inflate: inflate_default });
// node_modules/@cesium/engine/Source/DataSources/getElement.js
function getElement(element) {
if (typeof element === "string") {
const foundElement = document.getElementById(element);
if (foundElement === null) {
throw new DeveloperError_default(
`Element with id "${element}" does not exist in the document.`
);
}
element = foundElement;
}
return element;
}
var getElement_default = getElement;
// node_modules/@cesium/engine/Source/DataSources/KmlLookAt.js
function KmlLookAt(position, headingPitchRange) {
this.position = position;
this.headingPitchRange = headingPitchRange;
}
var KmlLookAt_default = KmlLookAt;
// node_modules/@cesium/engine/Source/DataSources/KmlTour.js
function KmlTour(name, id) {
this.id = id;
this.name = name;
this.playlistIndex = 0;
this.playlist = [];
this.tourStart = new Event_default();
this.tourEnd = new Event_default();
this.entryStart = new Event_default();
this.entryEnd = new Event_default();
this._activeEntries = [];
}
KmlTour.prototype.addPlaylistEntry = function(entry) {
this.playlist.push(entry);
};
KmlTour.prototype.play = function(widget, cameraOptions) {
if (defined_default(widget.cesiumWidget)) {
deprecationWarning_default(
"viewer",
"The viewer parameter has been deprecated in Cesium 1.99. It will be removed in 1.100. Instead of a Viewer, pass a CesiumWidget instead."
);
}
this.tourStart.raiseEvent();
const tour = this;
playEntry.call(this, widget, cameraOptions, function(terminated) {
tour.playlistIndex = 0;
if (!terminated) {
cancelAllEntries(tour._activeEntries);
}
tour.tourEnd.raiseEvent(terminated);
});
};
KmlTour.prototype.stop = function() {
cancelAllEntries(this._activeEntries);
};
function cancelAllEntries(activeEntries) {
for (let entry = activeEntries.pop(); entry !== void 0; entry = activeEntries.pop()) {
entry.stop();
}
}
function playEntry(widget, cameraOptions, allDone) {
const entry = this.playlist[this.playlistIndex];
if (entry) {
const _playNext = playNext.bind(this, widget, cameraOptions, allDone);
this._activeEntries.push(entry);
this.entryStart.raiseEvent(entry);
if (entry.blocking) {
entry.play(_playNext, widget.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(widget, cameraOptions, allDone);
}
} else if (defined_default(allDone)) {
allDone(false);
}
}
function playNext(widget, 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, widget, cameraOptions, allDone);
}
}
var KmlTour_default = KmlTour;
// node_modules/@tweenjs/tween.js/dist/tween.esm.js
var Easing = {
Linear: {
None: function(amount) {
return amount;
}
},
Quadratic: {
In: function(amount) {
return amount * amount;
},
Out: function(amount) {
return amount * (2 - amount);
},
InOut: function(amount) {
if ((amount *= 2) < 1) {
return 0.5 * amount * amount;
}
return -0.5 * (--amount * (amount - 2) - 1);
}
},
Cubic: {
In: function(amount) {
return amount * amount * amount;
},
Out: function(amount) {
return --amount * amount * amount + 1;
},
InOut: function(amount) {
if ((amount *= 2) < 1) {
return 0.5 * amount * amount * amount;
}
return 0.5 * ((amount -= 2) * amount * amount + 2);
}
},
Quartic: {
In: function(amount) {
return amount * amount * amount * amount;
},
Out: function(amount) {
return 1 - --amount * amount * amount * amount;
},
InOut: function(amount) {
if ((amount *= 2) < 1) {
return 0.5 * amount * amount * amount * amount;
}
return -0.5 * ((amount -= 2) * amount * amount * amount - 2);
}
},
Quintic: {
In: function(amount) {
return amount * amount * amount * amount * amount;
},
Out: function(amount) {
return --amount * amount * amount * amount * amount + 1;
},
InOut: function(amount) {
if ((amount *= 2) < 1) {
return 0.5 * amount * amount * amount * amount * amount;
}
return 0.5 * ((amount -= 2) * amount * amount * amount * amount + 2);
}
},
Sinusoidal: {
In: function(amount) {
return 1 - Math.cos(amount * Math.PI / 2);
},
Out: function(amount) {
return Math.sin(amount * Math.PI / 2);
},
InOut: function(amount) {
return 0.5 * (1 - Math.cos(Math.PI * amount));
}
},
Exponential: {
In: function(amount) {
return amount === 0 ? 0 : Math.pow(1024, amount - 1);
},
Out: function(amount) {
return amount === 1 ? 1 : 1 - Math.pow(2, -10 * amount);
},
InOut: function(amount) {
if (amount === 0) {
return 0;
}
if (amount === 1) {
return 1;
}
if ((amount *= 2) < 1) {
return 0.5 * Math.pow(1024, amount - 1);
}
return 0.5 * (-Math.pow(2, -10 * (amount - 1)) + 2);
}
},
Circular: {
In: function(amount) {
return 1 - Math.sqrt(1 - amount * amount);
},
Out: function(amount) {
return Math.sqrt(1 - --amount * amount);
},
InOut: function(amount) {
if ((amount *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - amount * amount) - 1);
}
return 0.5 * (Math.sqrt(1 - (amount -= 2) * amount) + 1);
}
},
Elastic: {
In: function(amount) {
if (amount === 0) {
return 0;
}
if (amount === 1) {
return 1;
}
return -Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI);
},
Out: function(amount) {
if (amount === 0) {
return 0;
}
if (amount === 1) {
return 1;
}
return Math.pow(2, -10 * amount) * Math.sin((amount - 0.1) * 5 * Math.PI) + 1;
},
InOut: function(amount) {
if (amount === 0) {
return 0;
}
if (amount === 1) {
return 1;
}
amount *= 2;
if (amount < 1) {
return -0.5 * Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI);
}
return 0.5 * Math.pow(2, -10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI) + 1;
}
},
Back: {
In: function(amount) {
var s = 1.70158;
return amount * amount * ((s + 1) * amount - s);
},
Out: function(amount) {
var s = 1.70158;
return --amount * amount * ((s + 1) * amount + s) + 1;
},
InOut: function(amount) {
var s = 1.70158 * 1.525;
if ((amount *= 2) < 1) {
return 0.5 * (amount * amount * ((s + 1) * amount - s));
}
return 0.5 * ((amount -= 2) * amount * ((s + 1) * amount + s) + 2);
}
},
Bounce: {
In: function(amount) {
return 1 - Easing.Bounce.Out(1 - amount);
},
Out: function(amount) {
if (amount < 1 / 2.75) {
return 7.5625 * amount * amount;
} else if (amount < 2 / 2.75) {
return 7.5625 * (amount -= 1.5 / 2.75) * amount + 0.75;
} else if (amount < 2.5 / 2.75) {
return 7.5625 * (amount -= 2.25 / 2.75) * amount + 0.9375;
} else {
return 7.5625 * (amount -= 2.625 / 2.75) * amount + 0.984375;
}
},
InOut: function(amount) {
if (amount < 0.5) {
return Easing.Bounce.In(amount * 2) * 0.5;
}
return Easing.Bounce.Out(amount * 2 - 1) * 0.5 + 0.5;
}
}
};
var now;
if (typeof self === "undefined" && typeof process !== "undefined" && process.hrtime) {
now = function() {
var time = process.hrtime();
return time[0] * 1e3 + time[1] / 1e6;
};
} else if (typeof self !== "undefined" && self.performance !== void 0 && self.performance.now !== void 0) {
now = self.performance.now.bind(self.performance);
} else if (Date.now !== void 0) {
now = Date.now;
} else {
now = function() {
return new Date().getTime();
};
}
var now$1 = now;
var Group = function() {
function Group2() {
this._tweens = {};
this._tweensAddedDuringUpdate = {};
}
Group2.prototype.getAll = function() {
var _this = this;
return Object.keys(this._tweens).map(function(tweenId) {
return _this._tweens[tweenId];
});
};
Group2.prototype.removeAll = function() {
this._tweens = {};
};
Group2.prototype.add = function(tween) {
this._tweens[tween.getId()] = tween;
this._tweensAddedDuringUpdate[tween.getId()] = tween;
};
Group2.prototype.remove = function(tween) {
delete this._tweens[tween.getId()];
delete this._tweensAddedDuringUpdate[tween.getId()];
};
Group2.prototype.update = function(time, preserve) {
if (time === void 0) {
time = now$1();
}
if (preserve === void 0) {
preserve = false;
}
var tweenIds = Object.keys(this._tweens);
if (tweenIds.length === 0) {
return false;
}
while (tweenIds.length > 0) {
this._tweensAddedDuringUpdate = {};
for (var i = 0; i < tweenIds.length; i++) {
var tween = this._tweens[tweenIds[i]];
var autoStart = !preserve;
if (tween && tween.update(time, autoStart) === false && !preserve) {
delete this._tweens[tweenIds[i]];
}
}
tweenIds = Object.keys(this._tweensAddedDuringUpdate);
}
return true;
};
return Group2;
}();
var Interpolation = {
Linear: function(v7, k) {
var m = v7.length - 1;
var f = m * k;
var i = Math.floor(f);
var fn = Interpolation.Utils.Linear;
if (k < 0) {
return fn(v7[0], v7[1], f);
}
if (k > 1) {
return fn(v7[m], v7[m - 1], m - f);
}
return fn(v7[i], v7[i + 1 > m ? m : i + 1], f - i);
},
Bezier: function(v7, k) {
var b = 0;
var n = v7.length - 1;
var pw = Math.pow;
var bn = Interpolation.Utils.Bernstein;
for (var i = 0; i <= n; i++) {
b += pw(1 - k, n - i) * pw(k, i) * v7[i] * bn(n, i);
}
return b;
},
CatmullRom: function(v7, k) {
var m = v7.length - 1;
var f = m * k;
var i = Math.floor(f);
var fn = Interpolation.Utils.CatmullRom;
if (v7[0] === v7[m]) {
if (k < 0) {
i = Math.floor(f = m * (1 + k));
}
return fn(v7[(i - 1 + m) % m], v7[i], v7[(i + 1) % m], v7[(i + 2) % m], f - i);
} else {
if (k < 0) {
return v7[0] - (fn(v7[0], v7[0], v7[1], v7[1], -f) - v7[0]);
}
if (k > 1) {
return v7[m] - (fn(v7[m], v7[m], v7[m - 1], v7[m - 1], f - m) - v7[m]);
}
return fn(v7[i ? i - 1 : 0], v7[i], v7[m < i + 1 ? m : i + 1], v7[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 = Interpolation.Utils.Factorial;
return fc(n) / fc(i) / fc(n - i);
},
Factorial: function() {
var a3 = [1];
return function(n) {
var s = 1;
if (a3[n]) {
return a3[n];
}
for (var i = n; i > 1; i--) {
s *= i;
}
a3[n] = s;
return s;
};
}(),
CatmullRom: function(p0, p1, p2, p3, t) {
var v02 = (p2 - p0) * 0.5;
var v13 = (p3 - p1) * 0.5;
var t2 = t * t;
var t3 = t * t2;
return (2 * p1 - 2 * p2 + v02 + v13) * t3 + (-3 * p1 + 3 * p2 - 2 * v02 - v13) * t2 + v02 * t + p1;
}
}
};
var Sequence = function() {
function Sequence2() {
}
Sequence2.nextId = function() {
return Sequence2._nextId++;
};
Sequence2._nextId = 0;
return Sequence2;
}();
var mainGroup = new Group();
var Tween = function() {
function Tween3(_object, _group) {
if (_group === void 0) {
_group = mainGroup;
}
this._object = _object;
this._group = _group;
this._isPaused = false;
this._pauseStart = 0;
this._valuesStart = {};
this._valuesEnd = {};
this._valuesStartRepeat = {};
this._duration = 1e3;
this._initialRepeat = 0;
this._repeat = 0;
this._yoyo = false;
this._isPlaying = false;
this._reversed = false;
this._delayTime = 0;
this._startTime = 0;
this._easingFunction = Easing.Linear.None;
this._interpolationFunction = Interpolation.Linear;
this._chainedTweens = [];
this._onStartCallbackFired = false;
this._id = Sequence.nextId();
this._isChainStopped = false;
this._goToEnd = false;
}
Tween3.prototype.getId = function() {
return this._id;
};
Tween3.prototype.isPlaying = function() {
return this._isPlaying;
};
Tween3.prototype.isPaused = function() {
return this._isPaused;
};
Tween3.prototype.to = function(properties, duration) {
this._valuesEnd = Object.create(properties);
if (duration !== void 0) {
this._duration = duration;
}
return this;
};
Tween3.prototype.duration = function(d) {
this._duration = d;
return this;
};
Tween3.prototype.start = function(time) {
if (this._isPlaying) {
return this;
}
this._group && this._group.add(this);
this._repeat = this._initialRepeat;
if (this._reversed) {
this._reversed = false;
for (var property in this._valuesStartRepeat) {
this._swapEndStartRepeatValues(property);
this._valuesStart[property] = this._valuesStartRepeat[property];
}
}
this._isPlaying = true;
this._isPaused = false;
this._onStartCallbackFired = false;
this._isChainStopped = false;
this._startTime = time !== void 0 ? typeof time === "string" ? now$1() + parseFloat(time) : time : now$1();
this._startTime += this._delayTime;
this._setupProperties(this._object, this._valuesStart, this._valuesEnd, this._valuesStartRepeat);
return this;
};
Tween3.prototype._setupProperties = function(_object, _valuesStart, _valuesEnd, _valuesStartRepeat) {
for (var property in _valuesEnd) {
var startValue = _object[property];
var startValueIsArray = Array.isArray(startValue);
var propType = startValueIsArray ? "array" : typeof startValue;
var isInterpolationList = !startValueIsArray && Array.isArray(_valuesEnd[property]);
if (propType === "undefined" || propType === "function") {
continue;
}
if (isInterpolationList) {
var endValues = _valuesEnd[property];
if (endValues.length === 0) {
continue;
}
endValues = endValues.map(this._handleRelativeValue.bind(this, startValue));
_valuesEnd[property] = [startValue].concat(endValues);
}
if ((propType === "object" || startValueIsArray) && startValue && !isInterpolationList) {
_valuesStart[property] = startValueIsArray ? [] : {};
for (var prop in startValue) {
_valuesStart[property][prop] = startValue[prop];
}
_valuesStartRepeat[property] = startValueIsArray ? [] : {};
this._setupProperties(startValue, _valuesStart[property], _valuesEnd[property], _valuesStartRepeat[property]);
} else {
if (typeof _valuesStart[property] === "undefined") {
_valuesStart[property] = startValue;
}
if (!startValueIsArray) {
_valuesStart[property] *= 1;
}
if (isInterpolationList) {
_valuesStartRepeat[property] = _valuesEnd[property].slice().reverse();
} else {
_valuesStartRepeat[property] = _valuesStart[property] || 0;
}
}
}
};
Tween3.prototype.stop = function() {
if (!this._isChainStopped) {
this._isChainStopped = true;
this.stopChainedTweens();
}
if (!this._isPlaying) {
return this;
}
this._group && this._group.remove(this);
this._isPlaying = false;
this._isPaused = false;
if (this._onStopCallback) {
this._onStopCallback(this._object);
}
return this;
};
Tween3.prototype.end = function() {
this._goToEnd = true;
this.update(Infinity);
return this;
};
Tween3.prototype.pause = function(time) {
if (time === void 0) {
time = now$1();
}
if (this._isPaused || !this._isPlaying) {
return this;
}
this._isPaused = true;
this._pauseStart = time;
this._group && this._group.remove(this);
return this;
};
Tween3.prototype.resume = function(time) {
if (time === void 0) {
time = now$1();
}
if (!this._isPaused || !this._isPlaying) {
return this;
}
this._isPaused = false;
this._startTime += time - this._pauseStart;
this._pauseStart = 0;
this._group && this._group.add(this);
return this;
};
Tween3.prototype.stopChainedTweens = function() {
for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
this._chainedTweens[i].stop();
}
return this;
};
Tween3.prototype.group = function(group) {
this._group = group;
return this;
};
Tween3.prototype.delay = function(amount) {
this._delayTime = amount;
return this;
};
Tween3.prototype.repeat = function(times) {
this._initialRepeat = times;
this._repeat = times;
return this;
};
Tween3.prototype.repeatDelay = function(amount) {
this._repeatDelayTime = amount;
return this;
};
Tween3.prototype.yoyo = function(yoyo) {
this._yoyo = yoyo;
return this;
};
Tween3.prototype.easing = function(easingFunction) {
this._easingFunction = easingFunction;
return this;
};
Tween3.prototype.interpolation = function(interpolationFunction) {
this._interpolationFunction = interpolationFunction;
return this;
};
Tween3.prototype.chain = function() {
var tweens = [];
for (var _i = 0; _i < arguments.length; _i++) {
tweens[_i] = arguments[_i];
}
this._chainedTweens = tweens;
return this;
};
Tween3.prototype.onStart = function(callback) {
this._onStartCallback = callback;
return this;
};
Tween3.prototype.onUpdate = function(callback) {
this._onUpdateCallback = callback;
return this;
};
Tween3.prototype.onRepeat = function(callback) {
this._onRepeatCallback = callback;
return this;
};
Tween3.prototype.onComplete = function(callback) {
this._onCompleteCallback = callback;
return this;
};
Tween3.prototype.onStop = function(callback) {
this._onStopCallback = callback;
return this;
};
Tween3.prototype.update = function(time, autoStart) {
if (time === void 0) {
time = now$1();
}
if (autoStart === void 0) {
autoStart = true;
}
if (this._isPaused)
return true;
var property;
var elapsed;
var endTime = this._startTime + this._duration;
if (!this._goToEnd && !this._isPlaying) {
if (time > endTime)
return false;
if (autoStart)
this.start(time);
}
this._goToEnd = false;
if (time < this._startTime) {
return true;
}
if (this._onStartCallbackFired === false) {
if (this._onStartCallback) {
this._onStartCallback(this._object);
}
this._onStartCallbackFired = true;
}
elapsed = (time - this._startTime) / this._duration;
elapsed = this._duration === 0 || elapsed > 1 ? 1 : elapsed;
var value = this._easingFunction(elapsed);
this._updateProperties(this._object, this._valuesStart, this._valuesEnd, value);
if (this._onUpdateCallback) {
this._onUpdateCallback(this._object, elapsed);
}
if (elapsed === 1) {
if (this._repeat > 0) {
if (isFinite(this._repeat)) {
this._repeat--;
}
for (property in this._valuesStartRepeat) {
if (!this._yoyo && typeof this._valuesEnd[property] === "string") {
this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]);
}
if (this._yoyo) {
this._swapEndStartRepeatValues(property);
}
this._valuesStart[property] = this._valuesStartRepeat[property];
}
if (this._yoyo) {
this._reversed = !this._reversed;
}
if (this._repeatDelayTime !== void 0) {
this._startTime = time + this._repeatDelayTime;
} else {
this._startTime = time + this._delayTime;
}
if (this._onRepeatCallback) {
this._onRepeatCallback(this._object);
}
return true;
} else {
if (this._onCompleteCallback) {
this._onCompleteCallback(this._object);
}
for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
this._chainedTweens[i].start(this._startTime + this._duration);
}
this._isPlaying = false;
return false;
}
}
return true;
};
Tween3.prototype._updateProperties = function(_object, _valuesStart, _valuesEnd, value) {
for (var property in _valuesEnd) {
if (_valuesStart[property] === void 0) {
continue;
}
var start = _valuesStart[property] || 0;
var end = _valuesEnd[property];
var startIsArray = Array.isArray(_object[property]);
var endIsArray = Array.isArray(end);
var isInterpolationList = !startIsArray && endIsArray;
if (isInterpolationList) {
_object[property] = this._interpolationFunction(end, value);
} else if (typeof end === "object" && end) {
this._updateProperties(_object[property], start, end, value);
} else {
end = this._handleRelativeValue(start, end);
if (typeof end === "number") {
_object[property] = start + (end - start) * value;
}
}
}
};
Tween3.prototype._handleRelativeValue = function(start, end) {
if (typeof end !== "string") {
return end;
}
if (end.charAt(0) === "+" || end.charAt(0) === "-") {
return start + parseFloat(end);
} else {
return parseFloat(end);
}
};
Tween3.prototype._swapEndStartRepeatValues = function(property) {
var tmp2 = this._valuesStartRepeat[property];
var endValue = this._valuesEnd[property];
if (typeof endValue === "string") {
this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(endValue);
} else {
this._valuesStartRepeat[property] = this._valuesEnd[property];
}
this._valuesEnd[property] = tmp2;
};
return Tween3;
}();
var nextId = Sequence.nextId;
var TWEEN = mainGroup;
var getAll = TWEEN.getAll.bind(TWEEN);
var removeAll = TWEEN.removeAll.bind(TWEEN);
var add = TWEEN.add.bind(TWEEN);
var remove3 = TWEEN.remove.bind(TWEEN);
var update4 = TWEEN.update.bind(TWEEN);
// node_modules/@cesium/engine/Source/Core/EasingFunction.js
var EasingFunction = {
LINEAR_NONE: Easing.Linear.None,
QUADRATIC_IN: Easing.Quadratic.In,
QUADRATIC_OUT: Easing.Quadratic.Out,
QUADRATIC_IN_OUT: Easing.Quadratic.InOut,
CUBIC_IN: Easing.Cubic.In,
CUBIC_OUT: Easing.Cubic.Out,
CUBIC_IN_OUT: Easing.Cubic.InOut,
QUARTIC_IN: Easing.Quartic.In,
QUARTIC_OUT: Easing.Quartic.Out,
QUARTIC_IN_OUT: Easing.Quartic.InOut,
QUINTIC_IN: Easing.Quintic.In,
QUINTIC_OUT: Easing.Quintic.Out,
QUINTIC_IN_OUT: Easing.Quintic.InOut,
SINUSOIDAL_IN: Easing.Sinusoidal.In,
SINUSOIDAL_OUT: Easing.Sinusoidal.Out,
SINUSOIDAL_IN_OUT: Easing.Sinusoidal.InOut,
EXPONENTIAL_IN: Easing.Exponential.In,
EXPONENTIAL_OUT: Easing.Exponential.Out,
EXPONENTIAL_IN_OUT: Easing.Exponential.InOut,
CIRCULAR_IN: Easing.Circular.In,
CIRCULAR_OUT: Easing.Circular.Out,
CIRCULAR_IN_OUT: Easing.Circular.InOut,
ELASTIC_IN: Easing.Elastic.In,
ELASTIC_OUT: Easing.Elastic.Out,
ELASTIC_IN_OUT: Easing.Elastic.InOut,
BACK_IN: Easing.Back.In,
BACK_OUT: Easing.Back.Out,
BACK_IN_OUT: Easing.Back.InOut,
BOUNCE_IN: Easing.Bounce.In,
BOUNCE_OUT: Easing.Bounce.Out,
BOUNCE_IN_OUT: Easing.Bounce.InOut
};
var EasingFunction_default = Object.freeze(EasingFunction);
// node_modules/@cesium/engine/Source/DataSources/KmlTourFlyTo.js
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;
}
KmlTourFlyTo.prototype.play = function(done, camera, cameraOptions) {
this.activeCamera = camera;
if (defined_default(done) && done !== null) {
const self2 = this;
this.activeCallback = function(terminated) {
delete self2.activeCallback;
delete self2.activeCamera;
done(defined_default(terminated) ? false : terminated);
};
}
const options = this.getCameraOptions(cameraOptions);
if (this.view.headingPitchRoll) {
camera.flyTo(options);
} else if (this.view.headingPitchRange) {
const target = new BoundingSphere_default(this.view.position);
camera.flyToBoundingSphere(target, options);
}
};
KmlTourFlyTo.prototype.stop = function() {
if (defined_default(this.activeCamera)) {
this.activeCamera.cancelFlight();
}
if (defined_default(this.activeCallback)) {
this.activeCallback(true);
}
};
KmlTourFlyTo.prototype.getCameraOptions = function(cameraOptions) {
let options = {
duration: this.duration
};
if (defined_default(this.activeCallback)) {
options.complete = this.activeCallback;
}
if (this.flyToMode === "smooth") {
options.easingFunction = EasingFunction_default.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_default(cameraOptions)) {
options = combine_default(options, cameraOptions);
}
return options;
};
var KmlTourFlyTo_default = KmlTourFlyTo;
// node_modules/@cesium/engine/Source/DataSources/KmlTourWait.js
function KmlTourWait(duration) {
this.type = "KmlTourWait";
this.blocking = true;
this.duration = duration;
this.timeout = null;
}
KmlTourWait.prototype.play = function(done) {
const self2 = this;
this.activeCallback = done;
this.timeout = setTimeout(function() {
delete self2.activeCallback;
done(false);
}, this.duration * 1e3);
};
KmlTourWait.prototype.stop = function() {
clearTimeout(this.timeout);
if (defined_default(this.activeCallback)) {
this.activeCallback(true);
}
};
var KmlTourWait_default = KmlTourWait;
// node_modules/@cesium/engine/Source/DataSources/KmlDataSource.js
var 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_default(ext);
return MimeTypes[ext];
}
};
var parser2;
if (typeof DOMParser !== "undefined") {
parser2 = new DOMParser();
}
var autolinker2 = new es2015_default({
stripPrefix: false,
email: false,
replaceFn: function(match) {
return match.urlMatchType === "scheme" || match.urlMatchType === "www";
}
});
var BILLBOARD_SIZE2 = 32;
var BILLBOARD_NEAR_DISTANCE2 = 2414016;
var BILLBOARD_NEAR_RATIO2 = 1;
var BILLBOARD_FAR_DISTANCE2 = 16093e3;
var BILLBOARD_FAR_RATIO2 = 0.1;
var kmlNamespaces = [
null,
void 0,
"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"
];
var gxNamespaces = ["http://www.google.com/kml/ext/2.2"];
var atomNamespaces = ["http://www.w3.org/2005/Atom"];
var namespaces2 = {
kml: kmlNamespaces,
gx: gxNamespaces,
atom: atomNamespaces,
kmlgx: kmlNamespaces.concat(gxNamespaces)
};
var featureTypes = {
Document: processDocument2,
Folder: processFolder,
Placemark: processPlacemark,
NetworkLink: processNetworkLink,
GroundOverlay: processGroundOverlay,
PhotoOverlay: processUnsupportedFeature,
ScreenOverlay: processScreenOverlay,
Tour: processTour
};
function DeferredLoading(dataSource) {
this._dataSource = dataSource;
this._deferred = defer_default();
this._stack = [];
this._promises = [];
this._timeoutSet = false;
this._used = false;
this._started = 0;
this._timeThreshold = 1e3;
}
Object.defineProperties(DeferredLoading.prototype, {
dataSource: {
get: function() {
return this._dataSource;
}
}
});
DeferredLoading.prototype.addNodes = function(nodes, processingData) {
this._stack.push({
nodes,
index: 0,
processingData
});
this._used = true;
};
DeferredLoading.prototype.addPromise = function(promise) {
this._promises.push(promise);
};
DeferredLoading.prototype.wait = function() {
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) {
return;
}
this._timeoutSet = true;
this._timeThreshold = 50;
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();
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_default(child)) {
const featureProcessor = featureTypes[child.localName];
if (defined_default(featureProcessor) && (namespaces2.kml.indexOf(child.namespaceURI) !== -1 || namespaces2.gx.indexOf(child.namespaceURI) !== -1)) {
featureProcessor(dataSource, child, processingData, this);
if (this._timeoutSet || KmlDataSource._getTimestamp() > this._started + this._timeThreshold) {
this._giveUpTime();
return;
}
}
child = this._nextNode();
}
if (this._pop() && isFirstCall) {
this._process(true);
}
};
function isZipFile(blob) {
const magicBlob = blob.slice(0, Math.min(4, blob.size));
const deferred = defer_default();
const reader = new FileReader();
reader.addEventListener("load", function() {
deferred.resolve(
new DataView(reader.result).getUint32(0, false) === 1347093252
);
});
reader.addEventListener("error", function() {
deferred.reject(reader.error);
});
reader.readAsArrayBuffer(magicBlob);
return deferred.promise;
}
function readBlobAsText2(blob) {
const deferred = defer_default();
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(text2) {
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(text2) && text2.indexOf(declaration) === -1) {
if (!defined_default(firstPart)) {
firstPart = text2.substr(0, text2.indexOf("", index);
let namespace, startIndex, endIndex;
while (index !== -1 && index < endDeclaration) {
namespace = text2.slice(index, text2.indexOf('"', index));
startIndex = index;
index = text2.indexOf(namespace, index + 1);
if (index !== -1) {
endIndex = text2.indexOf('"', text2.indexOf('"', index) + 1);
text2 = text2.slice(0, index - 1) + text2.slice(endIndex + 1, text2.length);
index = text2.indexOf("xmlns:", startIndex - 1);
} else {
index = text2.indexOf("xmlns:", startIndex + 1);
}
}
return text2;
}
function loadXmlFromZip(entry, uriResolver) {
return Promise.resolve(entry.getData(new TextWriter())).then(function(text2) {
text2 = insertNamespaces(text2);
text2 = removeDuplicateNamespaces(text2);
uriResolver.kml = parser2.parseFromString(text2, "application/xml");
});
}
function loadDataUriFromZip(entry, uriResolver) {
const mimeType = defaultValue_default(
MimeTypes.detectFromFilename(entry.filename),
"application/octet-stream"
);
return Promise.resolve(entry.getData(new Data64URIWriter(mimeType))).then(
function(dataUri) {
uriResolver[entry.filename] = dataUri;
}
);
}
function embedDataUris(div, elementType, attributeName, uriResolver) {
const keys = uriResolver.keys;
const baseUri = new import_urijs11.default(".");
const elements = div.querySelectorAll(elementType);
for (let i = 0; i < elements.length; i++) {
const element = elements[i];
const value = element.getAttribute(attributeName);
if (defined_default(value)) {
const relativeUri = new import_urijs11.default(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);
if (defined_default(resource)) {
element.setAttribute(attributeName, resource.url);
}
}
}
function createEntity(node, entityCollection, context) {
let id = queryStringAttribute2(node, "id");
id = defined_default(id) && id.length !== 0 ? id : createGuid_default();
if (defined_default(context)) {
id = context + id;
}
let entity = entityCollection.getById(id);
if (defined_default(entity)) {
id = createGuid_default();
if (defined_default(context)) {
id = context + id;
}
}
entity = entityCollection.add(new Entity_default({ id }));
if (!defined_default(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) {
if (!defined_default(value)) {
return Cartesian3_default.fromDegrees(0, 0, 0, ellipsoid);
}
const digits = value.match(/[^\s,\n]+/g);
if (!defined_default(digits)) {
return Cartesian3_default.fromDegrees(0, 0, 0, ellipsoid);
}
let longitude = parseFloat(digits[0]);
let latitude = parseFloat(digits[1]);
let height = parseFloat(digits[2]);
longitude = isNaN(longitude) ? 0 : longitude;
latitude = isNaN(latitude) ? 0 : latitude;
height = isNaN(height) ? 0 : height;
return Cartesian3_default.fromDegrees(longitude, latitude, height, ellipsoid);
}
function readCoordinates(element, ellipsoid) {
if (!defined_default(element)) {
return void 0;
}
const tuples = element.textContent.match(/[^\s\n]+/g);
if (!defined_default(tuples)) {
return void 0;
}
const length3 = tuples.length;
const result = new Array(length3);
let resultIndex = 0;
for (let i = 0; i < length3; i++) {
result[resultIndex++] = readCoordinate(tuples[i], ellipsoid);
}
return result;
}
function queryNumericAttribute2(node, attributeName) {
if (!defined_default(node)) {
return void 0;
}
const value = node.getAttribute(attributeName);
if (value !== null) {
const result = parseFloat(value);
return !isNaN(result) ? result : void 0;
}
return void 0;
}
function queryStringAttribute2(node, attributeName) {
if (!defined_default(node)) {
return void 0;
}
const value = node.getAttribute(attributeName);
return value !== null ? value : void 0;
}
function queryFirstNode2(node, tagName, namespace) {
if (!defined_default(node)) {
return void 0;
}
const childNodes = node.childNodes;
const length3 = childNodes.length;
for (let q = 0; q < length3; q++) {
const child = childNodes[q];
if (child.localName === tagName && namespace.indexOf(child.namespaceURI) !== -1) {
return child;
}
}
return void 0;
}
function queryNodes2(node, tagName, namespace) {
if (!defined_default(node)) {
return void 0;
}
const result = [];
const childNodes = node.getElementsByTagNameNS("*", tagName);
const length3 = childNodes.length;
for (let q = 0; q < length3; 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_default(node)) {
return [];
}
const result = [];
const childNodes = node.childNodes;
const length3 = childNodes.length;
for (let q = 0; q < length3; q++) {
const child = childNodes[q];
if (child.localName === tagName && namespace.indexOf(child.namespaceURI) !== -1) {
result.push(child);
}
}
return result;
}
function queryNumericValue2(node, tagName, namespace) {
const resultNode = queryFirstNode2(node, tagName, namespace);
if (defined_default(resultNode)) {
const result = parseFloat(resultNode.textContent);
return !isNaN(result) ? result : void 0;
}
return void 0;
}
function queryStringValue2(node, tagName, namespace) {
const result = queryFirstNode2(node, tagName, namespace);
if (defined_default(result)) {
return result.textContent.trim();
}
return void 0;
}
function queryBooleanValue(node, tagName, namespace) {
const result = queryFirstNode2(node, tagName, namespace);
if (defined_default(result)) {
const value = result.textContent.trim();
return value === "1" || /^true$/i.test(value);
}
return void 0;
}
function resolveHref(href, sourceResource, uriResolver) {
if (!defined_default(href)) {
return void 0;
}
let resource;
if (defined_default(uriResolver)) {
href = href.replace(/\\/g, "/");
let blob = uriResolver[href];
if (defined_default(blob)) {
resource = new Resource_default({
url: blob
});
} else {
const baseUri = new import_urijs11.default(sourceResource.getUrlComponent());
const uri = new import_urijs11.default(href);
blob = uriResolver[uri.absoluteTo(baseUri)];
if (defined_default(blob)) {
resource = new Resource_default({
url: blob
});
}
}
}
if (!defined_default(resource)) {
resource = sourceResource.getDerivedResource({
url: href
});
}
return resource;
}
var colorOptions = {
maximumRed: void 0,
red: void 0,
maximumGreen: void 0,
green: void 0,
maximumBlue: void 0,
blue: void 0
};
function parseColorString(value, isRandom) {
if (!defined_default(value) || /^\s*$/gm.test(value)) {
return void 0;
}
if (value[0] === "#") {
value = value.substring(1);
}
const alpha = parseInt(value.substring(0, 2), 16) / 255;
const blue = parseInt(value.substring(2, 4), 16) / 255;
const green = parseInt(value.substring(4, 6), 16) / 255;
const red = parseInt(value.substring(6, 8), 16) / 255;
if (!isRandom) {
return new Color_default(red, green, blue, alpha);
}
if (red > 0) {
colorOptions.maximumRed = red;
colorOptions.red = void 0;
} else {
colorOptions.maximumRed = void 0;
colorOptions.red = 0;
}
if (green > 0) {
colorOptions.maximumGreen = green;
colorOptions.green = void 0;
} else {
colorOptions.maximumGreen = void 0;
colorOptions.green = 0;
}
if (blue > 0) {
colorOptions.maximumBlue = blue;
colorOptions.blue = void 0;
} else {
colorOptions.maximumBlue = void 0;
colorOptions.blue = 0;
}
colorOptions.alpha = alpha;
return Color_default.fromRandom(colorOptions);
}
function queryColorValue(node, tagName, namespace) {
const value = queryStringValue2(node, tagName, namespace);
if (!defined_default(value)) {
return void 0;
}
return parseColorString(
value,
queryStringValue2(node, "colorMode", namespace) === "random"
);
}
function processTimeStamp(featureNode) {
const node = queryFirstNode2(featureNode, "TimeStamp", namespaces2.kmlgx);
const whenString = queryStringValue2(node, "when", namespaces2.kmlgx);
if (!defined_default(node) || !defined_default(whenString) || whenString.length === 0) {
return void 0;
}
const when = JulianDate_default.fromIso8601(whenString);
const result = new TimeIntervalCollection_default();
result.addInterval(
new TimeInterval_default({
start: when,
stop: Iso8601_default.MAXIMUM_VALUE
})
);
return result;
}
function processTimeSpan(featureNode) {
const node = queryFirstNode2(featureNode, "TimeSpan", namespaces2.kmlgx);
if (!defined_default(node)) {
return void 0;
}
let result;
const beginNode = queryFirstNode2(node, "begin", namespaces2.kmlgx);
let beginDate = defined_default(beginNode) ? JulianDate_default.fromIso8601(beginNode.textContent) : void 0;
const endNode = queryFirstNode2(node, "end", namespaces2.kmlgx);
let endDate = defined_default(endNode) ? JulianDate_default.fromIso8601(endNode.textContent) : void 0;
if (defined_default(beginDate) && defined_default(endDate)) {
if (JulianDate_default.lessThan(endDate, beginDate)) {
const tmp2 = beginDate;
beginDate = endDate;
endDate = tmp2;
}
result = new TimeIntervalCollection_default();
result.addInterval(
new TimeInterval_default({
start: beginDate,
stop: endDate
})
);
} else if (defined_default(beginDate)) {
result = new TimeIntervalCollection_default();
result.addInterval(
new TimeInterval_default({
start: beginDate,
stop: Iso8601_default.MAXIMUM_VALUE
})
);
} else if (defined_default(endDate)) {
result = new TimeIntervalCollection_default();
result.addInterval(
new TimeInterval_default({
start: Iso8601_default.MINIMUM_VALUE,
stop: endDate
})
);
}
return result;
}
function createDefaultBillboard2() {
const billboard = new BillboardGraphics_default();
billboard.width = BILLBOARD_SIZE2;
billboard.height = BILLBOARD_SIZE2;
billboard.scaleByDistance = new NearFarScalar_default(
BILLBOARD_NEAR_DISTANCE2,
BILLBOARD_NEAR_RATIO2,
BILLBOARD_FAR_DISTANCE2,
BILLBOARD_FAR_RATIO2
);
billboard.pixelOffsetScaleByDistance = new NearFarScalar_default(
BILLBOARD_NEAR_DISTANCE2,
BILLBOARD_NEAR_RATIO2,
BILLBOARD_FAR_DISTANCE2,
BILLBOARD_FAR_RATIO2
);
return billboard;
}
function createDefaultPolygon() {
const polygon = new PolygonGraphics_default();
polygon.outline = true;
polygon.outlineColor = Color_default.WHITE;
return polygon;
}
function createDefaultLabel2() {
const label = new LabelGraphics_default();
label.translucencyByDistance = new NearFarScalar_default(3e6, 1, 5e6, 0);
label.pixelOffset = new Cartesian2_default(17, 0);
label.horizontalOrigin = HorizontalOrigin_default.LEFT;
label.font = "16px sans-serif";
label.style = LabelStyle_default.FILL_AND_OUTLINE;
return label;
}
function getIconHref(iconNode, dataSource, sourceResource, uriResolver, canRefresh) {
let href = queryStringValue2(iconNode, "href", namespaces2.kml);
if (!defined_default(href) || href.length === 0) {
return void 0;
}
if (href.indexOf("root://icons/palette-") === 0) {
const palette = href.charAt(21);
let x = defaultValue_default(queryNumericValue2(iconNode, "x", namespaces2.gx), 0);
let y = defaultValue_default(queryNumericValue2(iconNode, "y", namespaces2.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 = queryStringValue2(
iconNode,
"refreshMode",
namespaces2.kml
);
const viewRefreshMode = queryStringValue2(
iconNode,
"viewRefreshMode",
namespaces2.kml
);
if (refreshMode === "onInterval" || refreshMode === "onExpire") {
oneTimeWarning_default(
`kml-refreshMode-${refreshMode}`,
`KML - Unsupported Icon refreshMode: ${refreshMode}`
);
} else if (viewRefreshMode === "onStop" || viewRefreshMode === "onRegion") {
oneTimeWarning_default(
`kml-refreshMode-${viewRefreshMode}`,
`KML - Unsupported Icon viewRefreshMode: ${viewRefreshMode}`
);
}
const viewBoundScale = defaultValue_default(
queryStringValue2(iconNode, "viewBoundScale", namespaces2.kml),
1
);
const defaultViewFormat = viewRefreshMode === "onStop" ? "BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]" : "";
const viewFormat = defaultValue_default(
queryStringValue2(iconNode, "viewFormat", namespaces2.kml),
defaultViewFormat
);
const httpQuery = queryStringValue2(iconNode, "httpQuery", namespaces2.kml);
if (defined_default(viewFormat)) {
hrefResource.setQueryParameters(queryToObject_default(cleanupString(viewFormat)));
}
if (defined_default(httpQuery)) {
hrefResource.setQueryParameters(queryToObject_default(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 = queryNumericValue2(node, "scale", namespaces2.kml);
const heading = queryNumericValue2(node, "heading", namespaces2.kml);
const color = queryColorValue(node, "color", namespaces2.kml);
const iconNode = queryFirstNode2(node, "Icon", namespaces2.kml);
let icon = getIconHref(
iconNode,
dataSource,
sourceResource,
uriResolver,
false
);
if (defined_default(iconNode) && !defined_default(icon)) {
icon = false;
}
const x = queryNumericValue2(iconNode, "x", namespaces2.gx);
const y = queryNumericValue2(iconNode, "y", namespaces2.gx);
const w = queryNumericValue2(iconNode, "w", namespaces2.gx);
const h = queryNumericValue2(iconNode, "h", namespaces2.gx);
const hotSpotNode = queryFirstNode2(node, "hotSpot", namespaces2.kml);
const hotSpotX = queryNumericAttribute2(hotSpotNode, "x");
const hotSpotY = queryNumericAttribute2(hotSpotNode, "y");
const hotSpotXUnit = queryStringAttribute2(hotSpotNode, "xunits");
const hotSpotYUnit = queryStringAttribute2(hotSpotNode, "yunits");
let billboard = targetEntity.billboard;
if (!defined_default(billboard)) {
billboard = createDefaultBillboard2();
targetEntity.billboard = billboard;
}
billboard.image = icon;
billboard.scale = scale;
billboard.color = color;
if (defined_default(x) || defined_default(y) || defined_default(w) || defined_default(h)) {
billboard.imageSubRegion = new BoundingRectangle_default(x, y, w, h);
}
if (defined_default(heading) && heading !== 0) {
billboard.rotation = Math_default.toRadians(-heading);
billboard.alignedAxis = Cartesian3_default.UNIT_Z;
}
scale = defaultValue_default(scale, 1);
let xOffset;
let yOffset;
if (defined_default(hotSpotX)) {
if (hotSpotXUnit === "pixels") {
xOffset = -hotSpotX * scale;
} else if (hotSpotXUnit === "insetPixels") {
xOffset = (hotSpotX - BILLBOARD_SIZE2) * scale;
} else if (hotSpotXUnit === "fraction") {
xOffset = -hotSpotX * BILLBOARD_SIZE2 * scale;
}
xOffset += BILLBOARD_SIZE2 * 0.5 * scale;
}
if (defined_default(hotSpotY)) {
if (hotSpotYUnit === "pixels") {
yOffset = hotSpotY * scale;
} else if (hotSpotYUnit === "insetPixels") {
yOffset = (-hotSpotY + BILLBOARD_SIZE2) * scale;
} else if (hotSpotYUnit === "fraction") {
yOffset = hotSpotY * BILLBOARD_SIZE2 * scale;
}
yOffset -= BILLBOARD_SIZE2 * 0.5 * scale;
}
if (defined_default(xOffset) || defined_default(yOffset)) {
billboard.pixelOffset = new Cartesian2_default(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_default(label)) {
label = createDefaultLabel2();
targetEntity.label = label;
}
label.scale = defaultValue_default(
queryNumericValue2(node, "scale", namespaces2.kml),
label.scale
);
label.fillColor = defaultValue_default(
queryColorValue(node, "color", namespaces2.kml),
label.fillColor
);
label.text = targetEntity.name;
} else if (node.localName === "LineStyle") {
let polyline = targetEntity.polyline;
if (!defined_default(polyline)) {
polyline = new PolylineGraphics_default();
targetEntity.polyline = polyline;
}
polyline.width = queryNumericValue2(node, "width", namespaces2.kml);
polyline.material = queryColorValue(node, "color", namespaces2.kml);
if (defined_default(queryColorValue(node, "outerColor", namespaces2.gx))) {
oneTimeWarning_default(
"kml-gx:outerColor",
"KML - gx:outerColor is not supported in a LineStyle"
);
}
if (defined_default(queryNumericValue2(node, "outerWidth", namespaces2.gx))) {
oneTimeWarning_default(
"kml-gx:outerWidth",
"KML - gx:outerWidth is not supported in a LineStyle"
);
}
if (defined_default(queryNumericValue2(node, "physicalWidth", namespaces2.gx))) {
oneTimeWarning_default(
"kml-gx:physicalWidth",
"KML - gx:physicalWidth is not supported in a LineStyle"
);
}
if (defined_default(queryBooleanValue(node, "labelVisibility", namespaces2.gx))) {
oneTimeWarning_default(
"kml-gx:labelVisibility",
"KML - gx:labelVisibility is not supported in a LineStyle"
);
}
} else if (node.localName === "PolyStyle") {
let polygon = targetEntity.polygon;
if (!defined_default(polygon)) {
polygon = createDefaultPolygon();
targetEntity.polygon = polygon;
}
polygon.material = defaultValue_default(
queryColorValue(node, "color", namespaces2.kml),
polygon.material
);
polygon.fill = defaultValue_default(
queryBooleanValue(node, "fill", namespaces2.kml),
polygon.fill
);
polygon.outline = defaultValue_default(
queryBooleanValue(node, "outline", namespaces2.kml),
polygon.outline
);
} else if (node.localName === "BalloonStyle") {
const bgColor = defaultValue_default(
parseColorString(queryStringValue2(node, "bgColor", namespaces2.kml)),
Color_default.WHITE
);
const textColor2 = defaultValue_default(
parseColorString(queryStringValue2(node, "textColor", namespaces2.kml)),
Color_default.BLACK
);
const text2 = queryStringValue2(node, "text", namespaces2.kml);
targetEntity.addProperty("balloonStyle");
targetEntity.balloonStyle = {
bgColor,
textColor: textColor2,
text: text2
};
} else if (node.localName === "ListStyle") {
const listItemType = queryStringValue2(
node,
"listItemType",
namespaces2.kml
);
if (listItemType === "radioFolder" || listItemType === "checkOffOnly") {
oneTimeWarning_default(
`kml-listStyle-${listItemType}`,
`KML - Unsupported ListStyle with listItemType: ${listItemType}`
);
}
}
}
}
function computeFinalStyle(dataSource, placeMark, styleCollection, sourceResource, uriResolver) {
const result = new Entity_default();
let styleEntity;
let styleIndex = -1;
const childNodes = placeMark.childNodes;
const length3 = childNodes.length;
for (let q = 0; q < length3; 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 {
const pairs = queryChildNodes(inlineStyleNode, "Pair", namespaces2.kml);
for (let p = 0; p < pairs.length; p++) {
const pair = pairs[p];
const key = queryStringValue2(pair, "key", namespaces2.kml);
if (key === "normal") {
const styleUrl = queryStringValue2(pair, "styleUrl", namespaces2.kml);
if (defined_default(styleUrl)) {
styleEntity = styleCollection.getById(styleUrl);
if (!defined_default(styleEntity)) {
styleEntity = styleCollection.getById(`#${styleUrl}`);
}
if (defined_default(styleEntity)) {
result.merge(styleEntity);
}
} else {
const node = queryFirstNode2(pair, "Style", namespaces2.kml);
applyStyle(dataSource, node, result, sourceResource, uriResolver);
}
} else {
oneTimeWarning_default(
`kml-styleMap-${key}`,
`KML - Unsupported StyleMap key: ${key}`
);
}
}
}
}
const externalStyle = queryStringValue2(placeMark, "styleUrl", namespaces2.kml);
if (defined_default(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_default(styleEntity)) {
styleEntity = styleCollection.getById(`#${id}`);
}
if (defined_default(styleEntity)) {
result.merge(styleEntity);
}
}
return result;
}
function processExternalStyles(dataSource, resource, styleCollection) {
return resource.fetchXML().then(function(styleKml) {
return processStyles(dataSource, styleKml, styleCollection, resource, true);
});
}
function processStyles(dataSource, kml, styleCollection, sourceResource, isExternal, uriResolver) {
let i;
let id;
let styleEntity;
let node;
const styleNodes = queryNodes2(kml, "Style", namespaces2.kml);
if (defined_default(styleNodes)) {
const styleNodesLength = styleNodes.length;
for (i = 0; i < styleNodesLength; i++) {
node = styleNodes[i];
id = queryStringAttribute2(node, "id");
if (defined_default(id)) {
id = `#${id}`;
if (isExternal && defined_default(sourceResource)) {
id = sourceResource.getUrlComponent() + id;
}
if (!defined_default(styleCollection.getById(id))) {
styleEntity = new Entity_default({
id
});
styleCollection.add(styleEntity);
applyStyle(
dataSource,
node,
styleEntity,
sourceResource,
uriResolver
);
}
}
}
}
const styleMaps = queryNodes2(kml, "StyleMap", namespaces2.kml);
if (defined_default(styleMaps)) {
const styleMapsLength = styleMaps.length;
for (i = 0; i < styleMapsLength; i++) {
const styleMap = styleMaps[i];
id = queryStringAttribute2(styleMap, "id");
if (defined_default(id)) {
const pairs = queryChildNodes(styleMap, "Pair", namespaces2.kml);
for (let p = 0; p < pairs.length; p++) {
const pair = pairs[p];
const key = queryStringValue2(pair, "key", namespaces2.kml);
if (key === "normal") {
id = `#${id}`;
if (isExternal && defined_default(sourceResource)) {
id = sourceResource.getUrlComponent() + id;
}
if (!defined_default(styleCollection.getById(id))) {
styleEntity = styleCollection.getOrCreateEntity(id);
let styleUrl = queryStringValue2(pair, "styleUrl", namespaces2.kml);
if (defined_default(styleUrl)) {
if (styleUrl[0] !== "#") {
styleUrl = `#${styleUrl}`;
}
if (isExternal && defined_default(sourceResource)) {
styleUrl = sourceResource.getUrlComponent() + styleUrl;
}
const base = styleCollection.getById(styleUrl);
if (defined_default(base)) {
styleEntity.merge(base);
}
} else {
node = queryFirstNode2(pair, "Style", namespaces2.kml);
applyStyle(
dataSource,
node,
styleEntity,
sourceResource,
uriResolver
);
}
}
} else {
oneTimeWarning_default(
`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] !== "#") {
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_default(entityCollection, entity.id, [
"position"
]);
const surfacePosition = new ScaledPositionProperty_default(entity.position);
entity.polyline = defined_default(styleEntity.polyline) ? styleEntity.polyline.clone() : new PolylineGraphics_default();
entity.polyline.positions = new PositionPropertyArray_default([
entityPosition,
surfacePosition
]);
}
function heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode) {
if (!defined_default(altitudeMode) && !defined_default(gxAltitudeMode) || altitudeMode === "clampToGround") {
return HeightReference_default.CLAMP_TO_GROUND;
}
if (altitudeMode === "relativeToGround") {
return HeightReference_default.RELATIVE_TO_GROUND;
}
if (altitudeMode === "absolute") {
return HeightReference_default.NONE;
}
if (gxAltitudeMode === "clampToSeaFloor") {
oneTimeWarning_default(
"kml-gx:altitudeMode-clampToSeaFloor",
"KML - :clampToSeaFloor is currently not supported, using :clampToGround."
);
return HeightReference_default.CLAMP_TO_GROUND;
}
if (gxAltitudeMode === "relativeToSeaFloor") {
oneTimeWarning_default(
"kml-gx:altitudeMode-relativeToSeaFloor",
"KML - :relativeToSeaFloor is currently not supported, using :relativeToGround."
);
return HeightReference_default.RELATIVE_TO_GROUND;
}
if (defined_default(altitudeMode)) {
oneTimeWarning_default(
"kml-altitudeMode-unknown",
`KML - Unknown :${altitudeMode}, using :CLAMP_TO_GROUND.`
);
} else {
oneTimeWarning_default(
"kml-gx:altitudeMode-unknown",
`KML - Unknown :${gxAltitudeMode}, using :CLAMP_TO_GROUND.`
);
}
return HeightReference_default.CLAMP_TO_GROUND;
}
function createPositionPropertyFromAltitudeMode(property, altitudeMode, gxAltitudeMode) {
if (gxAltitudeMode === "relativeToSeaFloor" || altitudeMode === "absolute" || altitudeMode === "relativeToGround") {
return property;
}
if (defined_default(altitudeMode) && altitudeMode !== "clampToGround" || defined_default(gxAltitudeMode) && gxAltitudeMode !== "clampToSeaFloor") {
oneTimeWarning_default(
"kml-altitudeMode-unknown",
`KML - Unknown altitudeMode: ${defaultValue_default(
altitudeMode,
gxAltitudeMode
)}`
);
}
return new ScaledPositionProperty_default(property);
}
function createPositionPropertyArrayFromAltitudeMode(properties, altitudeMode, gxAltitudeMode, ellipsoid) {
if (!defined_default(properties)) {
return void 0;
}
if (gxAltitudeMode === "relativeToSeaFloor" || altitudeMode === "absolute" || altitudeMode === "relativeToGround") {
return properties;
}
if (defined_default(altitudeMode) && altitudeMode !== "clampToGround" || defined_default(gxAltitudeMode) && gxAltitudeMode !== "clampToSeaFloor") {
oneTimeWarning_default(
"kml-altitudeMode-unknown",
`KML - Unknown altitudeMode: ${defaultValue_default(
altitudeMode,
gxAltitudeMode
)}`
);
}
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_default(label)) {
label = defined_default(styleEntity.label) ? styleEntity.label.clone() : createDefaultLabel2();
entity.label = label;
}
label.text = entity.name;
let billboard = entity.billboard;
if (!defined_default(billboard)) {
billboard = defined_default(styleEntity.billboard) ? styleEntity.billboard.clone() : createDefaultBillboard2();
entity.billboard = billboard;
}
if (!defined_default(billboard.image)) {
billboard.image = dataSource._pinBuilder.fromColor(Color_default.YELLOW, 64);
} else if (!billboard.image.getValue()) {
billboard.image = void 0;
}
let scale = 1;
if (defined_default(billboard.scale)) {
scale = billboard.scale.getValue();
if (scale !== 0) {
label.pixelOffset = new Cartesian2_default(scale * 16 + 1, 0);
} else {
label.pixelOffset = void 0;
label.horizontalOrigin = void 0;
}
}
if (defined_default(heightReference) && dataSource._clampToGround) {
billboard.heightReference = heightReference;
label.heightReference = heightReference;
}
}
function processPathGraphics(entity, styleEntity) {
let path = entity.path;
if (!defined_default(path)) {
path = new PathGraphics_default();
path.leadTime = 0;
entity.path = path;
}
const polyline = styleEntity.polyline;
if (defined_default(polyline)) {
path.material = polyline.material;
path.width = polyline.width;
}
}
function processPoint3(dataSource, entityCollection, geometryNode, entity, styleEntity) {
const coordinatesString = queryStringValue2(
geometryNode,
"coordinates",
namespaces2.kml
);
const altitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.kml
);
const gxAltitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.gx
);
const extrude = queryBooleanValue(geometryNode, "extrude", namespaces2.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 = queryFirstNode2(
geometryNode,
"coordinates",
namespaces2.kml
);
const altitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.kml
);
const gxAltitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.gx
);
const extrude = queryBooleanValue(geometryNode, "extrude", namespaces2.kml);
const tessellate = queryBooleanValue(
geometryNode,
"tessellate",
namespaces2.kml
);
const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
const zIndex = queryNumericValue2(geometryNode, "drawOrder", namespaces2.gx);
const ellipsoid = dataSource._ellipsoid;
const coordinates = readCoordinates(coordinatesNode, ellipsoid);
let polyline = styleEntity.polyline;
if (canExtrude && extrude) {
const wall = new WallGraphics_default();
entity.wall = wall;
wall.positions = coordinates;
const polygon = styleEntity.polygon;
if (defined_default(polygon)) {
wall.fill = polygon.fill;
wall.material = polygon.material;
}
wall.outline = true;
if (defined_default(polyline)) {
wall.outlineColor = defined_default(polyline.material) ? polyline.material.color : Color_default.WHITE;
wall.outlineWidth = polyline.width;
} else if (defined_default(polygon)) {
wall.outlineColor = defined_default(polygon.material) ? polygon.material.color : Color_default.WHITE;
}
} else if (dataSource._clampToGround && !canExtrude && tessellate) {
const polylineGraphics = new PolylineGraphics_default();
polylineGraphics.clampToGround = true;
entity.polyline = polylineGraphics;
polylineGraphics.positions = coordinates;
if (defined_default(polyline)) {
polylineGraphics.material = defined_default(polyline.material) ? polyline.material.color.getValue(Iso8601_default.MINIMUM_VALUE) : Color_default.WHITE;
polylineGraphics.width = defaultValue_default(polyline.width, 1);
} else {
polylineGraphics.material = Color_default.WHITE;
polylineGraphics.width = 1;
}
polylineGraphics.zIndex = zIndex;
} else {
if (defined_default(zIndex)) {
oneTimeWarning_default(
"kml-gx:drawOrder",
"KML - gx:drawOrder is not supported in LineStrings when clampToGround is false"
);
}
if (dataSource._clampToGround && !tessellate) {
oneTimeWarning_default(
"kml-line-tesselate",
"Ignoring clampToGround for KML lines without the tessellate flag."
);
}
polyline = defined_default(polyline) ? polyline.clone() : new PolylineGraphics_default();
entity.polyline = polyline;
polyline.positions = createPositionPropertyArrayFromAltitudeMode(
coordinates,
altitudeMode,
gxAltitudeMode,
ellipsoid
);
if (!tessellate || canExtrude) {
polyline.arcType = ArcType_default.NONE;
}
}
return true;
}
function processPolygon3(dataSource, entityCollection, geometryNode, entity, styleEntity) {
const outerBoundaryIsNode = queryFirstNode2(
geometryNode,
"outerBoundaryIs",
namespaces2.kml
);
let linearRingNode = queryFirstNode2(
outerBoundaryIsNode,
"LinearRing",
namespaces2.kml
);
let coordinatesNode = queryFirstNode2(
linearRingNode,
"coordinates",
namespaces2.kml
);
const ellipsoid = dataSource._ellipsoid;
let coordinates = readCoordinates(coordinatesNode, ellipsoid);
const extrude = queryBooleanValue(geometryNode, "extrude", namespaces2.kml);
const altitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.kml
);
const gxAltitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.gx
);
const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
const polygon = defined_default(styleEntity.polygon) ? styleEntity.polygon.clone() : createDefaultPolygon();
const polyline = styleEntity.polyline;
if (defined_default(polyline)) {
polygon.outlineColor = defined_default(polyline.material) ? polyline.material.color : Color_default.WHITE;
polygon.outlineWidth = polyline.width;
}
entity.polygon = polygon;
if (canExtrude) {
polygon.perPositionHeight = true;
polygon.extrudedHeight = extrude ? 0 : void 0;
} else if (!dataSource._clampToGround) {
polygon.height = 0;
}
if (defined_default(coordinates)) {
const hierarchy = new PolygonHierarchy_default(coordinates);
const innerBoundaryIsNodes = queryChildNodes(
geometryNode,
"innerBoundaryIs",
namespaces2.kml
);
for (let j = 0; j < innerBoundaryIsNodes.length; j++) {
linearRingNode = queryChildNodes(
innerBoundaryIsNodes[j],
"LinearRing",
namespaces2.kml
);
for (let k = 0; k < linearRingNode.length; k++) {
coordinatesNode = queryFirstNode2(
linearRingNode[k],
"coordinates",
namespaces2.kml
);
coordinates = readCoordinates(coordinatesNode, ellipsoid);
if (defined_default(coordinates)) {
hierarchy.holes.push(new PolygonHierarchy_default(coordinates));
}
}
}
polygon.hierarchy = hierarchy;
}
return true;
}
function processTrack(dataSource, entityCollection, geometryNode, entity, styleEntity) {
const altitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.kml
);
const gxAltitudeMode = queryStringValue2(
geometryNode,
"altitudeMode",
namespaces2.gx
);
const coordNodes = queryChildNodes(geometryNode, "coord", namespaces2.gx);
const angleNodes = queryChildNodes(geometryNode, "angles", namespaces2.gx);
const timeNodes = queryChildNodes(geometryNode, "when", namespaces2.kml);
const extrude = queryBooleanValue(geometryNode, "extrude", namespaces2.kml);
const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
const ellipsoid = dataSource._ellipsoid;
if (angleNodes.length > 0) {
oneTimeWarning_default(
"kml-gx:angles",
"KML - gx:angles are not supported in gx:Tracks"
);
}
const length3 = Math.min(coordNodes.length, timeNodes.length);
const coordinates = [];
const times = [];
for (let i = 0; i < length3; i++) {
const position = readCoordinate(coordNodes[i].textContent, ellipsoid);
coordinates.push(position);
times.push(JulianDate_default.fromIso8601(timeNodes[i].textContent));
}
const property = new SampledPositionProperty_default();
property.addSamples(times, coordinates);
entity.position = property;
processPositionGraphics(
dataSource,
entity,
styleEntity,
heightReferenceFromAltitudeMode(altitudeMode, gxAltitudeMode)
);
processPathGraphics(entity, styleEntity);
entity.availability = new TimeIntervalCollection_default();
if (timeNodes.length > 0) {
entity.availability.addInterval(
new TimeInterval_default({
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 stop2 = times[times.length - 1];
const data = new SampledPositionProperty_default();
data.addSamples(times, positions);
composite.intervals.addInterval(
new TimeInterval_default({
start,
stop: stop2,
isStartIncluded: includeEndPoints,
isStopIncluded: includeEndPoints,
data: createPositionPropertyFromAltitudeMode(
data,
altitudeMode,
gxAltitudeMode
)
})
);
availability.addInterval(
new TimeInterval_default({
start,
stop: stop2,
isStartIncluded: includeEndPoints,
isStopIncluded: includeEndPoints
})
);
dropShowProperty.intervals.addInterval(
new TimeInterval_default({
start,
stop: stop2,
isStartIncluded: includeEndPoints,
isStopIncluded: includeEndPoints,
data: extrude
})
);
}
function processMultiTrack(dataSource, entityCollection, geometryNode, entity, styleEntity) {
const interpolate2 = queryBooleanValue(
geometryNode,
"interpolate",
namespaces2.gx
);
const trackNodes = queryChildNodes(geometryNode, "Track", namespaces2.gx);
let times;
let lastStop;
let lastStopPosition;
let needDropLine = false;
const dropShowProperty = new TimeIntervalCollectionProperty_default();
const availability = new TimeIntervalCollection_default();
const composite = new CompositePositionProperty_default();
const ellipsoid = dataSource._ellipsoid;
for (let i = 0, len = trackNodes.length; i < len; i++) {
const trackNode = trackNodes[i];
const timeNodes = queryChildNodes(trackNode, "when", namespaces2.kml);
const coordNodes = queryChildNodes(trackNode, "coord", namespaces2.gx);
const altitudeMode = queryStringValue2(
trackNode,
"altitudeMode",
namespaces2.kml
);
const gxAltitudeMode = queryStringValue2(
trackNode,
"altitudeMode",
namespaces2.gx
);
const canExtrude = isExtrudable(altitudeMode, gxAltitudeMode);
const extrude = queryBooleanValue(trackNode, "extrude", namespaces2.kml);
const length3 = Math.min(coordNodes.length, timeNodes.length);
const positions = [];
times = [];
for (let x = 0; x < length3; x++) {
const position = readCoordinate(coordNodes[x].textContent, ellipsoid);
positions.push(position);
times.push(JulianDate_default.fromIso8601(timeNodes[x].textContent));
}
if (interpolate2) {
if (defined_default(lastStop)) {
addToMultiTrack(
[lastStop, times[0]],
[lastStopPosition, positions[0]],
composite,
availability,
dropShowProperty,
false,
"absolute",
void 0,
false
);
}
lastStop = times[length3 - 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;
}
var geometryTypes3 = {
Point: processPoint3,
LineString: processLineStringOrLinearRing,
LinearRing: processLineStringOrLinearRing,
Polygon: processPolygon3,
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 = geometryTypes3[childNode.localName];
if (defined_default(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_default(
"kml-unsupportedGeometry",
`KML - Unsupported geometry: ${geometryNode.localName}`
);
return false;
}
function processExtendedData(node, entity) {
const extendedDataNode = queryFirstNode2(node, "ExtendedData", namespaces2.kml);
if (!defined_default(extendedDataNode)) {
return void 0;
}
if (defined_default(queryFirstNode2(extendedDataNode, "SchemaData", namespaces2.kml))) {
oneTimeWarning_default("kml-schemaData", "KML - SchemaData is unsupported");
}
if (defined_default(queryStringAttribute2(extendedDataNode, "xmlns:prefix"))) {
oneTimeWarning_default(
"kml-extendedData",
"KML - ExtendedData with xmlns:prefix is unsupported"
);
}
const result = {};
const dataNodes = queryChildNodes(extendedDataNode, "Data", namespaces2.kml);
if (defined_default(dataNodes)) {
const length3 = dataNodes.length;
for (let i = 0; i < length3; i++) {
const dataNode = dataNodes[i];
const name = queryStringAttribute2(dataNode, "name");
if (defined_default(name)) {
result[name] = {
displayName: queryStringValue2(
dataNode,
"displayName",
namespaces2.kml
),
value: queryStringValue2(dataNode, "value", namespaces2.kml)
};
}
}
}
entity.kml.extendedData = result;
}
var scratchDiv2;
if (typeof document !== "undefined") {
scratchDiv2 = document.createElement("div");
}
function processDescription3(node, entity, styleEntity, uriResolver, sourceResource) {
let i;
let key;
let keys;
const kmlData = entity.kml;
const extendedData = kmlData.extendedData;
const description = queryStringValue2(node, "description", namespaces2.kml);
const balloonStyle = defaultValue_default(
entity.balloonStyle,
styleEntity.balloonStyle
);
let background = Color_default.WHITE;
let foreground = Color_default.BLACK;
let text2 = description;
if (defined_default(balloonStyle)) {
background = defaultValue_default(balloonStyle.bgColor, Color_default.WHITE);
foreground = defaultValue_default(balloonStyle.textColor, Color_default.BLACK);
text2 = defaultValue_default(balloonStyle.text, description);
}
let value;
if (defined_default(text2)) {
text2 = text2.replace("$[name]", defaultValue_default(entity.name, ""));
text2 = text2.replace("$[description]", defaultValue_default(description, ""));
text2 = text2.replace("$[address]", defaultValue_default(kmlData.address, ""));
text2 = text2.replace("$[Snippet]", defaultValue_default(kmlData.snippet, ""));
text2 = text2.replace("$[id]", entity.id);
text2 = text2.replace("$[geDirections]", "");
if (defined_default(extendedData)) {
const matches = text2.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_default(value)) {
value = isDisplayName ? value.displayName : value.value;
}
if (defined_default(value)) {
text2 = text2.replace(token, defaultValue_default(value, ""));
}
}
}
}
} else if (defined_default(extendedData)) {
keys = Object.keys(extendedData);
if (keys.length > 0) {
text2 = '
';
for (i = 0; i < keys.length; i++) {
key = keys[i];
value = extendedData[key];
text2 += `
`;
scratchDiv2.innerHTML = "";
entity.description = tmp2;
}
function processFeature2(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 = queryStringValue2(featureNode, "name", namespaces2.kml);
entity.name = name;
entity.parent = parent;
let availability = processTimeSpan(featureNode);
if (!defined_default(availability)) {
availability = processTimeStamp(featureNode);
}
entity.availability = availability;
mergeAvailabilityWithParent(entity);
function ancestryIsVisible(parentEntity) {
if (!parentEntity) {
return true;
}
return parentEntity.show && ancestryIsVisible(parentEntity.parent);
}
const visibility = queryBooleanValue(
featureNode,
"visibility",
namespaces2.kml
);
entity.show = ancestryIsVisible(parent) && defaultValue_default(visibility, true);
const authorNode = queryFirstNode2(featureNode, "author", namespaces2.atom);
const author = kmlData.author;
author.name = queryStringValue2(authorNode, "name", namespaces2.atom);
author.uri = queryStringValue2(authorNode, "uri", namespaces2.atom);
author.email = queryStringValue2(authorNode, "email", namespaces2.atom);
const linkNode = queryFirstNode2(featureNode, "link", namespaces2.atom);
const link = kmlData.link;
link.href = queryStringAttribute2(linkNode, "href");
link.hreflang = queryStringAttribute2(linkNode, "hreflang");
link.rel = queryStringAttribute2(linkNode, "rel");
link.type = queryStringAttribute2(linkNode, "type");
link.title = queryStringAttribute2(linkNode, "title");
link.length = queryStringAttribute2(linkNode, "length");
kmlData.address = queryStringValue2(featureNode, "address", namespaces2.kml);
kmlData.phoneNumber = queryStringValue2(
featureNode,
"phoneNumber",
namespaces2.kml
);
kmlData.snippet = queryStringValue2(featureNode, "Snippet", namespaces2.kml);
processExtendedData(featureNode, entity);
processDescription3(
featureNode,
entity,
styleEntity,
uriResolver,
sourceResource
);
const ellipsoid = dataSource._ellipsoid;
processLookAt(featureNode, entity, ellipsoid);
processCamera(featureNode, entity, ellipsoid);
if (defined_default(queryFirstNode2(featureNode, "Region", namespaces2.kml))) {
oneTimeWarning_default("kml-region", "KML - Placemark Regions are unsupported");
}
return {
entity,
styleEntity
};
}
function processDocument2(dataSource, node, processingData, deferredLoading) {
deferredLoading.addNodes(node.childNodes, processingData);
deferredLoading.process();
}
function processFolder(dataSource, node, processingData, deferredLoading) {
const r = processFeature2(dataSource, node, processingData);
const newProcessingData = clone_default(processingData);
newProcessingData.parentEntity = r.entity;
processDocument2(dataSource, node, newProcessingData, deferredLoading);
}
function processPlacemark(dataSource, placemark, processingData, deferredLoading) {
const r = processFeature2(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 = geometryTypes3[childNode.localName];
if (defined_default(geometryProcessor)) {
geometryProcessor(
dataSource,
processingData.entityCollection,
childNode,
entity,
styleEntity,
entity.id
);
hasGeometry = true;
}
}
if (!hasGeometry) {
entity.merge(styleEntity);
processPositionGraphics(dataSource, entity, styleEntity);
}
}
var playlistNodeProcessors = {
FlyTo: processTourFlyTo,
Wait: processTourWait,
SoundCue: processTourUnsupportedNode,
AnimatedUpdate: processTourUnsupportedNode,
TourControl: processTourUnsupportedNode
};
function processTour(dataSource, node, processingData, deferredLoading) {
const name = queryStringValue2(node, "name", namespaces2.kml);
const id = queryStringAttribute2(node, "id");
const tour = new KmlTour_default(name, id);
const playlistNode = queryFirstNode2(node, "Playlist", namespaces2.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_default(`KML Tour unsupported node ${entryNode.localName}`);
}
function processTourWait(tour, entryNode) {
const duration = queryNumericValue2(entryNode, "duration", namespaces2.gx);
tour.addPlaylistEntry(new KmlTourWait_default(duration));
}
function processTourFlyTo(tour, entryNode, ellipsoid) {
const duration = queryNumericValue2(entryNode, "duration", namespaces2.gx);
const flyToMode = queryStringValue2(entryNode, "flyToMode", namespaces2.gx);
const t = { kml: {} };
processLookAt(entryNode, t, ellipsoid);
processCamera(entryNode, t, ellipsoid);
const view = t.kml.lookAt || t.kml.camera;
const flyto = new KmlTourFlyTo_default(duration, flyToMode, view);
tour.addPlaylistEntry(flyto);
}
function processCamera(featureNode, entity, ellipsoid) {
const camera = queryFirstNode2(featureNode, "Camera", namespaces2.kml);
if (defined_default(camera)) {
const lon = defaultValue_default(
queryNumericValue2(camera, "longitude", namespaces2.kml),
0
);
const lat = defaultValue_default(
queryNumericValue2(camera, "latitude", namespaces2.kml),
0
);
const altitude = defaultValue_default(
queryNumericValue2(camera, "altitude", namespaces2.kml),
0
);
const heading = defaultValue_default(
queryNumericValue2(camera, "heading", namespaces2.kml),
0
);
const tilt = defaultValue_default(
queryNumericValue2(camera, "tilt", namespaces2.kml),
0
);
const roll = defaultValue_default(
queryNumericValue2(camera, "roll", namespaces2.kml),
0
);
const position = Cartesian3_default.fromDegrees(lon, lat, altitude, ellipsoid);
const hpr = HeadingPitchRoll_default.fromDegrees(heading, tilt - 90, roll);
entity.kml.camera = new KmlCamera_default(position, hpr);
}
}
function processLookAt(featureNode, entity, ellipsoid) {
const lookAt = queryFirstNode2(featureNode, "LookAt", namespaces2.kml);
if (defined_default(lookAt)) {
const lon = defaultValue_default(
queryNumericValue2(lookAt, "longitude", namespaces2.kml),
0
);
const lat = defaultValue_default(
queryNumericValue2(lookAt, "latitude", namespaces2.kml),
0
);
const altitude = defaultValue_default(
queryNumericValue2(lookAt, "altitude", namespaces2.kml),
0
);
let heading = queryNumericValue2(lookAt, "heading", namespaces2.kml);
let tilt = queryNumericValue2(lookAt, "tilt", namespaces2.kml);
const range = defaultValue_default(
queryNumericValue2(lookAt, "range", namespaces2.kml),
0
);
tilt = Math_default.toRadians(defaultValue_default(tilt, 0));
heading = Math_default.toRadians(defaultValue_default(heading, 0));
const hpr = new HeadingPitchRange_default(
heading,
tilt - Math_default.PI_OVER_TWO,
range
);
const viewPoint = Cartesian3_default.fromDegrees(lon, lat, altitude, ellipsoid);
entity.kml.lookAt = new KmlLookAt_default(viewPoint, hpr);
}
}
function processScreenOverlay(dataSource, screenOverlayNode, processingData, deferredLoading) {
const screenOverlay = processingData.screenOverlayContainer;
if (!defined_default(screenOverlay)) {
return void 0;
}
const sourceResource = processingData.sourceResource;
const uriResolver = processingData.uriResolver;
const iconNode = queryFirstNode2(screenOverlayNode, "Icon", namespaces2.kml);
const icon = getIconHref(
iconNode,
dataSource,
sourceResource,
uriResolver,
false
);
if (!defined_default(icon)) {
return void 0;
}
const img = document.createElement("img");
dataSource._screenOverlays.push(img);
img.src = icon.url;
img.onload = function() {
const styles = ["position: absolute"];
const screenXY = queryFirstNode2(
screenOverlayNode,
"screenXY",
namespaces2.kml
);
const overlayXY = queryFirstNode2(
screenOverlayNode,
"overlayXY",
namespaces2.kml
);
const size = queryFirstNode2(screenOverlayNode, "size", namespaces2.kml);
let x, y;
let xUnit, yUnit;
let xStyle, yStyle;
if (defined_default(size)) {
x = queryNumericAttribute2(size, "x");
y = queryNumericAttribute2(size, "y");
xUnit = queryStringAttribute2(size, "xunits");
yUnit = queryStringAttribute2(size, "yunits");
if (defined_default(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_default(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);
}
}
img.style = styles.join(";");
let xOrigin = 0;
let yOrigin = img.height;
if (defined_default(overlayXY)) {
x = queryNumericAttribute2(overlayXY, "x");
y = queryNumericAttribute2(overlayXY, "y");
xUnit = queryStringAttribute2(overlayXY, "xunits");
yUnit = queryStringAttribute2(overlayXY, "yunits");
if (defined_default(x)) {
if (xUnit === "fraction") {
xOrigin = x * img.width;
} else if (xUnit === "pixels") {
xOrigin = x;
} else if (xUnit === "insetPixels") {
xOrigin = x;
}
}
if (defined_default(y)) {
if (yUnit === "fraction") {
yOrigin = y * img.height;
} else if (yUnit === "pixels") {
yOrigin = y;
} else if (yUnit === "insetPixels") {
yOrigin = y;
}
}
}
if (defined_default(screenXY)) {
x = queryNumericAttribute2(screenXY, "x");
y = queryNumericAttribute2(screenXY, "y");
xUnit = queryStringAttribute2(screenXY, "xunits");
yUnit = queryStringAttribute2(screenXY, "yunits");
if (defined_default(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_default(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 = processFeature2(dataSource, groundOverlay, processingData);
const entity = r.entity;
let geometry;
let isLatLonQuad = false;
const ellipsoid = dataSource._ellipsoid;
const positions = readCoordinates(
queryFirstNode2(groundOverlay, "LatLonQuad", namespaces2.gx),
ellipsoid
);
const zIndex = queryNumericValue2(groundOverlay, "drawOrder", namespaces2.kml);
if (defined_default(positions)) {
geometry = createDefaultPolygon();
geometry.hierarchy = new PolygonHierarchy_default(positions);
geometry.zIndex = zIndex;
entity.polygon = geometry;
isLatLonQuad = true;
} else {
geometry = new RectangleGraphics_default();
geometry.zIndex = zIndex;
entity.rectangle = geometry;
const latLonBox = queryFirstNode2(
groundOverlay,
"LatLonBox",
namespaces2.kml
);
if (defined_default(latLonBox)) {
let west = queryNumericValue2(latLonBox, "west", namespaces2.kml);
let south = queryNumericValue2(latLonBox, "south", namespaces2.kml);
let east = queryNumericValue2(latLonBox, "east", namespaces2.kml);
let north = queryNumericValue2(latLonBox, "north", namespaces2.kml);
if (defined_default(west)) {
west = Math_default.negativePiToPi(Math_default.toRadians(west));
}
if (defined_default(south)) {
south = Math_default.clampToLatitudeRange(Math_default.toRadians(south));
}
if (defined_default(east)) {
east = Math_default.negativePiToPi(Math_default.toRadians(east));
}
if (defined_default(north)) {
north = Math_default.clampToLatitudeRange(Math_default.toRadians(north));
}
geometry.coordinates = new Rectangle_default(west, south, east, north);
const rotation = queryNumericValue2(latLonBox, "rotation", namespaces2.kml);
if (defined_default(rotation)) {
const rotationRadians = Math_default.toRadians(rotation);
geometry.rotation = rotationRadians;
geometry.stRotation = rotationRadians;
}
}
}
const iconNode = queryFirstNode2(groundOverlay, "Icon", namespaces2.kml);
const href = getIconHref(
iconNode,
dataSource,
processingData.sourceResource,
processingData.uriResolver,
true
);
if (defined_default(href)) {
if (isLatLonQuad) {
oneTimeWarning_default(
"kml-gx:LatLonQuad",
"KML - gx:LatLonQuad Icon does not support texture projection."
);
}
const x = queryNumericValue2(iconNode, "x", namespaces2.gx);
const y = queryNumericValue2(iconNode, "y", namespaces2.gx);
const w = queryNumericValue2(iconNode, "w", namespaces2.gx);
const h = queryNumericValue2(iconNode, "h", namespaces2.gx);
if (defined_default(x) || defined_default(y) || defined_default(w) || defined_default(h)) {
oneTimeWarning_default(
"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",
namespaces2.kml
);
geometry.material.transparent = true;
} else {
geometry.material = queryColorValue(groundOverlay, "color", namespaces2.kml);
}
let altitudeMode = queryStringValue2(
groundOverlay,
"altitudeMode",
namespaces2.kml
);
if (defined_default(altitudeMode)) {
if (altitudeMode === "absolute") {
geometry.height = queryNumericValue2(
groundOverlay,
"altitude",
namespaces2.kml
);
geometry.zIndex = void 0;
} else if (altitudeMode !== "clampToGround") {
oneTimeWarning_default(
"kml-altitudeMode-unknown",
`KML - Unknown altitudeMode: ${altitudeMode}`
);
}
} else {
altitudeMode = queryStringValue2(
groundOverlay,
"altitudeMode",
namespaces2.gx
);
if (altitudeMode === "relativeToSeaFloor") {
oneTimeWarning_default(
"kml-altitudeMode-relativeToSeaFloor",
"KML - altitudeMode relativeToSeaFloor is currently not supported, treating as absolute."
);
geometry.height = queryNumericValue2(
groundOverlay,
"altitude",
namespaces2.kml
);
geometry.zIndex = void 0;
} else if (altitudeMode === "clampToSeaFloor") {
oneTimeWarning_default(
"kml-altitudeMode-clampToSeaFloor",
"KML - altitudeMode clampToSeaFloor is currently not supported, treating as clampToGround."
);
} else if (defined_default(altitudeMode)) {
oneTimeWarning_default(
"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_default(
`kml-unsupportedFeature-${node.nodeName}`,
`KML - Unsupported feature: ${node.nodeName}`
);
}
var RefreshMode = {
INTERVAL: 0,
EXPIRE: 1,
STOP: 2
};
function cleanupString(s) {
if (!defined_default(s) || s.length === 0) {
return "";
}
const sFirst = s[0];
if (sFirst === "&" || sFirst === "?") {
s = s.substring(1);
}
return s;
}
var zeroRectangle = new Rectangle_default();
var scratchCartographic14 = new Cartographic_default();
var scratchCartesian210 = new Cartesian2_default();
var scratchCartesian310 = new Cartesian3_default();
function processNetworkLinkQueryString(resource, camera, canvas, viewBoundScale, bbox, ellipsoid) {
function fixLatitude(value) {
if (value < -Math_default.PI_OVER_TWO) {
return -Math_default.PI_OVER_TWO;
} else if (value > Math_default.PI_OVER_TWO) {
return Math_default.PI_OVER_TWO;
}
return value;
}
function fixLongitude(value) {
if (value > Math_default.PI) {
return value - Math_default.TWO_PI;
} else if (value < -Math_default.PI) {
return value + Math_default.TWO_PI;
}
return value;
}
let queryString = objectToQuery_default(resource.queryParameters);
queryString = queryString.replace(/%5B/g, "[").replace(/%5D/g, "]");
if (defined_default(camera) && camera._mode !== SceneMode_default.MORPHING) {
let centerCartesian2;
let centerCartographic;
bbox = defaultValue_default(bbox, zeroRectangle);
if (defined_default(canvas)) {
scratchCartesian210.x = canvas.clientWidth * 0.5;
scratchCartesian210.y = canvas.clientHeight * 0.5;
centerCartesian2 = camera.pickEllipsoid(
scratchCartesian210,
ellipsoid,
scratchCartesian310
);
}
if (defined_default(centerCartesian2)) {
centerCartographic = ellipsoid.cartesianToCartographic(
centerCartesian2,
scratchCartographic14
);
} else {
centerCartographic = Rectangle_default.center(bbox, scratchCartographic14);
centerCartesian2 = ellipsoid.cartographicToCartesian(centerCartographic);
}
if (defined_default(viewBoundScale) && !Math_default.equalsEpsilon(viewBoundScale, 1, Math_default.EPSILON9)) {
const newHalfWidth = bbox.width * viewBoundScale * 0.5;
const newHalfHeight = bbox.height * viewBoundScale * 0.5;
bbox = new Rectangle_default(
fixLongitude(centerCartographic.longitude - newHalfWidth),
fixLatitude(centerCartographic.latitude - newHalfHeight),
fixLongitude(centerCartographic.longitude + newHalfWidth),
fixLatitude(centerCartographic.latitude + newHalfHeight)
);
}
queryString = queryString.replace(
"[bboxWest]",
Math_default.toDegrees(bbox.west).toString()
);
queryString = queryString.replace(
"[bboxSouth]",
Math_default.toDegrees(bbox.south).toString()
);
queryString = queryString.replace(
"[bboxEast]",
Math_default.toDegrees(bbox.east).toString()
);
queryString = queryString.replace(
"[bboxNorth]",
Math_default.toDegrees(bbox.north).toString()
);
const lon = Math_default.toDegrees(centerCartographic.longitude).toString();
const lat = Math_default.toDegrees(centerCartographic.latitude).toString();
queryString = queryString.replace("[lookatLon]", lon);
queryString = queryString.replace("[lookatLat]", lat);
queryString = queryString.replace(
"[lookatTilt]",
Math_default.toDegrees(camera.pitch).toString()
);
queryString = queryString.replace(
"[lookatHeading]",
Math_default.toDegrees(camera.heading).toString()
);
queryString = queryString.replace(
"[lookatRange]",
Cartesian3_default.distance(camera.positionWC, centerCartesian2)
);
queryString = queryString.replace("[lookatTerrainLon]", lon);
queryString = queryString.replace("[lookatTerrainLat]", lat);
queryString = queryString.replace(
"[lookatTerrainAlt]",
centerCartographic.height.toString()
);
ellipsoid.cartesianToCartographic(camera.positionWC, scratchCartographic14);
queryString = queryString.replace(
"[cameraLon]",
Math_default.toDegrees(scratchCartographic14.longitude).toString()
);
queryString = queryString.replace(
"[cameraLat]",
Math_default.toDegrees(scratchCartographic14.latitude).toString()
);
queryString = queryString.replace(
"[cameraAlt]",
Math_default.toDegrees(scratchCartographic14.height).toString()
);
const frustum = camera.frustum;
const aspectRatio = frustum.aspectRatio;
let horizFov = "";
let vertFov = "";
if (defined_default(aspectRatio)) {
const fov = Math_default.toDegrees(frustum.fov);
if (aspectRatio > 1) {
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_default(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_default(queryString));
}
function processNetworkLink(dataSource, node, processingData, deferredLoading) {
const r = processFeature2(dataSource, node, processingData);
const networkEntity = r.entity;
const sourceResource = processingData.sourceResource;
const uriResolver = processingData.uriResolver;
let link = queryFirstNode2(node, "Link", namespaces2.kml);
if (!defined_default(link)) {
link = queryFirstNode2(node, "Url", namespaces2.kml);
}
if (defined_default(link)) {
let href = queryStringValue2(link, "href", namespaces2.kml);
let viewRefreshMode;
let viewBoundScale;
if (defined_default(href)) {
let newSourceUri = href;
href = resolveHref(href, sourceResource, processingData.uriResolver);
if (/^data:/.test(href.getUrlComponent())) {
if (!/\.kmz/i.test(sourceResource.getUrlComponent())) {
newSourceUri = sourceResource.getDerivedResource({
url: newSourceUri
});
}
} else {
newSourceUri = href.clone();
viewRefreshMode = queryStringValue2(
link,
"viewRefreshMode",
namespaces2.kml
);
if (viewRefreshMode === "onRegion") {
oneTimeWarning_default(
"kml-refrehMode-onRegion",
"KML - Unsupported viewRefreshMode: onRegion"
);
return;
}
viewBoundScale = defaultValue_default(
queryStringValue2(link, "viewBoundScale", namespaces2.kml),
1
);
const defaultViewFormat = viewRefreshMode === "onStop" ? "BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]" : "";
const viewFormat = defaultValue_default(
queryStringValue2(link, "viewFormat", namespaces2.kml),
defaultViewFormat
);
const httpQuery = queryStringValue2(link, "httpQuery", namespaces2.kml);
if (defined_default(viewFormat)) {
href.setQueryParameters(queryToObject_default(cleanupString(viewFormat)));
}
if (defined_default(httpQuery)) {
href.setQueryParameters(queryToObject_default(cleanupString(httpQuery)));
}
const ellipsoid = dataSource._ellipsoid;
processNetworkLinkQueryString(
href,
dataSource.camera,
dataSource.canvas,
viewBoundScale,
dataSource._lastCameraView.bbox,
ellipsoid
);
}
const options = {
sourceUri: newSourceUri,
uriResolver,
context: networkEntity.id,
screenOverlayContainer: processingData.screenOverlayContainer
};
const networkLinkCollection = new EntityCollection_default();
const promise = load4(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_default(newEntity.parent)) {
newEntity.parent = networkEntity;
mergeAvailabilityWithParent(newEntity);
}
entities.add(newEntity);
}
entities.resumeEvents();
const refreshMode = queryStringValue2(
link,
"refreshMode",
namespaces2.kml
);
let refreshInterval = defaultValue_default(
queryNumericValue2(link, "refreshInterval", namespaces2.kml),
0
);
if (refreshMode === "onInterval" && refreshInterval > 0 || refreshMode === "onExpire" || viewRefreshMode === "onStop") {
const networkLinkControl = queryFirstNode2(
rootElement,
"NetworkLinkControl",
namespaces2.kml
);
const hasNetworkLinkControl = defined_default(networkLinkControl);
const now2 = JulianDate_default.now();
const networkLinkInfo = {
id: createGuid_default(),
href,
cookie: {},
lastUpdated: now2,
updating: false,
entity: networkEntity,
viewBoundScale,
needsUpdate: false,
cameraUpdateTime: now2
};
let minRefreshPeriod = 0;
if (hasNetworkLinkControl) {
networkLinkInfo.cookie = queryToObject_default(
defaultValue_default(
queryStringValue2(
networkLinkControl,
"cookie",
namespaces2.kml
),
""
)
);
minRefreshPeriod = defaultValue_default(
queryNumericValue2(
networkLinkControl,
"minRefreshPeriod",
namespaces2.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 = queryStringValue2(
networkLinkControl,
"expires",
namespaces2.kml
);
}
if (defined_default(expires)) {
try {
const date = JulianDate_default.fromIso8601(expires);
const diff = JulianDate_default.secondsDifference(date, now2);
if (diff > 0 && diff < minRefreshPeriod) {
JulianDate_default.addSeconds(now2, minRefreshPeriod, date);
}
networkLinkInfo.refreshMode = RefreshMode.EXPIRE;
networkLinkInfo.time = date;
} catch (e) {
oneTimeWarning_default(
"kml-refreshMode-onInterval-onExpire",
"KML - NetworkLinkControl expires is not a valid date"
);
}
} else {
oneTimeWarning_default(
"kml-refreshMode-onExpire",
"KML - refreshMode of onExpire requires the NetworkLinkControl to have an expires element"
);
}
} else if (defined_default(dataSource.camera)) {
networkLinkInfo.refreshMode = RefreshMode.STOP;
networkLinkInfo.time = defaultValue_default(
queryNumericValue2(link, "viewRefreshTime", namespaces2.kml),
0
);
} else {
oneTimeWarning_default(
"kml-refrehMode-onStop-noCamera",
"A NetworkLink with viewRefreshMode=onStop requires the `camera` property to be defined."
);
}
if (defined_default(networkLinkInfo.refreshMode)) {
dataSource._networkLinks.set(networkLinkInfo.id, networkLinkInfo);
}
}
}).catch(function(error) {
oneTimeWarning_default(`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_default(featureProcessor)) {
return featureProcessor(dataSource, node, processingData, deferredLoading);
}
return processUnsupportedFeature(
dataSource,
node,
processingData,
deferredLoading
);
}
function loadKml(dataSource, entityCollection, kml, sourceResource, uriResolver, screenOverlayContainer, context) {
entityCollection.removeAll();
const documentElement = kml.documentElement;
const document2 = documentElement.localName === "Document" ? documentElement : queryFirstNode2(documentElement, "Document", namespaces2.kml);
let name = queryStringValue2(document2, "name", namespaces2.kml);
if (!defined_default(name)) {
name = getFilenameFromUri_default(sourceResource.getUrlComponent());
}
if (!defined_default(dataSource._name)) {
dataSource._name = name;
}
const deferredLoading = new KmlDataSource._DeferredLoading(dataSource);
const styleCollection = new EntityCollection_default(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 tmp2 = childNodes[i];
if (defined_default(featureTypes[tmp2.localName])) {
element = tmp2;
break;
}
}
}
const processingData = {
parentEntity: void 0,
entityCollection,
styleCollection,
sourceResource,
uriResolver,
context,
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_default("ThirdParty/Workers/z-worker-pako.js");
configure({
workerScripts: {
deflate: [zWorkerUrl, "./pako_deflate.min.js"],
inflate: [zWorkerUrl, "./pako_inflate.min.js"]
}
});
const reader = new ZipReader(new BlobReader(blob));
return Promise.resolve(reader.getEntries()).then(function(entries2) {
const promises = [];
const uriResolver = {};
let docEntry;
for (let i = 0; i < entries2.length; i++) {
const entry = entries2[i];
if (!entry.directory) {
if (/\.kml$/i.test(entry.filename)) {
if (!defined_default(docEntry) || !/\//i.test(entry.filename)) {
if (defined_default(docEntry)) {
promises.push(loadDataUriFromZip(docEntry, uriResolver));
}
docEntry = entry;
} else {
promises.push(loadDataUriFromZip(entry, uriResolver));
}
} else {
promises.push(loadDataUriFromZip(entry, uriResolver));
}
}
}
if (defined_default(docEntry)) {
promises.push(loadXmlFromZip(docEntry, uriResolver));
}
return Promise.all(promises).then(function() {
reader.close();
if (!defined_default(uriResolver.kml)) {
throw new RuntimeError_default("KMZ file does not contain a KML document.");
}
uriResolver.keys = Object.keys(uriResolver);
return loadKml(
dataSource,
entityCollection,
uriResolver.kml,
sourceResource,
uriResolver,
screenOverlayContainer
);
});
});
}
function load4(dataSource, entityCollection, data, options) {
options = defaultValue_default(options, defaultValue_default.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_default) {
data = Resource_default.createIfNeeded(data);
promise = data.fetchBlob();
sourceUri = defaultValue_default(sourceUri, data.clone());
const resourceCredits = dataSource._resourceCredits;
const credits = data.credits;
if (defined_default(credits)) {
const length3 = credits.length;
for (let i = 0; i < length3; i++) {
resourceCredits.push(credits[i]);
}
}
} else {
sourceUri = defaultValue_default(sourceUri, Resource_default.DEFAULT.clone());
}
sourceUri = Resource_default.createIfNeeded(sourceUri);
if (defined_default(screenOverlayContainer)) {
screenOverlayContainer = getElement_default(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 readBlobAsText2(dataToLoad).then(function(text2) {
text2 = insertNamespaces(text2);
text2 = removeDuplicateNamespaces(text2);
let kml;
let error;
try {
kml = parser2.parseFromString(text2, "application/xml");
} catch (e) {
error = e.toString();
}
if (defined_default(error) || kml.body || kml.documentElement.tagName === "parsererror") {
let msg = defined_default(error) ? error : kml.documentElement.firstChild.nodeValue;
if (!msg) {
msg = kml.body.innerText;
}
throw new RuntimeError_default(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);
});
}
function KmlDataSource(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const camera = options.camera;
const canvas = options.canvas;
this._changed = new Event_default();
this._error = new Event_default();
this._loading = new Event_default();
this._refresh = new Event_default();
this._unsupportedNode = new Event_default();
this._clock = void 0;
this._entityCollection = new EntityCollection_default(this);
this._name = void 0;
this._isLoading = false;
this._pinBuilder = new PinBuilder_default();
this._networkLinks = new AssociativeArray_default();
this._entityCluster = new EntityCluster_default();
this.canvas = canvas;
this.camera = camera;
this._lastCameraView = {
position: defined_default(camera) ? Cartesian3_default.clone(camera.positionWC) : void 0,
direction: defined_default(camera) ? Cartesian3_default.clone(camera.directionWC) : void 0,
up: defined_default(camera) ? Cartesian3_default.clone(camera.upWC) : void 0,
bbox: defined_default(camera) ? camera.computeViewRectangle() : Rectangle_default.clone(Rectangle_default.MAX_VALUE)
};
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
let credit = options.credit;
if (typeof credit === "string") {
credit = new Credit_default(credit);
}
this._credit = credit;
this._resourceCredits = [];
this._kmlTours = [];
this._screenOverlays = [];
}
KmlDataSource.load = function(data, options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const dataSource = new KmlDataSource(options);
return dataSource.load(data, options);
};
Object.defineProperties(KmlDataSource.prototype, {
name: {
get: function() {
return this._name;
},
set: function(value) {
if (this._name !== value) {
this._name = value;
this._changed.raiseEvent(this);
}
}
},
clock: {
get: function() {
return this._clock;
}
},
entities: {
get: function() {
return this._entityCollection;
}
},
isLoading: {
get: function() {
return this._isLoading;
}
},
changedEvent: {
get: function() {
return this._changed;
}
},
errorEvent: {
get: function() {
return this._error;
}
},
loadingEvent: {
get: function() {
return this._loading;
}
},
refreshEvent: {
get: function() {
return this._refresh;
}
},
unsupportedNodeEvent: {
get: function() {
return this._unsupportedNode;
}
},
show: {
get: function() {
return this._entityCollection.show;
},
set: function(value) {
this._entityCollection.show = value;
}
},
clustering: {
get: function() {
return this._entityCluster;
},
set: function(value) {
if (!defined_default(value)) {
throw new DeveloperError_default("value must be defined.");
}
this._entityCluster = value;
}
},
credit: {
get: function() {
return this._credit;
}
},
kmlTours: {
get: function() {
return this._kmlTours;
}
}
});
KmlDataSource.prototype.load = function(data, options) {
if (!defined_default(data)) {
throw new DeveloperError_default("data is required.");
}
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
DataSource_default.setLoading(this, true);
const oldName = this._name;
this._name = void 0;
this._clampToGround = defaultValue_default(options.clampToGround, false);
const that = this;
return load4(this, this._entityCollection, data, options).then(function() {
let clock;
const availability = that._entityCollection.computeAvailability();
let start = availability.start;
let stop2 = availability.stop;
const isMinStart = JulianDate_default.equals(start, Iso8601_default.MINIMUM_VALUE);
const isMaxStop = JulianDate_default.equals(stop2, Iso8601_default.MAXIMUM_VALUE);
if (!isMinStart || !isMaxStop) {
let date;
if (isMinStart) {
date = new Date();
date.setHours(0, 0, 0, 0);
start = JulianDate_default.fromDate(date);
}
if (isMaxStop) {
date = new Date();
date.setHours(24, 0, 0, 0);
stop2 = JulianDate_default.fromDate(date);
}
clock = new DataSourceClock_default();
clock.startTime = start;
clock.stopTime = stop2;
clock.currentTime = JulianDate_default.clone(start);
clock.clockRange = ClockRange_default.LOOP_STOP;
clock.clockStep = ClockStep_default.SYSTEM_CLOCK_MULTIPLIER;
clock.multiplier = Math.round(
Math.min(
Math.max(JulianDate_default.secondsDifference(stop2, start) / 60, 1),
31556900
)
);
}
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_default.setLoading(that, false);
return that;
}).catch(function(error) {
DataSource_default.setLoading(that, false);
that._error.raiseEvent(that, error);
console.log(error);
return Promise.reject(error);
});
};
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_default(parent)) {
const parentAvailability = parent.availability;
if (defined_default(parentAvailability)) {
const childAvailability = child.availability;
if (defined_default(childAvailability)) {
childAvailability.intersect(parentAvailability);
} else {
child.availability = parentAvailability;
}
}
}
}
function getNetworkLinkUpdateCallback(dataSource, networkLink, newEntityCollection, networkLinks, processedHref) {
return function(rootElement) {
if (!networkLinks.contains(networkLink.id)) {
return;
}
let remove5 = false;
const networkLinkControl = queryFirstNode2(
rootElement,
"NetworkLinkControl",
namespaces2.kml
);
const hasNetworkLinkControl = defined_default(networkLinkControl);
let minRefreshPeriod = 0;
if (hasNetworkLinkControl) {
if (defined_default(queryFirstNode2(networkLinkControl, "Update", namespaces2.kml))) {
oneTimeWarning_default(
"kml-networkLinkControl-update",
"KML - NetworkLinkControl updates aren't supported."
);
networkLink.updating = false;
networkLinks.remove(networkLink.id);
return;
}
networkLink.cookie = queryToObject_default(
defaultValue_default(
queryStringValue2(networkLinkControl, "cookie", namespaces2.kml),
""
)
);
minRefreshPeriod = defaultValue_default(
queryNumericValue2(
networkLinkControl,
"minRefreshPeriod",
namespaces2.kml
),
0
);
}
const now2 = JulianDate_default.now();
const refreshMode = networkLink.refreshMode;
if (refreshMode === RefreshMode.INTERVAL) {
if (defined_default(networkLinkControl)) {
networkLink.time = Math.max(minRefreshPeriod, networkLink.time);
}
} else if (refreshMode === RefreshMode.EXPIRE) {
let expires;
if (defined_default(networkLinkControl)) {
expires = queryStringValue2(
networkLinkControl,
"expires",
namespaces2.kml
);
}
if (defined_default(expires)) {
try {
const date = JulianDate_default.fromIso8601(expires);
const diff = JulianDate_default.secondsDifference(date, now2);
if (diff > 0 && diff < minRefreshPeriod) {
JulianDate_default.addSeconds(now2, minRefreshPeriod, date);
}
networkLink.time = date;
} catch (e) {
oneTimeWarning_default(
"kml-networkLinkControl-expires",
"KML - NetworkLinkControl expires is not a valid date"
);
remove5 = true;
}
} else {
oneTimeWarning_default(
"kml-refreshMode-onExpire",
"KML - refreshMode of onExpire requires the NetworkLinkControl to have an expires element"
);
remove5 = 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 i2 = 0; i2 < count; ++i2) {
removeChildren(children[i2]);
}
}
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 = void 0;
removeChildren(entityToRemove);
}
}
entityCollection.resumeEvents();
entityCollection.suspendEvents();
for (i = 0; i < newEntities.length; i++) {
const newEntity = newEntities[i];
if (!defined_default(newEntity.parent)) {
newEntity.parent = networkLinkEntity;
mergeAvailabilityWithParent(newEntity);
}
entityCollection.add(newEntity);
}
entityCollection.resumeEvents();
if (remove5) {
networkLinks.remove(networkLink.id);
} else {
networkLink.lastUpdated = now2;
}
const availability = entityCollection.computeAvailability();
const start = availability.start;
const stop2 = availability.stop;
const isMinStart = JulianDate_default.equals(start, Iso8601_default.MINIMUM_VALUE);
const isMaxStop = JulianDate_default.equals(stop2, Iso8601_default.MAXIMUM_VALUE);
if (!isMinStart || !isMaxStop) {
const clock = dataSource._clock;
if (clock.startTime !== start || clock.stopTime !== stop2) {
clock.startTime = start;
clock.stopTime = stop2;
dataSource._changed.raiseEvent(dataSource);
}
}
networkLink.updating = false;
networkLink.needsUpdate = false;
dataSource._refresh.raiseEvent(
dataSource,
processedHref.getUrlComponent(true)
);
};
}
var entitiesToIgnore = new AssociativeArray_default();
KmlDataSource.prototype.update = function(time) {
const networkLinks = this._networkLinks;
if (networkLinks.length === 0) {
return true;
}
const now2 = JulianDate_default.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_default(camera) && !(camera.positionWC.equalsEpsilon(
lastCameraView.position,
Math_default.EPSILON7
) && camera.directionWC.equalsEpsilon(
lastCameraView.direction,
Math_default.EPSILON7
) && camera.upWC.equalsEpsilon(lastCameraView.up, Math_default.EPSILON7))) {
lastCameraView.position = Cartesian3_default.clone(camera.positionWC);
lastCameraView.direction = Cartesian3_default.clone(camera.directionWC);
lastCameraView.up = Cartesian3_default.clone(camera.upWC);
lastCameraView.bbox = camera.computeViewRectangle();
cameraViewUpdate = true;
}
const newNetworkLinks = new AssociativeArray_default();
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_default.secondsDifference(now2, networkLink.lastUpdated) > networkLink.time) {
doUpdate = true;
}
} else if (networkLink.refreshMode === RefreshMode.EXPIRE) {
if (JulianDate_default.greaterThan(now2, networkLink.time)) {
doUpdate = true;
}
} else if (networkLink.refreshMode === RefreshMode.STOP) {
if (cameraViewUpdate) {
networkLink.needsUpdate = true;
networkLink.cameraUpdateTime = now2;
}
if (networkLink.needsUpdate && JulianDate_default.secondsDifference(now2, networkLink.cameraUpdateTime) >= networkLink.time) {
doUpdate = true;
}
}
if (doUpdate) {
recurseIgnoreEntities(entity);
networkLink.updating = true;
const newEntityCollection = new EntityCollection_default();
const href = networkLink.href.clone();
href.setQueryParameters(networkLink.cookie);
const ellipsoid = defaultValue_default(that._ellipsoid, Ellipsoid_default.WGS84);
processNetworkLinkQueryString(
href,
that.camera,
that.canvas,
networkLink.viewBoundScale,
lastCameraView.bbox,
ellipsoid
);
load4(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;
};
function KmlFeatureData() {
this.author = {
name: void 0,
uri: void 0,
email: void 0
};
this.link = {
href: void 0,
hreflang: void 0,
rel: void 0,
type: void 0,
title: void 0,
length: void 0
};
this.address = void 0;
this.phoneNumber = void 0;
this.snippet = void 0;
this.extendedData = void 0;
}
KmlDataSource._DeferredLoading = DeferredLoading;
KmlDataSource._getTimestamp = getTimestamp_default;
var KmlDataSource_default = KmlDataSource;
// node_modules/@cesium/engine/Source/DataSources/Visualizer.js
function Visualizer() {
DeveloperError_default.throwInstantiationError();
}
Visualizer.prototype.update = DeveloperError_default.throwInstantiationError;
Visualizer.prototype.getBoundingSphere = DeveloperError_default.throwInstantiationError;
Visualizer.prototype.isDestroyed = DeveloperError_default.throwInstantiationError;
Visualizer.prototype.destroy = DeveloperError_default.throwInstantiationError;
var Visualizer_default = Visualizer;
// node_modules/@cesium/engine/Source/DataSources/exportKml.js
var BILLBOARD_SIZE3 = 32;
var kmlNamespace = "http://www.opengis.net/kml/2.2";
var gxNamespace = "http://www.google.com/kml/ext/2.2";
var xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
function ExternalFileHandler(modelCallback) {
this._files = {};
this._promises = [];
this._count = 0;
this._modelCallback = modelCallback;
}
var imageTypeRegex = /^data:image\/([^,;]+)/;
ExternalFileHandler.prototype.texture = function(texture) {
const that = this;
let filename;
if (typeof texture === "string" || texture instanceof Resource_default) {
texture = Resource_default.createIfNeeded(texture);
if (!texture.isDataUri) {
return texture.url;
}
const regexResult = texture.url.match(imageTypeRegex);
filename = `texture_${++this._count}`;
if (defined_default(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) {
filename = `texture_${++this._count}.png`;
const promise = new Promise((resolve2) => {
texture.toBlob(function(blob) {
that._files[filename] = blob;
resolve2();
});
});
this._promises.push(promise);
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_default(modelCallback)) {
throw new RuntimeError_default(
"Encountered a model entity while exporting to KML, but no model callback was supplied."
);
}
const externalFiles = {};
const url2 = modelCallback(model, time, externalFiles);
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 url2;
};
Object.defineProperties(ExternalFileHandler.prototype, {
promise: {
get: function() {
return Promise.all(this._promises);
}
},
files: {
get: function() {
return this._files;
}
}
});
function ValueGetter(time) {
this._time = time;
}
ValueGetter.prototype.get = function(property, defaultVal, result) {
let value;
if (defined_default(property)) {
value = defined_default(property.getValue) ? property.getValue(this._time, result) : property;
}
return defaultValue_default(value, defaultVal);
};
ValueGetter.prototype.getColor = function(property, defaultVal) {
const result = this.get(property, defaultVal);
if (defined_default(result)) {
return colorToString(result);
}
};
ValueGetter.prototype.getMaterialType = function(property) {
if (!defined_default(property)) {
return;
}
return property.getType(this._time);
};
function StyleCache() {
this._ids = {};
this._styles = {};
this._count = 0;
}
StyleCache.prototype.get = function(element) {
const ids = this._ids;
const key = element.innerHTML;
if (defined_default(ids[key])) {
return ids[key];
}
let styleId = `style-${++this._count}`;
element.setAttribute("id", styleId);
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);
}
}
};
function IdManager() {
this._ids = {};
}
IdManager.prototype.get = function(id) {
if (!defined_default(id)) {
return this.get(createGuid_default());
}
const ids = this._ids;
if (!defined_default(ids[id])) {
ids[id] = 0;
return id;
}
return `${id.toString()}-${++ids[id]}`;
};
function exportKml(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
const entities = options.entities;
const kmz = defaultValue_default(options.kmz, false);
if (!defined_default(entities)) {
throw new DeveloperError_default("entities is required.");
}
const state = exportKml._createState(options);
const rootEntities = entities.values.filter(function(entity) {
return !defined_default(entity.parent);
});
const kmlDoc = state.kmlDoc;
const kmlElement = kmlDoc.documentElement;
kmlElement.setAttributeNS(xmlnsNamespace, "xmlns:gx", gxNamespace);
const kmlDocumentElement = kmlDoc.createElement("Document");
kmlElement.appendChild(kmlDocumentElement);
recurseEntities(state, kmlDocumentElement, rootEntities);
state.styleCache.save(kmlDocumentElement);
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_default("ThirdParty/Workers/z-worker-pako.js");
configure({
workerScripts: {
deflate: [zWorkerUrl, "./pako_deflate.min.js"],
inflate: [zWorkerUrl, "./pako_inflate.min.js"]
}
});
const blobWriter = new BlobWriter();
const writer = new ZipWriter(blobWriter);
return writer.add("doc.kml", new 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 BlobReader(externalFiles[filename])).then(function() {
return addExternalFilesToZip(writer, keys, externalFiles, index + 1);
});
}
exportKml._createState = function(options) {
const entities = options.entities;
const styleCache = new StyleCache();
const entityAvailability = entities.computeAvailability();
const time = defined_default(options.time) ? options.time : entityAvailability.start;
let defaultAvailability = defaultValue_default(
options.defaultAvailability,
entityAvailability
);
const sampleDuration = defaultValue_default(options.sampleDuration, 60);
if (defaultAvailability.start === Iso8601_default.MINIMUM_VALUE) {
if (defaultAvailability.stop === Iso8601_default.MAXIMUM_VALUE) {
defaultAvailability = new TimeInterval_default();
} else {
JulianDate_default.addSeconds(
defaultAvailability.stop,
-10 * sampleDuration,
defaultAvailability.start
);
}
} else if (defaultAvailability.stop === Iso8601_default.MAXIMUM_VALUE) {
JulianDate_default.addSeconds(
defaultAvailability.start,
10 * sampleDuration,
defaultAvailability.stop
);
}
const externalFileHandler = new ExternalFileHandler(options.modelCallback);
const kmlDoc = document.implementation.createDocument(kmlNamespace, "kml");
return {
kmlDoc,
ellipsoid: defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84),
idManager: new IdManager(),
styleCache,
externalFileHandler,
time,
valueGetter: new ValueGetter(time),
sampleDuration,
defaultAvailability: new TimeIntervalCollection_default([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 = [];
createPoint2(state, entity, geometries, styles);
createLineString2(state, entity.polyline, geometries, styles);
createPolygon2(state, entity.rectangle, geometries, styles, overlays);
createPolygon2(state, entity.polygon, geometries, styles, overlays);
createModel(state, entity, entity.model, geometries, styles);
let timeSpan;
const availability = entity.availability;
if (defined_default(availability)) {
timeSpan = kmlDoc.createElement("TimeSpan");
if (!JulianDate_default.equals(availability.start, Iso8601_default.MINIMUM_VALUE)) {
timeSpan.appendChild(
createBasicElementWithText(
kmlDoc,
"begin",
JulianDate_default.toIso8601(availability.start)
)
);
}
if (!JulianDate_default.equals(availability.stop, Iso8601_default.MAXIMUM_VALUE)) {
timeSpan.appendChild(
createBasicElementWithText(
kmlDoc,
"end",
JulianDate_default.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_default(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_default(labelGraphics)) {
const labelStyle = kmlDoc.createElement("LabelStyle");
const text2 = valueGetter.get(labelGraphics.text);
name = defined_default(text2) && text2.length > 0 ? text2 : name;
const color = valueGetter.getColor(labelGraphics.fillColor);
if (defined_default(color)) {
labelStyle.appendChild(
createBasicElementWithText(kmlDoc, "color", color)
);
labelStyle.appendChild(
createBasicElementWithText(kmlDoc, "colorMode", "normal")
);
}
const scale = valueGetter.get(labelGraphics.scale);
if (defined_default(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_default(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);
}
}
}
var scratchCartesian311 = new Cartesian3_default();
var scratchCartographic15 = new Cartographic_default();
var scratchJulianDate3 = new JulianDate_default();
function createPoint2(state, entity, geometries, styles) {
const kmlDoc = state.kmlDoc;
const ellipsoid = state.ellipsoid;
const valueGetter = state.valueGetter;
const pointGraphics = defaultValue_default(entity.billboard, entity.point);
if (!defined_default(pointGraphics) && !defined_default(entity.path)) {
return;
}
const entityPositionProperty = entity.position;
if (!entityPositionProperty.isConstant) {
createTracks(state, entity, pointGraphics, geometries, styles);
return;
}
valueGetter.get(entityPositionProperty, void 0, scratchCartesian311);
const coordinates = createBasicElementWithText(
kmlDoc,
"coordinates",
getCoordinates(scratchCartesian311, ellipsoid)
);
const pointGeometry = kmlDoc.createElement("Point");
const altitudeMode = kmlDoc.createElement("altitudeMode");
altitudeMode.appendChild(
getAltitudeMode(state, pointGraphics.heightReference)
);
pointGeometry.appendChild(altitudeMode);
pointGeometry.appendChild(coordinates);
geometries.push(pointGeometry);
const iconStyle = pointGraphics instanceof BillboardGraphics_default ? 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_default) {
intervals = entityPositionProperty.intervals;
useEntityPositionProperty = false;
} else {
intervals = defaultValue_default(entity.availability, state.defaultAvailability);
}
const isModel = pointGraphics instanceof ModelGraphics_default;
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");
if (positionProperty instanceof ScaledPositionProperty_default) {
positionProperty = positionProperty._value;
trackAltitudeMode.appendChild(
getAltitudeMode(state, HeightReference_default.CLAMP_TO_GROUND)
);
} else if (defined_default(pointGraphics)) {
trackAltitudeMode.appendChild(
getAltitudeMode(state, pointGraphics.heightReference)
);
} else {
trackAltitudeMode.appendChild(
getAltitudeMode(state, HeightReference_default.NONE)
);
}
const positionTimes = [];
const positionValues = [];
if (positionProperty.isConstant) {
valueGetter.get(positionProperty, void 0, scratchCartesian311);
const constCoordinates = createBasicElementWithText(
kmlDoc,
"coordinates",
getCoordinates(scratchCartesian311, ellipsoid)
);
positionTimes.push(JulianDate_default.toIso8601(interval.start));
positionValues.push(constCoordinates);
positionTimes.push(JulianDate_default.toIso8601(interval.stop));
positionValues.push(constCoordinates);
} else if (positionProperty instanceof SampledPositionProperty_default) {
times = positionProperty._property._times;
for (j = 0; j < times.length; ++j) {
positionTimes.push(JulianDate_default.toIso8601(times[j]));
positionProperty.getValueInReferenceFrame(
times[j],
ReferenceFrame_default.FIXED,
scratchCartesian311
);
positionValues.push(getCoordinates(scratchCartesian311, ellipsoid));
}
} else if (positionProperty instanceof SampledProperty_default) {
times = positionProperty._times;
const values = positionProperty._values;
for (j = 0; j < times.length; ++j) {
positionTimes.push(JulianDate_default.toIso8601(times[j]));
Cartesian3_default.fromArray(values, j * 3, scratchCartesian311);
positionValues.push(getCoordinates(scratchCartesian311, ellipsoid));
}
} else {
const duration = state.sampleDuration;
interval.start.clone(scratchJulianDate3);
if (!interval.isStartIncluded) {
JulianDate_default.addSeconds(scratchJulianDate3, duration, scratchJulianDate3);
}
const stopDate = interval.stop;
while (JulianDate_default.lessThan(scratchJulianDate3, stopDate)) {
positionProperty.getValue(scratchJulianDate3, scratchCartesian311);
positionTimes.push(JulianDate_default.toIso8601(scratchJulianDate3));
positionValues.push(getCoordinates(scratchCartesian311, ellipsoid));
JulianDate_default.addSeconds(scratchJulianDate3, duration, scratchJulianDate3);
}
if (interval.isStopIncluded && JulianDate_default.equals(scratchJulianDate3, stopDate)) {
positionProperty.getValue(scratchJulianDate3, scratchCartesian311);
positionTimes.push(JulianDate_default.toIso8601(scratchJulianDate3));
positionValues.push(getCoordinates(scratchCartesian311, 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 (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);
}
if (defined_default(pointGraphics) && !isModel) {
const iconStyle = pointGraphics instanceof BillboardGraphics_default ? createIconStyleFromBillboard(state, pointGraphics) : createIconStyleFromPoint(state, pointGraphics);
styles.push(iconStyle);
}
const path = entity.path;
if (defined_default(path)) {
const width = valueGetter.get(path.width);
const material = path.material;
if (defined_default(material) || defined_default(width)) {
const lineStyle = kmlDoc.createElement("LineStyle");
if (defined_default(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_default(color)) {
iconStyle.appendChild(createBasicElementWithText(kmlDoc, "color", color));
iconStyle.appendChild(
createBasicElementWithText(kmlDoc, "colorMode", "normal")
);
}
const pixelSize = valueGetter.get(pointGraphics.pixelSize);
if (defined_default(pixelSize)) {
iconStyle.appendChild(
createBasicElementWithText(kmlDoc, "scale", pixelSize / BILLBOARD_SIZE3)
);
}
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_default(image)) {
image = externalFileHandler.texture(image);
const icon = kmlDoc.createElement("Icon");
icon.appendChild(createBasicElementWithText(kmlDoc, "href", image));
const imageSubRegion = valueGetter.get(billboardGraphics.imageSubRegion);
if (defined_default(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_default(color)) {
iconStyle.appendChild(createBasicElementWithText(kmlDoc, "color", color));
iconStyle.appendChild(
createBasicElementWithText(kmlDoc, "colorMode", "normal")
);
}
let scale = valueGetter.get(billboardGraphics.scale);
if (defined_default(scale)) {
iconStyle.appendChild(createBasicElementWithText(kmlDoc, "scale", scale));
}
const pixelOffset = valueGetter.get(billboardGraphics.pixelOffset);
if (defined_default(pixelOffset)) {
scale = defaultValue_default(scale, 1);
Cartesian2_default.divideByScalar(pixelOffset, scale, pixelOffset);
const width = valueGetter.get(billboardGraphics.width, BILLBOARD_SIZE3);
const height = valueGetter.get(billboardGraphics.height, BILLBOARD_SIZE3);
const horizontalOrigin = valueGetter.get(
billboardGraphics.horizontalOrigin,
HorizontalOrigin_default.CENTER
);
if (horizontalOrigin === HorizontalOrigin_default.CENTER) {
pixelOffset.x -= width * 0.5;
} else if (horizontalOrigin === HorizontalOrigin_default.RIGHT) {
pixelOffset.x -= width;
}
const verticalOrigin = valueGetter.get(
billboardGraphics.verticalOrigin,
VerticalOrigin_default.CENTER
);
if (verticalOrigin === VerticalOrigin_default.TOP) {
pixelOffset.y += height;
} else if (verticalOrigin === VerticalOrigin_default.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);
}
let rotation = valueGetter.get(billboardGraphics.rotation);
const alignedAxis = valueGetter.get(billboardGraphics.alignedAxis);
if (defined_default(rotation) && Cartesian3_default.equals(Cartesian3_default.UNIT_Z, alignedAxis)) {
rotation = Math_default.toDegrees(-rotation);
if (rotation === 0) {
rotation = 360;
}
iconStyle.appendChild(
createBasicElementWithText(kmlDoc, "heading", rotation)
);
}
return iconStyle;
}
function createLineString2(state, polylineGraphics, geometries, styles) {
const kmlDoc = state.kmlDoc;
const ellipsoid = state.ellipsoid;
const valueGetter = state.valueGetter;
if (!defined_default(polylineGraphics)) {
return;
}
const lineStringGeometry = kmlDoc.createElement("LineString");
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);
const positionsProperty = polylineGraphics.positions;
const cartesians = valueGetter.get(positionsProperty);
const coordinates = createBasicElementWithText(
kmlDoc,
"coordinates",
getCoordinates(cartesians, ellipsoid)
);
lineStringGeometry.appendChild(coordinates);
const zIndex = valueGetter.get(polylineGraphics.zIndex);
if (clampToGround && defined_default(zIndex)) {
lineStringGeometry.appendChild(
createBasicElementWithText(kmlDoc, "drawOrder", zIndex, gxNamespace)
);
}
geometries.push(lineStringGeometry);
const lineStyle = kmlDoc.createElement("LineStyle");
const width = valueGetter.get(polylineGraphics.width);
if (defined_default(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);
if (extrudedHeight > 0) {
height = extrudedHeight;
}
const coordinatesProperty = rectangleGraphics.coordinates;
const rectangle = valueGetter.get(coordinatesProperty);
const coordinateStrings = [];
const cornerFunction = [
Rectangle_default.northeast,
Rectangle_default.southeast,
Rectangle_default.southwest,
Rectangle_default.northwest
];
for (let i = 0; i < 4; ++i) {
cornerFunction[i](rectangle, scratchCartographic15);
coordinateStrings.push(
`${Math_default.toDegrees(
scratchCartographic15.longitude
)},${Math_default.toDegrees(scratchCartographic15.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_default.fromCartesian(positions[i], ellipsoid, scratchCartographic15);
coordinateStrings.push(
`${Math_default.toDegrees(
scratchCartographic15.longitude
)},${Math_default.toDegrees(scratchCartographic15.latitude)},${perPositionHeight ? scratchCartographic15.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);
const perPositionHeight = valueGetter.get(
polygonGraphics.perPositionHeight,
false
);
if (!perPositionHeight && extrudedHeight > 0) {
height = extrudedHeight;
}
const boundaries = [];
const hierarchyProperty = polygonGraphics.hierarchy;
const hierarchy = valueGetter.get(hierarchyProperty);
const positions = Array.isArray(hierarchy) ? hierarchy : hierarchy.positions;
const outerBoundaryIs = kmlDoc.createElement("outerBoundaryIs");
outerBoundaryIs.appendChild(
getLinearRing(state, positions, height, perPositionHeight)
);
boundaries.push(outerBoundaryIs);
const holes = hierarchy.holes;
if (defined_default(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 createPolygon2(state, geometry, geometries, styles, overlays) {
const kmlDoc = state.kmlDoc;
const valueGetter = state.valueGetter;
if (!defined_default(geometry)) {
return;
}
const isRectangle = geometry instanceof RectangleGraphics_default;
if (isRectangle && valueGetter.getMaterialType(geometry.material) === "Image") {
createGroundOverlay(state, geometry, overlays);
return;
}
const polygonGeometry = kmlDoc.createElement("Polygon");
const extrudedHeight = valueGetter.get(geometry.extrudedHeight, 0);
if (extrudedHeight > 0) {
polygonGeometry.appendChild(
createBasicElementWithText(kmlDoc, "extrude", true)
);
}
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]);
}
const altitudeMode = kmlDoc.createElement("altitudeMode");
altitudeMode.appendChild(getAltitudeMode(state, geometry.heightReference));
polygonGeometry.appendChild(altitudeMode);
geometries.push(polygonGeometry);
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)
);
const lineStyle = kmlDoc.createElement("LineStyle");
const outlineWidth = valueGetter.get(geometry.outlineWidth, 1);
lineStyle.appendChild(
createBasicElementWithText(kmlDoc, "width", outlineWidth)
);
const outlineColor = valueGetter.getColor(
geometry.outlineColor,
Color_default.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");
const altitudeMode = kmlDoc.createElement("altitudeMode");
altitudeMode.appendChild(
getAltitudeMode(state, rectangleGraphics.heightReference)
);
groundOverlay.appendChild(altitudeMode);
const height = valueGetter.get(rectangleGraphics.height);
if (defined_default(height)) {
groundOverlay.appendChild(
createBasicElementWithText(kmlDoc, "altitude", height)
);
}
const rectangle = valueGetter.get(rectangleGraphics.coordinates);
const latLonBox = kmlDoc.createElement("LatLonBox");
latLonBox.appendChild(
createBasicElementWithText(
kmlDoc,
"north",
Math_default.toDegrees(rectangle.north)
)
);
latLonBox.appendChild(
createBasicElementWithText(
kmlDoc,
"south",
Math_default.toDegrees(rectangle.south)
)
);
latLonBox.appendChild(
createBasicElementWithText(
kmlDoc,
"east",
Math_default.toDegrees(rectangle.east)
)
);
latLonBox.appendChild(
createBasicElementWithText(
kmlDoc,
"west",
Math_default.toDegrees(rectangle.west)
)
);
groundOverlay.appendChild(latLonBox);
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_default(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_default(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_default(modelGraphics)) {
return;
}
const entityPositionProperty = entity.position;
if (!entityPositionProperty.isConstant) {
createTracks(state, entity, modelGraphics, geometries, styles);
return;
}
const modelGeometry = createModelGeometry(state, modelGraphics);
const altitudeMode = kmlDoc.createElement("altitudeMode");
altitudeMode.appendChild(
getAltitudeMode(state, modelGraphics.heightReference)
);
modelGeometry.appendChild(altitudeMode);
valueGetter.get(entityPositionProperty, void 0, scratchCartesian311);
Cartographic_default.fromCartesian(scratchCartesian311, ellipsoid, scratchCartographic15);
const location2 = kmlDoc.createElement("Location");
location2.appendChild(
createBasicElementWithText(
kmlDoc,
"longitude",
Math_default.toDegrees(scratchCartographic15.longitude)
)
);
location2.appendChild(
createBasicElementWithText(
kmlDoc,
"latitude",
Math_default.toDegrees(scratchCartographic15.latitude)
)
);
location2.appendChild(
createBasicElementWithText(kmlDoc, "altitude", scratchCartographic15.height)
);
modelGeometry.appendChild(location2);
geometries.push(modelGeometry);
}
function processMaterial(state, materialProperty, style) {
const kmlDoc = state.kmlDoc;
const valueGetter = state.valueGetter;
if (!defined_default(materialProperty)) {
return;
}
const material = valueGetter.get(materialProperty);
if (!defined_default(material)) {
return;
}
let color;
const type = valueGetter.getMaterialType(materialProperty);
let outlineColor;
let outlineWidth;
switch (type) {
case "Image":
color = colorToString(Color_default.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_default(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_default.NONE
);
let altitudeModeText;
switch (heightReference) {
case HeightReference_default.NONE:
altitudeModeText = kmlDoc.createTextNode("absolute");
break;
case HeightReference_default.CLAMP_TO_GROUND:
altitudeModeText = kmlDoc.createTextNode("clampToGround");
break;
case HeightReference_default.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_default.fromCartesian(coordinates[i], ellipsoid, scratchCartographic15);
coordinateStrings.push(
`${Math_default.toDegrees(
scratchCartographic15.longitude
)},${Math_default.toDegrees(scratchCartographic15.latitude)},${scratchCartographic15.height}`
);
}
return coordinateStrings.join(" ");
}
function createBasicElementWithText(kmlDoc, elementName, elementValue, namespace) {
elementValue = defaultValue_default(elementValue, "");
if (typeof elementValue === "boolean") {
elementValue = elementValue ? "1" : "0";
}
const element = defined_default(namespace) ? kmlDoc.createElementNS(namespace, elementName) : kmlDoc.createElement(elementName);
const text2 = elementValue === "string" && elementValue.indexOf("<") !== -1 ? kmlDoc.createCDATASection(elementValue) : kmlDoc.createTextNode(elementValue);
element.appendChild(text2);
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;
}
var exportKml_default = exportKml;
// node_modules/@cesium/engine/Source/Core/formatError.js
function formatError(object) {
let result;
const name = object.name;
const message = object.message;
if (defined_default(name) && defined_default(message)) {
result = `${name}: ${message}`;
} else {
result = object.toString();
}
const stack = object.stack;
if (defined_default(stack)) {
result += `
${stack}`;
}
return result;
}
var formatError_default = formatError;
// node_modules/@cesium/engine/Source/Core/HeightmapEncoding.js
var HeightmapEncoding = {
NONE: 0,
LERC: 1
};
var HeightmapEncoding_default = Object.freeze(HeightmapEncoding);
// node_modules/@cesium/engine/Source/Core/TerrainQuantization.js
var TerrainQuantization = {
NONE: 0,
BITS12: 1
};
var TerrainQuantization_default = Object.freeze(TerrainQuantization);
// node_modules/@cesium/engine/Source/Core/TerrainEncoding.js
var cartesian3Scratch7 = new Cartesian3_default();
var cartesian3DimScratch = new Cartesian3_default();
var cartesian2Scratch = new Cartesian2_default();
var matrix4Scratch = new Matrix4_default();
var matrix4Scratch2 = new Matrix4_default();
var SHIFT_LEFT_12 = Math.pow(2, 12);
function TerrainEncoding(center, axisAlignedBoundingBox, minimumHeight, maximumHeight, fromENU, hasVertexNormals, hasWebMercatorT, hasGeodeticSurfaceNormals, exaggeration, exaggerationRelativeHeight) {
let quantization = TerrainQuantization_default.NONE;
let toENU;
let matrix;
if (defined_default(axisAlignedBoundingBox) && defined_default(minimumHeight) && defined_default(maximumHeight) && defined_default(fromENU)) {
const minimum = axisAlignedBoundingBox.minimum;
const maximum = axisAlignedBoundingBox.maximum;
const dimensions = Cartesian3_default.subtract(
maximum,
minimum,
cartesian3DimScratch
);
const hDim = maximumHeight - minimumHeight;
const maxDim = Math.max(Cartesian3_default.maximumComponent(dimensions), hDim);
if (maxDim < SHIFT_LEFT_12 - 1) {
quantization = TerrainQuantization_default.BITS12;
} else {
quantization = TerrainQuantization_default.NONE;
}
toENU = Matrix4_default.inverseTransformation(fromENU, new Matrix4_default());
const translation3 = Cartesian3_default.negate(minimum, cartesian3Scratch7);
Matrix4_default.multiply(
Matrix4_default.fromTranslation(translation3, matrix4Scratch),
toENU,
toENU
);
const scale = cartesian3Scratch7;
scale.x = 1 / dimensions.x;
scale.y = 1 / dimensions.y;
scale.z = 1 / dimensions.z;
Matrix4_default.multiply(Matrix4_default.fromScale(scale, matrix4Scratch), toENU, toENU);
matrix = Matrix4_default.clone(fromENU);
Matrix4_default.setTranslation(matrix, Cartesian3_default.ZERO, matrix);
fromENU = Matrix4_default.clone(fromENU, new Matrix4_default());
const translationMatrix = Matrix4_default.fromTranslation(minimum, matrix4Scratch);
const scaleMatrix2 = Matrix4_default.fromScale(dimensions, matrix4Scratch2);
const st = Matrix4_default.multiply(translationMatrix, scaleMatrix2, matrix4Scratch);
Matrix4_default.multiply(fromENU, st, fromENU);
Matrix4_default.multiply(matrix, st, matrix);
}
this.quantization = quantization;
this.minimumHeight = minimumHeight;
this.maximumHeight = maximumHeight;
this.center = Cartesian3_default.clone(center);
this.toScaledENU = toENU;
this.fromScaledENU = fromENU;
this.matrix = matrix;
this.hasVertexNormals = hasVertexNormals;
this.hasWebMercatorT = defaultValue_default(hasWebMercatorT, false);
this.hasGeodeticSurfaceNormals = defaultValue_default(
hasGeodeticSurfaceNormals,
false
);
this.exaggeration = defaultValue_default(exaggeration, 1);
this.exaggerationRelativeHeight = defaultValue_default(
exaggerationRelativeHeight,
0
);
this.stride = 0;
this._offsetGeodeticSurfaceNormal = 0;
this._offsetVertexNormal = 0;
this._calculateStrideAndOffsets();
}
TerrainEncoding.prototype.encode = function(vertexBuffer, bufferIndex, position, uv, height, normalToPack, webMercatorT, geodeticSurfaceNormal) {
const u3 = uv.x;
const v7 = uv.y;
if (this.quantization === TerrainQuantization_default.BITS12) {
position = Matrix4_default.multiplyByPoint(
this.toScaledENU,
position,
cartesian3Scratch7
);
position.x = Math_default.clamp(position.x, 0, 1);
position.y = Math_default.clamp(position.y, 0, 1);
position.z = Math_default.clamp(position.z, 0, 1);
const hDim = this.maximumHeight - this.minimumHeight;
const h = Math_default.clamp((height - this.minimumHeight) / hDim, 0, 1);
Cartesian2_default.fromElements(position.x, position.y, cartesian2Scratch);
const compressed0 = AttributeCompression_default.compressTextureCoordinates(
cartesian2Scratch
);
Cartesian2_default.fromElements(position.z, h, cartesian2Scratch);
const compressed1 = AttributeCompression_default.compressTextureCoordinates(
cartesian2Scratch
);
Cartesian2_default.fromElements(u3, v7, cartesian2Scratch);
const compressed2 = AttributeCompression_default.compressTextureCoordinates(
cartesian2Scratch
);
vertexBuffer[bufferIndex++] = compressed0;
vertexBuffer[bufferIndex++] = compressed1;
vertexBuffer[bufferIndex++] = compressed2;
if (this.hasWebMercatorT) {
Cartesian2_default.fromElements(webMercatorT, 0, cartesian2Scratch);
const compressed3 = AttributeCompression_default.compressTextureCoordinates(
cartesian2Scratch
);
vertexBuffer[bufferIndex++] = compressed3;
}
} else {
Cartesian3_default.subtract(position, this.center, cartesian3Scratch7);
vertexBuffer[bufferIndex++] = cartesian3Scratch7.x;
vertexBuffer[bufferIndex++] = cartesian3Scratch7.y;
vertexBuffer[bufferIndex++] = cartesian3Scratch7.z;
vertexBuffer[bufferIndex++] = height;
vertexBuffer[bufferIndex++] = u3;
vertexBuffer[bufferIndex++] = v7;
if (this.hasWebMercatorT) {
vertexBuffer[bufferIndex++] = webMercatorT;
}
}
if (this.hasVertexNormals) {
vertexBuffer[bufferIndex++] = AttributeCompression_default.octPackFloat(
normalToPack
);
}
if (this.hasGeodeticSurfaceNormals) {
vertexBuffer[bufferIndex++] = geodeticSurfaceNormal.x;
vertexBuffer[bufferIndex++] = geodeticSurfaceNormal.y;
vertexBuffer[bufferIndex++] = geodeticSurfaceNormal.z;
}
return bufferIndex;
};
var scratchPosition13 = new Cartesian3_default();
var scratchGeodeticSurfaceNormal = new Cartesian3_default();
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 offset2 = 0; offset2 < oldStride; offset2++) {
const oldIndex = index * oldStride + offset2;
const newIndex = index * newStride + offset2;
newBuffer[newIndex] = oldBuffer[oldIndex];
}
const position = this.decodePosition(newBuffer, index, scratchPosition13);
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 offset2 = 0; offset2 < newStride; offset2++) {
const oldIndex = index * oldStride + offset2;
const newIndex = index * newStride + offset2;
newBuffer[newIndex] = oldBuffer[oldIndex];
}
}
};
TerrainEncoding.prototype.decodePosition = function(buffer, index, result) {
if (!defined_default(result)) {
result = new Cartesian3_default();
}
index *= this.stride;
if (this.quantization === TerrainQuantization_default.BITS12) {
const xy = AttributeCompression_default.decompressTextureCoordinates(
buffer[index],
cartesian2Scratch
);
result.x = xy.x;
result.y = xy.y;
const zh = AttributeCompression_default.decompressTextureCoordinates(
buffer[index + 1],
cartesian2Scratch
);
result.z = zh.x;
return Matrix4_default.multiplyByPoint(this.fromScaledENU, result, result);
}
result.x = buffer[index];
result.y = buffer[index + 1];
result.z = buffer[index + 2];
return Cartesian3_default.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;
if (hasExaggeration && this.hasGeodeticSurfaceNormals) {
const geodeticSurfaceNormal = this.decodeGeodeticSurfaceNormal(
buffer,
index,
scratchGeodeticSurfaceNormal
);
const rawHeight = this.decodeHeight(buffer, index);
const heightDifference = TerrainExaggeration_default.getHeight(
rawHeight,
exaggeration,
exaggerationRelativeHeight
) - rawHeight;
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_default(result)) {
result = new Cartesian2_default();
}
index *= this.stride;
if (this.quantization === TerrainQuantization_default.BITS12) {
return AttributeCompression_default.decompressTextureCoordinates(
buffer[index + 2],
result
);
}
return Cartesian2_default.fromElements(buffer[index + 4], buffer[index + 5], result);
};
TerrainEncoding.prototype.decodeHeight = function(buffer, index) {
index *= this.stride;
if (this.quantization === TerrainQuantization_default.BITS12) {
const zh = AttributeCompression_default.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_default.BITS12) {
return AttributeCompression_default.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;
const x = Math.floor(temp);
const y = (temp - x) * 256;
return Cartesian2_default.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_default.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;
};
var attributesIndicesNone = {
position3DAndHeight: 0,
textureCoordAndEncodedNormals: 1,
geodeticSurfaceNormal: 2
};
var attributesIndicesBits12 = {
compressed0: 0,
compressed1: 1,
geodeticSurfaceNormal: 2
};
TerrainEncoding.prototype.getAttributes = function(buffer) {
const datatype = ComponentDatatype_default.FLOAT;
const sizeInBytes = ComponentDatatype_default.getSizeInBytes(datatype);
const strideInBytes = this.stride * sizeInBytes;
let offsetInBytes = 0;
const attributes = [];
function addAttribute2(index, componentsPerAttribute) {
attributes.push({
index,
vertexBuffer: buffer,
componentDatatype: datatype,
componentsPerAttribute,
offsetInBytes,
strideInBytes
});
offsetInBytes += componentsPerAttribute * sizeInBytes;
}
if (this.quantization === TerrainQuantization_default.NONE) {
addAttribute2(attributesIndicesNone.position3DAndHeight, 4);
let componentsTexCoordAndNormals = 2;
componentsTexCoordAndNormals += this.hasWebMercatorT ? 1 : 0;
componentsTexCoordAndNormals += this.hasVertexNormals ? 1 : 0;
addAttribute2(
attributesIndicesNone.textureCoordAndEncodedNormals,
componentsTexCoordAndNormals
);
if (this.hasGeodeticSurfaceNormals) {
addAttribute2(attributesIndicesNone.geodeticSurfaceNormal, 3);
}
} else {
const usingAttribute0Component4 = this.hasWebMercatorT || this.hasVertexNormals;
const usingAttribute1Component1 = this.hasWebMercatorT && this.hasVertexNormals;
addAttribute2(
attributesIndicesBits12.compressed0,
usingAttribute0Component4 ? 4 : 3
);
if (usingAttribute1Component1) {
addAttribute2(attributesIndicesBits12.compressed1, 1);
}
if (this.hasGeodeticSurfaceNormals) {
addAttribute2(attributesIndicesBits12.geodeticSurfaceNormal, 3);
}
}
return attributes;
};
TerrainEncoding.prototype.getAttributeLocations = function() {
if (this.quantization === TerrainQuantization_default.NONE) {
return attributesIndicesNone;
}
return attributesIndicesBits12;
};
TerrainEncoding.clone = function(encoding, result) {
if (!defined_default(encoding)) {
return void 0;
}
if (!defined_default(result)) {
result = new TerrainEncoding();
}
result.quantization = encoding.quantization;
result.minimumHeight = encoding.minimumHeight;
result.maximumHeight = encoding.maximumHeight;
result.center = Cartesian3_default.clone(encoding.center);
result.toScaledENU = Matrix4_default.clone(encoding.toScaledENU);
result.fromScaledENU = Matrix4_default.clone(encoding.fromScaledENU);
result.matrix = Matrix4_default.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;
};
var TerrainEncoding_default = TerrainEncoding;
// node_modules/@cesium/engine/Source/Core/HeightmapTessellator.js
var HeightmapTessellator = {};
HeightmapTessellator.DEFAULT_STRUCTURE = Object.freeze({
heightScale: 1,
heightOffset: 0,
elementsPerHeight: 1,
stride: 1,
elementMultiplier: 256,
isBigEndian: false
});
var cartesian3Scratch8 = new Cartesian3_default();
var matrix4Scratch3 = new Matrix4_default();
var minimumScratch = new Cartesian3_default();
var maximumScratch = new Cartesian3_default();
HeightmapTessellator.computeVertices = function(options) {
if (!defined_default(options) || !defined_default(options.heightmap)) {
throw new DeveloperError_default("options.heightmap is required.");
}
if (!defined_default(options.width) || !defined_default(options.height)) {
throw new DeveloperError_default("options.width and options.height are required.");
}
if (!defined_default(options.nativeRectangle)) {
throw new DeveloperError_default("options.nativeRectangle is required.");
}
if (!defined_default(options.skirtHeight)) {
throw new DeveloperError_default("options.skirtHeight is required.");
}
const cos4 = Math.cos;
const sin4 = Math.sin;
const sqrt2 = Math.sqrt;
const atan = Math.atan;
const exp = Math.exp;
const piOverTwo = Math_default.PI_OVER_TWO;
const toRadians = Math_default.toRadians;
const heightmap = options.heightmap;
const width = options.width;
const height = options.height;
const skirtHeight = options.skirtHeight;
const hasSkirts = skirtHeight > 0;
const isGeographic = defaultValue_default(options.isGeographic, true);
const ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
const oneOverGlobeSemimajorAxis = 1 / ellipsoid.maximumRadius;
const nativeRectangle = Rectangle_default.clone(options.nativeRectangle);
const rectangle = Rectangle_default.clone(options.rectangle);
let geographicWest;
let geographicSouth;
let geographicEast;
let geographicNorth;
if (!defined_default(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 * atan(exp(-nativeRectangle.south * oneOverGlobeSemimajorAxis));
geographicEast = nativeRectangle.east * oneOverGlobeSemimajorAxis;
geographicNorth = piOverTwo - 2 * 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_default(relativeToCenter);
relativeToCenter = hasRelativeToCenter ? relativeToCenter : Cartesian3_default.ZERO;
const includeWebMercatorT = defaultValue_default(options.includeWebMercatorT, false);
const exaggeration = defaultValue_default(options.exaggeration, 1);
const exaggerationRelativeHeight = defaultValue_default(
options.exaggerationRelativeHeight,
0
);
const hasExaggeration = exaggeration !== 1;
const includeGeodeticSurfaceNormals = hasExaggeration;
const structure = defaultValue_default(
options.structure,
HeightmapTessellator.DEFAULT_STRUCTURE
);
const heightScale = defaultValue_default(
structure.heightScale,
HeightmapTessellator.DEFAULT_STRUCTURE.heightScale
);
const heightOffset = defaultValue_default(
structure.heightOffset,
HeightmapTessellator.DEFAULT_STRUCTURE.heightOffset
);
const elementsPerHeight = defaultValue_default(
structure.elementsPerHeight,
HeightmapTessellator.DEFAULT_STRUCTURE.elementsPerHeight
);
const stride = defaultValue_default(
structure.stride,
HeightmapTessellator.DEFAULT_STRUCTURE.stride
);
const elementMultiplier = defaultValue_default(
structure.elementMultiplier,
HeightmapTessellator.DEFAULT_STRUCTURE.elementMultiplier
);
const isBigEndian = defaultValue_default(
structure.isBigEndian,
HeightmapTessellator.DEFAULT_STRUCTURE.isBigEndian
);
let rectangleWidth = Rectangle_default.computeWidth(nativeRectangle);
let rectangleHeight = Rectangle_default.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;
let maximumHeight = -65536;
const fromENU = Transforms_default.eastNorthUpToFixedFrame(
relativeToCenter,
ellipsoid
);
const toENU = Matrix4_default.inverseTransformation(fromENU, matrix4Scratch3);
let southMercatorY;
let oneOverMercatorHeight;
if (includeWebMercatorT) {
southMercatorY = WebMercatorProjection_default.geodeticLatitudeToMercatorAngle(
geographicSouth
);
oneOverMercatorHeight = 1 / (WebMercatorProjection_default.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 ? 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 = 1e-5;
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 * atan(exp(-latitude * oneOverGlobeSemimajorAxis));
} else {
latitude = toRadians(latitude);
}
let v7 = (latitude - geographicSouth) / (geographicNorth - geographicSouth);
v7 = Math_default.clamp(v7, 0, 1);
const isNorthEdge = rowIndex === startRow;
const isSouthEdge = rowIndex === endRow - 1;
if (skirtHeight > 0) {
if (isNorthEdge) {
latitude += skirtOffsetPercentage * rectangleHeight;
} else if (isSouthEdge) {
latitude -= skirtOffsetPercentage * rectangleHeight;
}
}
const cosLatitude = cos4(latitude);
const nZ = sin4(latitude);
const kZ = radiiSquaredZ * nZ;
let webMercatorT;
if (includeWebMercatorT) {
webMercatorT = (WebMercatorProjection_default.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 u3 = (longitude - geographicWest) / (geographicEast - geographicWest);
u3 = Math_default.clamp(u3, 0, 1);
let index = row * width + col;
if (skirtHeight > 0) {
const isWestEdge = colIndex === startCol;
const isEastEdge = colIndex === endCol - 1;
const isEdge2 = isNorthEdge || isSouthEdge || isWestEdge || isEastEdge;
const isCorner = (isNorthEdge || isSouthEdge) && (isWestEdge || isEastEdge);
if (isCorner) {
continue;
} else if (isEdge2) {
heightSample -= skirtHeight;
if (isWestEdge) {
index = gridVertexCount + (height - row - 1);
longitude -= skirtOffsetPercentage * rectangleWidth;
} else if (isSouthEdge) {
index = gridVertexCount + height + (width - col - 1);
} else if (isEastEdge) {
index = gridVertexCount + height + width + row;
longitude += skirtOffsetPercentage * rectangleWidth;
} else if (isNorthEdge) {
index = gridVertexCount + height + width + height + col;
}
}
}
const nX = cosLatitude * cos4(longitude);
const nY = cosLatitude * sin4(longitude);
const kX = radiiSquaredX * nX;
const kY = radiiSquaredY * nY;
const gamma = sqrt2(kX * nX + kY * nY + kZ * nZ);
const oneOverGamma = 1 / gamma;
const rSurfaceX = kX * oneOverGamma;
const rSurfaceY = kY * oneOverGamma;
const rSurfaceZ = kZ * oneOverGamma;
const position = new Cartesian3_default();
position.x = rSurfaceX + nX * heightSample;
position.y = rSurfaceY + nY * heightSample;
position.z = rSurfaceZ + nZ * heightSample;
Matrix4_default.multiplyByPoint(toENU, position, cartesian3Scratch8);
Cartesian3_default.minimumByComponent(cartesian3Scratch8, minimum, minimum);
Cartesian3_default.maximumByComponent(cartesian3Scratch8, maximum, maximum);
hMin = Math.min(hMin, heightSample);
positions[index] = position;
uvs[index] = new Cartesian2_default(u3, v7);
heights[index] = heightSample;
if (includeWebMercatorT) {
webMercatorTs[index] = webMercatorT;
}
if (includeGeodeticSurfaceNormals) {
geodeticSurfaceNormals[index] = ellipsoid.geodeticSurfaceNormal(
position
);
}
}
}
const boundingSphere3D = BoundingSphere_default.fromPoints(positions);
let orientedBoundingBox;
if (defined_default(rectangle)) {
orientedBoundingBox = OrientedBoundingBox_default.fromRectangle(
rectangle,
minimumHeight,
maximumHeight,
ellipsoid
);
}
let occludeePointInScaledSpace;
if (hasRelativeToCenter) {
const occluder = new EllipsoidalOccluder_default(ellipsoid);
occludeePointInScaledSpace = occluder.computeHorizonCullingPointPossiblyUnderEllipsoid(
relativeToCenter,
positions,
minimumHeight
);
}
const aaBox = new AxisAlignedBoundingBox_default(minimum, maximum, relativeToCenter);
const encoding = new TerrainEncoding_default(
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],
void 0,
webMercatorTs[j],
geodeticSurfaceNormals[j]
);
}
return {
vertices,
maximumHeight,
minimumHeight,
encoding,
boundingSphere3D,
orientedBoundingBox,
occludeePointInScaledSpace
};
};
var HeightmapTessellator_default = HeightmapTessellator;
// node_modules/@cesium/engine/Source/Core/TerrainData.js
function TerrainData() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(TerrainData.prototype, {
credits: {
get: DeveloperError_default.throwInstantiationError
},
waterMask: {
get: DeveloperError_default.throwInstantiationError
}
});
TerrainData.prototype.interpolateHeight = DeveloperError_default.throwInstantiationError;
TerrainData.prototype.isChildAvailable = DeveloperError_default.throwInstantiationError;
TerrainData.prototype.createMesh = DeveloperError_default.throwInstantiationError;
TerrainData.prototype.upsample = DeveloperError_default.throwInstantiationError;
TerrainData.prototype.wasCreatedByUpsampling = DeveloperError_default.throwInstantiationError;
TerrainData.maximumAsynchronousTasks = 5;
var TerrainData_default = TerrainData;
// node_modules/@cesium/engine/Source/Core/TerrainMesh.js
function TerrainMesh(center, vertices, indices2, indexCountWithoutSkirts, vertexCountWithoutSkirts, minimumHeight, maximumHeight, boundingSphere3D, occludeePointInScaledSpace, vertexStride, orientedBoundingBox, encoding, westIndicesSouthToNorth, southIndicesEastToWest, eastIndicesNorthToSouth, northIndicesWestToEast) {
this.center = center;
this.vertices = vertices;
this.stride = defaultValue_default(vertexStride, 6);
this.indices = indices2;
this.indexCountWithoutSkirts = indexCountWithoutSkirts;
this.vertexCountWithoutSkirts = vertexCountWithoutSkirts;
this.minimumHeight = minimumHeight;
this.maximumHeight = maximumHeight;
this.boundingSphere3D = boundingSphere3D;
this.occludeePointInScaledSpace = occludeePointInScaledSpace;
this.orientedBoundingBox = orientedBoundingBox;
this.encoding = encoding;
this.westIndicesSouthToNorth = westIndicesSouthToNorth;
this.southIndicesEastToWest = southIndicesEastToWest;
this.eastIndicesNorthToSouth = eastIndicesNorthToSouth;
this.northIndicesWestToEast = northIndicesWestToEast;
}
var TerrainMesh_default = TerrainMesh;
// node_modules/@cesium/engine/Source/Core/TerrainProvider.js
function TerrainProvider() {
DeveloperError_default.throwInstantiationError();
}
Object.defineProperties(TerrainProvider.prototype, {
errorEvent: {
get: DeveloperError_default.throwInstantiationError
},
credit: {
get: DeveloperError_default.throwInstantiationError
},
tilingScheme: {
get: DeveloperError_default.throwInstantiationError
},
ready: {
get: DeveloperError_default.throwInstantiationError
},
readyPromise: {
get: DeveloperError_default.throwInstantiationError
},
hasWaterMask: {
get: DeveloperError_default.throwInstantiationError
},
hasVertexNormals: {
get: DeveloperError_default.throwInstantiationError
},
availability: {
get: DeveloperError_default.throwInstantiationError
}
});
var regularGridIndicesCache = [];
TerrainProvider.getRegularGridIndices = function(width, height) {
if (width * height >= Math_default.FOUR_GIGABYTES) {
throw new DeveloperError_default(
"The total number of vertices (width * height) must be less than 4,294,967,296."
);
}
let byWidth = regularGridIndicesCache[width];
if (!defined_default(byWidth)) {
regularGridIndicesCache[width] = byWidth = [];
}
let indices2 = byWidth[height];
if (!defined_default(indices2)) {
if (width * height < Math_default.SIXTY_FOUR_KILOBYTES) {
indices2 = byWidth[height] = new Uint16Array(
(width - 1) * (height - 1) * 6
);
} else {
indices2 = byWidth[height] = new Uint32Array(
(width - 1) * (height - 1) * 6
);
}
addRegularGridIndices(width, height, indices2, 0);
}
return indices2;
};
var regularGridAndEdgeIndicesCache = [];
TerrainProvider.getRegularGridIndicesAndEdgeIndices = function(width, height) {
if (width * height >= Math_default.FOUR_GIGABYTES) {
throw new DeveloperError_default(
"The total number of vertices (width * height) must be less than 4,294,967,296."
);
}
let byWidth = regularGridAndEdgeIndicesCache[width];
if (!defined_default(byWidth)) {
regularGridAndEdgeIndicesCache[width] = byWidth = [];
}
let indicesAndEdges = byWidth[height];
if (!defined_default(indicesAndEdges)) {
const indices2 = 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: indices2,
westIndicesSouthToNorth,
southIndicesEastToWest,
eastIndicesNorthToSouth,
northIndicesWestToEast
};
}
return indicesAndEdges;
};
var regularGridAndSkirtAndEdgeIndicesCache = [];
TerrainProvider.getRegularGridAndSkirtIndicesAndEdgeIndices = function(width, height) {
if (width * height >= Math_default.FOUR_GIGABYTES) {
throw new DeveloperError_default(
"The total number of vertices (width * height) must be less than 4,294,967,296."
);
}
let byWidth = regularGridAndSkirtAndEdgeIndicesCache[width];
if (!defined_default(byWidth)) {
regularGridAndSkirtAndEdgeIndicesCache[width] = byWidth = [];
}
let indicesAndEdges = byWidth[height];
if (!defined_default(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 indices2 = IndexDatatype_default.createTypedArray(vertexCount, indexCount);
addRegularGridIndices(width, height, indices2, 0);
TerrainProvider.addSkirtIndices(
westIndicesSouthToNorth,
southIndicesEastToWest,
eastIndicesNorthToSouth,
northIndicesWestToEast,
gridVertexCount,
indices2,
gridIndexCount
);
indicesAndEdges = byWidth[height] = {
indices: indices2,
westIndicesSouthToNorth,
southIndicesEastToWest,
eastIndicesNorthToSouth,
northIndicesWestToEast,
indexCountWithoutSkirts: gridIndexCount
};
}
return indicesAndEdges;
};
TerrainProvider.addSkirtIndices = function(westIndicesSouthToNorth, southIndicesEastToWest, eastIndicesNorthToSouth, northIndicesWestToEast, vertexCount, indices2, offset2) {
let vertexIndex = vertexCount;
offset2 = addSkirtIndices(
westIndicesSouthToNorth,
vertexIndex,
indices2,
offset2
);
vertexIndex += westIndicesSouthToNorth.length;
offset2 = addSkirtIndices(
southIndicesEastToWest,
vertexIndex,
indices2,
offset2
);
vertexIndex += southIndicesEastToWest.length;
offset2 = addSkirtIndices(
eastIndicesNorthToSouth,
vertexIndex,
indices2,
offset2
);
vertexIndex += eastIndicesNorthToSouth.length;
addSkirtIndices(northIndicesWestToEast, vertexIndex, indices2, offset2);
};
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,
southIndicesEastToWest,
eastIndicesNorthToSouth,
northIndicesWestToEast
};
}
function addRegularGridIndices(width, height, indices2, offset2) {
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;
indices2[offset2++] = upperLeft;
indices2[offset2++] = lowerLeft;
indices2[offset2++] = upperRight;
indices2[offset2++] = upperRight;
indices2[offset2++] = lowerLeft;
indices2[offset2++] = lowerRight;
++index;
}
++index;
}
}
function addSkirtIndices(edgeIndices, vertexIndex, indices2, offset2) {
let previousIndex = edgeIndices[0];
const length3 = edgeIndices.length;
for (let i = 1; i < length3; ++i) {
const index = edgeIndices[i];
indices2[offset2++] = previousIndex;
indices2[offset2++] = index;
indices2[offset2++] = vertexIndex;
indices2[offset2++] = vertexIndex;
indices2[offset2++] = index;
indices2[offset2++] = vertexIndex + 1;
previousIndex = index;
++vertexIndex;
}
return offset2;
}
TerrainProvider.heightmapTerrainQuality = 0.25;
TerrainProvider.getEstimatedLevelZeroGeometricErrorForAHeightmap = function(ellipsoid, tileImageWidth, numberOfTilesAtLevelZero) {
return ellipsoid.maximumRadius * 2 * Math.PI * TerrainProvider.heightmapTerrainQuality / (tileImageWidth * numberOfTilesAtLevelZero);
};
TerrainProvider.prototype.requestTileGeometry = DeveloperError_default.throwInstantiationError;
TerrainProvider.prototype.getLevelMaximumGeometricError = DeveloperError_default.throwInstantiationError;
TerrainProvider.prototype.getTileDataAvailable = DeveloperError_default.throwInstantiationError;
TerrainProvider.prototype.loadTileDataAvailability = DeveloperError_default.throwInstantiationError;
var TerrainProvider_default = TerrainProvider;
// node_modules/@cesium/engine/Source/Core/HeightmapTerrainData.js
function HeightmapTerrainData(options) {
if (!defined_default(options) || !defined_default(options.buffer)) {
throw new DeveloperError_default("options.buffer is required.");
}
if (!defined_default(options.width)) {
throw new DeveloperError_default("options.width is required.");
}
if (!defined_default(options.height)) {
throw new DeveloperError_default("options.height is required.");
}
this._buffer = options.buffer;
this._width = options.width;
this._height = options.height;
this._childTileMask = defaultValue_default(options.childTileMask, 15);
this._encoding = defaultValue_default(options.encoding, HeightmapEncoding_default.NONE);
const defaultStructure = HeightmapTessellator_default.DEFAULT_STRUCTURE;
let structure = options.structure;
if (!defined_default(structure)) {
structure = defaultStructure;
} else if (structure !== defaultStructure) {
structure.heightScale = defaultValue_default(
structure.heightScale,
defaultStructure.heightScale
);
structure.heightOffset = defaultValue_default(
structure.heightOffset,
defaultStructure.heightOffset
);
structure.elementsPerHeight = defaultValue_default(
structure.elementsPerHeight,
defaultStructure.elementsPerHeight
);
structure.stride = defaultValue_default(structure.stride, defaultStructure.stride);
structure.elementMultiplier = defaultValue_default(
structure.elementMultiplier,
defaultStructure.elementMultiplier
);
structure.isBigEndian = defaultValue_default(
structure.isBigEndian,
defaultStructure.isBigEndian
);
}
this._structure = structure;
this._createdByUpsampling = defaultValue_default(options.createdByUpsampling, false);
this._waterMask = options.waterMask;
this._skirtHeight = void 0;
this._bufferType = this._encoding === HeightmapEncoding_default.LERC ? Float32Array : this._buffer.constructor;
this._mesh = void 0;
}
Object.defineProperties(HeightmapTerrainData.prototype, {
credits: {
get: function() {
return void 0;
}
},
waterMask: {
get: function() {
return this._waterMask;
}
},
childTileMask: {
get: function() {
return this._childTileMask;
}
}
});
var createMeshTaskName = "createVerticesFromHeightmap";
var createMeshTaskProcessorNoThrottle = new TaskProcessor_default(createMeshTaskName);
var createMeshTaskProcessorThrottle = new TaskProcessor_default(
createMeshTaskName,
TerrainData_default.maximumAsynchronousTasks
);
HeightmapTerrainData.prototype.createMesh = function(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
Check_default.typeOf.object("options.tilingScheme", options.tilingScheme);
Check_default.typeOf.number("options.x", options.x);
Check_default.typeOf.number("options.y", options.y);
Check_default.typeOf.number("options.level", options.level);
const tilingScheme2 = options.tilingScheme;
const x = options.x;
const y = options.y;
const level = options.level;
const exaggeration = defaultValue_default(options.exaggeration, 1);
const exaggerationRelativeHeight = defaultValue_default(
options.exaggerationRelativeHeight,
0
);
const throttle = defaultValue_default(options.throttle, true);
const ellipsoid = tilingScheme2.ellipsoid;
const nativeRectangle = tilingScheme2.tileXYToNativeRectangle(x, y, level);
const rectangle = tilingScheme2.tileXYToRectangle(x, y, level);
const center = ellipsoid.cartographicToCartesian(Rectangle_default.center(rectangle));
const structure = this._structure;
const levelZeroMaxError = TerrainProvider_default.getEstimatedLevelZeroGeometricErrorForAHeightmap(
ellipsoid,
this._width,
tilingScheme2.getNumberOfXTilesAtLevel(0)
);
const thisLevelMaxError = levelZeroMaxError / (1 << level);
this._skirtHeight = Math.min(thisLevelMaxError * 4, 1e3);
const createMeshTaskProcessor = throttle ? createMeshTaskProcessorThrottle : createMeshTaskProcessorNoThrottle;
const verticesPromise = createMeshTaskProcessor.scheduleTask({
heightmap: this._buffer,
structure,
includeWebMercatorT: true,
width: this._width,
height: this._height,
nativeRectangle,
rectangle,
relativeToCenter: center,
ellipsoid,
skirtHeight: this._skirtHeight,
isGeographic: tilingScheme2.projection instanceof GeographicProjection_default,
exaggeration,
exaggerationRelativeHeight,
encoding: this._encoding
});
if (!defined_default(verticesPromise)) {
return void 0;
}
const that = this;
return Promise.resolve(verticesPromise).then(function(result) {
let indicesAndEdges;
if (that._skirtHeight > 0) {
indicesAndEdges = TerrainProvider_default.getRegularGridAndSkirtIndicesAndEdgeIndices(
result.gridWidth,
result.gridHeight
);
} else {
indicesAndEdges = TerrainProvider_default.getRegularGridIndicesAndEdgeIndices(
result.gridWidth,
result.gridHeight
);
}
const vertexCountWithoutSkirts = result.gridWidth * result.gridHeight;
that._mesh = new TerrainMesh_default(
center,
new Float32Array(result.vertices),
indicesAndEdges.indices,
indicesAndEdges.indexCountWithoutSkirts,
vertexCountWithoutSkirts,
result.minimumHeight,
result.maximumHeight,
BoundingSphere_default.clone(result.boundingSphere3D),
Cartesian3_default.clone(result.occludeePointInScaledSpace),
result.numberOfAttributes,
OrientedBoundingBox_default.clone(result.orientedBoundingBox),
TerrainEncoding_default.clone(result.encoding),
indicesAndEdges.westIndicesSouthToNorth,
indicesAndEdges.southIndicesEastToWest,
indicesAndEdges.eastIndicesNorthToSouth,
indicesAndEdges.northIndicesWestToEast
);
that._buffer = void 0;
return that._mesh;
});
};
HeightmapTerrainData.prototype._createMeshSync = function(options) {
Check_default.typeOf.object("options.tilingScheme", options.tilingScheme);
Check_default.typeOf.number("options.x", options.x);
Check_default.typeOf.number("options.y", options.y);
Check_default.typeOf.number("options.level", options.level);
const tilingScheme2 = options.tilingScheme;
const x = options.x;
const y = options.y;
const level = options.level;
const exaggeration = defaultValue_default(options.exaggeration, 1);
const exaggerationRelativeHeight = defaultValue_default(
options.exaggerationRelativeHeight,
0
);
const ellipsoid = tilingScheme2.ellipsoid;
const nativeRectangle = tilingScheme2.tileXYToNativeRectangle(x, y, level);
const rectangle = tilingScheme2.tileXYToRectangle(x, y, level);
const center = ellipsoid.cartographicToCartesian(Rectangle_default.center(rectangle));
const structure = this._structure;
const levelZeroMaxError = TerrainProvider_default.getEstimatedLevelZeroGeometricErrorForAHeightmap(
ellipsoid,
this._width,
tilingScheme2.getNumberOfXTilesAtLevel(0)
);
const thisLevelMaxError = levelZeroMaxError / (1 << level);
this._skirtHeight = Math.min(thisLevelMaxError * 4, 1e3);
const result = HeightmapTessellator_default.computeVertices({
heightmap: this._buffer,
structure,
includeWebMercatorT: true,
width: this._width,
height: this._height,
nativeRectangle,
rectangle,
relativeToCenter: center,
ellipsoid,
skirtHeight: this._skirtHeight,
isGeographic: tilingScheme2.projection instanceof GeographicProjection_default,
exaggeration,
exaggerationRelativeHeight
});
this._buffer = void 0;
let indicesAndEdges;
if (this._skirtHeight > 0) {
indicesAndEdges = TerrainProvider_default.getRegularGridAndSkirtIndicesAndEdgeIndices(
this._width,
this._height
);
} else {
indicesAndEdges = TerrainProvider_default.getRegularGridIndicesAndEdgeIndices(
this._width,
this._height
);
}
const vertexCountWithoutSkirts = result.gridWidth * result.gridHeight;
this._mesh = new TerrainMesh_default(
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;
};
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_default(this._mesh);
const isLERCEncoding = this._encoding === HeightmapEncoding_default.LERC;
const isInterpolationImpossible = !isMeshCreated && isLERCEncoding;
if (isInterpolationImpossible) {
return void 0;
}
let heightSample;
if (isMeshCreated) {
const buffer = this._mesh.vertices;
const encoding = this._mesh.encoding;
heightSample = interpolateMeshHeight(
buffer,
encoding,
heightOffset,
heightScale,
rectangle,
width,
height,
longitude,
latitude
);
} else {
heightSample = interpolateHeight(
this._buffer,
elementsPerHeight,
elementMultiplier,
stride,
isBigEndian,
rectangle,
width,
height,
longitude,
latitude
);
heightSample = heightSample * heightScale + heightOffset;
}
return heightSample;
};
HeightmapTerrainData.prototype.upsample = function(tilingScheme2, thisX, thisY, thisLevel, descendantX, descendantY, descendantLevel) {
if (!defined_default(tilingScheme2)) {
throw new DeveloperError_default("tilingScheme is required.");
}
if (!defined_default(thisX)) {
throw new DeveloperError_default("thisX is required.");
}
if (!defined_default(thisY)) {
throw new DeveloperError_default("thisY is required.");
}
if (!defined_default(thisLevel)) {
throw new DeveloperError_default("thisLevel is required.");
}
if (!defined_default(descendantX)) {
throw new DeveloperError_default("descendantX is required.");
}
if (!defined_default(descendantY)) {
throw new DeveloperError_default("descendantY is required.");
}
if (!defined_default(descendantLevel)) {
throw new DeveloperError_default("descendantLevel is required.");
}
const levelDifference = descendantLevel - thisLevel;
if (levelDifference > 1) {
throw new DeveloperError_default(
"Upsampling through more than one level at a time is not currently supported."
);
}
const meshData = this._mesh;
if (!defined_default(meshData)) {
return void 0;
}
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;
const sourceRectangle = tilingScheme2.tileXYToRectangle(
thisX,
thisY,
thisLevel
);
const destinationRectangle = tilingScheme2.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 = Math_default.lerp(
destinationRectangle.north,
destinationRectangle.south,
j / (height - 1)
);
for (let i = 0; i < width; ++i) {
const longitude = Math_default.lerp(
destinationRectangle.west,
destinationRectangle.east,
i / (width - 1)
);
let heightSample = interpolateMeshHeight(
buffer,
encoding,
heightOffset,
heightScale,
sourceRectangle,
width,
height,
longitude,
latitude
);
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,
height,
childTileMask: 0,
structure: this._structure,
createdByUpsampling: true
})
);
};
HeightmapTerrainData.prototype.isChildAvailable = function(thisX, thisY, childX, childY) {
if (!defined_default(thisX)) {
throw new DeveloperError_default("thisX is required.");
}
if (!defined_default(thisY)) {
throw new DeveloperError_default("thisY is required.");
}
if (!defined_default(childX)) {
throw new DeveloperError_default("childX is required.");
}
if (!defined_default(childY)) {
throw new DeveloperError_default("childY is required.");
}
let bitNumber = 2;
if (childX !== thisX * 2) {
++bitNumber;
}
if (childY !== thisY * 2) {
bitNumber -= 2;
}
return (this._childTileMask & 1 << bitNumber) !== 0;
};
HeightmapTerrainData.prototype.wasCreatedByUpsampling = function() {
return this._createdByUpsampling;
};
function interpolateHeight(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(buffer, encoding, heightOffset, heightScale, 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 = (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) {
if (dY < dX) {
return southwestHeight + dX * (southeastHeight - southwestHeight) + dY * (northeastHeight - southeastHeight);
}
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;
}
var HeightmapTerrainData_default = HeightmapTerrainData;
// node_modules/@cesium/engine/Source/Core/EllipsoidTerrainProvider.js
function EllipsoidTerrainProvider(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._tilingScheme = options.tilingScheme;
if (!defined_default(this._tilingScheme)) {
this._tilingScheme = new GeographicTilingScheme_default({
ellipsoid: defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84)
});
}
this._levelZeroMaximumGeometricError = TerrainProvider_default.getEstimatedLevelZeroGeometricErrorForAHeightmap(
this._tilingScheme.ellipsoid,
64,
this._tilingScheme.getNumberOfXTilesAtLevel(0)
);
this._errorEvent = new Event_default();
this._ready = true;
this._readyPromise = Promise.resolve(true);
}
Object.defineProperties(EllipsoidTerrainProvider.prototype, {
errorEvent: {
get: function() {
return this._errorEvent;
}
},
credit: {
get: function() {
return void 0;
}
},
tilingScheme: {
get: function() {
return this._tilingScheme;
}
},
ready: {
get: function() {
deprecationWarning_default(
"EllipsoidTerrainProvider.ready",
"EllipsoidTerrainProvider.ready was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107."
);
return true;
}
},
readyPromise: {
get: function() {
deprecationWarning_default(
"EllipsoidTerrainProvider.readyPromise",
"EllipsoidTerrainProvider.readyPromise was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107."
);
return this._readyPromise;
}
},
hasWaterMask: {
get: function() {
return false;
}
},
hasVertexNormals: {
get: function() {
return false;
}
},
availability: {
get: function() {
return void 0;
}
}
});
EllipsoidTerrainProvider.prototype.requestTileGeometry = function(x, y, level, request) {
const width = 16;
const height = 16;
return Promise.resolve(
new HeightmapTerrainData_default({
buffer: new Uint8Array(width * height),
width,
height
})
);
};
EllipsoidTerrainProvider.prototype.getLevelMaximumGeometricError = function(level) {
return this._levelZeroMaximumGeometricError / (1 << level);
};
EllipsoidTerrainProvider.prototype.getTileDataAvailable = function(x, y, level) {
return void 0;
};
EllipsoidTerrainProvider.prototype.loadTileDataAvailability = function(x, y, level) {
return void 0;
};
var EllipsoidTerrainProvider_default = EllipsoidTerrainProvider;
// node_modules/@cesium/engine/Source/Shaders/GlobeFS.js
var GlobeFS_default = `uniform vec4 u_initialColor;
#if TEXTURE_UNITS > 0
uniform sampler2D u_dayTextures[TEXTURE_UNITS];
uniform vec4 u_dayTextureTranslationAndScale[TEXTURE_UNITS];
uniform bool u_dayTextureUseWebMercatorT[TEXTURE_UNITS];
#ifdef APPLY_ALPHA
uniform float u_dayTextureAlpha[TEXTURE_UNITS];
#endif
#ifdef APPLY_DAY_NIGHT_ALPHA
uniform float u_dayTextureNightAlpha[TEXTURE_UNITS];
uniform float u_dayTextureDayAlpha[TEXTURE_UNITS];
#endif
#ifdef APPLY_SPLIT
uniform float u_dayTextureSplit[TEXTURE_UNITS];
#endif
#ifdef APPLY_BRIGHTNESS
uniform float u_dayTextureBrightness[TEXTURE_UNITS];
#endif
#ifdef APPLY_CONTRAST
uniform float u_dayTextureContrast[TEXTURE_UNITS];
#endif
#ifdef APPLY_HUE
uniform float u_dayTextureHue[TEXTURE_UNITS];
#endif
#ifdef APPLY_SATURATION
uniform float u_dayTextureSaturation[TEXTURE_UNITS];
#endif
#ifdef APPLY_GAMMA
uniform float u_dayTextureOneOverGamma[TEXTURE_UNITS];
#endif
#ifdef APPLY_IMAGERY_CUTOUT
uniform vec4 u_dayTextureCutoutRectangles[TEXTURE_UNITS];
#endif
#ifdef APPLY_COLOR_TO_ALPHA
uniform vec4 u_colorsToAlpha[TEXTURE_UNITS];
#endif
uniform vec4 u_dayTextureTexCoordsRectangle[TEXTURE_UNITS];
#endif
#ifdef SHOW_REFLECTIVE_OCEAN
uniform sampler2D u_waterMask;
uniform vec4 u_waterMaskTranslationAndScale;
uniform float u_zoomedOutOceanSpecularIntensity;
#endif
#ifdef SHOW_OCEAN_WAVES
uniform sampler2D u_oceanNormalMap;
#endif
#if defined(ENABLE_DAYNIGHT_SHADING) || defined(GROUND_ATMOSPHERE)
uniform vec2 u_lightingFadeDistance;
#endif
#ifdef TILE_LIMIT_RECTANGLE
uniform vec4 u_cartographicLimitRectangle;
#endif
#ifdef GROUND_ATMOSPHERE
uniform vec2 u_nightFadeDistance;
#endif
#ifdef ENABLE_CLIPPING_PLANES
uniform highp sampler2D u_clippingPlanes;
uniform mat4 u_clippingPlanesMatrix;
uniform vec4 u_clippingPlanesEdgeStyle;
#endif
#if defined(GROUND_ATMOSPHERE) || defined(FOG) && defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING))
uniform float u_minimumBrightness;
#endif
#ifdef COLOR_CORRECT
uniform vec3 u_hsbShift; // Hue, saturation, brightness
#endif
#ifdef HIGHLIGHT_FILL_TILE
uniform vec4 u_fillHighlightColor;
#endif
#ifdef TRANSLUCENT
uniform vec4 u_frontFaceAlphaByDistance;
uniform vec4 u_backFaceAlphaByDistance;
uniform vec4 u_translucencyRectangle;
#endif
#ifdef UNDERGROUND_COLOR
uniform vec4 u_undergroundColor;
uniform vec4 u_undergroundColorAlphaByDistance;
#endif
#ifdef ENABLE_VERTEX_LIGHTING
uniform float u_lambertDiffuseMultiplier;
uniform float u_vertexShadowDarkness;
#endif
in vec3 v_positionMC;
in vec3 v_positionEC;
in vec3 v_textureCoordinates;
in vec3 v_normalMC;
in vec3 v_normalEC;
#ifdef APPLY_MATERIAL
in float v_height;
in float v_slope;
in float v_aspect;
#endif
#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)
in float v_distance;
#endif
#if defined(GROUND_ATMOSPHERE) || defined(FOG)
in vec3 v_atmosphereRayleighColor;
in vec3 v_atmosphereMieColor;
in float v_atmosphereOpacity;
#endif
#if defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)
float interpolateByDistance(vec4 nearFarScalar, float distance)
{
float startDistance = nearFarScalar.x;
float startValue = nearFarScalar.y;
float endDistance = nearFarScalar.z;
float endValue = nearFarScalar.w;
float t = clamp((distance - startDistance) / (endDistance - startDistance), 0.0, 1.0);
return mix(startValue, endValue, t);
}
#endif
#if defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT) || defined(APPLY_MATERIAL)
vec4 alphaBlend(vec4 sourceColor, vec4 destinationColor)
{
return sourceColor * vec4(sourceColor.aaa, 1.0) + destinationColor * (1.0 - sourceColor.a);
}
#endif
#ifdef TRANSLUCENT
bool inTranslucencyRectangle()
{
return
v_textureCoordinates.x > u_translucencyRectangle.x &&
v_textureCoordinates.x < u_translucencyRectangle.z &&
v_textureCoordinates.y > u_translucencyRectangle.y &&
v_textureCoordinates.y < u_translucencyRectangle.w;
}
#endif
vec4 sampleAndBlend(
vec4 previousColor,
sampler2D textureToSample,
vec2 tileTextureCoordinates,
vec4 textureCoordinateRectangle,
vec4 textureCoordinateTranslationAndScale,
float textureAlpha,
float textureNightAlpha,
float textureDayAlpha,
float textureBrightness,
float textureContrast,
float textureHue,
float textureSaturation,
float textureOneOverGamma,
float split,
vec4 colorToAlpha,
float nightBlend)
{
// This crazy step stuff sets the alpha to 0.0 if this following condition is true:
// tileTextureCoordinates.s < textureCoordinateRectangle.s ||
// tileTextureCoordinates.s > textureCoordinateRectangle.p ||
// tileTextureCoordinates.t < textureCoordinateRectangle.t ||
// tileTextureCoordinates.t > textureCoordinateRectangle.q
// In other words, the alpha is zero if the fragment is outside the rectangle
// covered by this texture. Would an actual 'if' yield better performance?
vec2 alphaMultiplier = step(textureCoordinateRectangle.st, tileTextureCoordinates);
textureAlpha = textureAlpha * alphaMultiplier.x * alphaMultiplier.y;
alphaMultiplier = step(vec2(0.0), textureCoordinateRectangle.pq - tileTextureCoordinates);
textureAlpha = textureAlpha * alphaMultiplier.x * alphaMultiplier.y;
#if defined(APPLY_DAY_NIGHT_ALPHA) && defined(ENABLE_DAYNIGHT_SHADING)
textureAlpha *= mix(textureDayAlpha, textureNightAlpha, nightBlend);
#endif
vec2 translation = textureCoordinateTranslationAndScale.xy;
vec2 scale = textureCoordinateTranslationAndScale.zw;
vec2 textureCoordinates = tileTextureCoordinates * scale + translation;
vec4 value = texture(textureToSample, textureCoordinates);
vec3 color = value.rgb;
float alpha = value.a;
#ifdef APPLY_COLOR_TO_ALPHA
vec3 colorDiff = abs(color.rgb - colorToAlpha.rgb);
colorDiff.r = max(max(colorDiff.r, colorDiff.g), colorDiff.b);
alpha = czm_branchFreeTernary(colorDiff.r < colorToAlpha.a, 0.0, alpha);
#endif
#if !defined(APPLY_GAMMA)
vec4 tempColor = czm_gammaCorrect(vec4(color, alpha));
color = tempColor.rgb;
alpha = tempColor.a;
#else
color = pow(color, vec3(textureOneOverGamma));
#endif
#ifdef APPLY_SPLIT
float splitPosition = czm_splitPosition;
// Split to the left
if (split < 0.0 && gl_FragCoord.x > splitPosition) {
alpha = 0.0;
}
// Split to the right
else if (split > 0.0 && gl_FragCoord.x < splitPosition) {
alpha = 0.0;
}
#endif
#ifdef APPLY_BRIGHTNESS
color = mix(vec3(0.0), color, textureBrightness);
#endif
#ifdef APPLY_CONTRAST
color = mix(vec3(0.5), color, textureContrast);
#endif
#ifdef APPLY_HUE
color = czm_hue(color, textureHue);
#endif
#ifdef APPLY_SATURATION
color = czm_saturation(color, textureSaturation);
#endif
float sourceAlpha = alpha * textureAlpha;
float outAlpha = mix(previousColor.a, 1.0, sourceAlpha);
outAlpha += sign(outAlpha) - 1.0;
vec3 outColor = mix(previousColor.rgb * previousColor.a, color, sourceAlpha) / outAlpha;
// When rendering imagery for a tile in multiple passes,
// some GPU/WebGL implementation combinations will not blend fragments in
// additional passes correctly if their computation includes an unmasked
// divide-by-zero operation,
// even if it's not in the output or if the output has alpha zero.
//
// For example, without sanitization for outAlpha,
// this renders without artifacts:
// if (outAlpha == 0.0) { outColor = vec3(0.0); }
//
// but using czm_branchFreeTernary will cause portions of the tile that are
// alpha-zero in the additional pass to render as black instead of blending
// with the previous pass:
// outColor = czm_branchFreeTernary(outAlpha == 0.0, vec3(0.0), outColor);
//
// So instead, sanitize against divide-by-zero,
// store this state on the sign of outAlpha, and correct on return.
return vec4(outColor, max(outAlpha, 0.0));
}
vec3 colorCorrect(vec3 rgb) {
#ifdef COLOR_CORRECT
// Convert rgb color to hsb
vec3 hsb = czm_RGBToHSB(rgb);
// Perform hsb shift
hsb.x += u_hsbShift.x; // hue
hsb.y = clamp(hsb.y + u_hsbShift.y, 0.0, 1.0); // saturation
hsb.z = hsb.z > czm_epsilon7 ? hsb.z + u_hsbShift.z : 0.0; // brightness
// Convert shifted hsb back to rgb
rgb = czm_HSBToRGB(hsb);
#endif
return rgb;
}
vec4 computeDayColor(vec4 initialColor, vec3 textureCoordinates, float nightBlend);
vec4 computeWaterColor(vec3 positionEyeCoordinates, vec2 textureCoordinates, mat3 enuToEye, vec4 imageryColor, float specularMapValue, float fade);
const float fExposure = 2.0;
vec3 computeEllipsoidPosition()
{
float mpp = czm_metersPerPixel(vec4(0.0, 0.0, -czm_currentFrustum.x, 1.0), 1.0);
vec2 xy = gl_FragCoord.xy / czm_viewport.zw * 2.0 - vec2(1.0);
xy *= czm_viewport.zw * mpp * 0.5;
vec3 direction = normalize(vec3(xy, -czm_currentFrustum.x));
czm_ray ray = czm_ray(vec3(0.0), direction);
vec3 ellipsoid_center = czm_view[3].xyz;
czm_raySegment intersection = czm_rayEllipsoidIntersectionInterval(ray, ellipsoid_center, czm_ellipsoidInverseRadii);
vec3 ellipsoidPosition = czm_pointAlongRay(ray, intersection.start);
return (czm_inverseView * vec4(ellipsoidPosition, 1.0)).xyz;
}
void main()
{
#ifdef TILE_LIMIT_RECTANGLE
if (v_textureCoordinates.x < u_cartographicLimitRectangle.x || u_cartographicLimitRectangle.z < v_textureCoordinates.x ||
v_textureCoordinates.y < u_cartographicLimitRectangle.y || u_cartographicLimitRectangle.w < v_textureCoordinates.y)
{
discard;
}
#endif
#ifdef ENABLE_CLIPPING_PLANES
float clipDistance = clip(gl_FragCoord, u_clippingPlanes, u_clippingPlanesMatrix);
#endif
#if defined(SHOW_REFLECTIVE_OCEAN) || defined(ENABLE_DAYNIGHT_SHADING) || defined(HDR)
vec3 normalMC = czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)); // normalized surface normal in model coordinates
vec3 normalEC = czm_normal3D * normalMC; // normalized surface normal in eye coordiantes
#endif
#if defined(APPLY_DAY_NIGHT_ALPHA) && defined(ENABLE_DAYNIGHT_SHADING)
float nightBlend = 1.0 - clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * 5.0, 0.0, 1.0);
#else
float nightBlend = 0.0;
#endif
// The clamp below works around an apparent bug in Chrome Canary v23.0.1241.0
// where the fragment shader sees textures coordinates < 0.0 and > 1.0 for the
// fragments on the edges of tiles even though the vertex shader is outputting
// coordinates strictly in the 0-1 range.
vec4 color = computeDayColor(u_initialColor, clamp(v_textureCoordinates, 0.0, 1.0), nightBlend);
#ifdef SHOW_TILE_BOUNDARIES
if (v_textureCoordinates.x < (1.0/256.0) || v_textureCoordinates.x > (255.0/256.0) ||
v_textureCoordinates.y < (1.0/256.0) || v_textureCoordinates.y > (255.0/256.0))
{
color = vec4(1.0, 0.0, 0.0, 1.0);
}
#endif
#if defined(ENABLE_DAYNIGHT_SHADING) || defined(GROUND_ATMOSPHERE)
float cameraDist;
if (czm_sceneMode == czm_sceneMode2D)
{
cameraDist = max(czm_frustumPlanes.x - czm_frustumPlanes.y, czm_frustumPlanes.w - czm_frustumPlanes.z) * 0.5;
}
else if (czm_sceneMode == czm_sceneModeColumbusView)
{
cameraDist = -czm_view[3].z;
}
else
{
cameraDist = length(czm_view[3]);
}
float fadeOutDist = u_lightingFadeDistance.x;
float fadeInDist = u_lightingFadeDistance.y;
if (czm_sceneMode != czm_sceneMode3D) {
vec3 radii = czm_ellipsoidRadii;
float maxRadii = max(radii.x, max(radii.y, radii.z));
fadeOutDist -= maxRadii;
fadeInDist -= maxRadii;
}
float fade = clamp((cameraDist - fadeOutDist) / (fadeInDist - fadeOutDist), 0.0, 1.0);
#else
float fade = 0.0;
#endif
#ifdef SHOW_REFLECTIVE_OCEAN
vec2 waterMaskTranslation = u_waterMaskTranslationAndScale.xy;
vec2 waterMaskScale = u_waterMaskTranslationAndScale.zw;
vec2 waterMaskTextureCoordinates = v_textureCoordinates.xy * waterMaskScale + waterMaskTranslation;
waterMaskTextureCoordinates.y = 1.0 - waterMaskTextureCoordinates.y;
float mask = texture(u_waterMask, waterMaskTextureCoordinates).r;
if (mask > 0.0)
{
mat3 enuToEye = czm_eastNorthUpToEyeCoordinates(v_positionMC, normalEC);
vec2 ellipsoidTextureCoordinates = czm_ellipsoidWgs84TextureCoordinates(normalMC);
vec2 ellipsoidFlippedTextureCoordinates = czm_ellipsoidWgs84TextureCoordinates(normalMC.zyx);
vec2 textureCoordinates = mix(ellipsoidTextureCoordinates, ellipsoidFlippedTextureCoordinates, czm_morphTime * smoothstep(0.9, 0.95, normalMC.z));
color = computeWaterColor(v_positionEC, textureCoordinates, enuToEye, color, mask, fade);
}
#endif
#ifdef APPLY_MATERIAL
czm_materialInput materialInput;
materialInput.st = v_textureCoordinates.st;
materialInput.normalEC = normalize(v_normalEC);
materialInput.positionToEyeEC = -v_positionEC;
materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, normalize(v_normalEC));
materialInput.slope = v_slope;
materialInput.height = v_height;
materialInput.aspect = v_aspect;
czm_material material = czm_getMaterial(materialInput);
vec4 materialColor = vec4(material.diffuse, material.alpha);
color = alphaBlend(materialColor, color);
#endif
#ifdef ENABLE_VERTEX_LIGHTING
float diffuseIntensity = clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalize(v_normalEC)) * u_lambertDiffuseMultiplier + u_vertexShadowDarkness, 0.0, 1.0);
vec4 finalColor = vec4(color.rgb * czm_lightColor * diffuseIntensity, color.a);
#elif defined(ENABLE_DAYNIGHT_SHADING)
float diffuseIntensity = clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * 5.0 + 0.3, 0.0, 1.0);
diffuseIntensity = mix(1.0, diffuseIntensity, fade);
vec4 finalColor = vec4(color.rgb * czm_lightColor * diffuseIntensity, color.a);
#else
vec4 finalColor = color;
#endif
#ifdef ENABLE_CLIPPING_PLANES
vec4 clippingPlanesEdgeColor = vec4(1.0);
clippingPlanesEdgeColor.rgb = u_clippingPlanesEdgeStyle.rgb;
float clippingPlanesEdgeWidth = u_clippingPlanesEdgeStyle.a;
if (clipDistance < clippingPlanesEdgeWidth)
{
finalColor = clippingPlanesEdgeColor;
}
#endif
#ifdef HIGHLIGHT_FILL_TILE
finalColor = vec4(mix(finalColor.rgb, u_fillHighlightColor.rgb, u_fillHighlightColor.a), finalColor.a);
#endif
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN)
vec3 atmosphereLightDirection = czm_sunDirectionWC;
#else
vec3 atmosphereLightDirection = czm_lightDirectionWC;
#endif
#if defined(GROUND_ATMOSPHERE) || defined(FOG)
if (!czm_backFacing())
{
bool dynamicLighting = false;
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_DAYNIGHT_SHADING) || defined(ENABLE_VERTEX_LIGHTING))
dynamicLighting = true;
#endif
vec3 rayleighColor;
vec3 mieColor;
float opacity;
vec3 positionWC;
vec3 lightDirection;
// When the camera is far away (camera distance > nightFadeOutDistance), the scattering is computed in the fragment shader.
// Otherwise, the scattering is computed in the vertex shader.
#ifdef PER_FRAGMENT_GROUND_ATMOSPHERE
positionWC = computeEllipsoidPosition();
lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(positionWC));
computeAtmosphereScattering(
positionWC,
lightDirection,
rayleighColor,
mieColor,
opacity
);
#else
positionWC = v_positionMC;
lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(positionWC));
rayleighColor = v_atmosphereRayleighColor;
mieColor = v_atmosphereMieColor;
opacity = v_atmosphereOpacity;
#endif
rayleighColor = colorCorrect(rayleighColor);
mieColor = colorCorrect(mieColor);
vec4 groundAtmosphereColor = computeAtmosphereColor(positionWC, lightDirection, rayleighColor, mieColor, opacity);
// Fog is applied to tiles selected for fog, close to the Earth.
#ifdef FOG
vec3 fogColor = groundAtmosphereColor.rgb;
// If there is lighting, apply that to the fog.
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING))
float darken = clamp(dot(normalize(czm_viewerPositionWC), atmosphereLightDirection), u_minimumBrightness, 1.0);
fogColor *= darken;
#endif
#ifndef HDR
fogColor.rgb = czm_acesTonemapping(fogColor.rgb);
fogColor.rgb = czm_inverseGamma(fogColor.rgb);
#endif
const float modifier = 0.15;
finalColor = vec4(czm_fog(v_distance, finalColor.rgb, fogColor.rgb, modifier), finalColor.a);
#else
// The transmittance is based on optical depth i.e. the length of segment of the ray inside the atmosphere.
// This value is larger near the "circumference", as it is further away from the camera. We use it to
// brighten up that area of the ground atmosphere.
const float transmittanceModifier = 0.5;
float transmittance = transmittanceModifier + clamp(1.0 - groundAtmosphereColor.a, 0.0, 1.0);
vec3 finalAtmosphereColor = finalColor.rgb + groundAtmosphereColor.rgb * transmittance;
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING))
float fadeInDist = u_nightFadeDistance.x;
float fadeOutDist = u_nightFadeDistance.y;
float sunlitAtmosphereIntensity = clamp((cameraDist - fadeOutDist) / (fadeInDist - fadeOutDist), 0.05, 1.0);
float darken = clamp(dot(normalize(positionWC), atmosphereLightDirection), 0.0, 1.0);
vec3 darkenendGroundAtmosphereColor = mix(groundAtmosphereColor.rgb, finalAtmosphereColor.rgb, darken);
finalAtmosphereColor = mix(darkenendGroundAtmosphereColor, finalAtmosphereColor, sunlitAtmosphereIntensity);
#endif
#ifndef HDR
finalAtmosphereColor.rgb = vec3(1.0) - exp(-fExposure * finalAtmosphereColor.rgb);
#else
finalAtmosphereColor.rgb = czm_saturation(finalAtmosphereColor.rgb, 1.6);
#endif
finalColor.rgb = mix(finalColor.rgb, finalAtmosphereColor.rgb, fade);
#endif
}
#endif
#ifdef UNDERGROUND_COLOR
if (czm_backFacing())
{
float distanceFromEllipsoid = max(czm_eyeHeight, 0.0);
float distance = max(v_distance - distanceFromEllipsoid, 0.0);
float blendAmount = interpolateByDistance(u_undergroundColorAlphaByDistance, distance);
vec4 undergroundColor = vec4(u_undergroundColor.rgb, u_undergroundColor.a * blendAmount);
finalColor = alphaBlend(undergroundColor, finalColor);
}
#endif
#ifdef TRANSLUCENT
if (inTranslucencyRectangle())
{
vec4 alphaByDistance = gl_FrontFacing ? u_frontFaceAlphaByDistance : u_backFaceAlphaByDistance;
finalColor.a *= interpolateByDistance(alphaByDistance, v_distance);
}
#endif
out_FragColor = finalColor;
}
#ifdef SHOW_REFLECTIVE_OCEAN
float waveFade(float edge0, float edge1, float x)
{
float y = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
return pow(1.0 - y, 5.0);
}
float linearFade(float edge0, float edge1, float x)
{
return clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
}
// Based on water rendering by Jonas Wagner:
// http://29a.ch/2012/7/19/webgl-terrain-rendering-water-fog
// low altitude wave settings
const float oceanFrequencyLowAltitude = 825000.0;
const float oceanAnimationSpeedLowAltitude = 0.004;
const float oceanOneOverAmplitudeLowAltitude = 1.0 / 2.0;
const float oceanSpecularIntensity = 0.5;
// high altitude wave settings
const float oceanFrequencyHighAltitude = 125000.0;
const float oceanAnimationSpeedHighAltitude = 0.008;
const float oceanOneOverAmplitudeHighAltitude = 1.0 / 2.0;
vec4 computeWaterColor(vec3 positionEyeCoordinates, vec2 textureCoordinates, mat3 enuToEye, vec4 imageryColor, float maskValue, float fade)
{
vec3 positionToEyeEC = -positionEyeCoordinates;
float positionToEyeECLength = length(positionToEyeEC);
// The double normalize below works around a bug in Firefox on Android devices.
vec3 normalizedPositionToEyeEC = normalize(normalize(positionToEyeEC));
// Fade out the waves as the camera moves far from the surface.
float waveIntensity = waveFade(70000.0, 1000000.0, positionToEyeECLength);
#ifdef SHOW_OCEAN_WAVES
// high altitude waves
float time = czm_frameNumber * oceanAnimationSpeedHighAltitude;
vec4 noise = czm_getWaterNoise(u_oceanNormalMap, textureCoordinates * oceanFrequencyHighAltitude, time, 0.0);
vec3 normalTangentSpaceHighAltitude = vec3(noise.xy, noise.z * oceanOneOverAmplitudeHighAltitude);
// low altitude waves
time = czm_frameNumber * oceanAnimationSpeedLowAltitude;
noise = czm_getWaterNoise(u_oceanNormalMap, textureCoordinates * oceanFrequencyLowAltitude, time, 0.0);
vec3 normalTangentSpaceLowAltitude = vec3(noise.xy, noise.z * oceanOneOverAmplitudeLowAltitude);
// blend the 2 wave layers based on distance to surface
float highAltitudeFade = linearFade(0.0, 60000.0, positionToEyeECLength);
float lowAltitudeFade = 1.0 - linearFade(20000.0, 60000.0, positionToEyeECLength);
vec3 normalTangentSpace =
(highAltitudeFade * normalTangentSpaceHighAltitude) +
(lowAltitudeFade * normalTangentSpaceLowAltitude);
normalTangentSpace = normalize(normalTangentSpace);
// fade out the normal perturbation as we move farther from the water surface
normalTangentSpace.xy *= waveIntensity;
normalTangentSpace = normalize(normalTangentSpace);
#else
vec3 normalTangentSpace = vec3(0.0, 0.0, 1.0);
#endif
vec3 normalEC = enuToEye * normalTangentSpace;
const vec3 waveHighlightColor = vec3(0.3, 0.45, 0.6);
// Use diffuse light to highlight the waves
float diffuseIntensity = czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * maskValue;
vec3 diffuseHighlight = waveHighlightColor * diffuseIntensity * (1.0 - fade);
#ifdef SHOW_OCEAN_WAVES
// Where diffuse light is low or non-existent, use wave highlights based solely on
// the wave bumpiness and no particular light direction.
float tsPerturbationRatio = normalTangentSpace.z;
vec3 nonDiffuseHighlight = mix(waveHighlightColor * 5.0 * (1.0 - tsPerturbationRatio), vec3(0.0), diffuseIntensity);
#else
vec3 nonDiffuseHighlight = vec3(0.0);
#endif
// Add specular highlights in 3D, and in all modes when zoomed in.
float specularIntensity = czm_getSpecular(czm_lightDirectionEC, normalizedPositionToEyeEC, normalEC, 10.0);
float surfaceReflectance = mix(0.0, mix(u_zoomedOutOceanSpecularIntensity, oceanSpecularIntensity, waveIntensity), maskValue);
float specular = specularIntensity * surfaceReflectance;
#ifdef HDR
specular *= 1.4;
float e = 0.2;
float d = 3.3;
float c = 1.7;
vec3 color = imageryColor.rgb + (c * (vec3(e) + imageryColor.rgb * d) * (diffuseHighlight + nonDiffuseHighlight + specular));
#else
vec3 color = imageryColor.rgb + diffuseHighlight + nonDiffuseHighlight + specular;
#endif
return vec4(color, imageryColor.a);
}
#endif // #ifdef SHOW_REFLECTIVE_OCEAN
`;
// node_modules/@cesium/engine/Source/Shaders/GlobeVS.js
var GlobeVS_default = "#ifdef QUANTIZATION_BITS12\nin vec4 compressed0;\nin float compressed1;\n#else\nin vec4 position3DAndHeight;\nin vec4 textureCoordAndEncodedNormals;\n#endif\n\n#ifdef GEODETIC_SURFACE_NORMALS\nin vec3 geodeticSurfaceNormal;\n#endif\n\n#ifdef EXAGGERATION\nuniform vec2 u_terrainExaggerationAndRelativeHeight;\n#endif\n\nuniform vec3 u_center3D;\nuniform mat4 u_modifiedModelView;\nuniform mat4 u_modifiedModelViewProjection;\nuniform vec4 u_tileRectangle;\n\n// Uniforms for 2D Mercator projection\nuniform vec2 u_southAndNorthLatitude;\nuniform vec2 u_southMercatorYAndOneOverHeight;\n\nout vec3 v_positionMC;\nout vec3 v_positionEC;\n\nout vec3 v_textureCoordinates;\nout vec3 v_normalMC;\nout vec3 v_normalEC;\n\n#ifdef APPLY_MATERIAL\nout float v_slope;\nout float v_aspect;\nout float v_height;\n#endif\n\n#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)\nout float v_distance;\n#endif\n\n#if defined(FOG) || defined(GROUND_ATMOSPHERE)\nout vec3 v_atmosphereRayleighColor;\nout vec3 v_atmosphereMieColor;\nout float v_atmosphereOpacity;\n#endif\n\n// These functions are generated at runtime.\nvec4 getPosition(vec3 position, float height, vec2 textureCoordinates);\nfloat get2DYPositionFraction(vec2 textureCoordinates);\n\nvec4 getPosition3DMode(vec3 position, float height, vec2 textureCoordinates)\n{\n return u_modifiedModelViewProjection * vec4(position, 1.0);\n}\n\nfloat get2DMercatorYPositionFraction(vec2 textureCoordinates)\n{\n // The width of a tile at level 11, in radians and assuming a single root tile, is\n // 2.0 * czm_pi / pow(2.0, 11.0)\n // We want to just linearly interpolate the 2D position from the texture coordinates\n // when we're at this level or higher. The constant below is the expression\n // above evaluated and then rounded up at the 4th significant digit.\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\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\nfloat get2DGeographicYPositionFraction(vec2 textureCoordinates)\n{\n return textureCoordinates.y;\n}\n\nvec4 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\nvec4 getPosition2DMode(vec3 position, float height, vec2 textureCoordinates)\n{\n return getPositionPlanarEarth(position, 0.0, textureCoordinates);\n}\n\nvec4 getPositionColumbusViewMode(vec3 position, float height, vec2 textureCoordinates)\n{\n return getPositionPlanarEarth(position, height, textureCoordinates);\n}\n\nvec4 getPositionMorphingMode(vec3 position, float height, vec2 textureCoordinates)\n{\n // We do not do RTC while morphing, so there is potential for jitter.\n // This is unlikely to be noticeable, though.\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\n#ifdef QUANTIZATION_BITS12\nuniform vec2 u_minMaxHeight;\nuniform mat4 u_scaleAndBias;\n#endif\n\nvoid 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\n height = height * (u_minMaxHeight.y - u_minMaxHeight.x) + u_minMaxHeight.x;\n position = (u_scaleAndBias * vec4(position, 1.0)).xyz;\n\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\n#else\n // A single float per element\n vec3 position = position3DAndHeight.xyz;\n float height = position3DAndHeight.w;\n vec2 textureCoordinates = textureCoordAndEncodedNormals.xy;\n\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\n#endif\n\n vec3 position3DWC = position + u_center3D;\n\n#ifdef GEODETIC_SURFACE_NORMALS\n vec3 ellipsoidNormal = geodeticSurfaceNormal;\n#else\n vec3 ellipsoidNormal = normalize(position3DWC);\n#endif\n\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\n // stop from going through center of earth\n float minRadius = min(min(czm_ellipsoidRadii.x, czm_ellipsoidRadii.y), czm_ellipsoidRadii.z);\n newHeight = max(newHeight, -minRadius);\n\n vec3 offset = ellipsoidNormal * (newHeight - height);\n position += offset;\n position3DWC += offset;\n height = newHeight;\n#endif\n\n gl_Position = getPosition(position, height, textureCoordinates);\n\n v_positionEC = (u_modifiedModelView * vec4(position, 1.0)).xyz;\n v_positionMC = position3DWC; // position in model coordinates\n\n v_textureCoordinates = vec3(textureCoordinates, webMercatorT);\n\n#if defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL) || defined(APPLY_MATERIAL)\n vec3 normalMC = czm_octDecode(encodedNormal);\n\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\n v_normalMC = normalMC;\n v_normalEC = czm_normal3D * v_normalMC;\n#endif\n\n#if defined(FOG) || (defined(GROUND_ATMOSPHERE) && !defined(PER_FRAGMENT_GROUND_ATMOSPHERE))\n\n bool dynamicLighting = false;\n\n #if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_DAYNIGHT_SHADING) || defined(ENABLE_VERTEX_LIGHTING))\n dynamicLighting = true;\n #endif\n\n#if defined(DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN)\n vec3 atmosphereLightDirection = czm_sunDirectionWC;\n#else\n vec3 atmosphereLightDirection = czm_lightDirectionWC;\n#endif\n\n vec3 lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(position3DWC));\n\n computeAtmosphereScattering(\n position3DWC,\n lightDirection,\n v_atmosphereRayleighColor,\n v_atmosphereMieColor,\n v_atmosphereOpacity\n );\n#endif\n\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\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";
// node_modules/@cesium/engine/Source/Shaders/AtmosphereCommon.js
var AtmosphereCommon_default = "uniform vec3 u_radiiAndDynamicAtmosphereColor;\n\nuniform float u_atmosphereLightIntensity;\nuniform float u_atmosphereRayleighScaleHeight;\nuniform float u_atmosphereMieScaleHeight;\nuniform float u_atmosphereMieAnisotropy;\nuniform vec3 u_atmosphereRayleighCoefficient;\nuniform vec3 u_atmosphereMieCoefficient;\n\nconst float ATMOSPHERE_THICKNESS = 111e3; // The thickness of the atmosphere in meters.\nconst int PRIMARY_STEPS_MAX = 16; // Maximum number of times the ray from the camera to the world position (primary ray) is sampled.\nconst int LIGHT_STEPS_MAX = 4; // Maximum number of times the light is sampled from the light source's intersection with the atmosphere to a sample position on the primary ray.\n\n/**\n * Rational approximation to tanh(x)\n*/\nfloat approximateTanh(float x) {\n float x2 = x * x;\n return max(-1.0, min(+1.0, x * (27.0 + x2) / (27.0 + 9.0 * x2)));\n}\n\n/**\n * This function computes the colors contributed by Rayliegh and Mie scattering on a given ray, as well as\n * the transmittance value for the ray.\n *\n * @param {czm_ray} primaryRay The ray from the camera to the position.\n * @param {float} primaryRayLength The length of the primary ray.\n * @param {vec3} lightDirection The direction of the light to calculate the scattering from.\n * @param {vec3} rayleighColor The variable the Rayleigh scattering will be written to.\n * @param {vec3} mieColor The variable the Mie scattering will be written to.\n * @param {float} opacity The variable the transmittance will be written to.\n * @glslFunction\n */\nvoid 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\n // Initialize the default scattering amounts to 0.\n rayleighColor = vec3(0.0);\n mieColor = vec3(0.0);\n opacity = 0.0;\n\n float atmosphereOuterRadius = atmosphereInnerRadius + ATMOSPHERE_THICKNESS;\n\n vec3 origin = vec3(0.0);\n\n // Calculate intersection from the camera to the outer ring of the atmosphere.\n czm_raySegment primaryRayAtmosphereIntersect = czm_raySphereIntersectionInterval(primaryRay, origin, atmosphereOuterRadius);\n\n // Return empty colors if no intersection with the atmosphere geometry.\n if (primaryRayAtmosphereIntersect == czm_emptyRaySegment) {\n return;\n }\n\n // To deal with smaller values of PRIMARY_STEPS (e.g. 4)\n // we implement a split strategy: sky or horizon.\n // For performance reasons, instead of a if/else branch\n // a soft choice is implemented through a weight 0.0 <= w_stop_gt_lprl <= 1.0\n float x = 1e-7 * primaryRayAtmosphereIntersect.stop / length(primaryRayLength);\n // Value close to 0.0: close to the horizon\n // Value close to 1.0: above in the sky\n float w_stop_gt_lprl = 0.5 * (1.0 + approximateTanh(x));\n \n // The ray should start from the first intersection with the outer atmopshere, or from the camera position, if it is inside the atmosphere.\n float start_0 = primaryRayAtmosphereIntersect.start;\n primaryRayAtmosphereIntersect.start = max(primaryRayAtmosphereIntersect.start, 0.0);\n // The ray should end at the exit from the atmosphere or at the distance to the vertex, whichever is smaller.\n primaryRayAtmosphereIntersect.stop = min(primaryRayAtmosphereIntersect.stop, length(primaryRayLength));\n\n // For the number of ray steps, distinguish inside or outside atmosphere (outer space)\n // (1) from outer space we have to use more ray steps to get a realistic rendering\n // (2) within atmosphere we need fewer steps for faster rendering\n float x_o_a = start_0 - ATMOSPHERE_THICKNESS; // ATMOSPHERE_THICKNESS used as an ad-hoc constant, no precise meaning here, only the order of magnitude matters\n float w_inside_atmosphere = 1.0 - 0.5 * (1.0 + approximateTanh(x_o_a));\n int PRIMARY_STEPS = PRIMARY_STEPS_MAX - int(w_inside_atmosphere * 12.0); // Number of times the ray from the camera to the world position (primary ray) is sampled.\n int LIGHT_STEPS = LIGHT_STEPS_MAX - int(w_inside_atmosphere * 2.0); // Number of times the light is sampled from the light source's intersection with the atmosphere to a sample position on the primary ray.\n\n // Setup for sampling positions along the ray - starting from the intersection with the outer ring of the atmosphere.\n float rayPositionLength = primaryRayAtmosphereIntersect.start;\n // (1) Outside the atmosphere: constant rayStepLength\n // (2) Inside atmosphere: variable rayStepLength to compensate the rough rendering of the smaller number of ray steps\n float totalRayLength = primaryRayAtmosphereIntersect.stop - rayPositionLength;\n float rayStepLengthIncrease = w_inside_atmosphere * ((1.0 - w_stop_gt_lprl) * totalRayLength / (float(PRIMARY_STEPS * (PRIMARY_STEPS + 1)) / 2.0));\n float rayStepLength = max(1.0 - w_inside_atmosphere, w_stop_gt_lprl) * totalRayLength / max(7.0 * w_inside_atmosphere, float(PRIMARY_STEPS));\n\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\n // Sample positions on the primary ray.\n for (int i = 0; i < PRIMARY_STEPS_MAX; ++i) {\n\n // The loop should be: for (int i = 0; i < PRIMARY_STEPS; ++i) {...} but WebGL1 cannot\n // loop with non-constant condition, so it has to break early instead\n if (i >= PRIMARY_STEPS) {\n break;\n }\n\n // Calculate sample position along viewpoint ray.\n vec3 samplePosition = primaryRay.origin + primaryRay.direction * (rayPositionLength + rayStepLength);\n\n // Calculate height of sample position above ellipsoid.\n float sampleHeight = length(samplePosition) - atmosphereInnerRadius;\n\n // Calculate and accumulate density of particles at the sample position.\n vec2 sampleDensity = exp(-sampleHeight / heightScale) * rayStepLength;\n opticalDepth += sampleDensity;\n\n // Generate ray from the sample position segment to the light source, up to the outer ring of the atmosphere.\n czm_ray lightRay = czm_ray(samplePosition, lightDirection);\n czm_raySegment lightRayAtmosphereIntersect = czm_raySphereIntersectionInterval(lightRay, origin, atmosphereOuterRadius);\n\n float lightStepLength = lightRayAtmosphereIntersect.stop / float(LIGHT_STEPS);\n float lightPositionLength = 0.0;\n\n vec2 lightOpticalDepth = vec2(0.0);\n\n // Sample positions along the light ray, to accumulate incidence of light on the latest sample segment.\n for (int j = 0; j < LIGHT_STEPS_MAX; ++j) {\n\n // The loop should be: for (int j = 0; i < LIGHT_STEPS; ++j) {...} but WebGL1 cannot\n // loop with non-constant condition, so it has to break early instead\n if (j >= LIGHT_STEPS) {\n break;\n }\n\n // Calculate sample position along light ray.\n vec3 lightPosition = samplePosition + lightDirection * (lightPositionLength + lightStepLength * 0.5);\n\n // Calculate height of the light sample position above ellipsoid.\n float lightHeight = length(lightPosition) - atmosphereInnerRadius;\n\n // Calculate density of photons at the light sample position.\n lightOpticalDepth += exp(-lightHeight / heightScale) * lightStepLength;\n\n // Increment distance on light ray.\n lightPositionLength += lightStepLength;\n }\n\n // Compute attenuation via the primary ray and the light ray.\n vec3 attenuation = exp(-((u_atmosphereMieCoefficient * (opticalDepth.y + lightOpticalDepth.y)) + (u_atmosphereRayleighCoefficient * (opticalDepth.x + lightOpticalDepth.x))));\n\n // Accumulate the scattering.\n rayleighAccumulation += sampleDensity.x * attenuation;\n mieAccumulation += sampleDensity.y * attenuation;\n\n // Increment distance on primary ray.\n rayPositionLength += (rayStepLength += rayStepLengthIncrease);\n }\n\n // Compute the scattering amount.\n rayleighColor = u_atmosphereRayleighCoefficient * rayleighAccumulation;\n mieColor = u_atmosphereMieCoefficient * mieAccumulation;\n\n // Compute the transmittance i.e. how much light is passing through the atmosphere.\n opacity = length(exp(-((u_atmosphereMieCoefficient * opticalDepth.y) + (u_atmosphereRayleighCoefficient * opticalDepth.x))));\n}\n\nvec4 computeAtmosphereColor(\n vec3 positionWC,\n vec3 lightDirection,\n vec3 rayleighColor,\n vec3 mieColor,\n float opacity\n) {\n // Setup the primary ray: from the camera position to the vertex position.\n vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;\n vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);\n\n float cosAngle = dot(cameraToPositionWCDirection, lightDirection);\n float cosAngleSq = cosAngle * cosAngle;\n\n float G = u_atmosphereMieAnisotropy;\n float GSq = G * G;\n\n // The Rayleigh phase function.\n float rayleighPhase = 3.0 / (50.2654824574) * (1.0 + cosAngleSq);\n // The Mie phase function.\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\n // The final color is generated by combining the effects of the Rayleigh and Mie scattering.\n vec3 rayleigh = rayleighPhase * rayleighColor;\n vec3 mie = miePhase * mieColor;\n\n vec3 color = (rayleigh + mie) * u_atmosphereLightIntensity;\n\n return vec4(color, opacity);\n}\n";
// node_modules/@cesium/engine/Source/Shaders/GroundAtmosphere.js
var GroundAtmosphere_default = "void computeAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity) {\n\n vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;\n vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);\n czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);\n \n float atmosphereInnerRadius = length(positionWC);\n\n computeScattering(\n primaryRay,\n length(cameraToPositionWC),\n lightDirection,\n atmosphereInnerRadius,\n rayleighColor,\n mieColor,\n opacity\n );\n}\n";
// node_modules/@cesium/engine/Source/Scene/getClippingFunction.js
var textureResolutionScratch3 = new Cartesian2_default();
function getClippingFunction(clippingPlaneCollection, context) {
Check_default.typeOf.object("clippingPlaneCollection", clippingPlaneCollection);
Check_default.typeOf.object("context", context);
const unionClippingRegions = clippingPlaneCollection.unionClippingRegions;
const clippingPlanesLength = clippingPlaneCollection.length;
const usingFloatTexture = ClippingPlaneCollection_default.useFloatTexture(context);
const textureResolution = ClippingPlaneCollection_default.getTextureResolution(
clippingPlaneCollection,
context,
textureResolutionScratch3
);
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 float pixelWidth = czm_metersPerPixel(position);\n bool breakAndDiscard = false;\n for (int i = 0; i < "}${clippingPlanesLength}; ++i)
{
vec4 clippingPlane = getClippingPlane(clippingPlanes, i, clippingPlanesMatrix);
clipNormal = clippingPlane.xyz;
clipPosition = -clippingPlane.w * clipNormal;
float amount = dot(clipNormal, (position.xyz - clipPosition)) / pixelWidth;
clipAmount = czm_branchFreeTernary(i == 0, amount, min(amount, clipAmount));
if (amount <= 0.0)
{
breakAndDiscard = true;
break;
}
}
if (breakAndDiscard) {
discard;
}
return clipAmount;
}
`;
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)
{
vec4 clippingPlane = getClippingPlane(clippingPlanes, i, clippingPlanesMatrix);
clipNormal = clippingPlane.xyz;
clipPosition = -clippingPlane.w * clipNormal;
float amount = dot(clipNormal, (position.xyz - clipPosition)) / pixelWidth;
clipAmount = max(amount, clipAmount);
clipped = clipped && (amount <= 0.0);
}
if (clipped)
{
discard;
}
return clipAmount;
}
`;
return functionString;
}
function getClippingPlaneFloat(width, height) {
const pixelWidth = 1 / width;
const pixelHeight = 1 / 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};
int pixX = clippingPlaneNumber - (pixY * ${width});
float u = (float(pixX) + 0.5) * ${pixelWidthString};
float v = (float(pixY) + 0.5) * ${pixelHeightString};
vec4 plane = texture(packedClippingPlanes, vec2(u, v));
return czm_transformPlane(plane, transform);
}
`;
return functionString;
}
function getClippingPlaneUint8(width, height) {
const pixelWidth = 1 / width;
const pixelHeight = 1 / 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 int pixY = clippingPlaneStartIndex / "}${width};
int pixX = clippingPlaneStartIndex - (pixY * ${width});
float u = (float(pixX) + 0.5) * ${pixelWidthString};
float v = (float(pixY) + 0.5) * ${pixelHeightString};
vec4 oct32 = texture(packedClippingPlanes, vec2(u, v)) * 255.0;
vec2 oct = vec2(oct32.x * 256.0 + oct32.y, oct32.z * 256.0 + oct32.w);
vec4 plane;
plane.xyz = czm_octDecode(oct, 65535.0);
plane.w = czm_unpackFloat(texture(packedClippingPlanes, vec2(u + ${pixelWidthString}, v)));
return czm_transformPlane(plane, transform);
}
`;
return functionString;
}
var getClippingFunction_default = getClippingFunction;
// node_modules/@cesium/engine/Source/Scene/GlobeSurfaceShaderSet.js
function GlobeSurfaceShader(numberOfDayTextures, flags, material, shaderProgram, clippingShaderState) {
this.numberOfDayTextures = numberOfDayTextures;
this.flags = flags;
this.material = material;
this.shaderProgram = shaderProgram;
this.clippingShaderState = clippingShaderState;
}
function GlobeSurfaceShaderSet() {
this.baseVertexShaderSource = void 0;
this.baseFragmentShaderSource = void 0;
this._shadersByTexturesFlags = [];
this.material = void 0;
}
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_default.SCENE3D:
positionMode = getPosition3DMode;
break;
case SceneMode_default.SCENE2D:
case SceneMode_default.COLUMBUS_VIEW:
positionMode = getPositionColumbusViewAnd2DMode;
break;
case SceneMode_default.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_default.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_default(clippingPlanes) && clippingPlanes.length > 0) {
currentClippingShaderState = enableClippingPlanes ? clippingPlanes.clippingPlanesState : 0;
}
let surfaceShader = surfaceTile.surfaceShader;
if (defined_default(surfaceShader) && surfaceShader.numberOfDayTextures === numberOfDayTextures && surfaceShader.flags === flags && surfaceShader.material === this.material && surfaceShader.clippingShaderState === currentClippingShaderState) {
return surfaceShader.shaderProgram;
}
let shadersByFlags = this._shadersByTexturesFlags[numberOfDayTextures];
if (!defined_default(shadersByFlags)) {
shadersByFlags = this._shadersByTexturesFlags[numberOfDayTextures] = [];
}
surfaceShader = shadersByFlags[flags];
if (!defined_default(surfaceShader) || surfaceShader.material !== this.material || surfaceShader.clippingShaderState !== currentClippingShaderState) {
const vs = this.baseVertexShaderSource.clone();
const fs = this.baseFragmentShaderSource.clone();
if (currentClippingShaderState !== 0) {
fs.sources.unshift(
getClippingFunction_default(clippingPlanes, frameState.context)
);
}
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}];
texelUnclipped = v_textureCoordinates.x < cutoutAndColorResult.x || cutoutAndColorResult.z < v_textureCoordinates.x || v_textureCoordinates.y < cutoutAndColorResult.y || cutoutAndColorResult.w < v_textureCoordinates.y;
cutoutAndColorResult = sampleAndBlend(
`;
} else {
computeDayColor += " color = sampleAndBlend(\n";
}
computeDayColor += ` color,
u_dayTextures[${i}],
u_dayTextureUseWebMercatorT[${i}] ? textureCoordinates.xz : textureCoordinates.xy,
u_dayTextureTexCoordsRectangle[${i}],
u_dayTextureTranslationAndScale[${i}],
${applyAlpha ? `u_dayTextureAlpha[${i}]` : "1.0"},
${applyDayNightAlpha ? `u_dayTextureNightAlpha[${i}]` : "1.0"},
${applyDayNightAlpha ? `u_dayTextureDayAlpha[${i}]` : "1.0"},
${applyBrightness ? `u_dayTextureBrightness[${i}]` : "0.0"},
${applyContrast ? `u_dayTextureContrast[${i}]` : "0.0"},
${applyHue ? `u_dayTextureHue[${i}]` : "0.0"},
${applySaturation ? `u_dayTextureSaturation[${i}]` : "0.0"},
${applyGamma ? `u_dayTextureOneOverGamma[${i}]` : "0.0"},
${applySplit ? `u_dayTextureSplit[${i}]` : "0.0"},
${colorToAlpha ? `u_colorsToAlpha[${i}]` : "vec4(0.0)"},
nightBlend );
`;
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_default.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_default(shadersByFlags)) {
continue;
}
for (flags in shadersByFlags) {
if (shadersByFlags.hasOwnProperty(flags)) {
shader = shadersByFlags[flags];
if (defined_default(shader)) {
shader.shaderProgram.destroy();
}
}
}
}
}
return destroyObject_default(this);
};
var GlobeSurfaceShaderSet_default = GlobeSurfaceShaderSet;
// node_modules/@cesium/engine/Source/Core/Visibility.js
var Visibility = {
NONE: -1,
PARTIAL: 0,
FULL: 1
};
var Visibility_default = Object.freeze(Visibility);
// node_modules/@cesium/engine/Source/Core/TileProviderError.js
function TileProviderError(provider, message, x, y, level, timesRetried, error) {
this.provider = provider;
this.message = message;
this.x = x;
this.y = y;
this.level = level;
this.timesRetried = defaultValue_default(timesRetried, 0);
this.retry = false;
this.error = error;
}
TileProviderError.reportError = function(previousError, provider, event, message, x, y, level, errorDetails) {
let error = previousError;
if (!defined_default(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 (defined_default(event) && event.numberOfListeners > 0) {
event.raiseEvent(error);
} else if (defined_default(provider)) {
console.log(
`An error occurred in "${provider.constructor.name}": ${formatError_default(
message
)}`
);
}
return error;
};
TileProviderError.reportSuccess = function(previousError) {
if (defined_default(previousError)) {
previousError.timesRetried = -1;
}
};
var TileProviderError_default = TileProviderError;
// node_modules/@cesium/engine/Source/Scene/ImageryState.js
var ImageryState = {
UNLOADED: 0,
TRANSITIONING: 1,
RECEIVED: 2,
TEXTURE_LOADED: 3,
READY: 4,
FAILED: 5,
INVALID: 6,
PLACEHOLDER: 7
};
var ImageryState_default = Object.freeze(ImageryState);
// node_modules/@cesium/engine/Source/Scene/QuadtreeTileLoadState.js
var QuadtreeTileLoadState = {
START: 0,
LOADING: 1,
DONE: 2,
FAILED: 3
};
var QuadtreeTileLoadState_default = Object.freeze(QuadtreeTileLoadState);
// node_modules/@cesium/engine/Source/Scene/TerrainState.js
var TerrainState = {
FAILED: 0,
UNLOADED: 1,
RECEIVING: 2,
RECEIVED: 3,
TRANSFORMING: 4,
TRANSFORMED: 5,
READY: 6
};
var TerrainState_default = Object.freeze(TerrainState);
// node_modules/@cesium/engine/Source/Scene/GlobeSurfaceTile.js
function GlobeSurfaceTile() {
this.imagery = [];
this.waterMaskTexture = void 0;
this.waterMaskTranslationAndScale = new Cartesian4_default(0, 0, 1, 1);
this.terrainData = void 0;
this.vertexArray = void 0;
this.tileBoundingRegion = void 0;
this.occludeePointInScaledSpace = new Cartesian3_default();
this.boundingVolumeSourceTile = void 0;
this.boundingVolumeIsFromMesh = false;
this.terrainState = TerrainState_default.UNLOADED;
this.mesh = void 0;
this.fill = void 0;
this.pickBoundingSphere = new BoundingSphere_default();
this.surfaceShader = void 0;
this.isClipped = true;
this.clippedByBoundaries = false;
}
Object.defineProperties(GlobeSurfaceTile.prototype, {
eligibleForUnloading: {
get: function() {
const terrainState = this.terrainState;
const loadingIsTransitioning = terrainState === TerrainState_default.RECEIVING || terrainState === TerrainState_default.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_default(tileImagery.loadingImagery) || tileImagery.loadingImagery.state !== ImageryState_default.TRANSITIONING;
}
return shouldRemoveTile;
}
},
renderedMesh: {
get: function() {
if (defined_default(this.vertexArray)) {
return this.mesh;
} else if (defined_default(this.fill)) {
return this.fill.mesh;
}
return void 0;
}
}
});
var scratchCartographic16 = new Cartographic_default();
function getPosition2(encoding, mode2, projection, vertices, index, result) {
let position = encoding.getExaggeratedPosition(vertices, index, result);
if (defined_default(mode2) && mode2 !== SceneMode_default.SCENE3D) {
const ellipsoid = projection.ellipsoid;
const positionCartographic = ellipsoid.cartesianToCartographic(
position,
scratchCartographic16
);
position = projection.project(positionCartographic, result);
position = Cartesian3_default.fromElements(
position.z,
position.x,
position.y,
result
);
}
return position;
}
var scratchV0 = new Cartesian3_default();
var scratchV1 = new Cartesian3_default();
var scratchV2 = new Cartesian3_default();
GlobeSurfaceTile.prototype.pick = function(ray, mode2, projection, cullBackFaces, result) {
const mesh = this.renderedMesh;
if (!defined_default(mesh)) {
return void 0;
}
const vertices = mesh.vertices;
const indices2 = mesh.indices;
const encoding = mesh.encoding;
const indicesLength = indices2.length;
let minT = Number.MAX_VALUE;
for (let i = 0; i < indicesLength; i += 3) {
const i0 = indices2[i];
const i1 = indices2[i + 1];
const i2 = indices2[i + 2];
const v02 = getPosition2(encoding, mode2, projection, vertices, i0, scratchV0);
const v13 = getPosition2(encoding, mode2, projection, vertices, i1, scratchV1);
const v23 = getPosition2(encoding, mode2, projection, vertices, i2, scratchV2);
const t = IntersectionTests_default.rayTriangleParametric(
ray,
v02,
v13,
v23,
cullBackFaces
);
if (defined_default(t) && t < minT && t >= 0) {
minT = t;
}
}
return minT !== Number.MAX_VALUE ? Ray_default.getPoint(ray, minT, result) : void 0;
};
GlobeSurfaceTile.prototype.freeResources = function() {
if (defined_default(this.waterMaskTexture)) {
--this.waterMaskTexture.referenceCount;
if (this.waterMaskTexture.referenceCount === 0) {
this.waterMaskTexture.destroy();
}
this.waterMaskTexture = void 0;
}
this.terrainData = void 0;
this.terrainState = TerrainState_default.UNLOADED;
this.mesh = void 0;
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 = void 0;
GlobeSurfaceTile._freeVertexArray(this.wireframeVertexArray);
this.wireframeVertexArray = void 0;
};
GlobeSurfaceTile.initialize = function(tile, terrainProvider, imageryLayerCollection) {
let surfaceTile = tile.data;
if (!defined_default(surfaceTile)) {
surfaceTile = tile.data = new GlobeSurfaceTile();
}
if (tile.state === QuadtreeTileLoadState_default.START) {
prepareNewTile(tile, terrainProvider, imageryLayerCollection);
tile.state = QuadtreeTileLoadState_default.LOADING;
}
};
GlobeSurfaceTile.processStateMachine = function(tile, frameState, terrainProvider, imageryLayerCollection, quadtree, vertexArraysToDestroy, terrainOnly) {
GlobeSurfaceTile.initialize(tile, terrainProvider, imageryLayerCollection);
const surfaceTile = tile.data;
if (tile.state === QuadtreeTileLoadState_default.LOADING) {
processTerrainStateMachine(
tile,
frameState,
terrainProvider,
imageryLayerCollection,
quadtree,
vertexArraysToDestroy
);
}
if (terrainOnly) {
return;
}
const wasAlreadyRenderable = tile.renderable;
tile.renderable = defined_default(surfaceTile.vertexArray);
const isTerrainDoneLoading = surfaceTile.terrainState === TerrainState_default.READY;
tile.upsampledFromParent = defined_default(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_default.DONE;
}
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;
const tileImageryCollection = surfaceTile.imagery;
let i, len;
for (i = 0, len = tileImageryCollection.length; i < len; ++i) {
const tileImagery = tileImageryCollection[i];
if (!defined_default(tileImagery.loadingImagery)) {
isUpsampledOnly = false;
continue;
}
if (tileImagery.loadingImagery.state === ImageryState_default.PLACEHOLDER) {
const imageryLayer = tileImagery.loadingImagery.imageryLayer;
if (imageryLayer.ready && imageryLayer.imageryProvider._ready) {
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;
isAnyTileLoaded = isAnyTileLoaded || thisTileDoneLoading || defined_default(tileImagery.readyImagery);
isUpsampledOnly = isUpsampledOnly && defined_default(tileImagery.loadingImagery) && (tileImagery.loadingImagery.state === ImageryState_default.FAILED || tileImagery.loadingImagery.state === ImageryState_default.INVALID);
}
tile.upsampledFromParent = isUpsampledOnly;
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;
let newEncoding = TerrainEncoding_default.clone(encoding);
newEncoding.hasGeodeticSurfaceNormals = enabled;
newEncoding = TerrainEncoding_default.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;
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 = void 0;
}
GlobeSurfaceTile.prototype.addGeodeticSurfaceNormals = function(ellipsoid, frameState) {
toggleGeodeticSurfaceNormals(this, true, ellipsoid, frameState);
};
GlobeSurfaceTile.prototype.removeGeodeticSurfaceNormals = function(frameState) {
toggleGeodeticSurfaceNormals(this, false, void 0, frameState);
};
GlobeSurfaceTile.prototype.updateExaggeration = function(tile, frameState, quadtree) {
const surfaceTile = this;
const mesh = surfaceTile.renderedMesh;
if (mesh === void 0) {
return;
}
const exaggeration = frameState.terrainExaggeration;
const exaggerationRelativeHeight = frameState.terrainExaggerationRelativeHeight;
const hasExaggerationScale = exaggeration !== 1;
const encoding = mesh.encoding;
const encodingExaggerationScaleChanged = encoding.exaggeration !== exaggeration;
const encodingRelativeHeightChanged = encoding.exaggerationRelativeHeight !== exaggerationRelativeHeight;
if (encodingExaggerationScaleChanged || encodingRelativeHeightChanged) {
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;
if (quadtree !== void 0) {
quadtree._tileToUpdateHeights.push(tile);
const customData = tile.customData;
const customDataLength = customData.length;
for (let i = 0; i < customDataLength; i++) {
const data = customData[i];
data.level = -1;
}
}
}
};
function prepareNewTile(tile, terrainProvider, imageryLayerCollection) {
let available = terrainProvider.getTileDataAvailable(
tile.x,
tile.y,
tile.level
);
if (!defined_default(available) && defined_default(tile.parent)) {
const parent = tile.parent;
const parentSurfaceTile = parent.data;
if (defined_default(parentSurfaceTile) && defined_default(parentSurfaceTile.terrainData)) {
available = parentSurfaceTile.terrainData.isChildAvailable(
parent.x,
parent.y,
tile.x,
tile.y
);
}
}
if (available === false) {
tile.data.terrainState = TerrainState_default.FAILED;
}
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;
const parent = tile.parent;
if (surfaceTile.terrainState === TerrainState_default.FAILED && parent !== void 0) {
const parentReady = parent.data !== void 0 && parent.data.terrainData !== void 0 && parent.data.terrainData.canUpsample !== false;
if (!parentReady) {
GlobeSurfaceTile.processStateMachine(
parent,
frameState,
terrainProvider,
imageryLayerCollection,
quadtree,
vertexArraysToDestroy,
true
);
}
}
if (surfaceTile.terrainState === TerrainState_default.FAILED) {
upsample(
surfaceTile,
tile,
frameState,
terrainProvider,
tile.x,
tile.y,
tile.level
);
}
if (surfaceTile.terrainState === TerrainState_default.UNLOADED) {
requestTileGeometry(
surfaceTile,
terrainProvider,
tile.x,
tile.y,
tile.level
);
}
if (surfaceTile.terrainState === TerrainState_default.RECEIVED) {
transform2(
surfaceTile,
frameState,
terrainProvider,
tile.x,
tile.y,
tile.level
);
}
if (surfaceTile.terrainState === TerrainState_default.TRANSFORMED) {
createResources2(
surfaceTile,
frameState.context,
terrainProvider,
tile.x,
tile.y,
tile.level,
vertexArraysToDestroy
);
surfaceTile.updateExaggeration(tile, frameState, quadtree);
}
if (surfaceTile.terrainState >= TerrainState_default.RECEIVED && surfaceTile.waterMaskTexture === void 0 && terrainProvider.hasWaterMask) {
const terrainData = surfaceTile.terrainData;
if (terrainData.waterMask !== void 0) {
createWaterMaskTextureIfNeeded(frameState.context, surfaceTile);
} else {
const sourceTile = surfaceTile._findAncestorTileWithTerrainData(tile);
if (defined_default(sourceTile) && defined_default(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) {
tile.state = QuadtreeTileLoadState_default.FAILED;
return;
}
const sourceData = parent.data.terrainData;
const sourceX = parent.x;
const sourceY = parent.y;
const sourceLevel = parent.level;
if (!defined_default(sourceData)) {
return;
}
const terrainDataPromise = sourceData.upsample(
terrainProvider.tilingScheme,
sourceX,
sourceY,
sourceLevel,
x,
y,
level
);
if (!defined_default(terrainDataPromise)) {
return;
}
surfaceTile.terrainState = TerrainState_default.RECEIVING;
Promise.resolve(terrainDataPromise).then(function(terrainData) {
surfaceTile.terrainData = terrainData;
surfaceTile.terrainState = TerrainState_default.RECEIVED;
}).catch(function() {
surfaceTile.terrainState = TerrainState_default.FAILED;
});
}
function requestTileGeometry(surfaceTile, terrainProvider, x, y, level) {
function success(terrainData) {
surfaceTile.terrainData = terrainData;
surfaceTile.terrainState = TerrainState_default.RECEIVED;
surfaceTile.request = void 0;
}
function failure2(error) {
if (surfaceTile.request.state === RequestState_default.CANCELLED) {
surfaceTile.terrainData = void 0;
surfaceTile.terrainState = TerrainState_default.UNLOADED;
surfaceTile.request = void 0;
return;
}
surfaceTile.terrainState = TerrainState_default.FAILED;
surfaceTile.request = void 0;
const message = `Failed to obtain terrain tile X: ${x} Y: ${y} Level: ${level}. Error message: "${error}"`;
terrainProvider._requestError = TileProviderError_default.reportError(
terrainProvider._requestError,
terrainProvider,
terrainProvider.errorEvent,
message,
x,
y,
level
);
if (terrainProvider._requestError.retry) {
doRequest2();
}
}
function doRequest2() {
const request = new Request_default({
throttle: false,
throttleByServer: true,
type: RequestType_default.TERRAIN
});
surfaceTile.request = request;
const requestPromise = terrainProvider.requestTileGeometry(
x,
y,
level,
request
);
if (defined_default(requestPromise)) {
surfaceTile.terrainState = TerrainState_default.RECEIVING;
Promise.resolve(requestPromise).then(function(terrainData) {
success(terrainData);
}).catch(function(e) {
failure2(e);
});
} else {
surfaceTile.terrainState = TerrainState_default.UNLOADED;
surfaceTile.request = void 0;
}
}
doRequest2();
}
var scratchCreateMeshOptions = {
tilingScheme: void 0,
x: 0,
y: 0,
level: 0,
exaggeration: 1,
exaggerationRelativeHeight: 0,
throttle: true
};
function transform2(surfaceTile, frameState, terrainProvider, x, y, level) {
const tilingScheme2 = terrainProvider.tilingScheme;
const createMeshOptions = scratchCreateMeshOptions;
createMeshOptions.tilingScheme = tilingScheme2;
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_default(meshPromise)) {
return;
}
surfaceTile.terrainState = TerrainState_default.TRANSFORMING;
Promise.resolve(meshPromise).then(function(mesh) {
surfaceTile.mesh = mesh;
surfaceTile.terrainState = TerrainState_default.TRANSFORMED;
}).catch(function() {
surfaceTile.terrainState = TerrainState_default.FAILED;
});
}
GlobeSurfaceTile._createVertexArrayForMesh = function(context, mesh) {
const typedArray = mesh.vertices;
const buffer = Buffer_default.createVertexBuffer({
context,
typedArray,
usage: BufferUsage_default.STATIC_DRAW
});
const attributes = mesh.encoding.getAttributes(buffer);
const indexBuffers = mesh.indices.indexBuffers || {};
let indexBuffer = indexBuffers[context.id];
if (!defined_default(indexBuffer) || indexBuffer.isDestroyed()) {
const indices2 = mesh.indices;
indexBuffer = Buffer_default.createIndexBuffer({
context,
typedArray: indices2,
usage: BufferUsage_default.STATIC_DRAW,
indexDatatype: IndexDatatype_default.fromSizeInBytes(indices2.BYTES_PER_ELEMENT)
});
indexBuffer.vertexArrayDestroyable = false;
indexBuffer.referenceCount = 1;
indexBuffers[context.id] = indexBuffer;
mesh.indices.indexBuffers = indexBuffers;
} else {
++indexBuffer.referenceCount;
}
return new VertexArray_default({
context,
attributes,
indexBuffer
});
};
GlobeSurfaceTile._freeVertexArray = function(vertexArray) {
if (defined_default(vertexArray)) {
const indexBuffer = vertexArray.indexBuffer;
if (!vertexArray.isDestroyed()) {
vertexArray.destroy();
}
if (defined_default(indexBuffer) && !indexBuffer.isDestroyed() && defined_default(indexBuffer.referenceCount)) {
--indexBuffer.referenceCount;
if (indexBuffer.referenceCount === 0) {
indexBuffer.destroy();
}
}
}
};
function createResources2(surfaceTile, context, terrainProvider, x, y, level, vertexArraysToDestroy) {
surfaceTile.vertexArray = GlobeSurfaceTile._createVertexArrayForMesh(
context,
surfaceTile.mesh
);
surfaceTile.terrainState = TerrainState_default.READY;
surfaceTile.fill = surfaceTile.fill && surfaceTile.fill.destroy(vertexArraysToDestroy);
}
function getContextWaterMaskData(context) {
let data = context.cache.tile_waterMaskData;
if (!defined_default(data)) {
const allWaterTexture = Texture_default.create({
context,
pixelFormat: PixelFormat_default.LUMINANCE,
pixelDatatype: PixelDatatype_default.UNSIGNED_BYTE,
source: {
arrayBufferView: new Uint8Array([255]),
width: 1,
height: 1
}
});
allWaterTexture.referenceCount = 1;
const sampler = new Sampler_default({
wrapS: TextureWrap_default.CLAMP_TO_EDGE,
wrapT: TextureWrap_default.CLAMP_TO_EDGE,
minificationFilter: TextureMinificationFilter_default.LINEAR,
magnificationFilter: TextureMagnificationFilter_default.LINEAR
});
data = {
allWaterTexture,
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) {
if (waterMask[0] !== 0) {
texture = waterMaskData.allWaterTexture;
} else {
return;
}
} else {
const textureSize = Math.sqrt(waterMaskLength);
texture = Texture_default.create({
context,
pixelFormat: PixelFormat_default.LUMINANCE,
pixelDatatype: PixelDatatype_default.UNSIGNED_BYTE,
source: {
width: textureSize,
height: textureSize,
arrayBufferView: waterMask
},
sampler: waterMaskData.sampler,
flipY: false
});
texture.referenceCount = 0;
}
++texture.referenceCount;
surfaceTile.waterMaskTexture = texture;
Cartesian4_default.fromElements(
0,
0,
1,
1,
surfaceTile.waterMaskTranslationAndScale
);
}
GlobeSurfaceTile.prototype._findAncestorTileWithTerrainData = function(tile) {
let sourceTile = tile.parent;
while (defined_default(sourceTile) && (!defined_default(sourceTile.data) || !defined_default(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;
};
var GlobeSurfaceTile_default = GlobeSurfaceTile;
// node_modules/@cesium/engine/Source/Core/WebMercatorTilingScheme.js
function WebMercatorTilingScheme(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
this._ellipsoid = defaultValue_default(options.ellipsoid, Ellipsoid_default.WGS84);
this._numberOfLevelZeroTilesX = defaultValue_default(
options.numberOfLevelZeroTilesX,
1
);
this._numberOfLevelZeroTilesY = defaultValue_default(
options.numberOfLevelZeroTilesY,
1
);
this._projection = new WebMercatorProjection_default(this._ellipsoid);
if (defined_default(options.rectangleSouthwestInMeters) && defined_default(options.rectangleNortheastInMeters)) {
this._rectangleSouthwestInMeters = options.rectangleSouthwestInMeters;
this._rectangleNortheastInMeters = options.rectangleNortheastInMeters;
} else {
const semimajorAxisTimesPi = this._ellipsoid.maximumRadius * Math.PI;
this._rectangleSouthwestInMeters = new Cartesian2_default(
-semimajorAxisTimesPi,
-semimajorAxisTimesPi
);
this._rectangleNortheastInMeters = new Cartesian2_default(
semimajorAxisTimesPi,
semimajorAxisTimesPi
);
}
const southwest = this._projection.unproject(
this._rectangleSouthwestInMeters
);
const northeast = this._projection.unproject(
this._rectangleNortheastInMeters
);
this._rectangle = new Rectangle_default(
southwest.longitude,
southwest.latitude,
northeast.longitude,
northeast.latitude
);
}
Object.defineProperties(WebMercatorTilingScheme.prototype, {
ellipsoid: {
get: function() {
return this._ellipsoid;
}
},
rectangle: {
get: function() {
return this._rectangle;
}
},
projection: {
get: function() {
return this._projection;
}
}
});
WebMercatorTilingScheme.prototype.getNumberOfXTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesX << level;
};
WebMercatorTilingScheme.prototype.getNumberOfYTilesAtLevel = function(level) {
return this._numberOfLevelZeroTilesY << level;
};
WebMercatorTilingScheme.prototype.rectangleToNativeRectangle = function(rectangle, result) {
const projection = this._projection;
const southwest = projection.project(Rectangle_default.southwest(rectangle));
const northeast = projection.project(Rectangle_default.northeast(rectangle));
if (!defined_default(result)) {
return new Rectangle_default(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;
};
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_default(result)) {
return new Rectangle_default(west, south, east, north);
}
result.west = west;
result.south = south;
result.east = east;
result.north = north;
return result;
};
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_default(nativeRectangle.west, nativeRectangle.south)
);
const northeast = projection.unproject(
new Cartesian2_default(nativeRectangle.east, nativeRectangle.north)
);
nativeRectangle.west = southwest.longitude;
nativeRectangle.south = southwest.latitude;
nativeRectangle.east = northeast.longitude;
nativeRectangle.north = northeast.latitude;
return nativeRectangle;
};
WebMercatorTilingScheme.prototype.positionToTileXY = function(position, level, result) {
const rectangle = this._rectangle;
if (!Rectangle_default.contains(rectangle, position)) {
return void 0;
}
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_default(result)) {
return new Cartesian2_default(xTileCoordinate, yTileCoordinate);
}
result.x = xTileCoordinate;
result.y = yTileCoordinate;
return result;
};
var WebMercatorTilingScheme_default = WebMercatorTilingScheme;
// node_modules/@cesium/engine/Source/Scene/ArcGisMapService.js
var defaultTokenCredit2;
var defaultAccessToken2 = "AAPKd815e334cb774973b7245e23a67f4d08Js7A8e8xvfBpgnZIzp1jbL3FWJTmx7AKG8wa87OwDcWEu4CxQCNiydpPbGpALiTf";
var ArcGisMapService = {};
ArcGisMapService.defaultAccessToken = defaultAccessToken2;
ArcGisMapService.defaultWorldImageryServer = new Resource_default({
url: "https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer"
});
ArcGisMapService.defaultWorldHillshadeServer = new Resource_default({
url: "https://ibasemaps-api.arcgis.com/arcgis/rest/services/Elevation/World_Hillshade/MapServer"
});
ArcGisMapService.defaultWorldOceanServer = new Resource_default({
url: "https://ibasemaps-api.arcgis.com/arcgis/rest/services/Ocean/World_Ocean_Base/MapServer"
});
ArcGisMapService.getDefaultTokenCredit = function(providedKey) {
if (providedKey !== defaultAccessToken2) {
return void 0;
}
if (!defined_default(defaultTokenCredit2)) {
const defaultTokenMessage = ' This application is using a default ArcGIS access token. Please assign Cesium.ArcGisMapService.defaultAccessToken with an API key from your ArcGIS Developer account before using the ArcGIS tile services. You can sign up for a free ArcGIS Developer account at https://developers.arcgis.com/.';
defaultTokenCredit2 = new Credit_default(defaultTokenMessage, true);
}
return defaultTokenCredit2;
};
var ArcGisMapService_default = ArcGisMapService;
// node_modules/@cesium/engine/Source/Scene/DiscardMissingTileImagePolicy.js
function DiscardMissingTileImagePolicy(options) {
options = defaultValue_default(options, defaultValue_default.EMPTY_OBJECT);
if (!defined_default(options.missingImageUrl)) {
throw new DeveloperError_default("options.missingImageUrl is required.");
}
if (!defined_default(options.pixelsToCheck)) {
throw new DeveloperError_default("options.pixelsToCheck is required.");
}
this._pixelsToCheck = options.pixelsToCheck;
this._missingImagePixels = void 0;
this._missingImageByteLength = void 0;
this._isReady = false;
const resource = Resource_default.createIfNeeded(options.missingImageUrl);
const that = this;
function success(image) {
if (defined_default(image.blob)) {
that._missingImageByteLength = image.blob.size;
}
let pixels = getImagePixels_default(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 = void 0;
}
}
that._missingImagePixels = pixels;
that._isReady = true;
}
function failure2() {
that._missingImagePixels = void 0;
that._isReady = true;
}
resource.fetchImage({
preferBlob: true,
preferImageBitmap: true,
flipY: true
}).then(success).catch(failure2);
}
DiscardMissingTileImagePolicy.prototype.isReady = function() {
return this._isReady;
};
DiscardMissingTileImagePolicy.prototype.shouldDiscardImage = function(image) {
if (!this._isReady) {
throw new DeveloperError_default(
"shouldDiscardImage must not be called before the discard policy is ready."
);
}
const pixelsToCheck = this._pixelsToCheck;
const missingImagePixels = this._missingImagePixels;
if (!defined_default(missingImagePixels)) {
return false;
}
if (defined_default(image.blob) && image.blob.size !== this._missingImageByteLength) {
return false;
}
const pixels = getImagePixels_default(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 offset2 = 0; offset2 < 4; ++offset2) {
const pixel = index + offset2;
if (pixels[pixel] !== missingImagePixels[pixel]) {
return false;
}
}
}
return true;
};
var DiscardMissingTileImagePolicy_default = DiscardMissingTileImagePolicy;
// node_modules/@cesium/engine/Source/Scene/ImageryLayerFeatureInfo.js
function ImageryLayerFeatureInfo() {
this.name = void 0;
this.description = void 0;
this.position = void 0;
this.data = void 0;
this.imageryLayer = void 0;
}
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_default(nameProperty)) {
this.name = properties[nameProperty];
}
};
ImageryLayerFeatureInfo.prototype.configureDescriptionFromProperties = function(properties) {
function describe(properties2) {
let html2 = '
';
for (const key in properties2) {
if (properties2.hasOwnProperty(key)) {
const value = properties2[key];
if (defined_default(value)) {
if (typeof value === "object") {
html2 += `