Agriculture-front-end/dist/assets/Environment.dbf64ec6.js

14740 lines
3.3 MiB
JavaScript
Raw Normal View History

import{Q as pP,a3 as e_,_ as eU,r as Ps,a2 as zq,x as Uq,a4 as kq,d as ea,o as _x,c as gx,N as Vq,e as Xn,w as ic,l as is,A as jf,f as gr,m as tU,I as Hq,a5 as Gq,a6 as em,a7 as jq,n as dg,K as mL,M as _L,J as gL,O as yL,a8 as Wq}from"./index.9f28707e.js";import{R as qq}from"./index.030fe210.js";import{d as Yq}from"./download.da137c17.js";function $q(e){return pP({url:"/hjjc/sxjg",method:"get",params:e})}function Xq(e){return pP({url:"/hjjc/gjmchqjwd",method:"get",params:e})}function Tb(e){return pP({url:"/hjjc/gjdevhsjqcx",method:"get",params:e})}function c(e){return e!=null}function E(e){this.name="DeveloperError",this.message=e;let t;try{throw new Error}catch(n){t=n.stack}this.stack=t}c(Object.create)&&(E.prototype=Object.create(Error.prototype),E.prototype.constructor=E);E.prototype.toString=function(){let e=`${this.name}: ${this.message}`;return c(this.stack)&&(e+=`
${this.stack.toString()}`),e};E.throwInstantiationError=function(){throw new E("This function defines an interface and should not be called directly.")};const Wo={};Wo.typeOf={};function Qq(e){return`${e} is required, actual value was undefined`}function k_(e,t,n){return`Expected ${n} to be typeof ${t}, actual typeof was ${e}`}Wo.defined=function(e,t){if(!c(t))throw new E(Qq(e))};Wo.typeOf.func=function(e,t){if(typeof t!="function")throw new E(k_(typeof t,"function",e))};Wo.typeOf.string=function(e,t){if(typeof t!="string")throw new E(k_(typeof t,"string",e))};Wo.typeOf.number=function(e,t){if(typeof t!="number")throw new E(k_(typeof t,"number",e))};Wo.typeOf.number.lessThan=function(e,t,n){if(Wo.typeOf.number(e,t),t>=n)throw new E(`Expected ${e} to be less than ${n}, actual value was ${t}`)};Wo.typeOf.number.lessThanOrEquals=function(e,t,n){if(Wo.typeOf.number(e,t),t>n)throw new E(`Expected ${e} to be less than or equal to ${n}, actual value was ${t}`)};Wo.typeOf.number.greaterThan=function(e,t,n){if(Wo.typeOf.number(e,t),t<=n)throw new E(`Expected ${e} to be greater than ${n}, actual value was ${t}`)};Wo.typeOf.number.greaterThanOrEquals=function(e,t,n){if(Wo.typeOf.number(e,t),t<n)throw new E(`Expected ${e} to be greater than or equal to ${n}, actual value was ${t}`)};Wo.typeOf.object=function(e,t){if(typeof t!="object")throw new E(k_(typeof t,"object",e))};Wo.typeOf.bool=function(e,t){if(typeof t!="boolean")throw new E(k_(typeof t,"boolean",e))};Wo.typeOf.bigint=function(e,t){if(typeof t!="bigint")throw new E(k_(typeof t,"bigint",e))};Wo.typeOf.number.equals=function(e,t,n,i){if(Wo.typeOf.number(e,n),Wo.typeOf.number(t,i),n!==i)throw new E(`${e} must be equal to ${t}, the actual values are ${n} and ${i}`)};const A=Wo;function y(e,t){return e!=null?e:t}y.EMPTY_OBJECT=Object.freeze({});var yd=function(e){e==null&&(e=new Date().getTime()),this.N=624,this.M=397,this.MATRIX_A=2567483615,this.UPPER_MASK=2147483648,this.LOWER_MASK=2147483647,this.mt=new Array(this.N),this.mti=this.N+1,e.constructor==Array?this.init_by_array(e,e.length):this.init_seed(e)};yd.prototype.init_seed=function(e){for(this.mt[0]=e>>>0,this.mti=1;this.mti<this.N;this.mti++){var e=this.mt[this.mti-1]^this.mt[this.mti-1]>>>30;this.mt[this.mti]=(((e&4294901760)>>>16)*1812433253<<16)+(e&65535)*1812433253+this.mti,this.mt[this.mti]>>>=0}};yd.prototype.init_by_array=function(e,t){var n,i,o;for(this.init_seed(19650218),n=1,i=0,o=this.N>t?this.N:t;o;o--){var r=this.mt[n-1]^this.mt[n-1]>>>30;this.mt[n]=(this.mt[n]^(((r&4294901760)>>>16)*1664525<<16)+(r&65535)*1664525)+e[i]+i,this.mt[n]>>>=0,n++,i++,n>=this.N&&(this.mt[0]=this.mt[this.N-1],n=1),i>=t&&(i=0)}for(o=this.N-1;o;o--){var r=this.mt[n-1]^this.mt[n-1]>>>30;this.mt[n]=(this.mt[n]^(((r&4294901760)>>>16)*1566083941<<16)+(r&65535)*1566083941)-n,this.mt[n]>>>=0,n++,n>=this.N&&(this.mt[0]=this.mt[this.N-1],n=1)}this.mt[0]=2147483648};yd.prototype.random_int=function(){var e,t=new Array(0,this.MATRIX_A);if(this.mti>=this.N){var n;for(this.mti==this.N+1&&this.init_seed(5489),n=0;n<this.N-this.M;n++)e=this.mt[n]&this.UPPER_MASK|this.mt[n+1]&this.LOWER_MASK,this.mt[n]=this.mt[n+this.M]^e>>>1^t[e&1];for(;n<this.N-1;n++)e=this.mt[n]&this.UPPER_MASK|this.mt[n+1]&this.LOWER_MASK,this.mt[n]=this.mt[n+(this.M-this.N)]^e>>>1^t[e&1];e=this.mt[this.N-1]&this.UPPER_MASK|this.mt[0]&this.LOWER_MASK,this.mt[this.N-1]=this.mt[this.M-1]^e>>>1^t[e&1],this.mti=0}return e=this.mt[this.mti++],e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,e>>>0};yd.prototype.random_int31=function(){return this.random_int()>>>1};yd.prototype.random_incl=function(){return this.random_int()*(1/4294967295)};yd.prototype.random=function(){return this.random_int()*(1/4294967296)};yd.prototype.random_excl=function(){return(this.random_int()+.5)*(1/4294967296)};yd.prototype.random_long=function(){var e=this.random_int()>>>5,t=this.random_int()>>>6;return(e*67108864+t)*(1/9007199254740992)};var fC=yd;const Be={};Be.EPSILON1=.1;Be.EPSILON2=.01;Be.EPSILON3=.001;Be.EPSILON4=1e-4;Be.EPSILON5=1e-5;Be.EPSILON6=1e-6;Be.EPSILON7=1e-7;Be.EPSILON8=1e-8;
(${this[1]}, ${this[4]}, ${this[7]})
(${this[2]}, ${this[5]}, ${this[8]})`};function Te(e){this.name="RuntimeError",this.message=e;let t;try{throw new Error}catch(n){t=n.stack}this.stack=t}c(Object.create)&&(Te.prototype=Object.create(Error.prototype),Te.prototype.constructor=Te);Te.prototype.toString=function(){let e=`${this.name}: ${this.message}`;return c(this.stack)&&(e+=`
${this.stack.toString()}`),e};function L(e,t,n,i,o,r,s,a,l,u,h,f,_,g,m,b){this[0]=y(e,0),this[1]=y(o,0),this[2]=y(l,0),this[3]=y(_,0),this[4]=y(t,0),this[5]=y(r,0),this[6]=y(u,0),this[7]=y(g,0),this[8]=y(n,0),this[9]=y(s,0),this[10]=y(h,0),this[11]=y(m,0),this[12]=y(i,0),this[13]=y(a,0),this[14]=y(f,0),this[15]=y(b,0)}L.packedLength=16;L.pack=function(e,t,n){return A.typeOf.object("value",e),A.defined("array",t),n=y(n,0),t[n++]=e[0],t[n++]=e[1],t[n++]=e[2],t[n++]=e[3],t[n++]=e[4],t[n++]=e[5],t[n++]=e[6],t[n++]=e[7],t[n++]=e[8],t[n++]=e[9],t[n++]=e[10],t[n++]=e[11],t[n++]=e[12],t[n++]=e[13],t[n++]=e[14],t[n]=e[15],t};L.unpack=function(e,t,n){return A.defined("array",e),t=y(t,0),c(n)||(n=new L),n[0]=e[t++],n[1]=e[t++],n[2]=e[t++],n[3]=e[t++],n[4]=e[t++],n[5]=e[t++],n[6]=e[t++],n[7]=e[t++],n[8]=e[t++],n[9]=e[t++],n[10]=e[t++],n[11]=e[t++],n[12]=e[t++],n[13]=e[t++],n[14]=e[t++],n[15]=e[t],n};L.packArray=function(e,t){A.defined("array",e);const n=e.length,i=n*16;if(!c(t))t=new Array(i);else{if(!Array.isArray(t)&&t.length!==i)throw new E("If result is a typed array, it must have exactly array.length * 16 elements");t.length!==i&&(t.length=i)}for(let o=0;o<n;++o)L.pack(e[o],t,o*16);return t};L.unpackArray=function(e,t){if(A.defined("array",e),A.typeOf.number.greaterThanOrEquals("array.length",e.length,16),e.length%16!==0)throw new E("array length must be a multiple of 16.");const n=e.length;c(t)?t.length=n/16:t=new Array(n/16);for(let i=0;i<n;i+=16){const o=i/16;t[o]=L.unpack(e,i,t[o])}return t};L.clone=function(e,t){if(!!c(e))return c(t)?(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t):new L(e[0],e[4],e[8],e[12],e[1],e[5],e[9],e[13],e[2],e[6],e[10],e[14],e[3],e[7],e[11],e[15])};L.fromArray=L.unpack;L.fromColumnMajorArray=function(e,t){return A.defined("values",e),L.clone(e,t)};L.fromRowMajorArray=function(e,t){return A.defined("values",e),c(t)?(t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t):new L(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])};L.fromRotationTranslation=function(e,t,n){return A.typeOf.object("rotation",e),t=y(t,d.ZERO),c(n)?(n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=0,n[4]=e[3],n[5]=e[4],n[6]=e[5],n[7]=0,n[8]=e[6],n[9]=e[7],n[10]=e[8],n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,n):new L(e[0],e[3],e[6],t.x,e[1],e[4],e[7],t.y,e[2],e[5],e[8],t.z,0,0,0,1)};L.fromTranslationQuaternionRotationScale=function(e,t,n,i){A.typeOf.object("translation",e),A.typeOf.object("rotation",t),A.typeOf.object("scale",n),c(i)||(i=new L);const o=n.x,r=n.y,s=n.z,a=t.x*t.x,l=t.x*t.y,u=t.x*t.z,h=t.x*t.w,f=t.y*t.y,_=t.y*t.z,g=t.y*t.w,m=t.z*t.z,b=t.z*t.w,T=t.w*t.w,x=a-f-m+T,C=2*(l-b),w=2*(u+g),v=2*(l+b),P=-a+f-m+T,N=2*(_-h),k=2*(u-g),M=2*(_+h),U=-a-f+m+T;return i[0]=x*o,i[1]=v*o,i[2]=k*o,i[3]=0,i[4]=C*r,i[5]=P*r,i[6]=M*r,i[7]=0,i[8]=w*s,i[9]=N*s,i[10]=U*s,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,i};L.fromTranslationRotationScale=function(e,t){return A.typeOf.object("translationRotationScale",e),L.fromTranslationQuaternionRotationScale(e.translation,e.rotation,e.scale,t)};L.fromTranslation=function(e,t){return A.typeOf.object("translation",e),L.fromRotationTranslation($.IDENTITY,e,t)};L.fromScale=function(e,t){return A.typeOf.object("scale",e),c(t)?(t[0]=e.x,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e.y,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e.z,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t):new L(e.x,0,0,0,0,e.y,0,0,0,0,e.z,0,0,0,0,1)};L.fromUniformScale=function(e,t){return A.typeOf.number("scale",e),c(t)?(t[0]=e,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t):new L(e,0,0,0,0,e,0,0,0,0,e,0,0,0,0,1)};L.fromRotation=function(e,t){return A.typeOf.object("rotation",e),c(t)||(t=new L),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[
(${this[1]}, ${this[5]}, ${this[9]}, ${this[13]})
(${this[2]}, ${this[6]}, ${this[10]}, ${this[14]})
(${this[3]}, ${this[7]}, ${this[11]}, ${this[15]})`};const b7={DEPTH_BUFFER_BIT:256,STENCIL_BUFFER_BIT:1024,COLOR_BUFFER_BIT:16384,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,ZERO:0,ONE:1,SRC_COLOR:768,ONE_MINUS_SRC_COLOR:769,SRC_ALPHA:770,ONE_MINUS_SRC_ALPHA:771,DST_ALPHA:772,ONE_MINUS_DST_ALPHA:773,DST_COLOR:774,ONE_MINUS_DST_COLOR:775,SRC_ALPHA_SATURATE:776,FUNC_ADD:32774,BLEND_EQUATION:32777,BLEND_EQUATION_RGB:32777,BLEND_EQUATION_ALPHA:34877,FUNC_SUBTRACT:32778,FUNC_REVERSE_SUBTRACT:32779,BLEND_DST_RGB:32968,BLEND_SRC_RGB:32969,BLEND_DST_ALPHA:32970,BLEND_SRC_ALPHA:32971,CONSTANT_COLOR:32769,ONE_MINUS_CONSTANT_COLOR:32770,CONSTANT_ALPHA:32771,ONE_MINUS_CONSTANT_ALPHA:32772,BLEND_COLOR:32773,ARRAY_BUFFER:34962,ELEMENT_ARRAY_BUFFER:34963,ARRAY_BUFFER_BINDING:34964,ELEMENT_ARRAY_BUFFER_BINDING:34965,STREAM_DRAW:35040,STATIC_DRAW:35044,DYNAMIC_DRAW:35048,BUFFER_SIZE:34660,BUFFER_USAGE:34661,CURRENT_VERTEX_ATTRIB:34342,FRONT:1028,BACK:1029,FRONT_AND_BACK:1032,CULL_FACE:2884,BLEND:3042,DITHER:3024,STENCIL_TEST:2960,DEPTH_TEST:2929,SCISSOR_TEST:3089,POLYGON_OFFSET_FILL:32823,SAMPLE_ALPHA_TO_COVERAGE:32926,SAMPLE_COVERAGE:32928,NO_ERROR:0,INVALID_ENUM:1280,INVALID_VALUE:1281,INVALID_OPERATION:1282,OUT_OF_MEMORY:1285,CW:2304,CCW:2305,LINE_WIDTH:2849,ALIASED_POINT_SIZE_RANGE:33901,ALIASED_LINE_WIDTH_RANGE:33902,CULL_FACE_MODE:2885,FRONT_FACE:2886,DEPTH_RANGE:2928,DEPTH_WRITEMASK:2930,DEPTH_CLEAR_VALUE:2931,DEPTH_FUNC:2932,STENCIL_CLEAR_VALUE:2961,STENCIL_FUNC:2962,STENCIL_FAIL:2964,STENCIL_PASS_DEPTH_FAIL:2965,STENCIL_PASS_DEPTH_PASS:2966,STENCIL_REF:2967,STENCIL_VALUE_MASK:2963,STENCIL_WRITEMASK:2968,STENCIL_BACK_FUNC:34816,STENCIL_BACK_FAIL:34817,STENCIL_BACK_PASS_DEPTH_FAIL:34818,STENCIL_BACK_PASS_DEPTH_PASS:34819,STENCIL_BACK_REF:36003,STENCIL_BACK_VALUE_MASK:36004,STENCIL_BACK_WRITEMASK:36005,VIEWPORT:2978,SCISSOR_BOX:3088,COLOR_CLEAR_VALUE:3106,COLOR_WRITEMASK:3107,UNPACK_ALIGNMENT:3317,PACK_ALIGNMENT:3333,MAX_TEXTURE_SIZE:3379,MAX_VIEWPORT_DIMS:3386,SUBPIXEL_BITS:3408,RED_BITS:3410,GREEN_BITS:3411,BLUE_BITS:3412,ALPHA_BITS:3413,DEPTH_BITS:3414,STENCIL_BITS:3415,POLYGON_OFFSET_UNITS:10752,POLYGON_OFFSET_FACTOR:32824,TEXTURE_BINDING_2D:32873,SAMPLE_BUFFERS:32936,SAMPLES:32937,SAMPLE_COVERAGE_VALUE:32938,SAMPLE_COVERAGE_INVERT:32939,COMPRESSED_TEXTURE_FORMATS:34467,DONT_CARE:4352,FASTEST:4353,NICEST:4354,GENERATE_MIPMAP_HINT:33170,BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,DEPTH_COMPONENT:6402,ALPHA:6406,RGB:6407,RGBA:6408,LUMINANCE:6409,LUMINANCE_ALPHA:6410,UNSIGNED_SHORT_4_4_4_4:32819,UNSIGNED_SHORT_5_5_5_1:32820,UNSIGNED_SHORT_5_6_5:33635,FRAGMENT_SHADER:35632,VERTEX_SHADER:35633,MAX_VERTEX_ATTRIBS:34921,MAX_VERTEX_UNIFORM_VECTORS:36347,MAX_VARYING_VECTORS:36348,MAX_COMBINED_TEXTURE_IMAGE_UNITS:35661,MAX_VERTEX_TEXTURE_IMAGE_UNITS:35660,MAX_TEXTURE_IMAGE_UNITS:34930,MAX_FRAGMENT_UNIFORM_VECTORS:36349,SHADER_TYPE:35663,DELETE_STATUS:35712,LINK_STATUS:35714,VALIDATE_STATUS:35715,ATTACHED_SHADERS:35717,ACTIVE_UNIFORMS:35718,ACTIVE_ATTRIBUTES:35721,SHADING_LANGUAGE_VERSION:35724,CURRENT_PROGRAM:35725,NEVER:512,LESS:513,EQUAL:514,LEQUAL:515,GREATER:516,NOTEQUAL:517,GEQUAL:518,ALWAYS:519,KEEP:7680,REPLACE:7681,INCR:7682,DECR:7683,INVERT:5386,INCR_WRAP:34055,DECR_WRAP:34056,VENDOR:7936,RENDERER:7937,VERSION:7938,NEAREST:9728,LINEAR:9729,NEAREST_MIPMAP_NEAREST:9984,LINEAR_MIPMAP_NEAREST:9985,NEAREST_MIPMAP_LINEAR:9986,LINEAR_MIPMAP_LINEAR:9987,TEXTURE_MAG_FILTER:10240,TEXTURE_MIN_FILTER:10241,TEXTURE_WRAP_S:10242,TEXTURE_WRAP_T:10243,TEXTURE_2D:3553,TEXTURE:5890,TEXTURE_CUBE_MAP:34067,TEXTURE_BINDING_CUBE_MAP:34068,TEXTURE_CUBE_MAP_POSITIVE_X:34069,TEXTURE_CUBE_MAP_NEGATIVE_X:34070,TEXTURE_CUBE_MAP_POSITIVE_Y:34071,TEXTURE_CUBE_MAP_NEGATIVE_Y:34072,TEXTURE_CUBE_MAP_POSITIVE_Z:34073,TEXTURE_CUBE_MAP_NEGATIVE_Z:34074,MAX_CUBE_MAP_TEXTURE_SIZE:34076,TEXTURE0:33984,TEXTURE1:33985,TEXTURE2:33986,TEXTURE3:33987,TEXTURE4:33988,TEXTURE5:33989,TEXTURE6:33990,TEXTURE7:33991,TEXTURE8:33992,TEXTURE9:33993,TEXTURE10:33994,TEXTURE11:33995,TEXTU
* URI.js - Mutating URLs
* IPv6 Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/var OL;function fY(){return OL||(OL=1,function(e){(function(t,n){e.exports?e.exports=n():t.IPv6=n(t)})(e_,function(t){var n=t&&t.IPv6;function i(r){var s=r.toLowerCase(),a=s.split(":"),l=a.length,u=8;a[0]===""&&a[1]===""&&a[2]===""?(a.shift(),a.shift()):a[0]===""&&a[1]===""?a.shift():a[l-1]===""&&a[l-2]===""&&a.pop(),l=a.length,a[l-1].indexOf(".")!==-1&&(u=7);var h;for(h=0;h<l&&a[h]!=="";h++);if(h<u)for(a.splice(h,1,"0000");a.length<u;)a.splice(h,0,"0000");for(var f,_=0;_<u;_++){f=a[_].split("");for(var g=0;g<3&&(f[0]==="0"&&f.length>1);g++)f.splice(0,1);a[_]=f.join("")}var m=-1,b=0,T=0,x=-1,C=!1;for(_=0;_<u;_++)C?a[_]==="0"?T+=1:(C=!1,T>b&&(m=x,b=T)):a[_]==="0"&&(C=!0,x=_,T=1);T>b&&(m=x,b=T),b>1&&a.splice(m,b,""),l=a.length;var w="";for(a[0]===""&&(w=":"),_=0;_<l&&(w+=a[_],_!==l-1);_++)w+=":";return a[l-1]===""&&(w+=":"),w}function o(){return t.IPv6===this&&(t.IPv6=n),this}return{best:i,noConflict:o}})}(UE)),UE.exports}var kE={exports:{}};/*!
* URI.js - Mutating URLs
* Second Level Domain (SLD) Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/var LL;function pY(){return LL||(LL=1,function(e){(function(t,n){e.exports?e.exports=n():t.SecondLevelDomains=n(t)})(e_,function(t){var n=t&&t.SecondLevelDomains,i={list:{ac:" com gov mil net org ",ae:" ac co gov mil name net org pro sch ",af:" com edu gov net org ",al:" com edu gov mil net org ",ao:" co ed gv it og pb ",ar:" com edu gob gov int mil net org tur ",at:" ac co gv or ",au:" asn com csiro edu gov id net org ",ba:" co com edu gov mil net org rs unbi unmo unsa untz unze ",bb:" biz co com edu gov info net org store tv ",bh:" biz cc com edu gov info net org ",bn:" com edu gov net org ",bo:" com edu gob gov int mil net org tv ",br:" adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ",bs:" com edu gov net org ",bz:" du et om ov rg ",ca:" ab bc mb nb nf nl ns nt nu on pe qc sk yk ",ck:" biz co edu gen gov info net org ",cn:" ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ",co:" com edu gov mil net nom org ",cr:" ac c co ed fi go or sa ",cy:" ac biz com ekloges gov ltd name net org parliament press pro tm ",do:" art com edu gob gov mil net org sld web ",dz:" art asso com edu gov net org pol ",ec:" com edu fin gov info med mil net org pro ",eg:" com edu eun gov mil name net org sci ",er:" com edu gov ind mil net org rochest w ",es:" com edu gob nom org ",et:" biz com edu gov info name net org ",fj:" ac biz com info mil name net org pro ",fk:" ac co gov net nom org ",fr:" asso com f gouv nom prd presse tm ",gg:" co net org ",gh:" com edu gov mil org ",gn:" ac com gov net org ",gr:" com edu gov mil net org ",gt:" com edu gob ind mil net org ",gu:" com edu gov net org ",hk:" com edu gov idv net org ",hu:" 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ",id:" ac co go mil net or sch web ",il:" ac co gov idf k12 muni net org ",in:" ac co edu ernet firm gen gov i ind mil net nic org res ",iq:" com edu gov i mil net org ",ir:" ac co dnssec gov i id net org sch ",it:" edu gov ",je:" co net org ",jo:" com edu gov mil name net org sch ",jp:" ac ad co ed go gr lg ne or ",ke:" ac co go info me mobi ne or sc ",kh:" com edu gov mil net org per ",ki:" biz com de edu gov info mob net org tel ",km:" asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ",kn:" edu gov net org ",kr:" ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ",kw:" com edu gov net org ",ky:" com edu gov net org ",kz:" com edu gov mil net org ",lb:" com edu gov net org ",lk:" assn com edu gov grp hotel int ltd net ngo org sch soc web ",lr:" com edu gov net org ",lv:" asn com conf edu gov id mil net org ",ly:" com edu gov id med net org plc sch ",ma:" ac co gov m net org press ",mc:" asso tm ",me:" ac co edu gov its net org priv ",mg:" com edu gov mil nom org prd tm ",mk:" com edu gov inf name net org pro ",ml:" com edu gov net org presse ",mn:" edu gov org ",mo:" com edu gov net org ",mt:" com edu gov net org ",mv:" aero biz com coop edu gov info int mil museum name net org pro ",mw:" ac co com coop edu gov int museum net org ",mx:" com edu gob net org ",my:" com edu gov mil name net org sch ",nf:" arts com firm info net other per rec store web ",ng:" biz com edu gov mil mobi name net org sch ",ni:" ac co com edu gob mil net nom org ",np:" com edu gov mil net org ",nr:" biz com edu gov info net org ",om:" ac biz co com edu gov med mil museum net org pro sch ",pe:" com edu gob mil net nom org sld ",ph:" com edu gov i mil net ngo org ",pk:" biz com edu fam gob gok gon gop gos gov net org web ",pl:" art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr r
* URI.js - Mutating URLs
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/(function(e){(function(t,n){e.exports?e.exports=n(hY(),fY(),pY()):t.URI=n(t.punycode,t.IPv6,t.SecondLevelDomains,t)})(e_,function(t,n,i,o){var r=o&&o.URI;function s(p,I){var O=arguments.length>=1,F=arguments.length>=2;if(!(this instanceof s))return O?F?new s(p,I):new s(p):new s;if(p===void 0){if(O)throw new TypeError("undefined is not a valid argument for URI");typeof location<"u"?p=location.href+"":p=""}if(p===null&&O)throw new TypeError("null is not a valid argument for URI");return this.href(p),I!==void 0?this.absoluteTo(I):this}function a(p){return/^[0-9]+$/.test(p)}s.version="1.19.11";var l=s.prototype,u=Object.prototype.hasOwnProperty;function h(p){return p.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")}function f(p){return p===void 0?"Undefined":String(Object.prototype.toString.call(p)).slice(8,-1)}function _(p){return f(p)==="Array"}function g(p,I){var O={},F,V;if(f(I)==="RegExp")O=null;else if(_(I))for(F=0,V=I.length;F<V;F++)O[I[F]]=!0;else O[I]=!0;for(F=0,V=p.length;F<V;F++){var G=O&&O[p[F]]!==void 0||!O&&I.test(p[F]);G&&(p.splice(F,1),V--,F--)}return p}function m(p,I){var O,F;if(_(I)){for(O=0,F=I.length;O<F;O++)if(!m(p,I[O]))return!1;return!0}var V=f(I);for(O=0,F=p.length;O<F;O++)if(V==="RegExp"){if(typeof p[O]=="string"&&p[O].match(I))return!0}else if(p[O]===I)return!0;return!1}function b(p,I){if(!_(p)||!_(I)||p.length!==I.length)return!1;p.sort(),I.sort();for(var O=0,F=p.length;O<F;O++)if(p[O]!==I[O])return!1;return!0}function T(p){var I=/^\/+|\/+$/g;return p.replace(I,"")}s._parts=function(){return{protocol:null,username:null,password:null,hostname:null,urn:null,port:null,path:null,query:null,fragment:null,preventInvalidHostname:s.preventInvalidHostname,duplicateQueryParameters:s.duplicateQueryParameters,escapeQuerySpace:s.escapeQuerySpace}},s.preventInvalidHostname=!1,s.duplicateQueryParameters=!1,s.escapeQuerySpace=!0,s.protocol_expression=/^[a-z][a-z0-9.+-]*$/i,s.idn_expression=/[^a-z0-9\._-]/i,s.punycode_expression=/(xn--)/i,s.ip4_expression=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,s.ip6_expression=/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,s.find_uri_expression=/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig,s.findUri={start:/\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,end:/[\s\r\n]|$/,trim:/[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,parens:/(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g},s.leading_whitespace_expression=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,s.ascii_tab_whitespace=/[\u0009\u000A\u000D]+/g,s.defaultPorts={http:"80",https:"443",ftp:"21",gopher:"70",ws:"80",wss:"443"},s.hostProtocols=["http","https"],s.invalid_hostname_characters=/[^a-zA-Z0-9\.\-:_]/,s.domAttributes={a:"href",blockquote:"cite",link:"href",base:"href",script:"src",form:"action",img:"src",area:"href",iframe:"src",embed:"src",source:"src",track:"src",input:"src",audio:"src",video:"src"},s.getDomAttribute=func
`);for(let i=0;i<n.length;++i){const o=n[i],r=o.indexOf(": ");if(r>0){const s=o.substring(0,r),a=o.substring(r+2);t[s]=a}}return t}function E_(e,t,n){this.statusCode=e,this.response=t,this.responseHeaders=n,typeof this.responseHeaders=="string"&&(this.responseHeaders=wY(this.responseHeaders))}E_.prototype.toString=function(){let e="Request has failed.";return c(this.statusCode)&&(e+=` Status Code: ${this.statusCode}`),e};function Le(){this._listeners=[],this._scopes=[],this._toRemove=[],this._insideRaiseEvent=!1}Object.defineProperties(Le.prototype,{numberOfListeners:{get:function(){return this._listeners.length-this._toRemove.length}}});Le.prototype.addEventListener=function(e,t){A.typeOf.func("listener",e),this._listeners.push(e),this._scopes.push(t);const n=this;return function(){n.removeEventListener(e,t)}};Le.prototype.removeEventListener=function(e,t){A.typeOf.func("listener",e);const n=this._listeners,i=this._scopes;let o=-1;for(let r=0;r<n.length;r++)if(n[r]===e&&i[r]===t){o=r;break}return o!==-1?(this._insideRaiseEvent?(this._toRemove.push(o),n[o]=void 0,i[o]=void 0):(n.splice(o,1),i.splice(o,1)),!0):!1};function SY(e,t){return t-e}Le.prototype.raiseEvent=function(){this._insideRaiseEvent=!0;let e;const t=this._listeners,n=this._scopes;let i=t.length;for(e=0;e<i;e++){const r=t[e];c(r)&&t[e].apply(n[e],arguments)}const o=this._toRemove;if(i=o.length,i>0){for(o.sort(SY),e=0;e<i;e++){const r=o[e];t.splice(r,1),n.splice(r,1)}o.length=0}this._insideRaiseEvent=!1};function Dp(e){A.typeOf.object("options",e),A.defined("options.comparator",e.comparator),this._comparator=e.comparator,this._array=[],this._length=0,this._maximumLength=void 0}Object.defineProperties(Dp.prototype,{length:{get:function(){return this._length}},internalArray:{get:function(){return this._array}},maximumLength:{get:function(){return this._maximumLength},set:function(e){A.typeOf.number.greaterThanOrEquals("maximumLength",e,0);const t=this._length;if(e<t){const n=this._array;for(let i=e;i<t;++i)n[i]=void 0;this._length=e,n.length=e}this._maximumLength=e}},comparator:{get:function(){return this._comparator}}});function EP(e,t,n){const i=e[t];e[t]=e[n],e[n]=i}Dp.prototype.reserve=function(e){e=y(e,this._length),this._array.length=e};Dp.prototype.heapify=function(e){e=y(e,0);const t=this._length,n=this._comparator,i=this._array;let o=-1,r=!0;for(;r;){const s=2*(e+1),a=s-1;a<t&&n(i[a],i[e])<0?o=a:o=e,s<t&&n(i[s],i[o])<0&&(o=s),o!==e?(EP(i,o,e),e=o):r=!1}};Dp.prototype.resort=function(){const e=this._length;for(let t=Math.ceil(e/2);t>=0;--t)this.heapify(t)};Dp.prototype.insert=function(e){A.defined("element",e);const t=this._array,n=this._comparator,i=this._maximumLength;let o=this._length++;for(o<t.length?t[o]=e:t.push(e);o!==0;){const s=Math.floor((o-1)/2);if(n(t[o],t[s])<0)EP(t,o,s),o=s;else break}let r;return c(i)&&this._length>i&&(r=t[i],this._length=i),r};Dp.prototype.pop=function(e){if(e=y(e,0),this._length===0)return;A.typeOf.number.lessThan("index",e,this._length);const t=this._array,n=t[e];return EP(t,e,--this._length),this.heapify(e),t[this._length]=void 0,n};function vY(e,t){return e.priority-t.priority}const Un={numberOfAttemptedRequests:0,numberOfActiveRequests:0,numberOfCancelledRequests:0,numberOfCancelledActiveRequests:0,numberOfFailedRequests:0,numberOfActiveRequestsEver:0,lastNumberOfActiveRequests:0};let t_=20;const us=new Dp({comparator:vY});us.maximumLength=t_;us.reserve(t_);const Xl=[];let cd={};const IY=typeof document<"u"?new Ec(document.location.href):new Ec,gC=new Le;function Nn(){}Nn.maximumRequests=50;Nn.maximumRequestsPerServer=18;Nn.requestsByServer={};Nn.throttleRequests=!0;Nn.debugShowStatistics=!1;Nn.requestCompletedEvent=gC;Object.defineProperties(Nn,{statistics:{get:function(){return Un}},priorityHeapLength:{get:function(){return t_},set:function(e){if(e<t_)for(;us.length>e;){const t=us.pop();Xf(t)}t_=e,us.maximumLength=e,us.reserve(e)}}});function yU(e){c(e.priorityFunction)&&(e.priority=e.priorityFunction())}Nn.serverHasOpenSlots=function(e,t){t=y(t,1);const n=y(Nn.requestsByServer[e],Nn.maximumRequestsPerServer);r
in vec2 textureCoordinates;
out vec2 v_textureCoordinates;
void main()
{
gl_Position = position;
v_textureCoordinates = textureCoordinates;
}
`,Wi={CULL:1,OCCLUDE:2,EXECUTE_IN_CLOSEST_FRUSTUM:4,DEBUG_SHOW_BOUNDING_VOLUME:8,CAST_SHADOWS:16,RECEIVE_SHADOWS:32,PICK_ONLY:64,DEPTH_FOR_TRANSLUCENT_CLASSIFICATION:128};function Ze(e){e=y(e,y.EMPTY_OBJECT),this._boundingVolume=e.boundingVolume,this._orientedBoundingBox=e.orientedBoundingBox,this._modelMatrix=e.modelMatrix,this._primitiveType=y(e.primitiveType,ze.TRIANGLES),this._vertexArray=e.vertexArray,this._count=e.count,this._offset=y(e.offset,0),this._instanceCount=y(e.instanceCount,0),this._shaderProgram=e.shaderProgram,this._uniformMap=e.uniformMap,this._renderState=e.renderState,this._framebuffer=e.framebuffer,this._pass=e.pass,this._owner=e.owner,this._debugOverlappingFrustums=0,this._pickId=e.pickId,this._flags=0,this.cull=y(e.cull,!0),this.occlude=y(e.occlude,!0),this.executeInClosestFrustum=y(e.executeInClosestFrustum,!1),this.debugShowBoundingVolume=y(e.debugShowBoundingVolume,!1),this.castShadows=y(e.castShadows,!1),this.receiveShadows=y(e.receiveShadows,!1),this.pickOnly=y(e.pickOnly,!1),this.depthForTranslucentClassification=y(e.depthForTranslucentClassification,!1),this.dirty=!0,this.lastDirtyTime=0,this.derivedCommands={}}function Kr(e,t){return(e._flags&t)===t}function zd(e,t,n){n?e._flags|=t:e._flags&=~t}Object.defineProperties(Ze.prototype,{boundingVolume:{get:function(){return this._boundingVolume},set:function(e){this._boundingVolume!==e&&(this._boundingVolume=e,this.dirty=!0)}},orientedBoundingBox:{get:function(){return this._orientedBoundingBox},set:function(e){this._orientedBoundingBox!==e&&(this._orientedBoundingBox=e,this.dirty=!0)}},cull:{get:function(){return Kr(this,Wi.CULL)},set:function(e){Kr(this,Wi.CULL)!==e&&(zd(this,Wi.CULL,e),this.dirty=!0)}},occlude:{get:function(){return Kr(this,Wi.OCCLUDE)},set:function(e){Kr(this,Wi.OCCLUDE)!==e&&(zd(this,Wi.OCCLUDE,e),this.dirty=!0)}},modelMatrix:{get:function(){return this._modelMatrix},set:function(e){this._modelMatrix!==e&&(this._modelMatrix=e,this.dirty=!0)}},primitiveType:{get:function(){return this._primitiveType},set:function(e){this._primitiveType!==e&&(this._primitiveType=e,this.dirty=!0)}},vertexArray:{get:function(){return this._vertexArray},set:function(e){this._vertexArray!==e&&(this._vertexArray=e,this.dirty=!0)}},count:{get:function(){return this._count},set:function(e){this._count!==e&&(this._count=e,this.dirty=!0)}},offset:{get:function(){return this._offset},set:function(e){this._offset!==e&&(this._offset=e,this.dirty=!0)}},instanceCount:{get:function(){return this._instanceCount},set:function(e){this._instanceCount!==e&&(this._instanceCount=e,this.dirty=!0)}},shaderProgram:{get:function(){return this._shaderProgram},set:function(e){this._shaderProgram!==e&&(this._shaderProgram=e,this.dirty=!0)}},castShadows:{get:function(){return Kr(this,Wi.CAST_SHADOWS)},set:function(e){Kr(this,Wi.CAST_SHADOWS)!==e&&(zd(this,Wi.CAST_SHADOWS,e),this.dirty=!0)}},receiveShadows:{get:function(){return Kr(this,Wi.RECEIVE_SHADOWS)},set:function(e){Kr(this,Wi.RECEIVE_SHADOWS)!==e&&(zd(this,Wi.RECEIVE_SHADOWS,e),this.dirty=!0)}},uniformMap:{get:function(){return this._uniformMap},set:function(e){this._uniformMap!==e&&(this._uniformMap=e,this.dirty=!0)}},renderState:{get:function(){return this._renderState},set:function(e){this._renderState!==e&&(this._renderState=e,this.dirty=!0)}},framebuffer:{get:function(){return this._framebuffer},set:function(e){this._framebuffer!==e&&(this._framebuffer=e,this.dirty=!0)}},pass:{get:function(){return this._pass},set:function(e){this._pass!==e&&(this._pass=e,this.dirty=!0)}},executeInClosestFrustum:{get:function(){return Kr(this,Wi.EXECUTE_IN_CLOSEST_FRUSTUM)},set:function(e){Kr(this,Wi.EXECUTE_IN_CLOSEST_FRUSTUM)!==e&&(zd(this,Wi.EXECUTE_IN_CLOSEST_FRUSTUM,e),this.dirty=!0)}},owner:{get:function(){return this._owner},set:function(e){this._owner!==e&&(this._owner=e,this.dirty=!0)}},debugShowBoundingVolume:{get:function(){return Kr(this,Wi.DEBUG_SHOW_BOUNDING_VOLUME)},set:function(e){Kr(this,Wi.DEBUG_SHOW_BOUNDING_VOLUME)!==e&&(zd(this,Wi.DEBUG_SHOW_BOUNDING_VOLUME,e),this.dirty=!0)}},debugOverlappingFrustums:{g
(${this[1]}, ${this[3]})`};function U$(e,t,n,i){switch(t.type){case e.FLOAT:return new XU(e,t,n,i);case e.FLOAT_VEC2:return new QU(e,t,n,i);case e.FLOAT_VEC3:return new KU(e,t,n,i);case e.FLOAT_VEC4:return new ZU(e,t,n,i);case e.SAMPLER_2D:case e.SAMPLER_CUBE:return new vP(e,t,n,i);case e.INT:case e.BOOL:return new JU(e,t,n,i);case e.INT_VEC2:case e.BOOL_VEC2:return new ek(e,t,n,i);case e.INT_VEC3:case e.BOOL_VEC3:return new tk(e,t,n,i);case e.INT_VEC4:case e.BOOL_VEC4:return new nk(e,t,n,i);case e.FLOAT_MAT2:return new ik(e,t,n,i);case e.FLOAT_MAT3:return new ok(e,t,n,i);case e.FLOAT_MAT4:return new rk(e,t,n,i);default:throw new Te(`Unrecognized uniform type: ${t.type} for uniform "${n}".`)}}function XU(e,t,n,i){this.name=n,this.value=void 0,this._value=0,this._gl=e,this._location=i}XU.prototype.set=function(){this.value!==this._value&&(this._value=this.value,this._gl.uniform1f(this._location,this.value))};function QU(e,t,n,i){this.name=n,this.value=void 0,this._value=new H,this._gl=e,this._location=i}QU.prototype.set=function(){const e=this.value;H.equals(e,this._value)||(H.clone(e,this._value),this._gl.uniform2f(this._location,e.x,e.y))};function KU(e,t,n,i){this.name=n,this.value=void 0,this._value=void 0,this._gl=e,this._location=i}KU.prototype.set=function(){const e=this.value;if(c(e.red))z.equals(e,this._value)||(this._value=z.clone(e,this._value),this._gl.uniform3f(this._location,e.red,e.green,e.blue));else if(c(e.x))d.equals(e,this._value)||(this._value=d.clone(e,this._value),this._gl.uniform3f(this._location,e.x,e.y,e.z));else throw new E(`Invalid vec3 value for uniform "${this.name}".`)};function ZU(e,t,n,i){this.name=n,this.value=void 0,this._value=void 0,this._gl=e,this._location=i}ZU.prototype.set=function(){const e=this.value;if(c(e.red))z.equals(e,this._value)||(this._value=z.clone(e,this._value),this._gl.uniform4f(this._location,e.red,e.green,e.blue,e.alpha));else if(c(e.x))te.equals(e,this._value)||(this._value=te.clone(e,this._value),this._gl.uniform4f(this._location,e.x,e.y,e.z,e.w));else throw new E(`Invalid vec4 value for uniform "${this.name}".`)};function vP(e,t,n,i){this.name=n,this.value=void 0,this._gl=e,this._location=i,this.textureUnitIndex=void 0}vP.prototype.set=function(){const e=this._gl;e.activeTexture(e.TEXTURE0+this.textureUnitIndex);const t=this.value;e.bindTexture(t._target,t._texture)};vP.prototype._setSampler=function(e){return this.textureUnitIndex=e,this._gl.uniform1i(this._location,e),e+1};function JU(e,t,n,i){this.name=n,this.value=void 0,this._value=0,this._gl=e,this._location=i}JU.prototype.set=function(){this.value!==this._value&&(this._value=this.value,this._gl.uniform1i(this._location,this.value))};function ek(e,t,n,i){this.name=n,this.value=void 0,this._value=new H,this._gl=e,this._location=i}ek.prototype.set=function(){const e=this.value;H.equals(e,this._value)||(H.clone(e,this._value),this._gl.uniform2i(this._location,e.x,e.y))};function tk(e,t,n,i){this.name=n,this.value=void 0,this._value=new d,this._gl=e,this._location=i}tk.prototype.set=function(){const e=this.value;d.equals(e,this._value)||(d.clone(e,this._value),this._gl.uniform3i(this._location,e.x,e.y,e.z))};function nk(e,t,n,i){this.name=n,this.value=void 0,this._value=new te,this._gl=e,this._location=i}nk.prototype.set=function(){const e=this.value;te.equals(e,this._value)||(te.clone(e,this._value),this._gl.uniform4i(this._location,e.x,e.y,e.z,e.w))};const k$=new Float32Array(4);function ik(e,t,n,i){this.name=n,this.value=void 0,this._value=new Xe,this._gl=e,this._location=i}ik.prototype.set=function(){if(!Xe.equalsArray(this.value,this._value,0)){Xe.clone(this.value,this._value);const e=Xe.toArray(this.value,k$);this._gl.uniformMatrix2fv(this._location,!1,e)}};const V$=new Float32Array(9);function ok(e,t,n,i){this.name=n,this.value=void 0,this._value=new $,this._gl=e,this._location=i}ok.prototype.set=function(){if(!$.equalsArray(this.value,this._value,0)){$.clone(this.value,this._value);const e=$.toArray(this.value,V$);this._gl.uniformMatrix3fv(this._location,!1,e)}};const H$=new Float32Array(16);function rk
${n}`),u=`Vertex shader failed to compile. Compile log: ${l}`):(l=e.getShaderInfoLog(r),console.error(`${Hl}Fragment shader compile log: ${l}`),console.error(`${Hl} Fragment shader source:
${i}`),u=`Fragment shader failed to compile. Compile log: ${l}`),e.deleteShader(o),e.deleteShader(r),e.deleteProgram(s),new Te(u);function f(_,g){if(!c(h))return;const m=h.getTranslatedShaderSource(_);if(m===""){console.error(`${Hl}${g} shader translation failed.`);return}console.error(`${Hl}Translated ${g} shaderSource:
${m}`)}}function Y$(e,t,n){const i={};for(let o=0;o<n;++o){const r=e.getActiveAttrib(t,o),s=e.getAttribLocation(t,r.name);i[r.name]={name:r.name,type:r.type,index:s}}return i}function $$(e,t){const n={},i=[],o=[],r=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<r;++s){const a=e.getActiveUniform(t,s),l="[0]",u=a.name.indexOf(l,a.name.length-l.length)!==-1?a.name.slice(0,a.name.length-3):a.name;if(u.indexOf("gl_")!==0)if(a.name.indexOf("[")<0){const h=e.getUniformLocation(t,u);if(h!==null){const f=U$(e,a,u,h);n[u]=f,i.push(f),f._setSampler&&o.push(f)}}else{let h,f,_,g;const m=u.indexOf("[");if(m>=0){if(h=n[u.slice(0,m)],!c(h))continue;f=h._locations,f.length<=1&&(_=h.value,g=e.getUniformLocation(t,u),g!==null&&(f.push(g),_.push(e.getUniform(t,g))))}else{f=[];for(let b=0;b<a.size;++b)g=e.getUniformLocation(t,`${u}[${b}]`),g!==null&&f.push(g);h=G$(e,a,u,f),n[u]=h,i.push(h),h._setSampler&&o.push(h)}}}return{uniformsByName:n,uniforms:i,samplerUniforms:o}}function X$(e,t){const n=[],i=[];for(const o in t)if(t.hasOwnProperty(o)){const r=t[o];let s=o;const a=e._duplicateUniformNames[s];c(a)&&(r.name=a,s=a);const l=DA[s];c(l)?n.push({uniform:r,automaticUniform:l}):i.push(r)}return{automaticUniforms:n,manualUniforms:i}}function Q$(e,t,n){e.useProgram(t);let i=0;const o=n.length;for(let r=0;r<o;++r)i=n[r]._setSampler(i);return e.useProgram(null),i}function RA(e){c(e._program)||gk(e)}function gk(e){const t=e._program,n=e._gl,i=q$(n,e,e._debugShaders),o=n.getProgramParameter(i,n.ACTIVE_ATTRIBUTES),r=$$(n,i),s=X$(e,r.uniformsByName);e._program=i,e._numberOfVertexAttributes=o,e._vertexAttributes=Y$(n,i,o),e._uniformsByName=r.uniformsByName,e._uniforms=r.uniforms,e._automaticUniforms=s.automaticUniforms,e._manualUniforms=s.manualUniforms,e.maximumTextureUnitIndex=Q$(n,i,r.samplerUniforms),t&&e._gl.deleteProgram(t),typeof spector<"u"&&(e._program.__SPECTOR_rebuildProgram=function(a,l,u,h){const f=e._vertexShaderText,_=e._fragmentShaderText,g=/ ! = /g;e._vertexShaderText=a.replace(g," != "),e._fragmentShaderText=l.replace(g," != ");try{gk(e),u(e._program)}catch(m){e._vertexShaderText=f,e._fragmentShaderText=_;const T=/(?:Compile|Link) error: ([^]*)/.exec(m.message);h(T?T[1]:m.message)}})}Jt.prototype._bind=function(){RA(this),this._gl.useProgram(this._program)};Jt.prototype._setUniforms=function(e,t,n){let i,o;if(c(e)){const a=this._manualUniforms;for(i=a.length,o=0;o<i;++o){const l=a[o];l.value=e[l.name]()}}const r=this._automaticUniforms;for(i=r.length,o=0;o<i;++o){const a=r[o];a.uniform.value=a.automaticUniform.getValue(t)}const s=this._uniforms;for(i=s.length,o=0;o<i;++o)s[o].set();if(n){const a=this._gl,l=this._program;if(a.validateProgram(l),!a.getProgramParameter(l,a.VALIDATE_STATUS))throw new E(`Program validation failed. Program info log: ${a.getProgramInfoLog(l)}`)}};Jt.prototype.isDestroyed=function(){return!1};Jt.prototype.destroy=function(){this._cachedShader.cache.releaseShaderProgram(this)};Jt.prototype.finalDestroy=function(){return this._gl.deleteProgram(this._program),ve(this)};function yC(e){this._context=e}let _g;const K$=new Ze({primitiveType:ze.TRIANGLES}),Z$=new bi({color:new z(0,0,0,0)});function J$(e,t){return new ur({context:e,colorTextures:[t],destroyAttachments:!1})}function eX(e,t){return Jt.fromCache({context:e,vertexShaderSource:RU,fragmentShaderSource:t,attributeLocations:{position:0,textureCoordinates:1}})}function tX(e,t){return(!c(_g)||_g.viewport.width!==e||_g.viewport.height!==t)&&(_g=Ue.fromCache({viewport:new Re(0,0,e,t)})),_g}yC.prototype.execute=function(e){if(A.defined("computeCommand",e),c(e.preExecute)&&e.preExecute(e),!c(e.fragmentShaderSource)&&!c(e.shaderProgram))throw new E("computeCommand.fragmentShaderSource or computeCommand.shaderProgram is required.");A.defined("computeCommand.outputTexture",e.outputTexture);const t=e.outputTexture,n=t.width,i=t.height,o=this._context,r=c(e.vertexArray)?e.vertexArray:o.getViewportQuadVertexArray(),s=c(e.shaderProgram)?e.shaderProgram:eX(o,e.fragmentShaderSource),a=J$(o,t),l=tX(n,i),u=e.uniformMap,h=Z$;h.framebuffer=a,h.renderState=l,h.execute
importScripts("${KE(CESIUM_WORKERS)}");
CesiumWorkers["${r}"]();
`;return o=KE(s),new Worker(o,i)}if(o=e,n||(o=Zt(`${Kn._workerModulePrefix+r}.js`)),!Yt.supportsEsmWebWorkers())throw new Te("This browser is not supported. Please update your browser to continue.");return i.type="module",new Worker(o,i)}async function hX(e,t){const n={modulePath:void 0,wasmBinaryFile:void 0,wasmBinary:void 0};if(!Yt.supportsWebAssembly()){if(!c(t.fallbackModulePath))throw new Te(`This browser does not support Web Assembly, and no backup module was provided for ${e._workerPath}`);return n.modulePath=Zt(t.fallbackModulePath),n}n.wasmBinaryFile=Zt(t.wasmBinaryFile);const i=await Ae.fetchArrayBuffer({url:n.wasmBinaryFile});return n.wasmBinary=i,n}function Kn(e,t){this._workerPath=e,this._maximumActiveTasks=y(t,Number.POSITIVE_INFINITY),this._activeTasks=0,this._nextID=0,this._webAssemblyPromise=void 0}const fX=(e,t,n,i)=>{const o=({data:r})=>{if(r.id===t){if(c(r.error)){let s=r.error;s.name==="RuntimeError"?(s=new Te(r.error.message),s.stack=r.error.stack):s.name==="DeveloperError"?(s=new E(r.error.message),s.stack=r.error.stack):s.name==="Error"&&(s=new Error(r.error.message),s.stack=r.error.stack),xI.raiseEvent(s),i(s)}else xI.raiseEvent(),n(r.result);e.removeEventListener("message",o)}};return o},pX=[];async function mX(e,t,n){const i=await Promise.resolve(yk());c(n)?i||(n.length=0):n=pX;const o=e._nextID++,r=new Promise((s,a)=>{e._worker.addEventListener("message",fX(e._worker,o,s,a))});return e._worker.postMessage({id:o,baseUrl:Zt.getCesiumBaseUrl().url,parameters:t,canTransferArrayBuffer:i},n),r}async function _X(e,t,n){++e._activeTasks;try{const i=await mX(e,t,n);return--e._activeTasks,i}catch(i){throw--e._activeTasks,i}}Kn.prototype.scheduleTask=function(e,t){if(c(this._worker)||(this._worker=DP(this._workerPath)),!(this._activeTasks>=this._maximumActiveTasks))return _X(this,e,t)};Kn.prototype.initWebAssemblyModule=async function(e){if(c(this._webAssemblyPromise))return this._webAssemblyPromise;const t=async()=>{const n=this._worker=DP(this._workerPath),i=await hX(this,e),o=await Promise.resolve(yk());let r;const s=i.wasmBinary;c(s)&&o&&(r=[s]);const a=new Promise((l,u)=>{n.onmessage=function({data:h}){c(h)?l(h.result):u(new Te("Could not configure wasm module"))}});return n.postMessage({canTransferArrayBuffer:o,parameters:{webAssemblyConfig:i}},r),a};return this._webAssemblyPromise=t(),this._webAssemblyPromise};Kn.prototype.isDestroyed=function(){return!1};Kn.prototype.destroy=function(){return c(this._worker)&&this._worker.terminate(),ve(this)};Kn.taskCompletedEvent=xI;Kn._defaultWorkerModulePrefix="Workers/";Kn._workerModulePrefix=Kn._defaultWorkerModulePrefix;Kn._canTransferArrayBuffer=void 0;function Qu(){}Qu._transcodeTaskProcessor=new Kn("transcodeKTX2",Number.POSITIVE_INFINITY);Qu._readyPromise=void 0;function gX(){const e=Qu._transcodeTaskProcessor.initWebAssemblyModule({wasmBinaryFile:"ThirdParty/basis_transcoder.wasm"}).then(function(t){if(t)return Qu._transcodeTaskProcessor;throw new Te("KTX2 transcoder could not be initialized.")});Qu._readyPromise=e}Qu.transcode=function(e,t){return A.defined("supportedTargetFormats",t),c(Qu._readyPromise)||gX(),Qu._readyPromise.then(function(n){let i;if(e instanceof ArrayBuffer){const o=new Uint8Array(e);return i={supportedTargetFormats:t,ktx2Buffer:o},n.scheduleTask(i,[e])}return i={supportedTargetFormats:t,ktx2Buffer:e},n.scheduleTask(i,[e.buffer])}).then(function(n){const i=n.length,o=Object.keys(n[0]),r=o.length;let s;for(s=0;s<i;s++){const a=n[s];for(let l=0;l<r;l++){const u=a[o[l]];a[o[l]]=new S_(u.internalFormat,u.datatype,u.width,u.height,u.levelBuffer)}}if(r===1){for(s=0;s<i;++s)n[s]=n[s][o[0]];i===1&&(n=n[0])}return n}).catch(function(n){throw n})};let bk;Op.setKTX2SupportedFormats=function(e,t,n,i,o,r){bk={s3tc:e,pvrtc:t,astc:n,etc:i,etc1:o,bc7:r}};function Op(e){A.defined("resourceOrUrlOrBuffer",e);let t;return e instanceof ArrayBuffer||ArrayBuffer.isView(e)?t=Promise.resolve(e):t=Ae.createIfNeeded(e).fetchArrayBuffer(),t.then(function(n){return Qu.transcode(n,bk)})}function zu(e,t,n,i,o,r,s,a,l,u,h){this._context=e,this._texture=t,th
* A built-in GLSL floating-point constant for converting radians to degrees.
*
* @alias czm_degreesPerRadian
* @glslConstant
*
* @see CesiumMath.DEGREES_PER_RADIAN
*
* @example
* // GLSL declaration
* const float czm_degreesPerRadian = ...;
*
* // Example
* float deg = czm_degreesPerRadian * rad;
*/
const float czm_degreesPerRadian = 57.29577951308232;
`,bX=`/**
* A built-in GLSL vec2 constant for defining the depth range.
* This is a workaround to a bug where IE11 does not implement gl_DepthRange.
*
* @alias czm_depthRange
* @glslConstant
*
* @example
* // GLSL declaration
* float depthRangeNear = czm_depthRange.near;
* float depthRangeFar = czm_depthRange.far;
*
*/
const czm_depthRangeStruct czm_depthRange = czm_depthRangeStruct(0.0, 1.0);
`,TX=`/**
* 0.1
*
* @name czm_epsilon1
* @glslConstant
*/
const float czm_epsilon1 = 0.1;
`,AX=`/**
* 0.01
*
* @name czm_epsilon2
* @glslConstant
*/
const float czm_epsilon2 = 0.01;
`,xX=`/**
* 0.001
*
* @name czm_epsilon3
* @glslConstant
*/
const float czm_epsilon3 = 0.001;
`,CX=`/**
* 0.0001
*
* @name czm_epsilon4
* @glslConstant
*/
const float czm_epsilon4 = 0.0001;
`,EX=`/**
* 0.00001
*
* @name czm_epsilon5
* @glslConstant
*/
const float czm_epsilon5 = 0.00001;
`,wX=`/**
* 0.000001
*
* @name czm_epsilon6
* @glslConstant
*/
const float czm_epsilon6 = 0.000001;
`,SX=`/**
* 0.0000001
*
* @name czm_epsilon7
* @glslConstant
*/
const float czm_epsilon7 = 0.0000001;
`,vX=`/**
* DOC_TBA
*
* @name czm_infinity
* @glslConstant
*/
const float czm_infinity = 5906376272000.0; // Distance from the Sun to Pluto in meters. TODO: What is best given lowp, mediump, and highp?
`,IX=`/**
* A built-in GLSL floating-point constant for <code>1/pi</code>.
*
* @alias czm_oneOverPi
* @glslConstant
*
* @see CesiumMath.ONE_OVER_PI
*
* @example
* // GLSL declaration
* const float czm_oneOverPi = ...;
*
* // Example
* float pi = 1.0 / czm_oneOverPi;
*/
const float czm_oneOverPi = 0.3183098861837907;
`,DX=`/**
* A built-in GLSL floating-point constant for <code>1/2pi</code>.
*
* @alias czm_oneOverTwoPi
* @glslConstant
*
* @see CesiumMath.ONE_OVER_TWO_PI
*
* @example
* // GLSL declaration
* const float czm_oneOverTwoPi = ...;
*
* // Example
* float pi = 2.0 * czm_oneOverTwoPi;
*/
const float czm_oneOverTwoPi = 0.15915494309189535;
`,PX=`/**
* The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE}
*
* @name czm_passCesium3DTile
* @glslConstant
*
* @see czm_pass
*/
const float czm_passCesium3DTile = 4.0;
`,OX=`/**
* The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE_CLASSIFICATION}
*
* @name czm_passCesium3DTileClassification
* @glslConstant
*
* @see czm_pass
*/
const float czm_passCesium3DTileClassification = 5.0;
`,LX=`/**
* The automatic GLSL constant for {@link Pass#CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW}
*
* @name czm_passCesium3DTileClassificationIgnoreShow
* @glslConstant
*
* @see czm_pass
*/
const float czm_passCesium3DTileClassificationIgnoreShow = 6.0;
`,RX=`/**
* The automatic GLSL constant for {@link Pass#CLASSIFICATION}
*
* @name czm_passClassification
* @glslConstant
*
* @see czm_pass
*/
const float czm_passClassification = 7.0;
`,NX=`/**
* The automatic GLSL constant for {@link Pass#COMPUTE}
*
* @name czm_passCompute
* @glslConstant
*
* @see czm_pass
*/
const float czm_passCompute = 1.0;
`,MX=`/**
* The automatic GLSL constant for {@link Pass#ENVIRONMENT}
*
* @name czm_passEnvironment
* @glslConstant
*
* @see czm_pass
*/
const float czm_passEnvironment = 0.0;
`,FX=`/**
* The automatic GLSL constant for {@link Pass#GLOBE}
*
* @name czm_passGlobe
* @glslConstant
*
* @see czm_pass
*/
const float czm_passGlobe = 2.0;
`,BX=`/**
* The automatic GLSL constant for {@link Pass#OPAQUE}
*
* @name czm_passOpaque
* @glslConstant
*
* @see czm_pass
*/
const float czm_passOpaque = 7.0;
`,zX=`/**
* The automatic GLSL constant for {@link Pass#OVERLAY}
*
* @name czm_passOverlay
* @glslConstant
*
* @see czm_pass
*/
const float czm_passOverlay = 10.0;
`,UX=`/**
* The automatic GLSL constant for {@link Pass#TERRAIN_CLASSIFICATION}
*
* @name czm_passTerrainClassification
* @glslConstant
*
* @see czm_pass
*/
const float czm_passTerrainClassification = 3.0;
`,kX=`/**
* The automatic GLSL constant for {@link Pass#TRANSLUCENT}
*
* @name czm_passTranslucent
* @glslConstant
*
* @see czm_pass
*/
const float czm_passTranslucent = 8.0;
`,VX=`/**
* The automatic GLSL constant for {@link Pass#VOXELS}
*
* @name czm_passVoxels
* @glslConstant
*
* @see czm_pass
*/
const float czm_passVoxels = 9.0;
`,HX=`/**
* A built-in GLSL floating-point constant for <code>Math.PI</code>.
*
* @alias czm_pi
* @glslConstant
*
* @see CesiumMath.PI
*
* @example
* // GLSL declaration
* const float czm_pi = ...;
*
* // Example
* float twoPi = 2.0 * czm_pi;
*/
const float czm_pi = 3.141592653589793;
`,GX=`/**
* A built-in GLSL floating-point constant for <code>pi/4</code>.
*
* @alias czm_piOverFour
* @glslConstant
*
* @see CesiumMath.PI_OVER_FOUR
*
* @example
* // GLSL declaration
* const float czm_piOverFour = ...;
*
* // Example
* float pi = 4.0 * czm_piOverFour;
*/
const float czm_piOverFour = 0.7853981633974483;
`,jX=`/**
* A built-in GLSL floating-point constant for <code>pi/6</code>.
*
* @alias czm_piOverSix
* @glslConstant
*
* @see CesiumMath.PI_OVER_SIX
*
* @example
* // GLSL declaration
* const float czm_piOverSix = ...;
*
* // Example
* float pi = 6.0 * czm_piOverSix;
*/
const float czm_piOverSix = 0.5235987755982988;
`,WX=`/**
* A built-in GLSL floating-point constant for <code>pi/3</code>.
*
* @alias czm_piOverThree
* @glslConstant
*
* @see CesiumMath.PI_OVER_THREE
*
* @example
* // GLSL declaration
* const float czm_piOverThree = ...;
*
* // Example
* float pi = 3.0 * czm_piOverThree;
*/
const float czm_piOverThree = 1.0471975511965976;
`,qX=`/**
* A built-in GLSL floating-point constant for <code>pi/2</code>.
*
* @alias czm_piOverTwo
* @glslConstant
*
* @see CesiumMath.PI_OVER_TWO
*
* @example
* // GLSL declaration
* const float czm_piOverTwo = ...;
*
* // Example
* float pi = 2.0 * czm_piOverTwo;
*/
const float czm_piOverTwo = 1.5707963267948966;
`,YX=`/**
* A built-in GLSL floating-point constant for converting degrees to radians.
*
* @alias czm_radiansPerDegree
* @glslConstant
*
* @see CesiumMath.RADIANS_PER_DEGREE
*
* @example
* // GLSL declaration
* const float czm_radiansPerDegree = ...;
*
* // Example
* float rad = czm_radiansPerDegree * deg;
*/
const float czm_radiansPerDegree = 0.017453292519943295;
`,$X=`/**
* The constant identifier for the 2D {@link SceneMode}
*
* @name czm_sceneMode2D
* @glslConstant
* @see czm_sceneMode
* @see czm_sceneModeColumbusView
* @see czm_sceneMode3D
* @see czm_sceneModeMorphing
*/
const float czm_sceneMode2D = 2.0;
`,XX=`/**
* The constant identifier for the 3D {@link SceneMode}
*
* @name czm_sceneMode3D
* @glslConstant
* @see czm_sceneMode
* @see czm_sceneMode2D
* @see czm_sceneModeColumbusView
* @see czm_sceneModeMorphing
*/
const float czm_sceneMode3D = 3.0;
`,QX=`/**
* The constant identifier for the Columbus View {@link SceneMode}
*
* @name czm_sceneModeColumbusView
* @glslConstant
* @see czm_sceneMode
* @see czm_sceneMode2D
* @see czm_sceneMode3D
* @see czm_sceneModeMorphing
*/
const float czm_sceneModeColumbusView = 1.0;
`,KX=`/**
* The constant identifier for the Morphing {@link SceneMode}
*
* @name czm_sceneModeMorphing
* @glslConstant
* @see czm_sceneMode
* @see czm_sceneMode2D
* @see czm_sceneModeColumbusView
* @see czm_sceneMode3D
*/
const float czm_sceneModeMorphing = 0.0;
`,ZX=`/**
* A built-in GLSL floating-point constant for one solar radius.
*
* @alias czm_solarRadius
* @glslConstant
*
* @see CesiumMath.SOLAR_RADIUS
*
* @example
* // GLSL declaration
* const float czm_solarRadius = ...;
*/
const float czm_solarRadius = 695500000.0;
`,JX=`/**
* A built-in GLSL floating-point constant for <code>3pi/2</code>.
*
* @alias czm_threePiOver2
* @glslConstant
*
* @see CesiumMath.THREE_PI_OVER_TWO
*
* @example
* // GLSL declaration
* const float czm_threePiOver2 = ...;
*
* // Example
* float pi = (2.0 / 3.0) * czm_threePiOver2;
*/
const float czm_threePiOver2 = 4.71238898038469;
`,eQ=`/**
* A built-in GLSL floating-point constant for <code>2pi</code>.
*
* @alias czm_twoPi
* @glslConstant
*
* @see CesiumMath.TWO_PI
*
* @example
* // GLSL declaration
* const float czm_twoPi = ...;
*
* // Example
* float pi = czm_twoPi / 2.0;
*/
const float czm_twoPi = 6.283185307179586;
`,tQ=`/**
* The maximum latitude, in radians, both North and South, supported by a Web Mercator
* (EPSG:3857) projection. Technically, the Mercator projection is defined
* for any latitude up to (but not including) 90 degrees, but it makes sense
* to cut it off sooner because it grows exponentially with increasing latitude.
* The logic behind this particular cutoff value, which is the one used by
* Google Maps, Bing Maps, and Esri, is that it makes the projection
* square. That is, the rectangle is equal in the X and Y directions.
*
* The constant value is computed as follows:
* czm_pi * 0.5 - (2.0 * atan(exp(-czm_pi)))
*
* @name czm_webMercatorMaxLatitude
* @glslConstant
*/
const float czm_webMercatorMaxLatitude = 1.4844222297453324;
`,nQ=`/**
* @name czm_depthRangeStruct
* @glslStruct
*/
struct czm_depthRangeStruct
{
float near;
float far;
};
`,iQ=`/**
* Holds material information that can be used for lighting. Returned by all czm_getMaterial functions.
*
* @name czm_material
* @glslStruct
*
* @property {vec3} diffuse Incoming light that scatters evenly in all directions.
* @property {float} specular Intensity of incoming light reflecting in a single direction.
* @property {float} shininess The sharpness of the specular reflection. Higher values create a smaller, more focused specular highlight.
* @property {vec3} normal Surface's normal in eye coordinates. It is used for effects such as normal mapping. The default is the surface's unmodified normal.
* @property {vec3} emission Light emitted by the material equally in all directions. The default is vec3(0.0), which emits no light.
* @property {float} alpha Alpha of this material. 0.0 is completely transparent; 1.0 is completely opaque.
*/
struct czm_material
{
vec3 diffuse;
float specular;
float shininess;
vec3 normal;
vec3 emission;
float alpha;
};
`,oQ=`/**
* Used as input to every material's czm_getMaterial function.
*
* @name czm_materialInput
* @glslStruct
*
* @property {float} s 1D texture coordinates.
* @property {vec2} st 2D texture coordinates.
* @property {vec3} str 3D texture coordinates.
* @property {vec3} normalEC Unperturbed surface normal in eye coordinates.
* @property {mat3} tangentToEyeMatrix Matrix for converting a tangent space normal to eye space.
* @property {vec3} positionToEyeEC Vector from the fragment to the eye in eye coordinates. The magnitude is the distance in meters from the fragment to the eye.
* @property {float} height The height of the terrain in meters above or below the WGS84 ellipsoid. Only available for globe materials.
* @property {float} slope The slope of the terrain in radians. 0 is flat; pi/2 is vertical. Only available for globe materials.
* @property {float} aspect The aspect of the terrain in radians. 0 is East, pi/2 is North, pi is West, 3pi/2 is South. Only available for globe materials.
*/
struct czm_materialInput
{
float s;
vec2 st;
vec3 str;
vec3 normalEC;
mat3 tangentToEyeMatrix;
vec3 positionToEyeEC;
float height;
float slope;
float aspect;
};
`,rQ=`/**
* Struct for representing a material for a {@link Model}. The model
* rendering pipeline will pass this struct between material, custom shaders,
* and lighting stages. This is not to be confused with {@link czm_material}
* which is used by the older Fabric materials system, although they are similar.
* <p>
* All color values (diffuse, specular, emissive) are in linear color space.
* </p>
*
* @name czm_modelMaterial
* @glslStruct
*
* @property {vec3} diffuse Incoming light that scatters evenly in all directions.
* @property {float} alpha Alpha of this material. 0.0 is completely transparent; 1.0 is completely opaque.
* @property {vec3} specular Color of reflected light at normal incidence in PBR materials. This is sometimes referred to as f0 in the literature.
* @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.
* @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.
* @property {float} occlusion Ambient occlusion recieved at this point on the material. 1.0 means fully lit, 0.0 means fully occluded.
* @property {vec3} emissive Light emitted by the material equally in all directions. The default is vec3(0.0), which emits no light.
*/
struct czm_modelMaterial {
vec3 diffuse;
float alpha;
vec3 specular;
float roughness;
vec3 normalEC;
float occlusion;
vec3 emissive;
};
`,sQ=`/**
* Struct for representing the output of a custom vertex shader.
*
* @name czm_modelVertexOutput
* @glslStruct
*
* @see {@link CustomShader}
* @see {@link Model}
*
* @property {vec3} positionMC The position of the vertex in model coordinates
* @property {float} pointSize A custom value for gl_PointSize. This is only used for point primitives.
*/
struct czm_modelVertexOutput {
vec3 positionMC;
float pointSize;
};
`,aQ=`/**
* Parameters for {@link czm_pbrLighting}
*
* @name czm_material
* @glslStruct
*
* @property {vec3} diffuseColor the diffuse color of the material for the lambert term of the rendering equation
* @property {float} roughness a value from 0.0 to 1.0 that indicates how rough the surface of the material is.
* @property {vec3} f0 The reflectance of the material at normal incidence
*/
struct czm_pbrParameters
{
vec3 diffuseColor;
float roughness;
vec3 f0;
};
`,cQ=`/**
* DOC_TBA
*
* @name czm_ray
* @glslStruct
*/
struct czm_ray
{
vec3 origin;
vec3 direction;
};
`,lQ=`/**
* DOC_TBA
*
* @name czm_raySegment
* @glslStruct
*/
struct czm_raySegment
{
float start;
float stop;
};
/**
* DOC_TBA
*
* @name czm_emptyRaySegment
* @glslConstant
*/
const czm_raySegment czm_emptyRaySegment = czm_raySegment(-czm_infinity, -czm_infinity);
/**
* DOC_TBA
*
* @name czm_fullRaySegment
* @glslConstant
*/
const czm_raySegment czm_fullRaySegment = czm_raySegment(0.0, czm_infinity);
`,uQ=`struct czm_shadowParameters
{
#ifdef USE_CUBE_MAP_SHADOW
vec3 texCoords;
#else
vec2 texCoords;
#endif
float depthBias;
float depth;
float nDotL;
vec2 texelStepSize;
float normalShadingSmooth;
float darkness;
};
`,dQ=`/**
* Converts an HSB color (hue, saturation, brightness) to RGB
* HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}
*
* @name czm_HSBToRGB
* @glslFunction
*
* @param {vec3} hsb The color in HSB.
*
* @returns {vec3} The color in RGB.
*
* @example
* vec3 hsb = czm_RGBToHSB(rgb);
* hsb.z *= 0.1;
* rgb = czm_HSBToRGB(hsb);
*/
const vec4 K_HSB2RGB = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
vec3 czm_HSBToRGB(vec3 hsb)
{
vec3 p = abs(fract(hsb.xxx + K_HSB2RGB.xyz) * 6.0 - K_HSB2RGB.www);
return hsb.z * mix(K_HSB2RGB.xxx, clamp(p - K_HSB2RGB.xxx, 0.0, 1.0), hsb.y);
}
`,hQ=`/**
* Converts an HSL color (hue, saturation, lightness) to RGB
* HSL <-> RGB conversion: {@link http://www.chilliant.com/rgb2hsv.html}
*
* @name czm_HSLToRGB
* @glslFunction
*
* @param {vec3} rgb The color in HSL.
*
* @returns {vec3} The color in RGB.
*
* @example
* vec3 hsl = czm_RGBToHSL(rgb);
* hsl.z *= 0.1;
* rgb = czm_HSLToRGB(hsl);
*/
vec3 hueToRGB(float hue)
{
float r = abs(hue * 6.0 - 3.0) - 1.0;
float g = 2.0 - abs(hue * 6.0 - 2.0);
float b = 2.0 - abs(hue * 6.0 - 4.0);
return clamp(vec3(r, g, b), 0.0, 1.0);
}
vec3 czm_HSLToRGB(vec3 hsl)
{
vec3 rgb = hueToRGB(hsl.x);
float c = (1.0 - abs(2.0 * hsl.z - 1.0)) * hsl.y;
return (rgb - 0.5) * c + hsl.z;
}
`,fQ=`/**
* Converts an RGB color to HSB (hue, saturation, brightness)
* HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}
*
* @name czm_RGBToHSB
* @glslFunction
*
* @param {vec3} rgb The color in RGB.
*
* @returns {vec3} The color in HSB.
*
* @example
* vec3 hsb = czm_RGBToHSB(rgb);
* hsb.z *= 0.1;
* rgb = czm_HSBToRGB(hsb);
*/
const vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
vec3 czm_RGBToHSB(vec3 rgb)
{
vec4 p = mix(vec4(rgb.bg, K_RGB2HSB.wz), vec4(rgb.gb, K_RGB2HSB.xy), step(rgb.b, rgb.g));
vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r));
float d = q.x - min(q.w, q.y);
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + czm_epsilon7)), d / (q.x + czm_epsilon7), q.x);
}
`,pQ=`/**
* Converts an RGB color to HSL (hue, saturation, lightness)
* HSL <-> RGB conversion: {@link http://www.chilliant.com/rgb2hsv.html}
*
* @name czm_RGBToHSL
* @glslFunction
*
* @param {vec3} rgb The color in RGB.
*
* @returns {vec3} The color in HSL.
*
* @example
* vec3 hsl = czm_RGBToHSL(rgb);
* hsl.z *= 0.1;
* rgb = czm_HSLToRGB(hsl);
*/
vec3 RGBtoHCV(vec3 rgb)
{
// Based on work by Sam Hocevar and Emil Persson
vec4 p = (rgb.g < rgb.b) ? vec4(rgb.bg, -1.0, 2.0 / 3.0) : vec4(rgb.gb, 0.0, -1.0 / 3.0);
vec4 q = (rgb.r < p.x) ? vec4(p.xyw, rgb.r) : vec4(rgb.r, p.yzx);
float c = q.x - min(q.w, q.y);
float h = abs((q.w - q.y) / (6.0 * c + czm_epsilon7) + q.z);
return vec3(h, c, q.x);
}
vec3 czm_RGBToHSL(vec3 rgb)
{
vec3 hcv = RGBtoHCV(rgb);
float l = hcv.z - hcv.y * 0.5;
float s = hcv.y / (1.0 - abs(l * 2.0 - 1.0) + czm_epsilon7);
return vec3(hcv.x, s, l);
}
`,mQ=`/**
* Converts an RGB color to CIE Yxy.
* <p>The conversion is described in
* {@link http://content.gpwiki.org/index.php/D3DBook:High-Dynamic_Range_Rendering#Luminance_Transform|Luminance Transform}
* </p>
*
* @name czm_RGBToXYZ
* @glslFunction
*
* @param {vec3} rgb The color in RGB.
*
* @returns {vec3} The color in CIE Yxy.
*
* @example
* vec3 xyz = czm_RGBToXYZ(rgb);
* xyz.x = max(xyz.x - luminanceThreshold, 0.0);
* rgb = czm_XYZToRGB(xyz);
*/
vec3 czm_RGBToXYZ(vec3 rgb)
{
const mat3 RGB2XYZ = mat3(0.4124, 0.2126, 0.0193,
0.3576, 0.7152, 0.1192,
0.1805, 0.0722, 0.9505);
vec3 xyz = RGB2XYZ * rgb;
vec3 Yxy;
Yxy.r = xyz.g;
float temp = dot(vec3(1.0), xyz);
Yxy.gb = xyz.rg / temp;
return Yxy;
}
`,_Q=`/**
* Converts a CIE Yxy color to RGB.
* <p>The conversion is described in
* {@link http://content.gpwiki.org/index.php/D3DBook:High-Dynamic_Range_Rendering#Luminance_Transform|Luminance Transform}
* </p>
*
* @name czm_XYZToRGB
* @glslFunction
*
* @param {vec3} Yxy The color in CIE Yxy.
*
* @returns {vec3} The color in RGB.
*
* @example
* vec3 xyz = czm_RGBToXYZ(rgb);
* xyz.x = max(xyz.x - luminanceThreshold, 0.0);
* rgb = czm_XYZToRGB(xyz);
*/
vec3 czm_XYZToRGB(vec3 Yxy)
{
const mat3 XYZ2RGB = mat3( 3.2405, -0.9693, 0.0556,
-1.5371, 1.8760, -0.2040,
-0.4985, 0.0416, 1.0572);
vec3 xyz;
xyz.r = Yxy.r * Yxy.g / Yxy.b;
xyz.g = Yxy.r;
xyz.b = Yxy.r * (1.0 - Yxy.g - Yxy.b) / Yxy.b;
return XYZ2RGB * xyz;
}
`,gQ=`// See:
// https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/
vec3 czm_acesTonemapping(vec3 color) {
float g = 0.985;
float a = 0.065;
float b = 0.0001;
float c = 0.433;
float d = 0.238;
color = (color * (color + a) - b) / (color * (g * color + c) + d);
color = clamp(color, 0.0, 1.0);
return color;
}
`,yQ=`/**
* @private
*/
float czm_alphaWeight(float a)
{
float z = (gl_FragCoord.z - czm_viewportTransformation[3][2]) / czm_viewportTransformation[2][2];
// See Weighted Blended Order-Independent Transparency for examples of different weighting functions:
// http://jcgt.org/published/0002/02/09/
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))));
}
`,bQ=`/**
* Procedural anti-aliasing by blurring two colors that meet at a sharp edge.
*
* @name czm_antialias
* @glslFunction
*
* @param {vec4} color1 The color on one side of the edge.
* @param {vec4} color2 The color on the other side of the edge.
* @param {vec4} currentcolor The current color, either <code>color1</code> or <code>color2</code>.
* @param {float} dist The distance to the edge in texture coordinates.
* @param {float} [fuzzFactor=0.1] Controls the blurriness between the two colors.
* @returns {vec4} The anti-aliased color.
*
* @example
* // GLSL declarations
* vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist, float fuzzFactor);
* vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist);
*
* // get the color for a material that has a sharp edge at the line y = 0.5 in texture space
* float dist = abs(textureCoordinates.t - 0.5);
* vec4 currentColor = mix(bottomColor, topColor, step(0.5, textureCoordinates.t));
* vec4 color = czm_antialias(bottomColor, topColor, currentColor, dist, 0.1);
*/
vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist, float fuzzFactor)
{
float val1 = clamp(dist / fuzzFactor, 0.0, 1.0);
float val2 = clamp((dist - 0.5) / fuzzFactor, 0.0, 1.0);
val1 = val1 * (1.0 - val2);
val1 = val1 * val1 * (3.0 - (2.0 * val1));
val1 = pow(val1, 0.5); //makes the transition nicer
vec4 midColor = (color1 + color2) * 0.5;
return mix(midColor, currentColor, val1);
}
vec4 czm_antialias(vec4 color1, vec4 color2, vec4 currentColor, float dist)
{
return czm_antialias(color1, color2, currentColor, dist, 0.1);
}
`,TQ=`/**
* Apply a HSB color shift to an RGB color.
*
* @param {vec3} rgb The color in RGB space.
* @param {vec3} hsbShift The amount to shift each component. The xyz components correspond to hue, saturation, and brightness. Shifting the hue by +/- 1.0 corresponds to shifting the hue by a full cycle. Saturation and brightness are clamped between 0 and 1 after the adjustment
* @param {bool} ignoreBlackPixels If true, black pixels will be unchanged. This is necessary in some shaders such as atmosphere-related effects.
*
* @return {vec3} The RGB color after shifting in HSB space and clamping saturation and brightness to a valid range.
*/
vec3 czm_applyHSBShift(vec3 rgb, vec3 hsbShift, bool ignoreBlackPixels) {
// Convert rgb color to hsb
vec3 hsb = czm_RGBToHSB(rgb);
// Perform hsb shift
// Hue cycles around so no clamp is needed.
hsb.x += hsbShift.x; // hue
hsb.y = clamp(hsb.y + hsbShift.y, 0.0, 1.0); // saturation
// brightness
//
// Some shaders such as atmosphere-related effects need to leave black
// pixels unchanged
if (ignoreBlackPixels) {
hsb.z = hsb.z > czm_epsilon7 ? hsb.z + hsbShift.z : 0.0;
} else {
hsb.z = hsb.z + hsbShift.z;
}
hsb.z = clamp(hsb.z, 0.0, 1.0);
// Convert shifted hsb back to rgb
return czm_HSBToRGB(hsb);
}
`,AQ=`/**
* Approximately computes spherical coordinates given a normal.
* Uses approximate inverse trigonometry for speed and consistency,
* since inverse trigonometry can differ from vendor-to-vendor and when compared with the CPU.
*
* @name czm_approximateSphericalCoordinates
* @glslFunction
*
* @param {vec3} normal arbitrary-length normal.
*
* @returns {vec2} Approximate latitude and longitude spherical coordinates.
*/
vec2 czm_approximateSphericalCoordinates(vec3 normal) {
// Project into plane with vertical for latitude
float latitudeApproximation = czm_fastApproximateAtan(sqrt(normal.x * normal.x + normal.y * normal.y), normal.z);
float longitudeApproximation = czm_fastApproximateAtan(normal.x, normal.y);
return vec2(latitudeApproximation, longitudeApproximation);
}
`,xQ=`/**
* Compute a rational approximation to tanh(x)
*
* @param {float} x A real number input
* @returns {float} An approximation for tanh(x)
*/
float czm_approximateTanh(float x) {
float x2 = x * x;
return max(-1.0, min(1.0, x * (27.0 + x2) / (27.0 + 9.0 * x2)));
}
`,CQ=`/**
* Determines if the fragment is back facing
*
* @name czm_backFacing
* @glslFunction
*
* @returns {bool} <code>true</code> if the fragment is back facing; otherwise, <code>false</code>.
*/
bool czm_backFacing()
{
// !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.
return gl_FrontFacing == false;
}
`,EQ=`/**
* Branchless ternary operator to be used when it's inexpensive to explicitly
* evaluate both possibilities for a float expression.
*
* @name czm_branchFreeTernary
* @glslFunction
*
* @param {bool} comparison A comparison statement
* @param {float} a Value to return if the comparison is true.
* @param {float} b Value to return if the comparison is false.
*
* @returns {float} equivalent of comparison ? a : b
*/
float czm_branchFreeTernary(bool comparison, float a, float b) {
float useA = float(comparison);
return a * useA + b * (1.0 - useA);
}
/**
* Branchless ternary operator to be used when it's inexpensive to explicitly
* evaluate both possibilities for a vec2 expression.
*
* @name czm_branchFreeTernary
* @glslFunction
*
* @param {bool} comparison A comparison statement
* @param {vec2} a Value to return if the comparison is true.
* @param {vec2} b Value to return if the comparison is false.
*
* @returns {vec2} equivalent of comparison ? a : b
*/
vec2 czm_branchFreeTernary(bool comparison, vec2 a, vec2 b) {
float useA = float(comparison);
return a * useA + b * (1.0 - useA);
}
/**
* Branchless ternary operator to be used when it's inexpensive to explicitly
* evaluate both possibilities for a vec3 expression.
*
* @name czm_branchFreeTernary
* @glslFunction
*
* @param {bool} comparison A comparison statement
* @param {vec3} a Value to return if the comparison is true.
* @param {vec3} b Value to return if the comparison is false.
*
* @returns {vec3} equivalent of comparison ? a : b
*/
vec3 czm_branchFreeTernary(bool comparison, vec3 a, vec3 b) {
float useA = float(comparison);
return a * useA + b * (1.0 - useA);
}
/**
* Branchless ternary operator to be used when it's inexpensive to explicitly
* evaluate both possibilities for a vec4 expression.
*
* @name czm_branchFreeTernary
* @glslFunction
*
* @param {bool} comparison A comparison statement
* @param {vec3} a Value to return if the comparison is true.
* @param {vec3} b Value to return if the comparison is false.
*
* @returns {vec3} equivalent of comparison ? a : b
*/
vec4 czm_branchFreeTernary(bool comparison, vec4 a, vec4 b) {
float useA = float(comparison);
return a * useA + b * (1.0 - useA);
}
`,wQ=`
vec4 czm_cascadeColor(vec4 weights)
{
return vec4(1.0, 0.0, 0.0, 1.0) * weights.x +
vec4(0.0, 1.0, 0.0, 1.0) * weights.y +
vec4(0.0, 0.0, 1.0, 1.0) * weights.z +
vec4(1.0, 0.0, 1.0, 1.0) * weights.w;
}
`,SQ=`
uniform vec4 shadowMap_cascadeDistances;
float czm_cascadeDistance(vec4 weights)
{
return dot(shadowMap_cascadeDistances, weights);
}
`,vQ=`
uniform mat4 shadowMap_cascadeMatrices[4];
mat4 czm_cascadeMatrix(vec4 weights)
{
return shadowMap_cascadeMatrices[0] * weights.x +
shadowMap_cascadeMatrices[1] * weights.y +
shadowMap_cascadeMatrices[2] * weights.z +
shadowMap_cascadeMatrices[3] * weights.w;
}
`,IQ=`
uniform vec4 shadowMap_cascadeSplits[2];
vec4 czm_cascadeWeights(float depthEye)
{
// One component is set to 1.0 and all others set to 0.0.
vec4 near = step(shadowMap_cascadeSplits[0], vec4(depthEye));
vec4 far = step(depthEye, shadowMap_cascadeSplits[1]);
return near * far;
}
`,DQ=`float getSignedDistance(vec2 uv, highp sampler2D clippingDistance) {
float signedDistance = texture(clippingDistance, uv).r;
return (signedDistance - 0.5) * 2.0;
}
void czm_clipPolygons(highp sampler2D clippingDistance, int extentsLength, vec2 clippingPosition, int regionIndex) {
// Position is completely outside of polygons bounds
vec2 rectUv = clippingPosition;
if (regionIndex < 0 || rectUv.x <= 0.0 || rectUv.y <= 0.0 || rectUv.x >= 1.0 || rectUv.y >= 1.0) {
#ifdef CLIPPING_INVERSE
discard;
#endif
return;
}
vec2 clippingDistanceTextureDimensions = vec2(textureSize(clippingDistance, 0));
vec2 sampleOffset = max(1.0 / clippingDistanceTextureDimensions, vec2(0.005));
float dimension = float(extentsLength);
if (extentsLength > 2) {
dimension = ceil(log2(float(extentsLength)));
}
vec2 textureOffset = vec2(mod(float(regionIndex), dimension), floor(float(regionIndex) / dimension)) / dimension;
vec2 uv = textureOffset + rectUv / dimension;
float signedDistance = getSignedDistance(uv, clippingDistance);
#ifdef CLIPPING_INVERSE
if (signedDistance > 0.0) {
discard;
}
#else
if (signedDistance < 0.0) {
discard;
}
#endif
}
`,PQ=`/**
* DOC_TBA
*
* @name czm_columbusViewMorph
* @glslFunction
*/
vec4 czm_columbusViewMorph(vec4 position2D, vec4 position3D, float time)
{
// Just linear for now.
vec3 p = mix(position2D.xyz, position3D.xyz, time);
return vec4(p, 1.0);
}
`,OQ=`/**
* Compute the atmosphere color, applying Rayleigh and Mie scattering. This
* builtin uses automatic uniforms so the atmophere settings are synced with the
* state of the Scene, even in other contexts like Model.
*
* @name czm_computeAtmosphereColor
* @glslFunction
*
* @param {vec3} positionWC Position of the fragment in world coords (low precision)
* @param {vec3} lightDirection Light direction from the sun or other light source.
* @param {vec3} rayleighColor The Rayleigh scattering color computed by a scattering function
* @param {vec3} mieColor The Mie scattering color computed by a scattering function
* @param {float} opacity The opacity computed by a scattering function.
*/
vec4 czm_computeAtmosphereColor(
vec3 positionWC,
vec3 lightDirection,
vec3 rayleighColor,
vec3 mieColor,
float opacity
) {
// Setup the primary ray: from the camera position to the vertex position.
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);
float cosAngle = dot(cameraToPositionWCDirection, lightDirection);
float cosAngleSq = cosAngle * cosAngle;
float G = czm_atmosphereMieAnisotropy;
float GSq = G * G;
// The Rayleigh phase function.
float rayleighPhase = 3.0 / (50.2654824574) * (1.0 + cosAngleSq);
// The Mie phase function.
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));
// The final color is generated by combining the effects of the Rayleigh and Mie scattering.
vec3 rayleigh = rayleighPhase * rayleighColor;
vec3 mie = miePhase * mieColor;
vec3 color = (rayleigh + mie) * czm_atmosphereLightIntensity;
return vec4(color, opacity);
}
`,LQ=`/**
* Compute atmosphere scattering for the ground atmosphere and fog. This method
* uses automatic uniforms so it is always synced with the scene settings.
*
* @name czm_computeGroundAtmosphereScattering
* @glslfunction
*
* @param {vec3} positionWC The position of the fragment in world coordinates.
* @param {vec3} lightDirection The direction of the light to calculate the scattering from.
* @param {vec3} rayleighColor The variable the Rayleigh scattering will be written to.
* @param {vec3} mieColor The variable the Mie scattering will be written to.
* @param {float} opacity The variable the transmittance will be written to.
*/
void czm_computeGroundAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity) {
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);
czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);
float atmosphereInnerRadius = length(positionWC);
czm_computeScattering(
primaryRay,
length(cameraToPositionWC),
lightDirection,
atmosphereInnerRadius,
rayleighColor,
mieColor,
opacity
);
}
`,RQ=`/**
* Returns a position in model coordinates relative to eye taking into
* account the current scene mode: 3D, 2D, or Columbus view.
* <p>
* This uses standard position attributes, <code>position3DHigh</code>,
* <code>position3DLow</code>, <code>position2DHigh</code>, and <code>position2DLow</code>,
* and should be used when writing a vertex shader for an {@link Appearance}.
* </p>
*
* @name czm_computePosition
* @glslFunction
*
* @returns {vec4} The position relative to eye.
*
* @example
* vec4 p = czm_computePosition();
* v_positionEC = (czm_modelViewRelativeToEye * p).xyz;
* gl_Position = czm_modelViewProjectionRelativeToEye * p;
*
* @see czm_translateRelativeToEye
*/
vec4 czm_computePosition();
`,NQ=`/**
* This function computes the colors contributed by Rayliegh and Mie scattering on a given ray, as well as
* the transmittance value for the ray. This function uses automatic uniforms
* so the atmosphere settings are always synced with the current scene.
*
* @name czm_computeScattering
* @glslfunction
*
* @param {czm_ray} primaryRay The ray from the camera to the position.
* @param {float} primaryRayLength The length of the primary ray.
* @param {vec3} lightDirection The direction of the light to calculate the scattering from.
* @param {vec3} rayleighColor The variable the Rayleigh scattering will be written to.
* @param {vec3} mieColor The variable the Mie scattering will be written to.
* @param {float} opacity The variable the transmittance will be written to.
*/
void czm_computeScattering(
czm_ray primaryRay,
float primaryRayLength,
vec3 lightDirection,
float atmosphereInnerRadius,
out vec3 rayleighColor,
out vec3 mieColor,
out float opacity
) {
const float ATMOSPHERE_THICKNESS = 111e3; // The thickness of the atmosphere in meters.
const int PRIMARY_STEPS_MAX = 16; // Maximum number of times the ray from the camera to the world position (primary ray) is sampled.
const 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.
// Initialize the default scattering amounts to 0.
rayleighColor = vec3(0.0);
mieColor = vec3(0.0);
opacity = 0.0;
float atmosphereOuterRadius = atmosphereInnerRadius + ATMOSPHERE_THICKNESS;
vec3 origin = vec3(0.0);
// Calculate intersection from the camera to the outer ring of the atmosphere.
czm_raySegment primaryRayAtmosphereIntersect = czm_raySphereIntersectionInterval(primaryRay, origin, atmosphereOuterRadius);
// Return empty colors if no intersection with the atmosphere geometry.
if (primaryRayAtmosphereIntersect == czm_emptyRaySegment) {
rayleighColor = vec3(1.0, 0.0, 1.0);
return;
}
// To deal with smaller values of PRIMARY_STEPS (e.g. 4)
// we implement a split strategy: sky or horizon.
// For performance reasons, instead of a if/else branch
// a soft choice is implemented through a weight 0.0 <= w_stop_gt_lprl <= 1.0
float x = 1e-7 * primaryRayAtmosphereIntersect.stop / length(primaryRayLength);
// Value close to 0.0: close to the horizon
// Value close to 1.0: above in the sky
float w_stop_gt_lprl = 0.5 * (1.0 + czm_approximateTanh(x));
// The ray should start from the first intersection with the outer atmopshere, or from the camera position, if it is inside the atmosphere.
float start_0 = primaryRayAtmosphereIntersect.start;
primaryRayAtmosphereIntersect.start = max(primaryRayAtmosphereIntersect.start, 0.0);
// The ray should end at the exit from the atmosphere or at the distance to the vertex, whichever is smaller.
primaryRayAtmosphereIntersect.stop = min(primaryRayAtmosphereIntersect.stop, length(primaryRayLength));
// For the number of ray steps, distinguish inside or outside atmosphere (outer space)
// (1) from outer space we have to use more ray steps to get a realistic rendering
// (2) within atmosphere we need fewer steps for faster rendering
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
float w_inside_atmosphere = 1.0 - 0.5 * (1.0 + czm_approximateTanh(x_o_a));
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.
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.
// Setup for sampling positions along the ray - starting from the intersection with the outer ring of the atmosphere.
float rayPositionLength = primaryRayAtmosphereIntersect.start;
// (1) Outside the atmosphere: constant rayStepLength
// (2) Inside atmosphere: variable rayStepLength to compensate the rough rendering of the smaller number of ray steps
float totalRayLength = primaryRayAtmosphereIntersect.stop - rayPositionLength;
float rayStepLengthIncrease = w_inside_atmosphere * ((1.0 - w_stop_gt_lprl) * totalRayLength / (float(PRIMARY_STEPS * (PRIMARY_STEPS + 1)) / 2.0));
float rayStepLength = max(1.0 - w_inside_atmosphere, w_stop_gt_lprl) * totalRayLength / max(7.0 * w_inside_atmosphere, float(PRIMARY_STEPS));
vec3 rayleighAccumulation = vec3(0.0);
vec3 mieAccumulation = vec3(0.0);
vec2 opticalDepth = vec2(0.0);
vec2 heightScale = vec2(czm_atmosphereRayleighScaleHeight, czm_atmosphereMieScaleHeight);
// Sample positions on the primary ray.
for (int i = 0; i < PRIMARY_STEPS_MAX; ++i) {
// The loop should be: for (int i = 0; i < PRIMARY_STEPS; ++i) {...} but WebGL1 cannot
// loop with non-constant condition, so it has to break early instead
if (i >= PRIMARY_STEPS) {
break;
}
// Calculate sample position along viewpoint ray.
vec3 samplePosition = primaryRay.origin + primaryRay.direction * (rayPositionLength + rayStepLength);
// Calculate height of sample position above ellipsoid.
float sampleHeight = length(samplePosition) - atmosphereInnerRadius;
// Calculate and accumulate density of particles at the sample position.
vec2 sampleDensity = exp(-sampleHeight / heightScale) * rayStepLength;
opticalDepth += sampleDensity;
// Generate ray from the sample position segment to the light source, up to the outer ring of the atmosphere.
czm_ray lightRay = czm_ray(samplePosition, lightDirection);
czm_raySegment lightRayAtmosphereIntersect = czm_raySphereIntersectionInterval(lightRay, origin, atmosphereOuterRadius);
float lightStepLength = lightRayAtmosphereIntersect.stop / float(LIGHT_STEPS);
float lightPositionLength = 0.0;
vec2 lightOpticalDepth = vec2(0.0);
// Sample positions along the light ray, to accumulate incidence of light on the latest sample segment.
for (int j = 0; j < LIGHT_STEPS_MAX; ++j) {
// The loop should be: for (int j = 0; i < LIGHT_STEPS; ++j) {...} but WebGL1 cannot
// loop with non-constant condition, so it has to break early instead
if (j >= LIGHT_STEPS) {
break;
}
// Calculate sample position along light ray.
vec3 lightPosition = samplePosition + lightDirection * (lightPositionLength + lightStepLength * 0.5);
// Calculate height of the light sample position above ellipsoid.
float lightHeight = length(lightPosition) - atmosphereInnerRadius;
// Calculate density of photons at the light sample position.
lightOpticalDepth += exp(-lightHeight / heightScale) * lightStepLength;
// Increment distance on light ray.
lightPositionLength += lightStepLength;
}
// Compute attenuation via the primary ray and the light ray.
vec3 attenuation = exp(-((czm_atmosphereMieCoefficient * (opticalDepth.y + lightOpticalDepth.y)) + (czm_atmosphereRayleighCoefficient * (opticalDepth.x + lightOpticalDepth.x))));
// Accumulate the scattering.
rayleighAccumulation += sampleDensity.x * attenuation;
mieAccumulation += sampleDensity.y * attenuation;
// Increment distance on primary ray.
rayPositionLength += (rayStepLength += rayStepLengthIncrease);
}
// Compute the scattering amount.
rayleighColor = czm_atmosphereRayleighCoefficient * rayleighAccumulation;
mieColor = czm_atmosphereMieCoefficient * mieAccumulation;
// Compute the transmittance i.e. how much light is passing through the atmosphere.
opacity = length(exp(-((czm_atmosphereMieCoefficient * opticalDepth.y) + (czm_atmosphereRayleighCoefficient * opticalDepth.x))));
}
`,MQ=`/**
* @private
*/
vec2 cordic(float angle)
{
// Scale the vector by the appropriate factor for the 24 iterations to follow.
vec2 vector = vec2(6.0725293500888267e-1, 0.0);
// Iteration 1
float sense = (angle < 0.0) ? -1.0 : 1.0;
// float factor = sense * 1.0; // 2^-0
mat2 rotation = mat2(1.0, sense, -sense, 1.0);
vector = rotation * vector;
angle -= sense * 7.8539816339744828e-1; // atan(2^-0)
// Iteration 2
sense = (angle < 0.0) ? -1.0 : 1.0;
float factor = sense * 5.0e-1; // 2^-1
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 4.6364760900080609e-1; // atan(2^-1)
// Iteration 3
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 2.5e-1; // 2^-2
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 2.4497866312686414e-1; // atan(2^-2)
// Iteration 4
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 1.25e-1; // 2^-3
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 1.2435499454676144e-1; // atan(2^-3)
// Iteration 5
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 6.25e-2; // 2^-4
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 6.2418809995957350e-2; // atan(2^-4)
// Iteration 6
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 3.125e-2; // 2^-5
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 3.1239833430268277e-2; // atan(2^-5)
// Iteration 7
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 1.5625e-2; // 2^-6
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 1.5623728620476831e-2; // atan(2^-6)
// Iteration 8
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 7.8125e-3; // 2^-7
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 7.8123410601011111e-3; // atan(2^-7)
// Iteration 9
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 3.90625e-3; // 2^-8
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 3.9062301319669718e-3; // atan(2^-8)
// Iteration 10
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 1.953125e-3; // 2^-9
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 1.9531225164788188e-3; // atan(2^-9)
// Iteration 11
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 9.765625e-4; // 2^-10
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 9.7656218955931946e-4; // atan(2^-10)
// Iteration 12
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 4.8828125e-4; // 2^-11
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 4.8828121119489829e-4; // atan(2^-11)
// Iteration 13
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 2.44140625e-4; // 2^-12
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 2.4414062014936177e-4; // atan(2^-12)
// Iteration 14
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 1.220703125e-4; // 2^-13
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 1.2207031189367021e-4; // atan(2^-13)
// Iteration 15
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 6.103515625e-5; // 2^-14
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 6.1035156174208773e-5; // atan(2^-14)
// Iteration 16
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 3.0517578125e-5; // 2^-15
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 3.0517578115526096e-5; // atan(2^-15)
// Iteration 17
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 1.52587890625e-5; // 2^-16
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 1.5258789061315762e-5; // atan(2^-16)
// Iteration 18
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 7.62939453125e-6; // 2^-17
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 7.6293945311019700e-6; // atan(2^-17)
// Iteration 19
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 3.814697265625e-6; // 2^-18
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 3.8146972656064961e-6; // atan(2^-18)
// Iteration 20
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 1.9073486328125e-6; // 2^-19
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 1.9073486328101870e-6; // atan(2^-19)
// Iteration 21
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 9.5367431640625e-7; // 2^-20
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 9.5367431640596084e-7; // atan(2^-20)
// Iteration 22
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 4.76837158203125e-7; // 2^-21
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 4.7683715820308884e-7; // atan(2^-21)
// Iteration 23
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 2.384185791015625e-7; // 2^-22
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
angle -= sense * 2.3841857910155797e-7; // atan(2^-22)
// Iteration 24
sense = (angle < 0.0) ? -1.0 : 1.0;
factor = sense * 1.1920928955078125e-7; // 2^-23
rotation[0][1] = factor;
rotation[1][0] = -factor;
vector = rotation * vector;
// angle -= sense * 1.1920928955078068e-7; // atan(2^-23)
return vector;
}
/**
* Computes the cosine and sine of the provided angle using the CORDIC algorithm.
*
* @name czm_cosineAndSine
* @glslFunction
*
* @param {float} angle The angle in radians.
*
* @returns {vec2} The resulting cosine of the angle (as the x coordinate) and sine of the angle (as the y coordinate).
*
* @example
* vec2 v = czm_cosineAndSine(czm_piOverSix);
* float cosine = v.x;
* float sine = v.y;
*/
vec2 czm_cosineAndSine(float angle)
{
if (angle < -czm_piOverTwo || angle > czm_piOverTwo)
{
if (angle < 0.0)
{
return -cordic(angle + czm_pi);
}
else
{
return -cordic(angle - czm_pi);
}
}
else
{
return cordic(angle);
}
}
`,FQ=`/**
* Decompresses texture coordinates that were packed into a single float.
*
* @name czm_decompressTextureCoordinates
* @glslFunction
*
* @param {float} encoded The compressed texture coordinates.
* @returns {vec2} The decompressed texture coordinates.
*/
vec2 czm_decompressTextureCoordinates(float encoded)
{
float temp = encoded / 4096.0;
float xZeroTo4095 = floor(temp);
float stx = xZeroTo4095 / 4095.0;
float sty = (encoded - xZeroTo4095 * 4096.0) / 4095.0;
return vec2(stx, sty);
}
`,BQ=`/**
* Get default parameters for physically based rendering. These defaults
* describe a rough dielectric (non-metal) surface (e.g. rough plastic).
*
* @return {czm_pbrParameters} Default parameters for {@link czm_pbrLighting}
*/
czm_pbrParameters czm_defaultPbrMaterial()
{
czm_pbrParameters results;
results.diffuseColor = vec3(1.0);
results.roughness = 1.0;
const vec3 REFLECTANCE_DIELECTRIC = vec3(0.04);
results.f0 = REFLECTANCE_DIELECTRIC;
return results;
}
`,zQ=`// emulated noperspective
#if (__VERSION__ == 300 || defined(GL_EXT_frag_depth)) && !defined(LOG_DEPTH)
out float v_WindowZ;
#endif
/**
* Emulates GL_DEPTH_CLAMP, which is not available in WebGL 1 or 2.
* GL_DEPTH_CLAMP clamps geometry that is outside the near and far planes,
* capping the shadow volume. More information here:
* https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_depth_clamp.txt.
*
* When GL_EXT_frag_depth is available we emulate GL_DEPTH_CLAMP by ensuring
* no geometry gets clipped by setting the clip space z value to 0.0 and then
* sending the unaltered screen space z value (using emulated noperspective
* interpolation) to the frag shader where it is clamped to [0,1] and then
* written with gl_FragDepth (see czm_writeDepthClamp). This technique is based on:
* https://stackoverflow.com/questions/5960757/how-to-emulate-gl-depth-clamp-nv.
*
* When GL_EXT_frag_depth is not available, which is the case on some mobile
* devices, we must attempt to fix this only in the vertex shader.
* The approach is to clamp the z value to the far plane, which closes the
* shadow volume but also distorts the geometry, so there can still be artifacts
* on frustum seams.
*
* @name czm_depthClamp
* @glslFunction
*
* @param {vec4} coords The vertex in clip coordinates.
* @returns {vec4} The modified vertex.
*
* @example
* gl_Position = czm_depthClamp(czm_modelViewProjection * vec4(position, 1.0));
*
* @see czm_writeDepthClamp
*/
vec4 czm_depthClamp(vec4 coords)
{
#ifndef LOG_DEPTH
#if __VERSION__ == 300 || defined(GL_EXT_frag_depth)
v_WindowZ = (0.5 * (coords.z / coords.w) + 0.5) * coords.w;
coords.z = 0.0;
#else
coords.z = min(coords.z, coords.w);
#endif
#endif
return coords;
}
`,UQ=`/**
* Computes a 3x3 rotation matrix that transforms vectors from an ellipsoid's east-north-up coordinate system
* to eye coordinates. In east-north-up coordinates, x points east, y points north, and z points along the
* surface normal. East-north-up can be used as an ellipsoid's tangent space for operations such as bump mapping.
* <br /><br />
* The ellipsoid is assumed to be centered at the model coordinate's origin.
*
* @name czm_eastNorthUpToEyeCoordinates
* @glslFunction
*
* @param {vec3} positionMC The position on the ellipsoid in model coordinates.
* @param {vec3} normalEC The normalized ellipsoid surface normal, at <code>positionMC</code>, in eye coordinates.
*
* @returns {mat3} A 3x3 rotation matrix that transforms vectors from the east-north-up coordinate system to eye coordinates.
*
* @example
* // Transform a vector defined in the east-north-up coordinate
* // system, (0, 0, 1) which is the surface normal, to eye
* // coordinates.
* mat3 m = czm_eastNorthUpToEyeCoordinates(positionMC, normalEC);
* vec3 normalEC = m * vec3(0.0, 0.0, 1.0);
*/
mat3 czm_eastNorthUpToEyeCoordinates(vec3 positionMC, vec3 normalEC)
{
vec3 tangentMC = normalize(vec3(-positionMC.y, positionMC.x, 0.0)); // normalized surface tangent in model coordinates
vec3 tangentEC = normalize(czm_normal3D * tangentMC); // normalized surface tangent in eye coordinates
vec3 bitangentEC = normalize(cross(normalEC, tangentEC)); // normalized surface bitangent in eye coordinates
return mat3(
tangentEC.x, tangentEC.y, tangentEC.z,
bitangentEC.x, bitangentEC.y, bitangentEC.z,
normalEC.x, normalEC.y, normalEC.z);
}
`,kQ=`/**
* DOC_TBA
*
* @name czm_ellipsoidContainsPoint
* @glslFunction
*
*/
bool czm_ellipsoidContainsPoint(vec3 ellipsoid_inverseRadii, vec3 point)
{
vec3 scaled = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(point, 1.0)).xyz;
return (dot(scaled, scaled) <= 1.0);
}
`,VQ=`/**
* DOC_TBA
*
* @name czm_ellipsoidWgs84TextureCoordinates
* @glslFunction
*/
vec2 czm_ellipsoidWgs84TextureCoordinates(vec3 normal)
{
return vec2(atan(normal.y, normal.x) * czm_oneOverTwoPi + 0.5, asin(normal.z) * czm_oneOverPi + 0.5);
}
`,HQ=`/**
* Compares <code>left</code> and <code>right</code> componentwise. Returns <code>true</code>
* if they are within <code>epsilon</code> and <code>false</code> otherwise. The inputs
* <code>left</code> and <code>right</code> can be <code>float</code>s, <code>vec2</code>s,
* <code>vec3</code>s, or <code>vec4</code>s.
*
* @name czm_equalsEpsilon
* @glslFunction
*
* @param {} left The first vector.
* @param {} right The second vector.
* @param {float} epsilon The epsilon to use for equality testing.
* @returns {bool} <code>true</code> if the components are within <code>epsilon</code> and <code>false</code> otherwise.
*
* @example
* // GLSL declarations
* bool czm_equalsEpsilon(float left, float right, float epsilon);
* bool czm_equalsEpsilon(vec2 left, vec2 right, float epsilon);
* bool czm_equalsEpsilon(vec3 left, vec3 right, float epsilon);
* bool czm_equalsEpsilon(vec4 left, vec4 right, float epsilon);
*/
bool czm_equalsEpsilon(vec4 left, vec4 right, float epsilon) {
return all(lessThanEqual(abs(left - right), vec4(epsilon)));
}
bool czm_equalsEpsilon(vec3 left, vec3 right, float epsilon) {
return all(lessThanEqual(abs(left - right), vec3(epsilon)));
}
bool czm_equalsEpsilon(vec2 left, vec2 right, float epsilon) {
return all(lessThanEqual(abs(left - right), vec2(epsilon)));
}
bool czm_equalsEpsilon(float left, float right, float epsilon) {
return (abs(left - right) <= epsilon);
}
`,GQ=`/**
* DOC_TBA
*
* @name czm_eyeOffset
* @glslFunction
*
* @param {vec4} positionEC DOC_TBA.
* @param {vec3} eyeOffset DOC_TBA.
*
* @returns {vec4} DOC_TBA.
*/
vec4 czm_eyeOffset(vec4 positionEC, vec3 eyeOffset)
{
// This equation is approximate in x and y.
vec4 p = positionEC;
vec4 zEyeOffset = normalize(p) * eyeOffset.z;
p.xy += eyeOffset.xy + zEyeOffset.xy;
p.z += zEyeOffset.z;
return p;
}
`,jQ=`/**
* Transforms a position from eye to window coordinates. The transformation
* from eye to clip coordinates is done using {@link czm_projection}.
* The transform from normalized device coordinates to window coordinates is
* done using {@link czm_viewportTransformation}, which assumes a depth range
* of <code>near = 0</code> and <code>far = 1</code>.
* <br /><br />
* This transform is useful when there is a need to manipulate window coordinates
* in a vertex shader as done by {@link BillboardCollection}.
*
* @name czm_eyeToWindowCoordinates
* @glslFunction
*
* @param {vec4} position The position in eye coordinates to transform.
*
* @returns {vec4} The transformed position in window coordinates.
*
* @see czm_modelToWindowCoordinates
* @see czm_projection
* @see czm_viewportTransformation
* @see BillboardCollection
*
* @example
* vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);
*/
vec4 czm_eyeToWindowCoordinates(vec4 positionEC)
{
vec4 q = czm_projection * positionEC; // clip coordinates
q.xyz /= q.w; // normalized device coordinates
q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // window coordinates
return q;
}
`,WQ=`/**
* 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;
}
`,qQ=`/**
* Gets the color with fog at a distance from the camera.
*
* @name czm_fog
* @glslFunction
*
* @param {float} distanceToCamera The distance to the camera in meters.
* @param {vec3} color The original color.
* @param {vec3} fogColor The color of the fog.
*
* @returns {vec3} The color adjusted for fog at the distance from the camera.
*/
vec3 czm_fog(float distanceToCamera, vec3 color, vec3 fogColor)
{
float scalar = distanceToCamera * czm_fogDensity;
float fog = 1.0 - exp(-(scalar * scalar));
return mix(color, fogColor, fog);
}
/**
* Gets the color with fog at a distance from the camera.
*
* @name czm_fog
* @glslFunction
*
* @param {float} distanceToCamera The distance to the camera in meters.
* @param {vec3} color The original color.
* @param {vec3} fogColor The color of the fog.
* @param {float} fogModifierConstant A constant to modify the appearance of fog.
*
* @returns {vec3} The color adjusted for fog at the distance from the camera.
*/
vec3 czm_fog(float distanceToCamera, vec3 color, vec3 fogColor, float fogModifierConstant)
{
float scalar = distanceToCamera * czm_fogDensity;
float fog = 1.0 - exp(-((fogModifierConstant * scalar + fogModifierConstant) * (scalar * (1.0 + fogModifierConstant))));
return mix(color, fogColor, fog);
}
`,YQ=`/**
* Converts a color from RGB space to linear space.
*
* @name czm_gammaCorrect
* @glslFunction
*
* @param {vec3} color The color in RGB space.
* @returns {vec3} The color in linear space.
*/
vec3 czm_gammaCorrect(vec3 color) {
#ifdef HDR
color = pow(color, vec3(czm_gamma));
#endif
return color;
}
vec4 czm_gammaCorrect(vec4 color) {
#ifdef HDR
color.rgb = pow(color.rgb, vec3(czm_gamma));
#endif
return color;
}
`,$Q=`/**
* DOC_TBA
*
* @name czm_geodeticSurfaceNormal
* @glslFunction
*
* @param {vec3} positionOnEllipsoid DOC_TBA
* @param {vec3} ellipsoidCenter DOC_TBA
* @param {vec3} oneOverEllipsoidRadiiSquared DOC_TBA
*
* @returns {vec3} DOC_TBA.
*/
vec3 czm_geodeticSurfaceNormal(vec3 positionOnEllipsoid, vec3 ellipsoidCenter, vec3 oneOverEllipsoidRadiiSquared)
{
return normalize((positionOnEllipsoid - ellipsoidCenter) * oneOverEllipsoidRadiiSquared);
}
`,XQ=`/**
* An czm_material with default values. Every material's czm_getMaterial
* should use this default material as a base for the material it returns.
* The default normal value is given by materialInput.normalEC.
*
* @name czm_getDefaultMaterial
* @glslFunction
*
* @param {czm_materialInput} input The input used to construct the default material.
*
* @returns {czm_material} The default material.
*
* @see czm_materialInput
* @see czm_material
* @see czm_getMaterial
*/
czm_material czm_getDefaultMaterial(czm_materialInput materialInput)
{
czm_material material;
material.diffuse = vec3(0.0);
material.specular = 0.0;
material.shininess = 1.0;
material.normal = materialInput.normalEC;
material.emission = vec3(0.0);
material.alpha = 1.0;
return material;
}
`,QQ=`/**
* Select which direction vector to use for dynamic atmosphere lighting based on an enum value
*
* @name czm_getDynamicAtmosphereLightDirection
* @glslfunction
* @see DynamicAtmosphereLightingType.js
*
* @param {vec3} positionWC the position of the vertex/fragment in world coordinates. This is normalized and returned when dynamic lighting is turned off.
* @param {float} lightEnum The enum value for selecting between light sources.
* @return {vec3} The normalized light direction vector. Depending on the enum value, it is either positionWC, czm_lightDirectionWC or czm_sunDirectionWC
*/
vec3 czm_getDynamicAtmosphereLightDirection(vec3 positionWC, float lightEnum) {
const float NONE = 0.0;
const float SCENE_LIGHT = 1.0;
const float SUNLIGHT = 2.0;
vec3 lightDirection =
positionWC * float(lightEnum == NONE) +
czm_lightDirectionWC * float(lightEnum == SCENE_LIGHT) +
czm_sunDirectionWC * float(lightEnum == SUNLIGHT);
return normalize(lightDirection);
}
`,KQ=`/**
* Calculates the intensity of diffusely reflected light.
*
* @name czm_getLambertDiffuse
* @glslFunction
*
* @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.
* @param {vec3} normalEC The surface normal in eye coordinates.
*
* @returns {float} The intensity of the diffuse reflection.
*
* @see czm_phong
*
* @example
* float diffuseIntensity = czm_getLambertDiffuse(lightDirectionEC, normalEC);
* float specularIntensity = czm_getSpecular(lightDirectionEC, toEyeEC, normalEC, 200);
* vec3 color = (diffuseColor * diffuseIntensity) + (specularColor * specularIntensity);
*/
float czm_getLambertDiffuse(vec3 lightDirectionEC, vec3 normalEC)
{
return max(dot(lightDirectionEC, normalEC), 0.0);
}
`,ZQ=`/**
* Calculates the specular intensity of reflected light.
*
* @name czm_getSpecular
* @glslFunction
*
* @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.
* @param {vec3} toEyeEC Unit vector pointing to the eye position in eye coordinates.
* @param {vec3} normalEC The surface normal in eye coordinates.
* @param {float} shininess The sharpness of the specular reflection. Higher values create a smaller, more focused specular highlight.
*
* @returns {float} The intensity of the specular highlight.
*
* @see czm_phong
*
* @example
* float diffuseIntensity = czm_getLambertDiffuse(lightDirectionEC, normalEC);
* float specularIntensity = czm_getSpecular(lightDirectionEC, toEyeEC, normalEC, 200);
* vec3 color = (diffuseColor * diffuseIntensity) + (specularColor * specularIntensity);
*/
float czm_getSpecular(vec3 lightDirectionEC, vec3 toEyeEC, vec3 normalEC, float shininess)
{
vec3 toReflectedLight = reflect(-lightDirectionEC, normalEC);
float specular = max(dot(toReflectedLight, toEyeEC), 0.0);
// pow has undefined behavior if both parameters <= 0.
// Prevent this by making sure shininess is at least czm_epsilon2.
return pow(specular, max(shininess, czm_epsilon2));
}
`,JQ=`/**
* @private
*/
vec4 czm_getWaterNoise(sampler2D normalMap, vec2 uv, float time, float angleInRadians)
{
float cosAngle = cos(angleInRadians);
float sinAngle = sin(angleInRadians);
// time dependent sampling directions
vec2 s0 = vec2(1.0/17.0, 0.0);
vec2 s1 = vec2(-1.0/29.0, 0.0);
vec2 s2 = vec2(1.0/101.0, 1.0/59.0);
vec2 s3 = vec2(-1.0/109.0, -1.0/57.0);
// rotate sampling direction by specified angle
s0 = vec2((cosAngle * s0.x) - (sinAngle * s0.y), (sinAngle * s0.x) + (cosAngle * s0.y));
s1 = vec2((cosAngle * s1.x) - (sinAngle * s1.y), (sinAngle * s1.x) + (cosAngle * s1.y));
s2 = vec2((cosAngle * s2.x) - (sinAngle * s2.y), (sinAngle * s2.x) + (cosAngle * s2.y));
s3 = vec2((cosAngle * s3.x) - (sinAngle * s3.y), (sinAngle * s3.x) + (cosAngle * s3.y));
vec2 uv0 = (uv/103.0) + (time * s0);
vec2 uv1 = uv/107.0 + (time * s1) + vec2(0.23);
vec2 uv2 = uv/vec2(897.0, 983.0) + (time * s2) + vec2(0.51);
vec2 uv3 = uv/vec2(991.0, 877.0) + (time * s3) + vec2(0.71);
uv0 = fract(uv0);
uv1 = fract(uv1);
uv2 = fract(uv2);
uv3 = fract(uv3);
vec4 noise = (texture(normalMap, uv0)) +
(texture(normalMap, uv1)) +
(texture(normalMap, uv2)) +
(texture(normalMap, uv3));
// average and scale to between -1 and 1
return ((noise / 4.0) - 0.5) * 2.0;
}
`,eK=`/**
* Adjusts the hue of a color.
*
* @name czm_hue
* @glslFunction
*
* @param {vec3} rgb The color.
* @param {float} adjustment The amount to adjust the hue of the color in radians.
*
* @returns {float} The color with the hue adjusted.
*
* @example
* vec3 adjustHue = czm_hue(color, czm_pi); // The same as czm_hue(color, -czm_pi)
*/
vec3 czm_hue(vec3 rgb, float adjustment)
{
const mat3 toYIQ = mat3(0.299, 0.587, 0.114,
0.595716, -0.274453, -0.321263,
0.211456, -0.522591, 0.311135);
const mat3 toRGB = mat3(1.0, 0.9563, 0.6210,
1.0, -0.2721, -0.6474,
1.0, -1.107, 1.7046);
vec3 yiq = toYIQ * rgb;
float hue = atan(yiq.z, yiq.y) + adjustment;
float chroma = sqrt(yiq.z * yiq.z + yiq.y * yiq.y);
vec3 color = vec3(yiq.x, chroma * cos(hue), chroma * sin(hue));
return toRGB * color;
}
`,tK=`/**
* Converts a color in linear space to RGB space.
*
* @name czm_inverseGamma
* @glslFunction
*
* @param {vec3} color The color in linear space.
* @returns {vec3} The color in RGB space.
*/
vec3 czm_inverseGamma(vec3 color) {
return pow(color, vec3(1.0 / czm_gamma));
}
`,nK=`/**
* Determines if a time interval is empty.
*
* @name czm_isEmpty
* @glslFunction
*
* @param {czm_raySegment} interval The interval to test.
*
* @returns {bool} <code>true</code> if the time interval is empty; otherwise, <code>false</code>.
*
* @example
* bool b0 = czm_isEmpty(czm_emptyRaySegment); // true
* bool b1 = czm_isEmpty(czm_raySegment(0.0, 1.0)); // false
* bool b2 = czm_isEmpty(czm_raySegment(1.0, 1.0)); // false, contains 1.0.
*/
bool czm_isEmpty(czm_raySegment interval)
{
return (interval.stop < 0.0);
}
`,iK=`/**
* Determines if a time interval is empty.
*
* @name czm_isFull
* @glslFunction
*
* @param {czm_raySegment} interval The interval to test.
*
* @returns {bool} <code>true</code> if the time interval is empty; otherwise, <code>false</code>.
*
* @example
* bool b0 = czm_isEmpty(czm_emptyRaySegment); // true
* bool b1 = czm_isEmpty(czm_raySegment(0.0, 1.0)); // false
* bool b2 = czm_isEmpty(czm_raySegment(1.0, 1.0)); // false, contains 1.0.
*/
bool czm_isFull(czm_raySegment interval)
{
return (interval.start == 0.0 && interval.stop == czm_infinity);
}
`,oK=`/**
* Computes the fraction of a Web Wercator rectangle at which a given geodetic latitude is located.
*
* @name czm_latitudeToWebMercatorFraction
* @glslFunction
*
* @param {float} latitude The geodetic latitude, in radians.
* @param {float} southMercatorY The Web Mercator coordinate of the southern boundary of the rectangle.
* @param {float} oneOverMercatorHeight The total height of the rectangle in Web Mercator coordinates.
*
* @returns {float} The fraction of the rectangle at which the latitude occurs. If the latitude is the southern
* boundary of the rectangle, the return value will be zero. If it is the northern boundary, the return
* value will be 1.0. Latitudes in between are mapped according to the Web Mercator projection.
*/
float czm_latitudeToWebMercatorFraction(float latitude, float southMercatorY, float oneOverMercatorHeight)
{
float sinLatitude = sin(latitude);
float mercatorY = 0.5 * log((1.0 + sinLatitude) / (1.0 - sinLatitude));
return (mercatorY - southMercatorY) * oneOverMercatorHeight;
}
`,rK=`/**
* Computes distance from an point in 2D to a line in 2D.
*
* @name czm_lineDistance
* @glslFunction
*
* param {vec2} point1 A point along the line.
* param {vec2} point2 A point along the line.
* param {vec2} point A point that may or may not be on the line.
* returns {float} The distance from the point to the line.
*/
float czm_lineDistance(vec2 point1, vec2 point2, vec2 point) {
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);
}
`,sK=`/**
* Converts a linear RGB color to an sRGB color.
*
* @param {vec3|vec4} linearIn The color in linear color space.
* @returns {vec3|vec4} The color in sRGB color space. The vector type matches the input.
*/
vec3 czm_linearToSrgb(vec3 linearIn)
{
return pow(linearIn, vec3(1.0/2.2));
}
vec4 czm_linearToSrgb(vec4 linearIn)
{
vec3 srgbOut = pow(linearIn.rgb, vec3(1.0/2.2));
return vec4(srgbOut, linearIn.a);
}
`,aK=`/**
* Computes the luminance of a color.
*
* @name czm_luminance
* @glslFunction
*
* @param {vec3} rgb The color.
*
* @returns {float} The luminance.
*
* @example
* float light = czm_luminance(vec3(0.0)); // 0.0
* float dark = czm_luminance(vec3(1.0)); // ~1.0
*/
float czm_luminance(vec3 rgb)
{
// Algorithm from Chapter 10 of Graphics Shaders.
const vec3 W = vec3(0.2125, 0.7154, 0.0721);
return dot(rgb, W);
}
`,cK=`/**
* Computes the size of a pixel in meters at a distance from the eye.
* <p>
* Use this version when passing in a custom pixel ratio. For example, passing in 1.0 will return meters per native device pixel.
* </p>
* @name czm_metersPerPixel
* @glslFunction
*
* @param {vec3} positionEC The position to get the meters per pixel in eye coordinates.
* @param {float} pixelRatio The scaling factor from pixel space to coordinate space
*
* @returns {float} The meters per pixel at positionEC.
*/
float czm_metersPerPixel(vec4 positionEC, float pixelRatio)
{
float width = czm_viewport.z;
float height = czm_viewport.w;
float pixelWidth;
float pixelHeight;
float top = czm_frustumPlanes.x;
float bottom = czm_frustumPlanes.y;
float left = czm_frustumPlanes.z;
float right = czm_frustumPlanes.w;
if (czm_sceneMode == czm_sceneMode2D || czm_orthographicIn3D == 1.0)
{
float frustumWidth = right - left;
float frustumHeight = top - bottom;
pixelWidth = frustumWidth / width;
pixelHeight = frustumHeight / height;
}
else
{
float distanceToPixel = -positionEC.z;
float inverseNear = 1.0 / czm_currentFrustum.x;
float tanTheta = top * inverseNear;
pixelHeight = 2.0 * distanceToPixel * tanTheta / height;
tanTheta = right * inverseNear;
pixelWidth = 2.0 * distanceToPixel * tanTheta / width;
}
return max(pixelWidth, pixelHeight) * pixelRatio;
}
/**
* Computes the size of a pixel in meters at a distance from the eye.
* <p>
* Use this version when scaling by pixel ratio.
* </p>
* @name czm_metersPerPixel
* @glslFunction
*
* @param {vec3} positionEC The position to get the meters per pixel in eye coordinates.
*
* @returns {float} The meters per pixel at positionEC.
*/
float czm_metersPerPixel(vec4 positionEC)
{
return czm_metersPerPixel(positionEC, czm_pixelRatio);
}
`,lK=`/**
* Transforms a position from model to window coordinates. The transformation
* from model to clip coordinates is done using {@link czm_modelViewProjection}.
* The transform from normalized device coordinates to window coordinates is
* done using {@link czm_viewportTransformation}, which assumes a depth range
* of <code>near = 0</code> and <code>far = 1</code>.
* <br /><br />
* This transform is useful when there is a need to manipulate window coordinates
* in a vertex shader as done by {@link BillboardCollection}.
* <br /><br />
* This function should not be confused with {@link czm_viewportOrthographic},
* which is an orthographic projection matrix that transforms from window
* coordinates to clip coordinates.
*
* @name czm_modelToWindowCoordinates
* @glslFunction
*
* @param {vec4} position The position in model coordinates to transform.
*
* @returns {vec4} The transformed position in window coordinates.
*
* @see czm_eyeToWindowCoordinates
* @see czm_modelViewProjection
* @see czm_viewportTransformation
* @see czm_viewportOrthographic
* @see BillboardCollection
*
* @example
* vec4 positionWC = czm_modelToWindowCoordinates(positionMC);
*/
vec4 czm_modelToWindowCoordinates(vec4 position)
{
vec4 q = czm_modelViewProjection * position; // clip coordinates
q.xyz /= q.w; // normalized device coordinates
q.xyz = (czm_viewportTransformation * vec4(q.xyz, 1.0)).xyz; // window coordinates
return q;
}
`,uK=`/**
* DOC_TBA
*
* @name czm_multiplyWithColorBalance
* @glslFunction
*/
vec3 czm_multiplyWithColorBalance(vec3 left, vec3 right)
{
// Algorithm from Chapter 10 of Graphics Shaders.
const vec3 W = vec3(0.2125, 0.7154, 0.0721);
vec3 target = left * right;
float leftLuminance = dot(left, W);
float rightLuminance = dot(right, W);
float targetLuminance = dot(target, W);
return ((leftLuminance + rightLuminance) / (2.0 * targetLuminance)) * target;
}
`,dK=`/**
* Computes a value that scales with distance. The scaling is clamped at the near and
* far distances, and does not extrapolate. This function works with the
* {@link NearFarScalar} JavaScript class.
*
* @name czm_nearFarScalar
* @glslFunction
*
* @param {vec4} nearFarScalar A vector with 4 components: Near distance (x), Near value (y), Far distance (z), Far value (w).
* @param {float} cameraDistSq The square of the current distance from the camera.
*
* @returns {float} The value at this distance.
*/
float czm_nearFarScalar(vec4 nearFarScalar, float cameraDistSq)
{
float valueAtMin = nearFarScalar.y;
float valueAtMax = nearFarScalar.w;
float nearDistanceSq = nearFarScalar.x * nearFarScalar.x;
float farDistanceSq = nearFarScalar.z * nearFarScalar.z;
float t = (cameraDistSq - nearDistanceSq) / (farDistanceSq - nearDistanceSq);
t = pow(clamp(t, 0.0, 1.0), 0.2);
return mix(valueAtMin, valueAtMax, t);
}
`,hK=` /**
* 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));
}
`,fK=`/**
* Packs a depth value into a vec3 that can be represented by unsigned bytes.
*
* @name czm_packDepth
* @glslFunction
*
* @param {float} depth The floating-point depth.
* @returns {vec3} The packed depth.
*/
vec4 czm_packDepth(float depth)
{
// See Aras Pranckevi\u010Dius' post Encoding Floats to RGBA
// http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
vec4 enc = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;
enc = fract(enc);
enc -= enc.yzww * vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0);
return enc;
}
`,pK=`vec3 lambertianDiffuse(vec3 diffuseColor)
{
return diffuseColor / czm_pi;
}
vec3 fresnelSchlick2(vec3 f0, vec3 f90, float VdotH)
{
return f0 + (f90 - f0) * pow(clamp(1.0 - VdotH, 0.0, 1.0), 5.0);
}
float smithVisibilityG1(float NdotV, float roughness)
{
// this is the k value for direct lighting.
// for image based lighting it will be roughness^2 / 2
float k = (roughness + 1.0) * (roughness + 1.0) / 8.0;
return NdotV / (NdotV * (1.0 - k) + k);
}
float smithVisibilityGGX(float roughness, float NdotL, float NdotV)
{
return (
smithVisibilityG1(NdotL, roughness) *
smithVisibilityG1(NdotV, roughness)
);
}
float GGX(float roughness, float NdotH)
{
float roughnessSquared = roughness * roughness;
float f = (NdotH * roughnessSquared - NdotH) * NdotH + 1.0;
return roughnessSquared / (czm_pi * f * f);
}
/**
* Compute the diffuse and specular contributions using physically based
* rendering. This function only handles direct lighting.
* <p>
* This function only handles the lighting calculations. Metallic/roughness
* and specular/glossy must be handled separately. See {@czm_pbrMetallicRoughnessMaterial}, {@czm_pbrSpecularGlossinessMaterial} and {@czm_defaultPbrMaterial}
* </p>
*
* @name czm_pbrlighting
* @glslFunction
*
* @param {vec3} positionEC The position of the fragment in eye coordinates
* @param {vec3} normalEC The surface normal in eye coordinates
* @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.
* @param {vec3} lightColorHdr radiance of the light source. This is a HDR value.
* @param {czm_pbrParameters} The computed PBR parameters.
* @return {vec3} The computed HDR color
*
* @example
* czm_pbrParameters pbrParameters = czm_pbrMetallicRoughnessMaterial(
* baseColor,
* metallic,
* roughness
* );
* vec3 color = czm_pbrlighting(
* positionEC,
* normalEC,
* lightDirectionEC,
* lightColorHdr,
* pbrParameters);
*/
vec3 czm_pbrLighting(
vec3 positionEC,
vec3 normalEC,
vec3 lightDirectionEC,
vec3 lightColorHdr,
czm_pbrParameters pbrParameters
)
{
vec3 v = -normalize(positionEC);
vec3 l = normalize(lightDirectionEC);
vec3 h = normalize(v + l);
vec3 n = normalEC;
float NdotL = clamp(dot(n, l), 0.001, 1.0);
float NdotV = abs(dot(n, v)) + 0.001;
float NdotH = clamp(dot(n, h), 0.0, 1.0);
float LdotH = clamp(dot(l, h), 0.0, 1.0);
float VdotH = clamp(dot(v, h), 0.0, 1.0);
vec3 f0 = pbrParameters.f0;
float reflectance = max(max(f0.r, f0.g), f0.b);
vec3 f90 = vec3(clamp(reflectance * 25.0, 0.0, 1.0));
vec3 F = fresnelSchlick2(f0, f90, VdotH);
float alpha = pbrParameters.roughness;
float G = smithVisibilityGGX(alpha, NdotL, NdotV);
float D = GGX(alpha, NdotH);
vec3 specularContribution = F * G * D / (4.0 * NdotL * NdotV);
vec3 diffuseColor = pbrParameters.diffuseColor;
// F here represents the specular contribution
vec3 diffuseContribution = (1.0 - F) * lambertianDiffuse(diffuseColor);
// Lo = (diffuse + specular) * Li * NdotL
return (diffuseContribution + specularContribution) * NdotL * lightColorHdr;
}
`,mK=`/**
* Compute parameters for physically based rendering using the
* metallic/roughness workflow. All inputs are linear; sRGB texture values must
* be decoded beforehand
*
* @name czm_pbrMetallicRoughnessMaterial
* @glslFunction
*
* @param {vec3} baseColor For dielectrics, this is the base color. For metals, this is the f0 value (reflectance at normal incidence)
* @param {float} metallic 0.0 indicates dielectric. 1.0 indicates metal. Values in between are allowed (e.g. to model rust or dirt);
* @param {float} roughness A value between 0.0 and 1.0
* @return {czm_pbrParameters} parameters to pass into {@link czm_pbrLighting}
*/
czm_pbrParameters czm_pbrMetallicRoughnessMaterial(
vec3 baseColor,
float metallic,
float roughness
)
{
czm_pbrParameters results;
// roughness is authored as perceptual roughness
// square it to get material roughness
roughness = clamp(roughness, 0.0, 1.0);
results.roughness = roughness * roughness;
// dielectrics use f0 = 0.04, metals use albedo as f0
metallic = clamp(metallic, 0.0, 1.0);
const vec3 REFLECTANCE_DIELECTRIC = vec3(0.04);
vec3 f0 = mix(REFLECTANCE_DIELECTRIC, baseColor, metallic);
results.f0 = f0;
// diffuse only applies to dielectrics.
results.diffuseColor = baseColor * (1.0 - f0) * (1.0 - metallic);
return results;
}
`,_K=`/**
* Compute parameters for physically based rendering using the
* specular/glossy workflow. All inputs are linear; sRGB texture values must
* be decoded beforehand
*
* @name czm_pbrSpecularGlossinessMaterial
* @glslFunction
*
* @param {vec3} diffuse The diffuse color for dielectrics (non-metals)
* @param {vec3} specular The reflectance at normal incidence (f0)
* @param {float} glossiness A number from 0.0 to 1.0 indicating how smooth the surface is.
* @return {czm_pbrParameters} parameters to pass into {@link czm_pbrLighting}
*/
czm_pbrParameters czm_pbrSpecularGlossinessMaterial(
vec3 diffuse,
vec3 specular,
float glossiness
)
{
czm_pbrParameters results;
// glossiness is the opposite of roughness, but easier for artists to use.
float roughness = 1.0 - glossiness;
results.roughness = roughness * roughness;
results.diffuseColor = diffuse * (1.0 - max(max(specular.r, specular.g), specular.b));
results.f0 = specular;
return results;
}
`,gK=`float czm_private_getLambertDiffuseOfMaterial(vec3 lightDirectionEC, czm_material material)
{
return czm_getLambertDiffuse(lightDirectionEC, material.normal);
}
float czm_private_getSpecularOfMaterial(vec3 lightDirectionEC, vec3 toEyeEC, czm_material material)
{
return czm_getSpecular(lightDirectionEC, toEyeEC, material.normal, material.shininess);
}
/**
* Computes a color using the Phong lighting model.
*
* @name czm_phong
* @glslFunction
*
* @param {vec3} toEye A normalized vector from the fragment to the eye in eye coordinates.
* @param {czm_material} material The fragment's material.
*
* @returns {vec4} The computed color.
*
* @example
* vec3 positionToEyeEC = // ...
* czm_material material = // ...
* vec3 lightDirectionEC = // ...
* out_FragColor = czm_phong(normalize(positionToEyeEC), material, lightDirectionEC);
*
* @see czm_getMaterial
*/
vec4 czm_phong(vec3 toEye, czm_material material, vec3 lightDirectionEC)
{
// Diffuse from directional light sources at eye (for top-down)
float diffuse = czm_private_getLambertDiffuseOfMaterial(vec3(0.0, 0.0, 1.0), material);
if (czm_sceneMode == czm_sceneMode3D) {
// (and horizon views in 3D)
diffuse += czm_private_getLambertDiffuseOfMaterial(vec3(0.0, 1.0, 0.0), material);
}
float specular = czm_private_getSpecularOfMaterial(lightDirectionEC, toEye, material);
// Temporary workaround for adding ambient.
vec3 materialDiffuse = material.diffuse * 0.5;
vec3 ambient = materialDiffuse;
vec3 color = ambient + material.emission;
color += materialDiffuse * diffuse * czm_lightColor;
color += material.specular * specular * czm_lightColor;
return vec4(color, material.alpha);
}
vec4 czm_private_phong(vec3 toEye, czm_material material, vec3 lightDirectionEC)
{
float diffuse = czm_private_getLambertDiffuseOfMaterial(lightDirectionEC, material);
float specular = czm_private_getSpecularOfMaterial(lightDirectionEC, toEye, material);
vec3 ambient = vec3(0.0);
vec3 color = ambient + material.emission;
color += material.diffuse * diffuse * czm_lightColor;
color += material.specular * specular * czm_lightColor;
return vec4(color, material.alpha);
}
`,yK=`/**
* Computes distance from a point to a plane.
*
* @name czm_planeDistance
* @glslFunction
*
* param {vec4} plane A Plane in Hessian Normal Form. See Plane.js
* param {vec3} point A point in the same space as the plane.
* returns {float} The distance from the point to the plane.
*/
float czm_planeDistance(vec4 plane, vec3 point) {
return (dot(plane.xyz, point) + plane.w);
}
/**
* Computes distance from a point to a plane.
*
* @name czm_planeDistance
* @glslFunction
*
* param {vec3} planeNormal Normal for a plane in Hessian Normal Form. See Plane.js
* param {float} planeDistance Distance for a plane in Hessian Normal form. See Plane.js
* param {vec3} point A point in the same space as the plane.
* returns {float} The distance from the point to the plane.
*/
float czm_planeDistance(vec3 planeNormal, float planeDistance, vec3 point) {
return (dot(planeNormal, point) + planeDistance);
}
`,bK=`/**
* Computes the point along a ray at the given time. <code>time</code> can be positive, negative, or zero.
*
* @name czm_pointAlongRay
* @glslFunction
*
* @param {czm_ray} ray The ray to compute the point along.
* @param {float} time The time along the ray.
*
* @returns {vec3} The point along the ray at the given time.
*
* @example
* czm_ray ray = czm_ray(vec3(0.0), vec3(1.0, 0.0, 0.0)); // origin, direction
* vec3 v = czm_pointAlongRay(ray, 2.0); // (2.0, 0.0, 0.0)
*/
vec3 czm_pointAlongRay(czm_ray ray, float time)
{
return ray.origin + (time * ray.direction);
}
`,TK=`/**
* DOC_TBA
*
* @name czm_rayEllipsoidIntersectionInterval
* @glslFunction
*/
czm_raySegment czm_rayEllipsoidIntersectionInterval(czm_ray ray, vec3 ellipsoid_center, vec3 ellipsoid_inverseRadii)
{
// ray and ellipsoid center in eye coordinates. radii in model coordinates.
vec3 q = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ray.origin, 1.0)).xyz;
vec3 w = ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ray.direction, 0.0)).xyz;
q = q - ellipsoid_inverseRadii * (czm_inverseModelView * vec4(ellipsoid_center, 1.0)).xyz;
float q2 = dot(q, q);
float qw = dot(q, w);
if (q2 > 1.0) // Outside ellipsoid.
{
if (qw >= 0.0) // Looking outward or tangent (0 intersections).
{
return czm_emptyRaySegment;
}
else // qw < 0.0.
{
float qw2 = qw * qw;
float difference = q2 - 1.0; // Positively valued.
float w2 = dot(w, w);
float product = w2 * difference;
if (qw2 < product) // Imaginary roots (0 intersections).
{
return czm_emptyRaySegment;
}
else if (qw2 > product) // Distinct roots (2 intersections).
{
float discriminant = qw * qw - product;
float temp = -qw + sqrt(discriminant); // Avoid cancellation.
float root0 = temp / w2;
float root1 = difference / temp;
if (root0 < root1)
{
czm_raySegment i = czm_raySegment(root0, root1);
return i;
}
else
{
czm_raySegment i = czm_raySegment(root1, root0);
return i;
}
}
else // qw2 == product. Repeated roots (2 intersections).
{
float root = sqrt(difference / w2);
czm_raySegment i = czm_raySegment(root, root);
return i;
}
}
}
else if (q2 < 1.0) // Inside ellipsoid (2 intersections).
{
float difference = q2 - 1.0; // Negatively valued.
float w2 = dot(w, w);
float product = w2 * difference; // Negatively valued.
float discriminant = qw * qw - product;
float temp = -qw + sqrt(discriminant); // Positively valued.
czm_raySegment i = czm_raySegment(0.0, temp / w2);
return i;
}
else // q2 == 1.0. On ellipsoid.
{
if (qw < 0.0) // Looking inward.
{
float w2 = dot(w, w);
czm_raySegment i = czm_raySegment(0.0, -qw / w2);
return i;
}
else // qw >= 0.0. Looking outward or tangent.
{
return czm_emptyRaySegment;
}
}
}
`,AK=`/**
* Compute the intersection interval of a ray with a sphere.
*
* @name czm_raySphereIntersectionInterval
* @glslFunction
*
* @param {czm_ray} ray The ray.
* @param {vec3} center The center of the sphere.
* @param {float} radius The radius of the sphere.
* @return {czm_raySegment} The intersection interval of the ray with the sphere.
*/
czm_raySegment czm_raySphereIntersectionInterval(czm_ray ray, vec3 center, float radius)
{
vec3 o = ray.origin;
vec3 d = ray.direction;
vec3 oc = o - center;
float a = dot(d, d);
float b = 2.0 * dot(d, oc);
float c = dot(oc, oc) - (radius * radius);
float det = (b * b) - (4.0 * a * c);
if (det < 0.0) {
return czm_emptyRaySegment;
}
float sqrtDet = sqrt(det);
float t0 = (-b - sqrtDet) / (2.0 * a);
float t1 = (-b + sqrtDet) / (2.0 * a);
czm_raySegment result = czm_raySegment(t0, t1);
return result;
}
`,xK=`float czm_readDepth(sampler2D depthTexture, vec2 texCoords)
{
return czm_reverseLogDepth(texture(depthTexture, texCoords).r);
}
`,CK=`/**
* Reads a value previously transformed with {@link czm_writeNonPerspective}
* by dividing it by \`w\`, the value used in the perspective divide.
* This function is intended to be called in a fragment shader to access a
* \`varying\` that should not be subject to perspective interpolation.
* For example, screen-space texture coordinates. The value should have been
* previously written in the vertex shader with a call to
* {@link czm_writeNonPerspective}.
*
* @name czm_readNonPerspective
* @glslFunction
*
* @param {float|vec2|vec3|vec4} value The non-perspective value to be read.
* @param {float} oneOverW One over the perspective divide value, \`w\`. Usually this is simply \`gl_FragCoord.w\`.
* @returns {float|vec2|vec3|vec4} The usable value.
*/
float czm_readNonPerspective(float value, float oneOverW) {
return value * oneOverW;
}
vec2 czm_readNonPerspective(vec2 value, float oneOverW) {
return value * oneOverW;
}
vec3 czm_readNonPerspective(vec3 value, float oneOverW) {
return value * oneOverW;
}
vec4 czm_readNonPerspective(vec4 value, float oneOverW) {
return value * oneOverW;
}
`,EK=`float czm_reverseLogDepth(float logZ)
{
#ifdef LOG_DEPTH
float near = czm_currentFrustum.x;
float far = czm_currentFrustum.y;
float log2Depth = logZ * czm_log2FarDepthFromNearPlusOne;
float depthFromNear = pow(2.0, log2Depth) - 1.0;
return far * (1.0 - near / (depthFromNear + near)) / (far - near);
#endif
return logZ;
}
`,wK=`/**
* Round a floating point value. This function exists because round() doesn't
* exist in GLSL 1.00.
*
* @param {float|vec2|vec3|vec4} value The value to round
* @param {float|vec2|vec3|vec3} The rounded value. The type matches the input.
*/
float czm_round(float value) {
return floor(value + 0.5);
}
vec2 czm_round(vec2 value) {
return floor(value + 0.5);
}
vec3 czm_round(vec3 value) {
return floor(value + 0.5);
}
vec4 czm_round(vec4 value) {
return floor(value + 0.5);
}
`,SK=`/**
* Samples the 4 neighboring pixels and return the weighted average.
*
* @private
*/
vec3 czm_sampleOctahedralProjectionWithFiltering(sampler2D projectedMap, vec2 textureSize, vec3 direction, float lod)
{
direction /= dot(vec3(1.0), abs(direction));
vec2 rev = abs(direction.zx) - vec2(1.0);
vec2 neg = vec2(direction.x < 0.0 ? rev.x : -rev.x,
direction.z < 0.0 ? rev.y : -rev.y);
vec2 uv = direction.y < 0.0 ? neg : direction.xz;
vec2 coord = 0.5 * uv + vec2(0.5);
vec2 pixel = 1.0 / textureSize;
if (lod > 0.0)
{
// Each subseqeuent mip level is half the size
float scale = 1.0 / pow(2.0, lod);
float offset = ((textureSize.y + 1.0) / textureSize.x);
coord.x *= offset;
coord *= scale;
coord.x += offset + pixel.x;
coord.y += (1.0 - (1.0 / pow(2.0, lod - 1.0))) + pixel.y * (lod - 1.0) * 2.0;
}
else
{
coord.x *= (textureSize.y / textureSize.x);
}
// Do bilinear filtering
#ifndef OES_texture_float_linear
vec3 color1 = texture(projectedMap, coord + vec2(0.0, pixel.y)).rgb;
vec3 color2 = texture(projectedMap, coord + vec2(pixel.x, 0.0)).rgb;
vec3 color3 = texture(projectedMap, coord + pixel).rgb;
vec3 color4 = texture(projectedMap, coord).rgb;
vec2 texturePosition = coord * textureSize;
float fu = fract(texturePosition.x);
float fv = fract(texturePosition.y);
vec3 average1 = mix(color4, color2, fu);
vec3 average2 = mix(color1, color3, fu);
vec3 color = mix(average1, average2, fv);
#else
vec3 color = texture(projectedMap, coord).rgb;
#endif
return color;
}
/**
* Samples from a cube map that has been projected using an octahedral projection from the given direction.
*
* @name czm_sampleOctahedralProjection
* @glslFunction
*
* @param {sampler2D} projectedMap The texture with the octahedral projected cube map.
* @param {vec2} textureSize The width and height dimensions in pixels of the projected map.
* @param {vec3} direction The normalized direction used to sample the cube map.
* @param {float} lod The level of detail to sample.
* @param {float} maxLod The maximum level of detail.
* @returns {vec3} The color of the cube map at the direction.
*/
vec3 czm_sampleOctahedralProjection(sampler2D projectedMap, vec2 textureSize, vec3 direction, float lod, float maxLod) {
float currentLod = floor(lod + 0.5);
float nextLod = min(currentLod + 1.0, maxLod);
vec3 colorCurrentLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, currentLod);
vec3 colorNextLod = czm_sampleOctahedralProjectionWithFiltering(projectedMap, textureSize, direction, nextLod);
return mix(colorNextLod, colorCurrentLod, nextLod - lod);
}
`,vK=`/**
* Adjusts the saturation of a color.
*
* @name czm_saturation
* @glslFunction
*
* @param {vec3} rgb The color.
* @param {float} adjustment The amount to adjust the saturation of the color.
*
* @returns {float} The color with the saturation adjusted.
*
* @example
* vec3 greyScale = czm_saturation(color, 0.0);
* vec3 doubleSaturation = czm_saturation(color, 2.0);
*/
vec3 czm_saturation(vec3 rgb, float adjustment)
{
// Algorithm from Chapter 16 of OpenGL Shading Language
const vec3 W = vec3(0.2125, 0.7154, 0.0721);
vec3 intensity = vec3(dot(rgb, W));
return mix(intensity, rgb, adjustment);
}
`,IK=`
float czm_sampleShadowMap(highp samplerCube shadowMap, vec3 d)
{
return czm_unpackDepth(czm_textureCube(shadowMap, d));
}
float czm_sampleShadowMap(highp sampler2D shadowMap, vec2 uv)
{
#ifdef USE_SHADOW_DEPTH_TEXTURE
return texture(shadowMap, uv).r;
#else
return czm_unpackDepth(texture(shadowMap, uv));
#endif
}
float czm_shadowDepthCompare(samplerCube shadowMap, vec3 uv, float depth)
{
return step(depth, czm_sampleShadowMap(shadowMap, uv));
}
float czm_shadowDepthCompare(sampler2D shadowMap, vec2 uv, float depth)
{
return step(depth, czm_sampleShadowMap(shadowMap, uv));
}
`,DK=`
float czm_private_shadowVisibility(float visibility, float nDotL, float normalShadingSmooth, float darkness)
{
#ifdef USE_NORMAL_SHADING
#ifdef USE_NORMAL_SHADING_SMOOTH
float strength = clamp(nDotL / normalShadingSmooth, 0.0, 1.0);
#else
float strength = step(0.0, nDotL);
#endif
visibility *= strength;
#endif
visibility = max(visibility, darkness);
return visibility;
}
#ifdef USE_CUBE_MAP_SHADOW
float czm_shadowVisibility(samplerCube shadowMap, czm_shadowParameters shadowParameters)
{
float depthBias = shadowParameters.depthBias;
float depth = shadowParameters.depth;
float nDotL = shadowParameters.nDotL;
float normalShadingSmooth = shadowParameters.normalShadingSmooth;
float darkness = shadowParameters.darkness;
vec3 uvw = shadowParameters.texCoords;
depth -= depthBias;
float visibility = czm_shadowDepthCompare(shadowMap, uvw, depth);
return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);
}
#else
float czm_shadowVisibility(sampler2D shadowMap, czm_shadowParameters shadowParameters)
{
float depthBias = shadowParameters.depthBias;
float depth = shadowParameters.depth;
float nDotL = shadowParameters.nDotL;
float normalShadingSmooth = shadowParameters.normalShadingSmooth;
float darkness = shadowParameters.darkness;
vec2 uv = shadowParameters.texCoords;
depth -= depthBias;
#ifdef USE_SOFT_SHADOWS
vec2 texelStepSize = shadowParameters.texelStepSize;
float radius = 1.0;
float dx0 = -texelStepSize.x * radius;
float dy0 = -texelStepSize.y * radius;
float dx1 = texelStepSize.x * radius;
float dy1 = texelStepSize.y * radius;
float visibility = (
czm_shadowDepthCompare(shadowMap, uv, depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy0), depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy0), depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy0), depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, 0.0), depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, 0.0), depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(dx0, dy1), depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(0.0, dy1), depth) +
czm_shadowDepthCompare(shadowMap, uv + vec2(dx1, dy1), depth)
) * (1.0 / 9.0);
#else
float visibility = czm_shadowDepthCompare(shadowMap, uv, depth);
#endif
return czm_private_shadowVisibility(visibility, nDotL, normalShadingSmooth, darkness);
}
#endif
`,PK=`/**
* Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative. This is similar to the GLSL
* built-in function <code>sign</code> except that returns 1.0 instead of 0.0 when the input value is 0.0.
*
* @name czm_signNotZero
* @glslFunction
*
* @param {} value The value for which to determine the sign.
* @returns {} 1.0 if the value is positive or zero, -1.0 if the value is negative.
*/
float czm_signNotZero(float value)
{
return value >= 0.0 ? 1.0 : -1.0;
}
vec2 czm_signNotZero(vec2 value)
{
return vec2(czm_signNotZero(value.x), czm_signNotZero(value.y));
}
vec3 czm_signNotZero(vec3 value)
{
return vec3(czm_signNotZero(value.x), czm_signNotZero(value.y), czm_signNotZero(value.z));
}
vec4 czm_signNotZero(vec4 value)
{
return vec4(czm_signNotZero(value.x), czm_signNotZero(value.y), czm_signNotZero(value.z), czm_signNotZero(value.w));
}
`,OK=`/**
* Computes a color from the third order spherical harmonic coefficients and a normalized direction vector.
* <p>
* The order of the coefficients is [L00, L1_1, L10, L11, L2_2, L2_1, L20, L21, L22].
* </p>
*
* @name czm_sphericalHarmonics
* @glslFunction
*
* @param {vec3} normal The normalized direction.
* @param {vec3[9]} coefficients The third order spherical harmonic coefficients.
* @returns {vec3} The color at the direction.
*
* @see https://graphics.stanford.edu/papers/envmap/envmap.pdf
*/
vec3 czm_sphericalHarmonics(vec3 normal, vec3 coefficients[9])
{
vec3 L00 = coefficients[0];
vec3 L1_1 = coefficients[1];
vec3 L10 = coefficients[2];
vec3 L11 = coefficients[3];
vec3 L2_2 = coefficients[4];
vec3 L2_1 = coefficients[5];
vec3 L20 = coefficients[6];
vec3 L21 = coefficients[7];
vec3 L22 = coefficients[8];
float x = normal.x;
float y = normal.y;
float z = normal.z;
return
L00
+ L1_1 * y
+ L10 * z
+ L11 * x
+ L2_2 * (y * x)
+ L2_1 * (y * z)
+ L20 * (3.0 * z * z - 1.0)
+ L21 * (z * x)
+ L22 * (x * x - y * y);
}
`,LK=`/**
* Converts an sRGB color to a linear RGB color.
*
* @param {vec3|vec4} srgbIn The color in sRGB space
* @returns {vec3|vec4} The color in linear color space. The vector type matches the input.
*/
vec3 czm_srgbToLinear(vec3 srgbIn)
{
return pow(srgbIn, vec3(2.2));
}
vec4 czm_srgbToLinear(vec4 srgbIn)
{
vec3 linearOut = pow(srgbIn.rgb, vec3(2.2));
return vec4(linearOut, srgbIn.a);
}
`,RK=`/**
* Creates a matrix that transforms vectors from tangent space to eye space.
*
* @name czm_tangentToEyeSpaceMatrix
* @glslFunction
*
* @param {vec3} normalEC The normal vector in eye coordinates.
* @param {vec3} tangentEC The tangent vector in eye coordinates.
* @param {vec3} bitangentEC The bitangent vector in eye coordinates.
*
* @returns {mat3} The matrix that transforms from tangent space to eye space.
*
* @example
* mat3 tangentToEye = czm_tangentToEyeSpaceMatrix(normalEC, tangentEC, bitangentEC);
* vec3 normal = tangentToEye * texture(normalMap, st).xyz;
*/
mat3 czm_tangentToEyeSpaceMatrix(vec3 normalEC, vec3 tangentEC, vec3 bitangentEC)
{
vec3 normal = normalize(normalEC);
vec3 tangent = normalize(tangentEC);
vec3 bitangent = normalize(bitangentEC);
return mat3(tangent.x , tangent.y , tangent.z,
bitangent.x, bitangent.y, bitangent.z,
normal.x , normal.y , normal.z);
}
`,NK=`/**
* A wrapper around the texture (WebGL2) / textureCube (WebGL1)
* function to allow for WebGL 1 support.
*
* @name czm_textureCube
* @glslFunction
*
* @param {samplerCube} sampler The sampler.
* @param {vec3} p The coordinates to sample the texture at.
*/
vec4 czm_textureCube(samplerCube sampler, vec3 p) {
#if __VERSION__ == 300
return texture(sampler, p);
#else
return textureCube(sampler, p);
#endif
}`,MK=`/**
* Transforms a plane.
*
* @name czm_transformPlane
* @glslFunction
*
* @param {vec4} plane The plane in Hessian Normal Form.
* @param {mat4} transform The inverse-transpose of a transformation matrix.
*/
vec4 czm_transformPlane(vec4 plane, mat4 transform) {
vec4 transformedPlane = transform * plane;
// Convert the transformed plane to Hessian Normal Form
float normalMagnitude = length(transformedPlane.xyz);
return transformedPlane / normalMagnitude;
}
`,FK=`/**
* Translates a position (or any <code>vec3</code>) that was encoded with {@link EncodedCartesian3},
* and then provided to the shader as separate <code>high</code> and <code>low</code> bits to
* be relative to the eye. As shown in the example, the position can then be transformed in eye
* or clip coordinates using {@link czm_modelViewRelativeToEye} or {@link czm_modelViewProjectionRelativeToEye},
* respectively.
* <p>
* This technique, called GPU RTE, eliminates jittering artifacts when using large coordinates as
* described in {@link http://help.agi.com/AGIComponents/html/BlogPrecisionsPrecisions.htm|Precisions, Precisions}.
* </p>
*
* @name czm_translateRelativeToEye
* @glslFunction
*
* @param {vec3} high The position's high bits.
* @param {vec3} low The position's low bits.
* @returns {vec3} The position translated to be relative to the camera's position.
*
* @example
* in vec3 positionHigh;
* in vec3 positionLow;
*
* void main()
* {
* vec4 p = czm_translateRelativeToEye(positionHigh, positionLow);
* gl_Position = czm_modelViewProjectionRelativeToEye * p;
* }
*
* @see czm_modelViewRelativeToEye
* @see czm_modelViewProjectionRelativeToEye
* @see czm_computePosition
* @see EncodedCartesian3
*/
vec4 czm_translateRelativeToEye(vec3 high, vec3 low)
{
vec3 highDifference = high - czm_encodedCameraPositionMCHigh;
// This check handles the case when NaN values have gotten into \`highDifference\`.
// Such a thing could happen on devices running iOS.
if (length(highDifference) == 0.0) {
highDifference = vec3(0);
}
vec3 lowDifference = low - czm_encodedCameraPositionMCLow;
return vec4(highDifference + lowDifference, 1.0);
}
`,BK=`/**
* @private
*/
vec4 czm_translucentPhong(vec3 toEye, czm_material material, vec3 lightDirectionEC)
{
// Diffuse from directional light sources at eye (for top-down and horizon views)
float diffuse = czm_getLambertDiffuse(vec3(0.0, 0.0, 1.0), material.normal);
if (czm_sceneMode == czm_sceneMode3D) {
// (and horizon views in 3D)
diffuse += czm_getLambertDiffuse(vec3(0.0, 1.0, 0.0), material.normal);
}
diffuse = clamp(diffuse, 0.0, 1.0);
float specular = czm_getSpecular(lightDirectionEC, toEye, material.normal, material.shininess);
// Temporary workaround for adding ambient.
vec3 materialDiffuse = material.diffuse * 0.5;
vec3 ambient = materialDiffuse;
vec3 color = ambient + material.emission;
color += materialDiffuse * diffuse * czm_lightColor;
color += material.specular * specular * czm_lightColor;
return vec4(color, material.alpha);
}
`,zK=`/**
* Returns the transpose of the matrix. The input <code>matrix</code> can be
* a <code>mat2</code>, <code>mat3</code>, or <code>mat4</code>.
*
* @name czm_transpose
* @glslFunction
*
* @param {} matrix The matrix to transpose.
*
* @returns {} The transposed matrix.
*
* @example
* // GLSL declarations
* mat2 czm_transpose(mat2 matrix);
* mat3 czm_transpose(mat3 matrix);
* mat4 czm_transpose(mat4 matrix);
*
* // Transpose a 3x3 rotation matrix to find its inverse.
* mat3 eastNorthUpToEye = czm_eastNorthUpToEyeCoordinates(
* positionMC, normalEC);
* mat3 eyeToEastNorthUp = czm_transpose(eastNorthUpToEye);
*/
mat2 czm_transpose(mat2 matrix)
{
return mat2(
matrix[0][0], matrix[1][0],
matrix[0][1], matrix[1][1]);
}
mat3 czm_transpose(mat3 matrix)
{
return mat3(
matrix[0][0], matrix[1][0], matrix[2][0],
matrix[0][1], matrix[1][1], matrix[2][1],
matrix[0][2], matrix[1][2], matrix[2][2]);
}
mat4 czm_transpose(mat4 matrix)
{
return mat4(
matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
}
`,UK=`vec2 getLookupUv(vec2 dimensions, int i) {
int pixY = i / int(dimensions.x);
int pixX = i - (pixY * int(dimensions.x));
float pixelWidth = 1.0 / dimensions.x;
float pixelHeight = 1.0 / dimensions.y;
float u = (float(pixX) + 0.5) * pixelWidth; // sample from center of pixel
float v = (float(pixY) + 0.5) * pixelHeight;
return vec2(u, v);
}
vec4 czm_unpackClippingExtents(highp sampler2D extentsTexture, int index) {
vec2 textureDimensions = vec2(textureSize(extentsTexture, 0));
return texture(extentsTexture, getLookupUv(textureDimensions, index));
}`,kK=`/**
* Unpacks a vec4 depth value to a float in [0, 1) range.
*
* @name czm_unpackDepth
* @glslFunction
*
* @param {vec4} packedDepth The packed depth.
*
* @returns {float} The floating-point depth in [0, 1) range.
*/
float czm_unpackDepth(vec4 packedDepth)
{
// See Aras Pranckevi\u010Dius' post Encoding Floats to RGBA
// http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
return dot(packedDepth, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));
}
`,VK=`/**
* Unpack an IEEE 754 single-precision float that is packed as a little-endian unsigned normalized vec4.
*
* @name czm_unpackFloat
* @glslFunction
*
* @param {vec4} packedFloat The packed float.
*
* @returns {float} The floating-point depth in arbitrary range.
*/
float czm_unpackFloat(vec4 packedFloat)
{
// Convert to [0.0, 255.0] and round to integer
packedFloat = floor(packedFloat * 255.0 + 0.5);
float sign = 1.0 - step(128.0, packedFloat[3]) * 2.0;
float exponent = 2.0 * mod(packedFloat[3], 128.0) + step(128.0, packedFloat[2]) - 127.0;
if (exponent == -127.0)
{
return 0.0;
}
float mantissa = mod(packedFloat[2], 128.0) * 65536.0 + packedFloat[1] * 256.0 + packedFloat[0] + float(0x800000);
float result = sign * exp2(exponent - 23.0) * mantissa;
return result;
}
`,HK=`/**
* Unpack unsigned integers of 1-4 bytes. in WebGL 1, there is no uint type,
* so the return value is an int.
* <p>
* There are also precision limitations in WebGL 1. highp int is still limited
* to 24 bits. Above the value of 2^24 = 16777216, precision loss may occur.
* </p>
*
* @param {float|vec2|vec3|vec4} packed The packed value. For vectors, the components are listed in little-endian order.
*
* @return {int} The unpacked value.
*/
int czm_unpackUint(float packedValue) {
float rounded = czm_round(packedValue * 255.0);
return int(rounded);
}
int czm_unpackUint(vec2 packedValue) {
vec2 rounded = czm_round(packedValue * 255.0);
return int(dot(rounded, vec2(1.0, 256.0)));
}
int czm_unpackUint(vec3 packedValue) {
vec3 rounded = czm_round(packedValue * 255.0);
return int(dot(rounded, vec3(1.0, 256.0, 65536.0)));
}
int czm_unpackUint(vec4 packedValue) {
vec4 rounded = czm_round(packedValue * 255.0);
return int(dot(rounded, vec4(1.0, 256.0, 65536.0, 16777216.0)));
}
`,GK=`/**
* Transform metadata values following the EXT_structural_metadata spec
* by multiplying by scale and adding the offset. Operations are always
* performed component-wise, even for matrices.
*
* @param {float|vec2|vec3|vec4|mat2|mat3|mat4} offset The offset to add
* @param {float|vec2|vec3|vec4|mat2|mat3|mat4} scale The scale factor to multiply
* @param {float|vec2|vec3|vec4|mat2|mat3|mat4} value The original value.
*
* @return {float|vec2|vec3|vec4|mat2|mat3|mat4} The transformed value of the same scalar/vector/matrix type as the input.
*/
float czm_valueTransform(float offset, float scale, float value) {
return scale * value + offset;
}
vec2 czm_valueTransform(vec2 offset, vec2 scale, vec2 value) {
return scale * value + offset;
}
vec3 czm_valueTransform(vec3 offset, vec3 scale, vec3 value) {
return scale * value + offset;
}
vec4 czm_valueTransform(vec4 offset, vec4 scale, vec4 value) {
return scale * value + offset;
}
mat2 czm_valueTransform(mat2 offset, mat2 scale, mat2 value) {
return matrixCompMult(scale, value) + offset;
}
mat3 czm_valueTransform(mat3 offset, mat3 scale, mat3 value) {
return matrixCompMult(scale, value) + offset;
}
mat4 czm_valueTransform(mat4 offset, mat4 scale, mat4 value) {
return matrixCompMult(scale, value) + offset;
}
`,jK=`#ifdef LOG_DEPTH
// 1.0 at the near plane, increasing linearly from there.
out float v_depthFromNearPlusOne;
#ifdef SHADOW_MAP
out vec3 v_logPositionEC;
#endif
#endif
vec4 czm_updatePositionDepth(vec4 coords) {
#if defined(LOG_DEPTH)
#ifdef SHADOW_MAP
vec3 logPositionEC = (czm_inverseProjection * coords).xyz;
v_logPositionEC = logPositionEC;
#endif
// With the very high far/near ratios used with the logarithmic depth
// buffer, floating point rounding errors can cause linear depth values
// to end up on the wrong side of the far plane, even for vertices that
// are really nowhere near it. Since we always write a correct logarithmic
// depth value in the fragment shader anyway, we just need to make sure
// such errors don't cause the primitive to be clipped entirely before
// we even get to the fragment shader.
coords.z = clamp(coords.z / coords.w, -1.0, 1.0) * coords.w;
#endif
return coords;
}
/**
* Writes the logarithmic depth to gl_Position using the already computed gl_Position.
*
* @name czm_vertexLogDepth
* @glslFunction
*/
void czm_vertexLogDepth()
{
#ifdef LOG_DEPTH
v_depthFromNearPlusOne = (gl_Position.w - czm_currentFrustum.x) + 1.0;
gl_Position = czm_updatePositionDepth(gl_Position);
#endif
}
/**
* Writes the logarithmic depth to gl_Position using the provided clip coordinates.
* <p>
* An example use case for this function would be moving the vertex in window coordinates
* before converting back to clip coordinates. Use the original vertex clip coordinates.
* </p>
* @name czm_vertexLogDepth
* @glslFunction
*
* @param {vec4} clipCoords The vertex in clip coordinates.
*
* @example
* czm_vertexLogDepth(czm_projection * vec4(positionEyeCoordinates, 1.0));
*/
void czm_vertexLogDepth(vec4 clipCoords)
{
#ifdef LOG_DEPTH
v_depthFromNearPlusOne = (clipCoords.w - czm_currentFrustum.x) + 1.0;
czm_updatePositionDepth(clipCoords);
#endif
}
`,WK=`vec4 czm_screenToEyeCoordinates(vec4 screenCoordinate)
{
// Reconstruct NDC coordinates
float x = 2.0 * screenCoordinate.x - 1.0;
float y = 2.0 * screenCoordinate.y - 1.0;
float z = (screenCoordinate.z - czm_viewportTransformation[3][2]) / czm_viewportTransformation[2][2];
vec4 q = vec4(x, y, z, 1.0);
// Reverse the perspective division to obtain clip coordinates.
q /= screenCoordinate.w;
// Reverse the projection transformation to obtain eye coordinates.
if (!(czm_inverseProjection == mat4(0.0))) // IE and Edge sometimes do something weird with != between mat4s
{
q = czm_inverseProjection * q;
}
else
{
float top = czm_frustumPlanes.x;
float bottom = czm_frustumPlanes.y;
float left = czm_frustumPlanes.z;
float right = czm_frustumPlanes.w;
float near = czm_currentFrustum.x;
float far = czm_currentFrustum.y;
q.x = (q.x * (right - left) + left + right) * 0.5;
q.y = (q.y * (top - bottom) + bottom + top) * 0.5;
q.z = (q.z * (near - far) - near - far) * 0.5;
q.w = 1.0;
}
return q;
}
/**
* Transforms a position from window to eye coordinates.
* The transform from window to normalized device coordinates is done using components
* of (@link czm_viewport} and {@link czm_viewportTransformation} instead of calculating
* the inverse of <code>czm_viewportTransformation</code>. The transformation from
* normalized device coordinates to clip coordinates is done using <code>fragmentCoordinate.w</code>,
* which is expected to be the scalar used in the perspective divide. The transformation
* from clip to eye coordinates is done using {@link czm_inverseProjection}.
*
* @name czm_windowToEyeCoordinates
* @glslFunction
*
* @param {vec4} fragmentCoordinate The position in window coordinates to transform.
*
* @returns {vec4} The transformed position in eye coordinates.
*
* @see czm_modelToWindowCoordinates
* @see czm_eyeToWindowCoordinates
* @see czm_inverseProjection
* @see czm_viewport
* @see czm_viewportTransformation
*
* @example
* vec4 positionEC = czm_windowToEyeCoordinates(gl_FragCoord);
*/
vec4 czm_windowToEyeCoordinates(vec4 fragmentCoordinate)
{
vec2 screenCoordXY = (fragmentCoordinate.xy - czm_viewport.xy) / czm_viewport.zw;
return czm_screenToEyeCoordinates(vec4(screenCoordXY, fragmentCoordinate.zw));
}
vec4 czm_screenToEyeCoordinates(vec2 screenCoordinateXY, float depthOrLogDepth)
{
// See reverseLogDepth.glsl. This is separate to re-use the pow.
#if defined(LOG_DEPTH) || defined(LOG_DEPTH_READ_ONLY)
float near = czm_currentFrustum.x;
float far = czm_currentFrustum.y;
float log2Depth = depthOrLogDepth * czm_log2FarDepthFromNearPlusOne;
float depthFromNear = pow(2.0, log2Depth) - 1.0;
float depthFromCamera = depthFromNear + near;
vec4 screenCoord = vec4(screenCoordinateXY, far * (1.0 - near / depthFromCamera) / (far - near), 1.0);
vec4 eyeCoordinate = czm_screenToEyeCoordinates(screenCoord);
eyeCoordinate.w = 1.0 / depthFromCamera; // Better precision
return eyeCoordinate;
#else
vec4 screenCoord = vec4(screenCoordinateXY, depthOrLogDepth, 1.0);
vec4 eyeCoordinate = czm_screenToEyeCoordinates(screenCoord);
#endif
return eyeCoordinate;
}
/**
* Transforms a position given as window x/y and a depth or a log depth from window to eye coordinates.
* This function produces more accurate results for window positions with log depth than
* conventionally unpacking the log depth using czm_reverseLogDepth and using the standard version
* of czm_windowToEyeCoordinates.
*
* @name czm_windowToEyeCoordinates
* @glslFunction
*
* @param {vec2} fragmentCoordinateXY The XY position in window coordinates to transform.
* @param {float} depthOrLogDepth A depth or log depth for the fragment.
*
* @see czm_modelToWindowCoordinates
* @see czm_eyeToWindowCoordinates
* @see czm_inverseProjection
* @see czm_viewport
* @see czm_viewportTransformation
*
* @returns {vec4} The transformed position in eye coordinates.
*/
vec4 czm_windowToEyeCoordinates(vec2 fragmentCoordinateXY, float depthOrLogDepth)
{
vec2 screenCoordXY = (fragmentCoordinateXY.xy - czm_viewport.xy) / czm_viewport.zw;
return czm_screenToEyeCoordinates(screenCoordXY, depthOrLogDepth);
}
`,qK=`// emulated noperspective
#if !defined(LOG_DEPTH)
in float v_WindowZ;
#endif
/**
* Emulates GL_DEPTH_CLAMP. Clamps a fragment to the near and far plane
* by writing the fragment's depth. See czm_depthClamp for more details.
*
* @name czm_writeDepthClamp
* @glslFunction
*
* @example
* out_FragColor = color;
* czm_writeDepthClamp();
*
* @see czm_depthClamp
*/
void czm_writeDepthClamp()
{
#if (!defined(LOG_DEPTH) && (__VERSION__ == 300 || defined(GL_EXT_frag_depth)))
gl_FragDepth = clamp(v_WindowZ * gl_FragCoord.w, 0.0, 1.0);
#endif
}
`,YK=`#ifdef LOG_DEPTH
in float v_depthFromNearPlusOne;
#ifdef POLYGON_OFFSET
uniform vec2 u_polygonOffset;
#endif
#endif
/**
* Writes the fragment depth to the logarithmic depth buffer.
* <p>
* Use this when the vertex shader does not call {@link czm_vertexlogDepth}, for example, when
* ray-casting geometry using a full screen quad.
* </p>
* @name czm_writeLogDepth
* @glslFunction
*
* @param {float} depth The depth coordinate, where 1.0 is on the near plane and
* depth increases in eye-space units from there
*
* @example
* czm_writeLogDepth((czm_projection * v_positionEyeCoordinates).w + 1.0);
*/
void czm_writeLogDepth(float depth)
{
#if (defined(LOG_DEPTH) && (__VERSION__ == 300 || defined(GL_EXT_frag_depth)))
// Discard the vertex if it's not between the near and far planes.
// We allow a bit of epsilon on the near plane comparison because a 1.0
// from the vertex shader (indicating the vertex should be _on_ the near
// plane) will not necessarily come here as exactly 1.0.
if (depth <= 0.9999999 || depth > czm_farDepthFromNearPlusOne) {
discard;
}
#ifdef POLYGON_OFFSET
// Polygon offset: m * factor + r * units
float factor = u_polygonOffset[0];
float units = u_polygonOffset[1];
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
// This factor doesn't work in IE 10
if (factor != 0.0) {
// m = sqrt(dZdX^2 + dZdY^2);
float x = dFdx(depth);
float y = dFdy(depth);
float m = sqrt(x * x + y * y);
// Apply the factor before computing the log depth.
depth += m * factor;
}
#endif
#endif
gl_FragDepth = log2(depth) * czm_oneOverLog2FarDepthFromNearPlusOne;
#ifdef POLYGON_OFFSET
// Apply the units after the log depth.
gl_FragDepth += czm_epsilon7 * units;
#endif
#endif
}
/**
* Writes the fragment depth to the logarithmic depth buffer.
* <p>
* Use this when the vertex shader calls {@link czm_vertexlogDepth}.
* </p>
*
* @name czm_writeLogDepth
* @glslFunction
*/
void czm_writeLogDepth() {
#ifdef LOG_DEPTH
czm_writeLogDepth(v_depthFromNearPlusOne);
#endif
}
`,$K=`/**
* Transforms a value for non-perspective interpolation by multiplying
* it by w, the value used in the perspective divide. This function is
* intended to be called in a vertex shader to compute the value of a
* \`varying\` that should not be subject to perspective interpolation.
* For example, screen-space texture coordinates. The fragment shader
* must call {@link czm_readNonPerspective} to retrieve the final
* non-perspective value.
*
* @name czm_writeNonPerspective
* @glslFunction
*
* @param {float|vec2|vec3|vec4} value The value to be interpolated without accounting for perspective.
* @param {float} w The perspective divide value. Usually this is the computed \`gl_Position.w\`.
* @returns {float|vec2|vec3|vec4} The transformed value, intended to be stored in a \`varying\` and read in the
* fragment shader with {@link czm_readNonPerspective}.
*/
float czm_writeNonPerspective(float value, float w) {
return value * w;
}
vec2 czm_writeNonPerspective(vec2 value, float w) {
return value * w;
}
vec3 czm_writeNonPerspective(vec3 value, float w) {
return value * w;
}
vec4 czm_writeNonPerspective(vec4 value, float w) {
return value * w;
}
`,ZE={czm_degreesPerRadian:yX,czm_depthRange:bX,czm_epsilon1:TX,czm_epsilon2:AX,czm_epsilon3:xX,czm_epsilon4:CX,czm_epsilon5:EX,czm_epsilon6:wX,czm_epsilon7:SX,czm_infinity:vX,czm_oneOverPi:IX,czm_oneOverTwoPi:DX,czm_passCesium3DTile:PX,czm_passCesium3DTileClassification:OX,czm_passCesium3DTileClassificationIgnoreShow:LX,czm_passClassification:RX,czm_passCompute:NX,czm_passEnvironment:MX,czm_passGlobe:FX,czm_passOpaque:BX,czm_passOverlay:zX,czm_passTerrainClassification:UX,czm_passTranslucent:kX,czm_passVoxels:VX,czm_pi:HX,czm_piOverFour:GX,czm_piOverSix:jX,czm_piOverThree:WX,czm_piOverTwo:qX,czm_radiansPerDegree:YX,czm_sceneMode2D:$X,czm_sceneMode3D:XX,czm_sceneModeColumbusView:QX,czm_sceneModeMorphing:KX,czm_solarRadius:ZX,czm_threePiOver2:JX,czm_twoPi:eQ,czm_webMercatorMaxLatitude:tQ,czm_depthRangeStruct:nQ,czm_material:iQ,czm_materialInput:oQ,czm_modelMaterial:rQ,czm_modelVertexOutput:sQ,czm_pbrParameters:aQ,czm_ray:cQ,czm_raySegment:lQ,czm_shadowParameters:uQ,czm_HSBToRGB:dQ,czm_HSLToRGB:hQ,czm_RGBToHSB:fQ,czm_RGBToHSL:pQ,czm_RGBToXYZ:mQ,czm_XYZToRGB:_Q,czm_acesTonemapping:gQ,czm_alphaWeight:yQ,czm_antialias:bQ,czm_applyHSBShift:TQ,czm_approximateSphericalCoordinates:AQ,czm_approximateTanh:xQ,czm_backFacing:CQ,czm_branchFreeTernary:EQ,czm_cascadeColor:wQ,czm_cascadeDistance:SQ,czm_cascadeMatrix:vQ,czm_cascadeWeights:IQ,czm_clipPolygons:DQ,czm_columbusViewMorph:PQ,czm_computeAtmosphereColor:OQ,czm_computeGroundAtmosphereScattering:LQ,czm_computePosition:RQ,czm_computeScattering:NQ,czm_cosineAndSine:MQ,czm_decompressTextureCoordinates:FQ,czm_defaultPbrMaterial:BQ,czm_depthClamp:zQ,czm_eastNorthUpToEyeCoordinates:UQ,czm_ellipsoidContainsPoint:kQ,czm_ellipsoidWgs84TextureCoordinates:VQ,czm_equalsEpsilon:HQ,czm_eyeOffset:GQ,czm_eyeToWindowCoordinates:jQ,czm_fastApproximateAtan:WQ,czm_fog:qQ,czm_gammaCorrect:YQ,czm_geodeticSurfaceNormal:$Q,czm_getDefaultMaterial:XQ,czm_getDynamicAtmosphereLightDirection:QQ,czm_getLambertDiffuse:KQ,czm_getSpecular:ZQ,czm_getWaterNoise:JQ,czm_hue:eK,czm_inverseGamma:tK,czm_isEmpty:nK,czm_isFull:iK,czm_latitudeToWebMercatorFraction:oK,czm_lineDistance:rK,czm_linearToSrgb:sK,czm_luminance:aK,czm_metersPerPixel:cK,czm_modelToWindowCoordinates:lK,czm_multiplyWithColorBalance:uK,czm_nearFarScalar:dK,czm_octDecode:hK,czm_packDepth:fK,czm_pbrLighting:pK,czm_pbrMetallicRoughnessMaterial:mK,czm_pbrSpecularGlossinessMaterial:_K,czm_phong:gK,czm_planeDistance:yK,czm_pointAlongRay:bK,czm_rayEllipsoidIntersectionInterval:TK,czm_raySphereIntersectionInterval:AK,czm_readDepth:xK,czm_readNonPerspective:CK,czm_reverseLogDepth:EK,czm_round:wK,czm_sampleOctahedralProjection:SK,czm_saturation:vK,czm_shadowDepthCompare:IK,czm_shadowVisibility:DK,czm_signNotZero:PK,czm_sphericalHarmonics:OK,czm_srgbToLinear:LK,czm_tangentToEyeSpaceMatrix:RK,czm_textureCube:NK,czm_transformPlane:MK,czm_translateRelativeToEye:FK,czm_translucentPhong:BK,czm_transpose:zK,czm_unpackClippingExtents:UK,czm_unpackDepth:kK,czm_unpackFloat:VK,czm_unpackUint:HK,czm_valueTransform:GK,czm_vertexLogDepth:jK,czm_windowToEyeCoordinates:WK,czm_writeDepthClamp:qK,czm_writeLogDepth:YK,czm_writeNonPerspective:$K};function XK(e,t){let n=e;return n=n.replaceAll("version 300 es",""),n=n.replaceAll(/(texture\()/g,"texture2D("),t?(n=n.replaceAll(/\n\s*(in)\s+(vec\d|mat\d|float)/g,`
varying $2`),/out_FragData_(\d+)/.test(n)&&(n=`#extension GL_EXT_draw_buffers : enable
${n}`,n=n.replaceAll(/layout\s+\(location\s*=\s*\d+\)\s*out\s+vec4\s+out_FragData_\d+;/g,""),n=n.replaceAll(/out_FragData_(\d+)/g,"gl_FragData[$1]")),n=n.replaceAll(/layout\s+\(location\s*=\s*0\)\s*out\s+vec4\s+out_FragColor;/g,""),n=n.replaceAll(/out_FragColor/g,"gl_FragColor"),n=n.replaceAll(/out_FragColor\[(\d+)\]/g,"gl_FragColor[$1]"),/gl_FragDepth/.test(n)&&(n=`#extension GL_EXT_frag_depth : enable
${n}`,n=n.replaceAll(/gl_FragDepth/g,"gl_FragDepthEXT")),n=`#ifdef GL_OES_standard_derivatives
#extension GL_OES_standard_derivatives : enable
#endif
${n}`):(n=n.replaceAll(/(in)\s+(vec\d|mat\d|float)/g,"attribute $2"),n=n.replaceAll(/(out)\s+(vec\d|mat\d|float)\s+([\w]+);/g,"varying $2 $3;")),n=`#version 100
${n}`,n}function Tk(e){return e=e.replace(/\/\/.*/g,""),e.replace(/\/\*\*[\s\S]*?\*\//gm,function(t){const n=t.match(/\n/gm).length;let i="";for(let o=0;o<n;++o)i+=`
`;return i})}function Ak(e,t,n){let i;for(let o=0;o<n.length;++o)n[o].name===e&&(i=n[o]);return c(i)||(t=Tk(t),i={name:e,glslSource:t,dependsOn:[],requiredBy:[],evaluated:!1},n.push(i)),i}function xk(e,t){if(e.evaluated)return;e.evaluated=!0;let n=e.glslSource.match(/\bczm_[a-zA-Z0-9_]*/g);c(n)&&n!==null&&(n=n.filter(function(i,o){return n.indexOf(i)===o}),n.forEach(function(i){if(i!==e.name&&Oe._czmBuiltinsAndUniforms.hasOwnProperty(i)){const o=Ak(i,Oe._czmBuiltinsAndUniforms[i],t);e.dependsOn.push(o),o.requiredBy.push(e),xk(o,t)}}))}function QK(e){const t=[],n=[];for(;e.length>0;){const o=e.pop();n.push(o),o.requiredBy.length===0&&t.push(o)}for(;t.length>0;){const o=t.shift();e.push(o);for(let r=0;r<o.dependsOn.length;++r){const s=o.dependsOn[r],a=s.requiredBy.indexOf(o);s.requiredBy.splice(a,1),s.requiredBy.length===0&&t.push(s)}}const i=[];for(let o=0;o<n.length;++o)n[o].requiredBy.length!==0&&i.push(n[o]);if(i.length!==0){let o=`A circular dependency was found in the following built-in functions/structs/constants:
`;for(let r=0;r<i.length;++r)o=`${o+i[r].name}
`;throw new E(o)}}function KK(e){const t=[],n=Ak("main",e,t);xk(n,t),QK(t);let i="";for(let o=t.length-1;o>=0;--o)i=`${i+t[o].glslSource}
`;return i.replace(n.glslSource,"")}function Ck(e,t,n){let i,o,r="";const s=e.sources;if(c(s))for(i=0,o=s.length;i<o;++i)r+=`
#line 0
${s[i]}`;r=Tk(r);let a;r=r.replace(/#version\s+(.*?)\n/gm,function(b,T){if(c(a)&&a!==T)throw new E(`inconsistent versions found: ${a} and ${T}`);return a=T,`
`});const l=[];r=r.replace(/#extension.*\n/gm,function(b){return l.push(b),`
`}),r=r.replace(/precision\s(lowp|mediump|highp)\s(float|int);/,"");const u=e.pickColorQualifier;c(u)&&(r=Oe.createPickFragmentShaderSource(r,u));let h="";const f=l.length;for(i=0;i<f;i++)h+=l[i];t&&(h+=`#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
precision highp int;
#else
precision mediump float;
precision mediump int;
#define highp mediump
#endif
`);const _=e.defines;if(c(_))for(i=0,o=_.length;i<o;++i){const b=_[i];b.length!==0&&(h+=`#define ${b}
`)}n.textureFloatLinear&&(h+=`#define OES_texture_float_linear
`),n.floatingPointTexture&&(h+=`#define OES_texture_float
`);let g="";e.includeBuiltIns&&(g=KK(r)),h+=`
#line 0
`;const m=g+r;return n.webgl2&&t&&!/layout\s*\(location\s*=\s*0\)\s*out\s+vec4\s+out_FragColor;/g.test(m)&&!/czm_out_FragColor/g.test(m)&&/out_FragColor/g.test(m)&&(h+=`layout(location = 0) out vec4 out_FragColor;
`),h+=g,h+=r,n.webgl2?h=`#version 300 es
${h}`:h=XK(h,t),h}function Oe(e){e=y(e,y.EMPTY_OBJECT);const t=e.pickColorQualifier;if(c(t)&&t!=="uniform"&&t!=="in")throw new E("options.pickColorQualifier must be 'uniform' or 'in'.");this.defines=c(e.defines)?e.defines.slice(0):[],this.sources=c(e.sources)?e.sources.slice(0):[],this.pickColorQualifier=t,this.includeBuiltIns=y(e.includeBuiltIns,!0)}Oe.prototype.clone=function(){return new Oe({sources:this.sources,defines:this.defines,pickColorQualifier:this.pickColorQualifier,includeBuiltIns:this.includeBuiltIns})};Oe.replaceMain=function(e,t){return t=`void ${t}()`,e.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g,t)};Oe.prototype.getCacheKey=function(){const t=this.defines.slice().sort().join(","),n=this.pickColorQualifier,i=this.includeBuiltIns,o=this.sources.join(`
`);return`${t}:${n}:${i}:${o}`};Oe.prototype.createCombinedVertexShader=function(e){return Ck(this,!1,e)};Oe.prototype.createCombinedFragmentShader=function(e){return Ck(this,!0,e)};Oe._czmBuiltinsAndUniforms={};for(const e in ZE)ZE.hasOwnProperty(e)&&(Oe._czmBuiltinsAndUniforms[e]=ZE[e]);for(const e in DA)if(DA.hasOwnProperty(e)){const t=DA[e];typeof t.getDeclaration=="function"&&(Oe._czmBuiltinsAndUniforms[e]=t.getDeclaration(e))}Oe.createPickVertexShaderSource=function(e){return`${Oe.replaceMain(e,"czm_old_main")}
in vec4 pickColor;
out vec4 czm_pickColor;
void main()
{
czm_old_main();
czm_pickColor = pickColor;
}`};Oe.createPickFragmentShaderSource=function(e,t){const n=Oe.replaceMain(e,"czm_old_main"),i=`${t} vec4 czm_pickColor;
void main()
{
czm_old_main();
if (out_FragColor.a == 0.0) {
discard;
}
out_FragColor = czm_pickColor;
}`;return`${n}
${i}`};function ZK(e,t){const n=e.defines,i=n.length;for(let o=0;o<i;++o)if(n[o]===t)return!0;return!1}function Ek(e,t){const n=e.sources,i=n.length;for(let o=0;o<i;++o)if(n[o].indexOf(t)!==-1)return!0;return!1}function wk(e,t){const n=t.length;for(let i=0;i<n;++i){const o=t[i];if(Ek(e,o))return o}}const JK=["v_normalEC","v_normal"];Oe.findNormalVarying=function(e){return Ek(e,"#ifdef HAS_NORMALS")?ZK(e,"HAS_NORMALS")?"v_normalEC":void 0:wk(e,JK)};const eZ=["v_positionEC"];Oe.findPositionVarying=function(e){return wk(e,eZ)};function vl(e){this._context=e,this._shaders={},this._numberOfShaders=0,this._shadersToRelease={}}Object.defineProperties(vl.prototype,{numberOfShaders:{get:function(){return this._numberOfShaders}}});vl.prototype.replaceShaderProgram=function(e){return c(e.shaderProgram)&&e.shaderProgram.destroy(),this.getShaderProgram(e)};function tZ(e){const t=Object.keys(e).sort();return JSON.stringify(e,t)}vl.prototype.getShaderProgram=function(e){let t=e.vertexShaderSource,n=e.fragmentShaderSource;const i=e.attributeLocations;typeof t=="string"&&(t=new Oe({sources:[t]})),typeof n=="string"&&(n=new Oe({sources:[n]}));const o=t.getCacheKey(),r=n.getCacheKey(),s=c(i)?tZ(i):"",a=`${o}:${r}:${s}`;let l;if(c(this._shaders[a]))l=this._shaders[a],delete this._shadersToRelease[a];else{const u=this._context,h=t.createCombinedVertexShader(u),f=n.createCombinedFragmentShader(u),_=new Jt({gl:u._gl,logShaderCompilation:u.logShaderCompilation,debugShaders:u.debugShaders,vertexShaderSource:t,vertexShaderText:h,fragmentShaderSource:n,fragmentShaderText:f,attributeLocations:i});l={cache:this,shaderProgram:_,keyword:a,derivedKeywords:[],count:0},_._cachedShader=l,this._shaders[a]=l,++this._numberOfShaders}return++l.count,l.shaderProgram};vl.prototype.replaceDerivedShaderProgram=function(e,t,n){const i=e._cachedShader,o=t+i.keyword,r=this._shaders[o];if(c(r)){PP(this,r);const s=i.derivedKeywords.indexOf(t);s>-1&&i.derivedKeywords.splice(s,1)}return this.createDerivedShaderProgram(e,t,n)};vl.prototype.getDerivedShaderProgram=function(e,t){const n=e._cachedShader,i=t+n.keyword,o=this._shaders[i];if(!!c(o))return o.shaderProgram};vl.prototype.createDerivedShaderProgram=function(e,t,n){const i=e._cachedShader,o=t+i.keyword;let r=n.vertexShaderSource,s=n.fragmentShaderSource;const a=n.attributeLocations;typeof r=="string"&&(r=new Oe({sources:[r]})),typeof s=="string"&&(s=new Oe({sources:[s]}));const l=this._context,u=r.createCombinedVertexShader(l),h=s.createCombinedFragmentShader(l),f=new Jt({gl:l._gl,logShaderCompilation:l.logShaderCompilation,debugShaders:l.debugShaders,vertexShaderSource:r,vertexShaderText:u,fragmentShaderSource:s,fragmentShaderText:h,attributeLocations:a}),_={cache:this,shaderProgram:f,keyword:o,derivedKeywords:[],count:0};return i.derivedKeywords.push(t),f._cachedShader=_,this._shaders[o]=_,f};function PP(e,t){const n=t.derivedKeywords,i=n.length;for(let o=0;o<i;++o){const r=n[o]+t.keyword,s=e._shaders[r];PP(e,s)}delete e._shaders[t.keyword],t.shaderProgram.finalDestroy()}vl.prototype.destroyReleasedShaderPrograms=function(){const e=this._shadersToRelease;for(const t in e)if(e.hasOwnProperty(t)){const n=e[t];PP(this,n),--this._numberOfShaders}this._shadersToRelease={}};vl.prototype.releaseShaderProgram=function(e){if(c(e)){const t=e._cachedShader;t&&--t.count===0&&(this._shadersToRelease[t.keyword]=t)}};vl.prototype.isDestroyed=function(){return!1};vl.prototype.destroy=function(){const e=this._shaders;for(const t in e)e.hasOwnProperty(t)&&e[t].shaderProgram.finalDestroy();return ve(this)};function xt(e){e=y(e,y.EMPTY_OBJECT),A.defined("options.context",e.context);const t=e.context;let n=e.width,i=e.height;const o=e.source;c(o)&&(c(n)||(n=y(o.videoWidth,o.width)),c(i)||(i=y(o.videoHeight,o.height)));const r=y(e.pixelFormat,Ve.RGBA),s=y(e.pixelDatatype,Me.UNSIGNED_BYTE),a=Ve.toInternalFormat(r,s,t),l=Ve.isCompressedFormat(a);if(!c(n)||!c(i))throw new E("options requires a source field to create an initialized texture or width and height fields to create a blank texture.");if(A.typeOf.number.greaterThan("width",n,0)
`),r=new Oe({defines:this._vertexShaderParts.defineLines,sources:[o]}),s=this._fragmentShaderParts.uniformLines.concat(this._fragmentShaderParts.varyingLines,n.fragmentLines,i.fragmentLines,this._fragmentShaderParts.shaderLines).join(`
`),a=new Oe({defines:this._fragmentShaderParts.defineLines,sources:[s]});return Jt.fromCache({context:e,vertexShaderSource:r,fragmentShaderSource:a,attributeLocations:this._attributeLocations})};Es.prototype.clone=function(){return Je(this,!0)};function tee(e){const t=[],n=[];let i,o=e._vertexShaderParts.structIds,r,s,a;for(i=0;i<o.length;i++)r=o[i],s=e._structs[r],a=s.generateGlslLines(),t.push.apply(t,a);for(o=e._fragmentShaderParts.structIds,i=0;i<o.length;i++)r=o[i],s=e._structs[r],a=s.generateGlslLines(),n.push.apply(n,a);return{vertexLines:t,fragmentLines:n}}function nee(e){switch(e){case"mat2":return 2;case"mat3":return 3;case"mat4":return 4;default:return 1}}function iee(e){const t=[],n=[];let i,o=e._vertexShaderParts.functionIds,r,s,a;for(i=0;i<o.length;i++)r=o[i],s=e._functions[r],a=s.generateGlslLines(),t.push.apply(t,a);for(o=e._fragmentShaderParts.functionIds,i=0;i<o.length;i++)r=o[i],s=e._functions[r],a=s.generateGlslLines(),n.push.apply(n,a);return{vertexLines:t,fragmentLines:n}}function qo(e,t,n,i){if(A.defined("context",e),!t||t.length===0)throw new E("At least one attribute is required.");const o=qo._verifyAttributes(t);n=y(n,0);const r=[],s={};let a,l;const u=o.length;for(let f=0;f<u;++f){const _=o[f];if(_.vertexBuffer){r.push(_);continue}l=_.usage,a=s[l],c(a)||(a=s[l]=[]),a.push(_)}function h(f,_){return Z.getSizeInBytes(_.componentDatatype)-Z.getSizeInBytes(f.componentDatatype)}this._allBuffers=[];for(l in s)if(s.hasOwnProperty(l)){a=s[l],a.sort(h);const f=qo._vertexSizeInBytes(a),_=a[0].usage,g={vertexSizeInBytes:f,vertexBuffer:void 0,usage:_,needsCommit:!1,arrayBuffer:void 0,arrayViews:qo._createArrayViews(a,f)};this._allBuffers.push(g)}this._size=0,this._instanced=y(i,!1),this._precreated=r,this._context=e,this.writers=void 0,this.va=void 0,this.resize(n)}qo._verifyAttributes=function(e){const t=[];for(let i=0;i<e.length;++i){const o=e[i],r={index:y(o.index,i),enabled:y(o.enabled,!0),componentsPerAttribute:o.componentsPerAttribute,componentDatatype:y(o.componentDatatype,Z.FLOAT),normalize:y(o.normalize,!1),vertexBuffer:o.vertexBuffer,usage:y(o.usage,ke.STATIC_DRAW)};if(t.push(r),r.componentsPerAttribute!==1&&r.componentsPerAttribute!==2&&r.componentsPerAttribute!==3&&r.componentsPerAttribute!==4)throw new E("attribute.componentsPerAttribute must be in the range [1, 4].");const s=r.componentDatatype;if(!Z.validate(s))throw new E("Attribute must have a valid componentDatatype or not specify it.");if(!ke.validate(r.usage))throw new E("Attribute must have a valid usage or not specify it.")}const n=new Array(t.length);for(let i=0;i<t.length;++i){const r=t[i].index;if(n[r])throw new E(`Index ${r} is used by more than one attribute.`);n[r]=!0}return t};qo._vertexSizeInBytes=function(e){let t=0;const n=e.length;for(let s=0;s<n;++s){const a=e[s];t+=a.componentsPerAttribute*Z.getSizeInBytes(a.componentDatatype)}const i=n>0?Z.getSizeInBytes(e[0].componentDatatype):0,o=i>0?t%i:0,r=o===0?0:i-o;return t+=r,t};qo._createArrayViews=function(e,t){const n=[];let i=0;const o=e.length;for(let r=0;r<o;++r){const s=e[r],a=s.componentDatatype;n.push({index:s.index,enabled:s.enabled,componentsPerAttribute:s.componentsPerAttribute,componentDatatype:a,normalize:s.normalize,offsetInBytes:i,vertexSizeInComponentType:t/Z.getSizeInBytes(a),view:void 0}),i+=s.componentsPerAttribute*Z.getSizeInBytes(a)}return n};qo.prototype.resize=function(e){this._size=e;const t=this._allBuffers;this.writers=[];for(let n=0,i=t.length;n<i;++n){const o=t[n];qo._resize(o,this._size),qo._appendWriters(this.writers,o)}BP(this)};qo._resize=function(e,t){if(e.vertexSizeInBytes>0){const n=new ArrayBuffer(t*e.vertexSizeInBytes);if(c(e.arrayBuffer)){const r=new Uint8Array(n),s=new Uint8Array(e.arrayBuffer),a=s.length;for(let l=0;l<a;++l)r[l]=s[l]}const i=e.arrayViews,o=i.length;for(let r=0;r<o;++r){const s=i[r];s.view=Z.createArrayBufferView(s.componentDatatype,n,s.offsetInBytes)}e.arrayBuffer=n}};const oee=[function(e,t,n){return function(i,o){t[i*n]=o,e.needsCommit=!0}},function(e,t,n){return function(i,o,r){const s=i*n;t[s]=o,t[s+1]=r,e.needsCommit=
in vec3 v_normalEC;
in vec3 v_tangentEC;
in vec3 v_bitangentEC;
in vec2 v_st;
void main()
{
vec3 positionToEyeEC = -v_positionEC;
mat3 tangentToEyeMatrix = czm_tangentToEyeSpaceMatrix(v_normalEC, v_tangentEC, v_bitangentEC);
vec3 normalEC = normalize(v_normalEC);
#ifdef FACE_FORWARD
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);
#endif
czm_materialInput materialInput;
materialInput.normalEC = normalEC;
materialInput.tangentToEyeMatrix = tangentToEyeMatrix;
materialInput.positionToEyeEC = positionToEyeEC;
materialInput.st = v_st;
czm_material material = czm_getMaterial(materialInput);
#ifdef FLAT
out_FragColor = vec4(material.diffuse + material.emission, material.alpha);
#else
out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);
#endif
}
`,ste=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec3 normal;
in vec3 tangent;
in vec3 bitangent;
in vec2 st;
in float batchId;
out vec3 v_positionEC;
out vec3 v_normalEC;
out vec3 v_tangentEC;
out vec3 v_bitangentEC;
out vec2 v_st;
void main()
{
vec4 p = czm_computePosition();
v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates
v_normalEC = czm_normal * normal; // normal in eye coordinates
v_tangentEC = czm_normal * tangent; // tangent in eye coordinates
v_bitangentEC = czm_normal * bitangent; // bitangent in eye coordinates
v_st = st;
gl_Position = czm_modelViewProjectionRelativeToEye * p;
}
`,ate=`in vec3 v_positionEC;
in vec3 v_normalEC;
void main()
{
vec3 positionToEyeEC = -v_positionEC;
vec3 normalEC = normalize(v_normalEC);
#ifdef FACE_FORWARD
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);
#endif
czm_materialInput materialInput;
materialInput.normalEC = normalEC;
materialInput.positionToEyeEC = positionToEyeEC;
czm_material material = czm_getMaterial(materialInput);
#ifdef FLAT
out_FragColor = vec4(material.diffuse + material.emission, material.alpha);
#else
out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);
#endif
}
`,cte=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec3 normal;
in float batchId;
out vec3 v_positionEC;
out vec3 v_normalEC;
void main()
{
vec4 p = czm_computePosition();
v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates
v_normalEC = czm_normal * normal; // normal in eye coordinates
gl_Position = czm_modelViewProjectionRelativeToEye * p;
}
`,lte=`in vec3 v_positionEC;
in vec3 v_normalEC;
in vec2 v_st;
void main()
{
vec3 positionToEyeEC = -v_positionEC;
vec3 normalEC = normalize(v_normalEC);
#ifdef FACE_FORWARD
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);
#endif
czm_materialInput materialInput;
materialInput.normalEC = normalEC;
materialInput.positionToEyeEC = positionToEyeEC;
materialInput.st = v_st;
czm_material material = czm_getMaterial(materialInput);
#ifdef FLAT
out_FragColor = vec4(material.diffuse + material.emission, material.alpha);
#else
out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);
#endif
}
`,ute=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec3 normal;
in vec2 st;
in float batchId;
out vec3 v_positionEC;
out vec3 v_normalEC;
out vec2 v_st;
void main()
{
vec4 p = czm_computePosition();
v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates
v_normalEC = czm_normal * normal; // normal in eye coordinates
v_st = st;
gl_Position = czm_modelViewProjectionRelativeToEye * p;
}
`,dte={ADD:J.FUNC_ADD,SUBTRACT:J.FUNC_SUBTRACT,REVERSE_SUBTRACT:J.FUNC_REVERSE_SUBTRACT,MIN:J.MIN,MAX:J.MAX},cc=Object.freeze(dte),hte={ZERO:J.ZERO,ONE:J.ONE,SOURCE_COLOR:J.SRC_COLOR,ONE_MINUS_SOURCE_COLOR:J.ONE_MINUS_SRC_COLOR,DESTINATION_COLOR:J.DST_COLOR,ONE_MINUS_DESTINATION_COLOR:J.ONE_MINUS_DST_COLOR,SOURCE_ALPHA:J.SRC_ALPHA,ONE_MINUS_SOURCE_ALPHA:J.ONE_MINUS_SRC_ALPHA,DESTINATION_ALPHA:J.DST_ALPHA,ONE_MINUS_DESTINATION_ALPHA:J.ONE_MINUS_DST_ALPHA,CONSTANT_COLOR:J.CONSTANT_COLOR,ONE_MINUS_CONSTANT_COLOR:J.ONE_MINUS_CONSTANT_COLOR,CONSTANT_ALPHA:J.CONSTANT_ALPHA,ONE_MINUS_CONSTANT_ALPHA:J.ONE_MINUS_CONSTANT_ALPHA,SOURCE_ALPHA_SATURATE:J.SRC_ALPHA_SATURATE},Yi=Object.freeze(hte),fte={DISABLED:Object.freeze({enabled:!1}),ALPHA_BLEND:Object.freeze({enabled:!0,equationRgb:cc.ADD,equationAlpha:cc.ADD,functionSourceRgb:Yi.SOURCE_ALPHA,functionSourceAlpha:Yi.ONE,functionDestinationRgb:Yi.ONE_MINUS_SOURCE_ALPHA,functionDestinationAlpha:Yi.ONE_MINUS_SOURCE_ALPHA}),PRE_MULTIPLIED_ALPHA_BLEND:Object.freeze({enabled:!0,equationRgb:cc.ADD,equationAlpha:cc.ADD,functionSourceRgb:Yi.ONE,functionSourceAlpha:Yi.ONE,functionDestinationRgb:Yi.ONE_MINUS_SOURCE_ALPHA,functionDestinationAlpha:Yi.ONE_MINUS_SOURCE_ALPHA}),ADDITIVE_BLEND:Object.freeze({enabled:!0,equationRgb:cc.ADD,equationAlpha:cc.ADD,functionSourceRgb:Yi.SOURCE_ALPHA,functionSourceAlpha:Yi.ONE,functionDestinationRgb:Yi.ONE,functionDestinationAlpha:Yi.ONE})},Zn=Object.freeze(fte),pte={FRONT:J.FRONT,BACK:J.BACK,FRONT_AND_BACK:J.FRONT_AND_BACK},Qi=Object.freeze(pte);function Lo(e){e=y(e,y.EMPTY_OBJECT),this.material=e.material,this.translucent=y(e.translucent,!0),this._vertexShaderSource=e.vertexShaderSource,this._fragmentShaderSource=e.fragmentShaderSource,this._renderState=e.renderState,this._closed=y(e.closed,!1)}Object.defineProperties(Lo.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}}});Lo.prototype.getFragmentShaderSource=function(){const e=[];return this.flat&&e.push("#define FLAT"),this.faceForward&&e.push("#define FACE_FORWARD"),c(this.material)&&e.push(this.material.shaderSource),e.push(this.fragmentShaderSource),e.join(`
`)};Lo.prototype.isTranslucent=function(){return c(this.material)&&this.material.isTranslucent()||!c(this.material)&&this.translucent};Lo.prototype.getRenderState=function(){const e=this.isTranslucent(),t=Je(this.renderState,!1);return e?(t.depthMask=!1,t.blending=Zn.ALPHA_BLEND):t.depthMask=!0,t};Lo.getDefaultRenderState=function(e,t,n){let i={depthTest:{enabled:!0}};return e&&(i.depthMask=!1,i.blending=Zn.ALPHA_BLEND),t&&(i.cull={enabled:!0,face:Qi.BACK}),c(n)&&(i=jt(n,i,!0)),i};const mte=`uniform sampler2D image;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec4 rampColor = texture(image, vec2(materialInput.aspect / (2.0 * czm_pi), 0.5));
rampColor = czm_gammaCorrect(rampColor);
material.diffuse = rampColor.rgb;
material.alpha = rampColor.a;
return material;
}
`,_te=`uniform sampler2D image;
uniform float strength;
uniform vec2 repeat;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
vec2 centerPixel = fract(repeat * st);
float centerBump = texture(image, centerPixel).channel;
float imageWidth = float(imageDimensions.x);
vec2 rightPixel = fract(repeat * (st + vec2(1.0 / imageWidth, 0.0)));
float rightBump = texture(image, rightPixel).channel;
float imageHeight = float(imageDimensions.y);
vec2 leftPixel = fract(repeat * (st + vec2(0.0, 1.0 / imageHeight)));
float topBump = texture(image, leftPixel).channel;
vec3 normalTangentSpace = normalize(vec3(centerBump - rightBump, centerBump - topBump, clamp(1.0 - strength, 0.1, 1.0)));
vec3 normalEC = materialInput.tangentToEyeMatrix * normalTangentSpace;
material.normal = normalEC;
material.diffuse = vec3(0.01);
return material;
}
`,gte=`uniform vec4 lightColor;
uniform vec4 darkColor;
uniform vec2 repeat;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
// From Stefan Gustavson's Procedural Textures in GLSL in OpenGL Insights
float b = mod(floor(repeat.s * st.s) + floor(repeat.t * st.t), 2.0); // 0.0 or 1.0
// Find the distance from the closest separator (region between two colors)
float scaledWidth = fract(repeat.s * st.s);
scaledWidth = abs(scaledWidth - floor(scaledWidth + 0.5));
float scaledHeight = fract(repeat.t * st.t);
scaledHeight = abs(scaledHeight - floor(scaledHeight + 0.5));
float value = min(scaledWidth, scaledHeight);
vec4 currentColor = mix(lightColor, darkColor, b);
vec4 color = czm_antialias(lightColor, darkColor, currentColor, value, 0.03);
color = czm_gammaCorrect(color);
material.diffuse = color.rgb;
material.alpha = color.a;
return material;
}
`,yte=`uniform vec4 lightColor;
uniform vec4 darkColor;
uniform vec2 repeat;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
// From Stefan Gustavson's Procedural Textures in GLSL in OpenGL Insights
float b = smoothstep(0.3, 0.32, length(fract(repeat * materialInput.st) - 0.5)); // 0.0 or 1.0
vec4 color = mix(lightColor, darkColor, b);
color = czm_gammaCorrect(color);
material.diffuse = color.rgb;
material.alpha = color.a;
return material;
}
`,bte=`uniform sampler2D heights;
uniform sampler2D colors;
// This material expects heights to be sorted from lowest to highest.
float getHeight(int idx, float invTexSize)
{
vec2 uv = vec2((float(idx) + 0.5) * invTexSize, 0.5);
#ifdef OES_texture_float
return texture(heights, uv).x;
#else
return czm_unpackFloat(texture(heights, uv));
#endif
}
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
float height = materialInput.height;
float invTexSize = 1.0 / float(heightsDimensions.x);
float minHeight = getHeight(0, invTexSize);
float maxHeight = getHeight(heightsDimensions.x - 1, invTexSize);
// early-out when outside the height range
if (height < minHeight || height > maxHeight) {
material.diffuse = vec3(0.0);
material.alpha = 0.0;
return material;
}
// Binary search to find heights above and below.
int idxBelow = 0;
int idxAbove = heightsDimensions.x;
float heightBelow = minHeight;
float heightAbove = maxHeight;
// while loop not allowed, so use for loop with max iterations.
// maxIterations of 16 supports a texture size up to 65536 (2^16).
const int maxIterations = 16;
for (int i = 0; i < maxIterations; i++) {
if (idxBelow >= idxAbove - 1) {
break;
}
int idxMid = (idxBelow + idxAbove) / 2;
float heightTex = getHeight(idxMid, invTexSize);
if (height > heightTex) {
idxBelow = idxMid;
heightBelow = heightTex;
} else {
idxAbove = idxMid;
heightAbove = heightTex;
}
}
float lerper = heightBelow == heightAbove ? 1.0 : (height - heightBelow) / (heightAbove - heightBelow);
vec2 colorUv = vec2(invTexSize * (float(idxBelow) + 0.5 + lerper), 0.5);
vec4 color = texture(colors, colorUv);
// undo preumultiplied alpha
if (color.a > 0.0)
{
color.rgb /= color.a;
}
color.rgb = czm_gammaCorrect(color.rgb);
material.diffuse = color.rgb;
material.alpha = color.a;
return material;
}
`,Tte=`uniform vec4 color;
uniform float spacing;
uniform float width;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
float distanceToContour = mod(materialInput.height, spacing);
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
float dxc = abs(dFdx(materialInput.height));
float dyc = abs(dFdy(materialInput.height));
float dF = max(dxc, dyc) * czm_pixelRatio * width;
float alpha = (distanceToContour < dF) ? 1.0 : 0.0;
#else
// If no derivatives available (IE 10?), use pixel ratio
float alpha = (distanceToContour < (czm_pixelRatio * width)) ? 1.0 : 0.0;
#endif
vec4 outColor = czm_gammaCorrect(vec4(color.rgb, alpha * color.a));
material.diffuse = outColor.rgb;
material.alpha = outColor.a;
return material;
}
`,Ate=`uniform sampler2D image;
uniform float minimumHeight;
uniform float maximumHeight;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
float scaledHeight = clamp((materialInput.height - minimumHeight) / (maximumHeight - minimumHeight), 0.0, 1.0);
vec4 rampColor = texture(image, vec2(scaledHeight, 0.5));
rampColor = czm_gammaCorrect(rampColor);
material.diffuse = rampColor.rgb;
material.alpha = rampColor.a;
return material;
}
`,xte=`uniform vec4 fadeInColor;
uniform vec4 fadeOutColor;
uniform float maximumDistance;
uniform bool repeat;
uniform vec2 fadeDirection;
uniform vec2 time;
float getTime(float t, float coord)
{
float scalar = 1.0 / maximumDistance;
float q = distance(t, coord) * scalar;
if (repeat)
{
float r = distance(t, coord + 1.0) * scalar;
float s = distance(t, coord - 1.0) * scalar;
q = min(min(r, s), q);
}
return clamp(q, 0.0, 1.0);
}
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
float s = getTime(time.x, st.s) * fadeDirection.s;
float t = getTime(time.y, st.t) * fadeDirection.t;
float u = length(vec2(s, t));
vec4 color = mix(fadeInColor, fadeOutColor, u);
color = czm_gammaCorrect(color);
material.emission = color.rgb;
material.alpha = color.a;
return material;
}
`,Cte=`uniform vec4 color;
uniform float cellAlpha;
uniform vec2 lineCount;
uniform vec2 lineThickness;
uniform vec2 lineOffset;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
float scaledWidth = fract(lineCount.s * st.s - lineOffset.s);
scaledWidth = abs(scaledWidth - floor(scaledWidth + 0.5));
float scaledHeight = fract(lineCount.t * st.t - lineOffset.t);
scaledHeight = abs(scaledHeight - floor(scaledHeight + 0.5));
float value;
// Fuzz Factor - Controls blurriness of lines
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
const float fuzz = 1.2;
vec2 thickness = (lineThickness * czm_pixelRatio) - 1.0;
// From "3D Engine Design for Virtual Globes" by Cozzi and Ring, Listing 4.13.
vec2 dx = abs(dFdx(st));
vec2 dy = abs(dFdy(st));
vec2 dF = vec2(max(dx.s, dy.s), max(dx.t, dy.t)) * lineCount;
value = min(
smoothstep(dF.s * thickness.s, dF.s * (fuzz + thickness.s), scaledWidth),
smoothstep(dF.t * thickness.t, dF.t * (fuzz + thickness.t), scaledHeight));
#else
// If no derivatives available (IE 10?), revert to view-dependent fuzz
const float fuzz = 0.05;
vec2 range = 0.5 - (lineThickness * 0.05);
value = min(
1.0 - smoothstep(range.s, range.s + fuzz, scaledWidth),
1.0 - smoothstep(range.t, range.t + fuzz, scaledHeight));
#endif
// Edges taken from RimLightingMaterial.glsl
// See http://www.fundza.com/rman_shaders/surface/fake_rim/fake_rim1.html
float dRim = 1.0 - abs(dot(materialInput.normalEC, normalize(materialInput.positionToEyeEC)));
float sRim = smoothstep(0.8, 1.0, dRim);
value *= (1.0 - sRim);
vec4 halfColor;
halfColor.rgb = color.rgb * 0.5;
halfColor.a = color.a * (1.0 - ((1.0 - cellAlpha) * value));
halfColor = czm_gammaCorrect(halfColor);
material.diffuse = halfColor.rgb;
material.emission = halfColor.rgb;
material.alpha = halfColor.a;
return material;
}
`,Ete=`uniform sampler2D image;
uniform float strength;
uniform vec2 repeat;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec4 textureValue = texture(image, fract(repeat * materialInput.st));
vec3 normalTangentSpace = textureValue.channels;
normalTangentSpace.xy = normalTangentSpace.xy * 2.0 - 1.0;
normalTangentSpace.z = clamp(1.0 - strength, 0.1, 1.0);
normalTangentSpace = normalize(normalTangentSpace);
vec3 normalEC = materialInput.tangentToEyeMatrix * normalTangentSpace;
material.normal = normalEC;
return material;
}
`,wte=`uniform vec4 color;
float getPointOnLine(vec2 p0, vec2 p1, float x)
{
float slope = (p0.y - p1.y) / (p0.x - p1.x);
return slope * (x - p0.x) + p0.y;
}
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
#if (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
float base = 1.0 - abs(fwidth(st.s)) * 10.0 * czm_pixelRatio;
#else
// If no derivatives available (IE 10?), 2.5% of the line will be the arrow head
float base = 0.975;
#endif
vec2 center = vec2(1.0, 0.5);
float ptOnUpperLine = getPointOnLine(vec2(base, 1.0), center, st.s);
float ptOnLowerLine = getPointOnLine(vec2(base, 0.0), center, st.s);
float halfWidth = 0.15;
float s = step(0.5 - halfWidth, st.t);
s *= 1.0 - step(0.5 + halfWidth, st.t);
s *= 1.0 - step(base, st.s);
float t = step(base, materialInput.st.s);
t *= 1.0 - step(ptOnUpperLine, st.t);
t *= step(ptOnLowerLine, st.t);
// Find the distance from the closest separator (region between two colors)
float dist;
if (st.s < base)
{
float d1 = abs(st.t - (0.5 - halfWidth));
float d2 = abs(st.t - (0.5 + halfWidth));
dist = min(d1, d2);
}
else
{
float d1 = czm_infinity;
if (st.t < 0.5 - halfWidth && st.t > 0.5 + halfWidth)
{
d1 = abs(st.s - base);
}
float d2 = abs(st.t - ptOnUpperLine);
float d3 = abs(st.t - ptOnLowerLine);
dist = min(min(d1, d2), d3);
}
vec4 outsideColor = vec4(0.0);
vec4 currentColor = mix(outsideColor, color, clamp(s + t, 0.0, 1.0));
vec4 outColor = czm_antialias(outsideColor, color, currentColor, dist);
outColor = czm_gammaCorrect(outColor);
material.diffuse = outColor.rgb;
material.alpha = outColor.a;
return material;
}
`,Ste=`uniform vec4 color;
uniform vec4 gapColor;
uniform float dashLength;
uniform float dashPattern;
in float v_polylineAngle;
const float maskLength = 16.0;
mat2 rotate(float rad) {
float c = cos(rad);
float s = sin(rad);
return mat2(
c, s,
-s, c
);
}
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 pos = rotate(v_polylineAngle) * gl_FragCoord.xy;
// Get the relative position within the dash from 0 to 1
float dashPosition = fract(pos.x / (dashLength * czm_pixelRatio));
// Figure out the mask index.
float maskIndex = floor(dashPosition * maskLength);
// Test the bit mask.
float maskTest = floor(dashPattern / pow(2.0, maskIndex));
vec4 fragColor = (mod(maskTest, 2.0) < 1.0) ? gapColor : color;
if (fragColor.a < 0.005) { // matches 0/255 and 1/255
discard;
}
fragColor = czm_gammaCorrect(fragColor);
material.emission = fragColor.rgb;
material.alpha = fragColor.a;
return material;
}
`,vte=`uniform vec4 color;
uniform float glowPower;
uniform float taperPower;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
float glow = glowPower / abs(st.t - 0.5) - (glowPower / 0.5);
if (taperPower <= 0.99999) {
glow *= min(1.0, taperPower / (0.5 - st.s * 0.5) - (taperPower / 0.5));
}
vec4 fragColor;
fragColor.rgb = max(vec3(glow - 1.0 + color.rgb), color.rgb);
fragColor.a = clamp(0.0, 1.0, glow) * color.a;
fragColor = czm_gammaCorrect(fragColor);
material.emission = fragColor.rgb;
material.alpha = fragColor.a;
return material;
}
`,Ite=`uniform vec4 color;
uniform vec4 outlineColor;
uniform float outlineWidth;
in float v_width;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
float halfInteriorWidth = 0.5 * (v_width - outlineWidth) / v_width;
float b = step(0.5 - halfInteriorWidth, st.t);
b *= 1.0 - step(0.5 + halfInteriorWidth, st.t);
// Find the distance from the closest separator (region between two colors)
float d1 = abs(st.t - (0.5 - halfInteriorWidth));
float d2 = abs(st.t - (0.5 + halfInteriorWidth));
float dist = min(d1, d2);
vec4 currentColor = mix(outlineColor, color, b);
vec4 outColor = czm_antialias(outlineColor, color, currentColor, dist);
outColor = czm_gammaCorrect(outColor);
material.diffuse = outColor.rgb;
material.alpha = outColor.a;
return material;
}
`,Dte=`uniform vec4 color;
uniform vec4 rimColor;
uniform float width;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
// See http://www.fundza.com/rman_shaders/surface/fake_rim/fake_rim1.html
float d = 1.0 - dot(materialInput.normalEC, normalize(materialInput.positionToEyeEC));
float s = smoothstep(1.0 - width, 1.0, d);
vec4 outColor = czm_gammaCorrect(color);
vec4 outRimColor = czm_gammaCorrect(rimColor);
material.diffuse = outColor.rgb;
material.emission = outRimColor.rgb * s;
material.alpha = mix(outColor.a, outRimColor.a, s);
return material;
}
`,Pte=`uniform sampler2D image;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
vec4 rampColor = texture(image, vec2(materialInput.slope / (czm_pi / 2.0), 0.5));
rampColor = czm_gammaCorrect(rampColor);
material.diffuse = rampColor.rgb;
material.alpha = rampColor.a;
return material;
}
`,Ote=`uniform vec4 evenColor;
uniform vec4 oddColor;
uniform float offset;
uniform float repeat;
uniform bool horizontal;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
// Based on the Stripes Fragment Shader in the Orange Book (11.1.2)
float coord = mix(materialInput.st.s, materialInput.st.t, float(horizontal));
float value = fract((coord - offset) * (repeat * 0.5));
float dist = min(value, min(abs(value - 0.5), 1.0 - value));
vec4 currentColor = mix(evenColor, oddColor, step(0.5, value));
vec4 color = czm_antialias(evenColor, oddColor, currentColor, dist);
color = czm_gammaCorrect(color);
material.diffuse = color.rgb;
material.alpha = color.a;
return material;
}
`,Lte=`// Thanks for the contribution Jonas
// http://29a.ch/2012/7/19/webgl-terrain-rendering-water-fog
uniform sampler2D specularMap;
uniform sampler2D normalMap;
uniform vec4 baseWaterColor;
uniform vec4 blendColor;
uniform float frequency;
uniform float animationSpeed;
uniform float amplitude;
uniform float specularIntensity;
uniform float fadeFactor;
czm_material czm_getMaterial(czm_materialInput materialInput)
{
czm_material material = czm_getDefaultMaterial(materialInput);
float time = czm_frameNumber * animationSpeed;
// fade is a function of the distance from the fragment and the frequency of the waves
float fade = max(1.0, (length(materialInput.positionToEyeEC) / 10000000000.0) * frequency * fadeFactor);
float specularMapValue = texture(specularMap, materialInput.st).r;
// note: not using directional motion at this time, just set the angle to 0.0;
vec4 noise = czm_getWaterNoise(normalMap, materialInput.st * frequency, time, 0.0);
vec3 normalTangentSpace = noise.xyz * vec3(1.0, 1.0, (1.0 / amplitude));
// fade out the normal perturbation as we move further from the water surface
normalTangentSpace.xy /= fade;
// attempt to fade out the normal perturbation as we approach non water areas (low specular map value)
normalTangentSpace = mix(vec3(0.0, 0.0, 50.0), normalTangentSpace, specularMapValue);
normalTangentSpace = normalize(normalTangentSpace);
// get ratios for alignment of the new normal vector with a vector perpendicular to the tangent plane
float tsPerturbationRatio = clamp(dot(normalTangentSpace, vec3(0.0, 0.0, 1.0)), 0.0, 1.0);
// fade out water effect as specular map value decreases
material.alpha = mix(blendColor.a, baseWaterColor.a, specularMapValue) * specularMapValue;
// base color is a blend of the water and non-water color based on the value from the specular map
// may need a uniform blend factor to better control this
material.diffuse = mix(blendColor.rgb, baseWaterColor.rgb, specularMapValue);
// diffuse highlights are based on how perturbed the normal is
material.diffuse += (0.1 * tsPerturbationRatio);
material.diffuse = material.diffuse;
material.normal = normalize(materialInput.tangentToEyeMatrix * normalTangentSpace);
material.specular = specularIntensity;
material.shininess = 10.0;
return material;
}
`;function Se(e){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=y(e.minificationFilter,en.LINEAR),this._magnificationFilter=y(e.magnificationFilter,Yo.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,Rte(e,this),Object.defineProperties(this,{type:{value:this.type,writable:!1}}),c(Se._uniformList[this.type])||(Se._uniformList[this.type]=Object.keys(this._uniforms))}Se._uniformList={};Se.fromType=function(e,t){if(!c(Se._materialCache.getMaterial(e)))throw new E(`material with type '${e}' does not exist.`);const n=new Se({fabric:{type:e}});if(c(t))for(const i in t)t.hasOwnProperty(i)&&(n.uniforms[i]=t[i]);return n};Se.prototype.isTranslucent=function(){if(c(this.translucent))return typeof this.translucent=="function"?this.translucent():this.translucent;let e=!0;const t=this._translucentFunctions,n=t.length;for(let i=0;i<n;++i){const o=t[i];if(typeof o=="function"?e=e&&o():e=e&&o,!e)break}return e};Se.prototype.update=function(e){this._defaultTexture=e.defaultTexture;let t,n;const i=this._loadedImages;let o=i.length;for(t=0;t<o;++t){const l=i[t];n=l.id;let u=l.image,h;Array.isArray(u)&&(h=u.slice(1,u.length).map(function(b){return b.bufferView}),u=u[0]);const f=new un({minificationFilter:this._minificationFilter,magnificationFilter:this._magnificationFilter});let _;c(u.internalFormat)?_=new xt({context:e,pixelFormat:u.internalFormat,width:u.width,height:u.height,source:{arrayBufferView:u.bufferView,mipLevels:h},sampler:f}):_=new xt({context:e,source:u,sampler:f});const g=this._textures[n];c(g)&&g!==this._defaultTexture&&g.destroy(),this._textures[n]=_;const m=`${n}Dimensions`;if(this.uniforms.hasOwnProperty(m)){const b=this.uniforms[m];b.x=_._width,b.y=_._height}}i.length=0;const r=this._loadedCubeMaps;for(o=r.length,t=0;t<o;++t){const l=r[t];n=l.id;const u=l.images,h=new Sl({context:e,source:{positiveX:u[0],negativeX:u[1],positiveY:u[2],negativeY:u[3],positiveZ:u[4],negativeZ:u[5]},sampler:new un({minificationFilter:this._minificationFilter,magnificationFilter:this._magnificationFilter})});this._textures[n]=h}r.length=0;const s=this._updateFunctions;for(o=s.length,t=0;t<o;++t)s[t](this,e);const a=this.materials;for(const l in a)a.hasOwnProperty(l)&&a[l].update(e)};Se.prototype.isDestroyed=function(){return!1};Se.prototype.destroy=function(){const e=this._textures;for(const n in e)if(e.hasOwnProperty(n)){const i=e[n];i!==this._defaultTexture&&i.destroy()}const t=this.materials;for(const n in t)t.hasOwnProperty(n)&&t[n].destroy();return ve(this)};function Rte(e,t){e=y(e,y.EMPTY_OBJECT),t._strict=y(e.strict,!1),t._count=y(e.count,0),t._template=Je(y(e.fabric,y.EMPTY_OBJECT)),t._template.uniforms=Je(y(t._template.uniforms,y.EMPTY_OBJECT)),t._template.materials=Je(y(t._template.materials,y.EMPTY_OBJECT)),t.type=c(t._template.type)?t._template.type:Wr(),t.shaderSource="",t.materials={},t.uniforms={},t._uniforms={},t._translucentFunctions=[];let n;const i=Se._materialCache.getMaterial(t.type);if(c(i)){const r=Je(i.fabric,!0);t._template=jt(t._template,r,!0),n=i.translucent}Bte(t),c(i)||Se._materialCache.addMaterial(t.type,t),Ute(t),Gte(t),Wte(t);const o=t._translucentFunctions.length===0?!0:void 0;if(n=y(n,o),n=y(e.translucent,n),c(n))if(typeof n=="function"){const r=function(){return n(t)};t._translucentFunctions.push(r)}else t._translucentFunctions.push(n)}function rw(e,t,n,i){if(c(e)){for(const o in e)if(e.hasOwnProperty(o)){const r=t.indexOf(o)!==-1;(i&&!r||!i&&r)&&n(o,t)}}}function SR(e,t){let n=`fabric: property name '${e}' is not valid. It should be `;for(let i=0;i<t.length;i++){const o=`'${t[i]}'`;n+=i===t.length-1?`or ${o}.`:`${o}, `}throw new E(n)}function Nte(e,t){const n=`fabric: uniforms and materials cannot share the same property '${e}'`;throw new E(n)}const Mte=["type","materials","uniforms","components","source"],Fte=["diffuse","specular","shininess"
`;else{if(e.shaderSource+=`czm_material czm_getMaterial(czm_materialInput materialInput)
{
`,e.shaderSource+=`czm_material material = czm_getDefaultMaterial(materialInput);
`,c(t)){const i=Object.keys(e._template.materials).length>0;for(const o in t)if(t.hasOwnProperty(o))if(o==="diffuse"||o==="emission"){const s=i&&zte(t[o],e)?t[o]:`czm_gammaCorrect(${t[o]})`;e.shaderSource+=`material.${o} = ${s};
`}else o==="alpha"?e.shaderSource+=`material.alpha = ${t.alpha};
`:e.shaderSource+=`material.${o} = ${t[o]};
`}e.shaderSource+=`return material;
}
`}}const vR={mat2:Xe,mat3:$,mat4:L},kte=/\.ktx2$/i;function Vte(e){let t;return function(n,i){const o=n.uniforms,r=o[e],s=t!==r,a=!c(r)||r===Se.DefaultImageId;t=r;let l=n._textures[e],u,h;if(r instanceof HTMLVideoElement){if(r.readyState>=2){if(s&&c(l)&&(l!==i.defaultTexture&&l.destroy(),l=void 0),!c(l)||l===i.defaultTexture){const _=new un({minificationFilter:n._minificationFilter,magnificationFilter:n._magnificationFilter});l=new xt({context:i,source:r,sampler:_}),n._textures[e]=l;return}l.copyFrom({source:r})}else c(l)||(n._textures[e]=i.defaultTexture);return}if(r instanceof xt&&r!==l){n._texturePaths[e]=void 0;const _=n._textures[e];c(_)&&_!==n._defaultTexture&&_.destroy(),n._textures[e]=r,u=`${e}Dimensions`,o.hasOwnProperty(u)&&(h=o[u],h.x=r._width,h.y=r._height);return}if(s&&c(l)&&a&&(l!==n._defaultTexture&&l.destroy(),l=void 0),c(l)||(n._texturePaths[e]=void 0,l=n._textures[e]=n._defaultTexture,u=`${e}Dimensions`,o.hasOwnProperty(u)&&(h=o[u],h.x=l._width,h.y=l._height)),a)return;const f=r instanceof Ae;if(!c(n._texturePaths[e])||f&&r.url!==n._texturePaths[e].url||!f&&r!==n._texturePaths[e]){if(typeof r=="string"||f){const _=f?r:Ae.createIfNeeded(r);let g;kte.test(_.url)?g=Op(_.url):g=_.fetchImage(),Promise.resolve(g).then(function(m){n._loadedImages.push({id:e,image:m})}).catch(function(){c(l)&&l!==n._defaultTexture&&l.destroy(),n._textures[e]=n._defaultTexture})}else(r instanceof HTMLCanvasElement||r instanceof HTMLImageElement)&&n._loadedImages.push({id:e,image:r});n._texturePaths[e]=r}}}function Hte(e){return function(t,n){const i=t.uniforms[e];if(i instanceof Sl){const r=t._textures[e];r!==t._defaultTexture&&r.destroy(),t._texturePaths[e]=void 0,t._textures[e]=i;return}if(c(t._textures[e])||(t._texturePaths[e]=void 0,t._textures[e]=n.defaultCubeMap),i===Se.DefaultCubeMapId)return;const o=i.positiveX+i.negativeX+i.positiveY+i.negativeY+i.positiveZ+i.negativeZ;if(o!==t._texturePaths[e]){const r=[Ae.createIfNeeded(i.positiveX).fetchImage(),Ae.createIfNeeded(i.negativeX).fetchImage(),Ae.createIfNeeded(i.positiveY).fetchImage(),Ae.createIfNeeded(i.negativeY).fetchImage(),Ae.createIfNeeded(i.positiveZ).fetchImage(),Ae.createIfNeeded(i.negativeZ).fetchImage()];Promise.all(r).then(function(s){t._loadedCubeMaps.push({id:e,images:s})}),t._texturePaths[e]=o}}}function Gte(e){const t=e._template.uniforms;for(const n in t)t.hasOwnProperty(n)&&Gk(e,n)}function Gk(e,t){const n=e._strict,i=e._template.uniforms,o=i[t],r=jte(o);if(!c(r))throw new E(`fabric: uniform '${t}' has invalid type.`);let s;if(r==="channels"){if(s=Zy(e,t,o,!1),s===0&&n)throw new E(`strict: shader source does not use channels '${t}'.`)}else{if(r==="sampler2D"){const u=`${t}Dimensions`;qte(e,u)>0&&(i[u]={type:"ivec3",x:1,y:1},Gk(e,u))}if(!new RegExp(`uniform\\s+${r}\\s+${t}\\s*;`).test(e.shaderSource)){const u=`uniform ${r} ${t};`;e.shaderSource=u+e.shaderSource}const l=`${t}_${e._count++}`;if(s=Zy(e,t,l),s===1&&n)throw new E(`strict: shader source does not use uniform '${t}'.`);if(e.uniforms[t]=o,r==="sampler2D")e._uniforms[l]=function(){return e._textures[t]},e._updateFunctions.push(Vte(t));else if(r==="samplerCube")e._uniforms[l]=function(){return e._textures[t]},e._updateFunctions.push(Hte(t));else if(r.indexOf("mat")!==-1){const u=new vR[r];e._uniforms[l]=function(){return vR[r].fromColumnMajorArray(e.uniforms[t],u)}}else e._uniforms[l]=function(){return e.uniforms[t]}}}function jte(e){let t=e.type;if(!c(t)){const n=typeof e;if(n==="number")t="float";else if(n==="boolean")t="bool";else if(n==="string"||e instanceof Ae||e instanceof HTMLCanvasElement||e instanceof HTMLImageElement)/^([rgba]){1,4}$/i.test(e)?t="channels":e===Se.DefaultCubeMapId?t="samplerCube":t="sampler2D";else if(n==="object")if(Array.isArray(e))(e.length===4||e.length===9||e.length===16)&&(t=`mat${Math.sqrt(e.length)}`);else{let i=0;for(const o in e)e.hasOwnProperty(o)&&(i+=1);i>=2&&i<=4?t=`vec${i}`:i===6&&(t="samplerCube")}}return t}function Wte(e){const t=e._strict,n=e._template.materials;for(const i in n)if(n.hasOwnProperty(i)){const o=new Se({strict:t,fabric:n[i],count:e._count
in vec3 v_normalEC;
in vec4 v_color;
void main()
{
vec3 positionToEyeEC = -v_positionEC;
vec3 normalEC = normalize(v_normalEC);
#ifdef FACE_FORWARD
normalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);
#endif
vec4 color = czm_gammaCorrect(v_color);
czm_materialInput materialInput;
materialInput.normalEC = normalEC;
materialInput.positionToEyeEC = positionToEyeEC;
czm_material material = czm_getDefaultMaterial(materialInput);
material.diffuse = color.rgb;
material.alpha = color.a;
out_FragColor = czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);
}
`,$te=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec3 normal;
in vec4 color;
in float batchId;
out vec3 v_positionEC;
out vec3 v_normalEC;
out vec4 v_color;
void main()
{
vec4 p = czm_computePosition();
v_positionEC = (czm_modelViewRelativeToEye * p).xyz; // position in eye coordinates
v_normalEC = czm_normal * normal; // normal in eye coordinates
v_color = color;
gl_Position = czm_modelViewProjectionRelativeToEye * p;
}
`,jk=`in vec4 v_color;
void main()
{
out_FragColor = czm_gammaCorrect(v_color);
}
`,Xte=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec4 color;
in float batchId;
out vec4 v_color;
void main()
{
vec4 p = czm_computePosition();
v_color = color;
gl_Position = czm_modelViewProjectionRelativeToEye * p;
}
`;function tn(e){e=y(e,y.EMPTY_OBJECT);const t=y(e.translucent,!0),n=y(e.closed,!1),i=y(e.flat,!1),o=i?Xte:$te,r=i?jk:Yte,s=i?tn.FLAT_VERTEX_FORMAT:tn.VERTEX_FORMAT;this.material=void 0,this.translucent=t,this._vertexShaderSource=y(e.vertexShaderSource,o),this._fragmentShaderSource=y(e.fragmentShaderSource,r),this._renderState=Lo.getDefaultRenderState(t,n,e.renderState),this._closed=n,this._vertexFormat=s,this._flat=i,this._faceForward=y(e.faceForward,!n)}Object.defineProperties(tn.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}}});tn.VERTEX_FORMAT=Ee.POSITION_AND_NORMAL;tn.FLAT_VERTEX_FORMAT=Ee.POSITION_ONLY;tn.prototype.getFragmentShaderSource=Lo.prototype.getFragmentShaderSource;tn.prototype.isTranslucent=Lo.prototype.isTranslucent;tn.prototype.getRenderState=Lo.prototype.getRenderState;function kt(e){this._definitionChanged=new Le,this._color=void 0,this._colorSubscription=void 0,this.color=e}Object.defineProperties(kt.prototype,{isConstant:{get:function(){return K.isConstant(this._color)}},definitionChanged:{get:function(){return this._definitionChanged}},color:ue("color")});kt.prototype.getType=function(e){return"Color"};kt.prototype.getValue=function(e,t){return c(t)||(t={}),t.color=K.getValueOrClonedDefault(this._color,e,z.WHITE,t.color),t};kt.prototype.equals=function(e){return this===e||e instanceof kt&&K.equals(this._color,e._color)};function Yr(e){e=y(e,y.EMPTY_OBJECT),this._ellipsoid=y(e.ellipsoid,ae.WGS84),this._rectangle=y(e.rectangle,ce.MAX_VALUE),this._projection=new co(this._ellipsoid),this._numberOfLevelZeroTilesX=y(e.numberOfLevelZeroTilesX,2),this._numberOfLevelZeroTilesY=y(e.numberOfLevelZeroTilesY,1)}Object.defineProperties(Yr.prototype,{ellipsoid:{get:function(){return this._ellipsoid}},rectangle:{get:function(){return this._rectangle}},projection:{get:function(){return this._projection}}});Yr.prototype.getNumberOfXTilesAtLevel=function(e){return this._numberOfLevelZeroTilesX<<e};Yr.prototype.getNumberOfYTilesAtLevel=function(e){return this._numberOfLevelZeroTilesY<<e};Yr.prototype.rectangleToNativeRectangle=function(e,t){A.defined("rectangle",e);const n=R.toDegrees(e.west),i=R.toDegrees(e.south),o=R.toDegrees(e.east),r=R.toDegrees(e.north);return c(t)?(t.west=n,t.south=i,t.east=o,t.north=r,t):new ce(n,i,o,r)};Yr.prototype.tileXYToNativeRectangle=function(e,t,n,i){const o=this.tileXYToRectangle(e,t,n,i);return o.west=R.toDegrees(o.west),o.south=R.toDegrees(o.south),o.east=R.toDegrees(o.east),o.north=R.toDegrees(o.north),o};Yr.prototype.tileXYToRectangle=function(e,t,n,i){const o=this._rectangle,r=this.getNumberOfXTilesAtLevel(n),s=this.getNumberOfYTilesAtLevel(n),a=o.width/r,l=e*a+o.west,u=(e+1)*a+o.west,h=o.height/s,f=o.north-t*h,_=o.north-(t+1)*h;return c(i)||(i=new ce(l,_,u,f)),i.west=l,i.south=_,i.east=u,i.north=f,i};Yr.prototype.positionToTileXY=function(e,t,n){const i=this._rectangle;if(!ce.contains(i,e))return;const o=this.getNumberOfXTilesAtLevel(t),r=this.getNumberOfYTilesAtLevel(t),s=i.width/o,a=i.height/r;let l=e.longitude;i.east<i.west&&(l+=R.TWO_PI);let u=(l-i.west)/s|0;u>=o&&(u=o-1);let h=(i.north-e.latitude)/a|0;return h>=r&&(h=r-1),c(n)?(n.x=u,n.y=h,n):new H(u,h)};const IR=new d,DR=new d,PR=new he,sw=new d,Qte=new d,OR=new se,Kte=new Yr,bg=[new he,new he,new he,new he],Tg=new H,Xi={};Xi.initialize=function(){let e=Xi._initPromise;return c(e)||(e=Ae.fetchJson(Zt("Assets/approximateTerrainHeights.json")).then(function(t){Xi._terrainHeights=t}),Xi._initPromise=e),e};Xi.getMinimumMaximumHeights=function(e,t){if(A.defined("rectangle",e),!c(Xi._terrainHeights))throw new E("You must call ApproximateTerrainHeights.initialize and wait for the promise to resolve before using this function");t=y(t,ae.WGS84);const n=Wk(e);let i=Xi._defaultMin
in vec3 position3DLow;
in float batchId;
#ifdef EXTRUDED_GEOMETRY
in vec3 extrudeDirection;
uniform float u_globeMinimumAltitude;
#endif // EXTRUDED_GEOMETRY
#ifdef PER_INSTANCE_COLOR
out vec4 v_color;
#endif // PER_INSTANCE_COLOR
#ifdef TEXTURE_COORDINATES
#ifdef SPHERICAL
out vec4 v_sphericalExtents;
#else // SPHERICAL
out vec2 v_inversePlaneExtents;
out vec4 v_westPlane;
out vec4 v_southPlane;
#endif // SPHERICAL
out vec3 v_uvMinAndSphericalLongitudeRotation;
out vec3 v_uMaxAndInverseDistance;
out vec3 v_vMaxAndInverseDistance;
#endif // TEXTURE_COORDINATES
void main()
{
vec4 position = czm_computePosition();
#ifdef EXTRUDED_GEOMETRY
float delta = min(u_globeMinimumAltitude, czm_geometricToleranceOverMeter * length(position.xyz));
delta *= czm_sceneMode == czm_sceneMode3D ? 1.0 : 0.0;
//extrudeDirection is zero for the top layer
position = position + vec4(extrudeDirection * delta, 0.0);
#endif
#ifdef TEXTURE_COORDINATES
#ifdef SPHERICAL
v_sphericalExtents = czm_batchTable_sphericalExtents(batchId);
v_uvMinAndSphericalLongitudeRotation.z = czm_batchTable_longitudeRotation(batchId);
#else // SPHERICAL
#ifdef COLUMBUS_VIEW_2D
vec4 planes2D_high = czm_batchTable_planes2D_HIGH(batchId);
vec4 planes2D_low = czm_batchTable_planes2D_LOW(batchId);
// If the primitive is split across the IDL (planes2D_high.x > planes2D_high.w):
// - If this vertex is on the east side of the IDL (position3DLow.y > 0.0, comparison with position3DHigh may produce artifacts)
// - existing "east" is on the wrong side of the world, far away (planes2D_high/low.w)
// - so set "east" as beyond the eastmost extent of the projection (idlSplitNewPlaneHiLow)
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));
bool idlSplit = planes2D_high.x > planes2D_high.w && position3DLow.y > 0.0;
planes2D_high.w = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.x, planes2D_high.w);
planes2D_low.w = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.y, planes2D_low.w);
// - else, if this vertex is on the west side of the IDL (position3DLow.y < 0.0)
// - existing "west" is on the wrong side of the world, far away (planes2D_high/low.x)
// - so set "west" as beyond the westmost extent of the projection (idlSplitNewPlaneHiLow)
idlSplit = planes2D_high.x > planes2D_high.w && position3DLow.y < 0.0;
idlSplitNewPlaneHiLow = vec2(WEST_MOST_X_HIGH - (EAST_MOST_X_HIGH - planes2D_high.x), WEST_MOST_X_LOW - (EAST_MOST_X_LOW - planes2D_low.x));
planes2D_high.x = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.x, planes2D_high.x);
planes2D_low.x = czm_branchFreeTernary(idlSplit, idlSplitNewPlaneHiLow.y, planes2D_low.x);
vec3 southWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, planes2D_high.xy), vec3(0.0, planes2D_low.xy))).xyz;
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;
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;
#else // COLUMBUS_VIEW_2D
// 3D case has smaller "plane extents," so planes encoded as a 64 bit position and 2 vec3s for distances/direction
vec3 southWestCorner = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(czm_batchTable_southWest_HIGH(batchId), czm_batchTable_southWest_LOW(batchId))).xyz;
vec3 northWestCorner = czm_normal * czm_batchTable_northward(batchId) + southWestCorner;
vec3 southEastCorner = czm_normal * czm_batchTable_eastward(batchId) + southWestCorner;
#endif // COLUMBUS_VIEW_2D
vec3 eastWard = southEastCorner - southWestCorner;
float eastExtent = length(eastWard);
eastWard /= eastExtent;
vec3 northWard = northWestCorner - southWestCorner;
float northExtent = length(northWard);
northWard /= northExtent;
v_westPlane = vec4(eastWard, -dot(eastWard, southWestCorner));
v_southPlane = vec4(northWard, -dot(northWard, southWestCorner));
v_inversePlaneExtents = vec2(1.0 / eastExtent, 1.0 / northExtent);
#endif // SPHERICAL
vec4 uvMinAndExtents = czm_batchTable_uvMinAndExtents(batchId);
vec4 uMaxVmax = czm_batchTable_uMaxVmax(batchId);
v_uMaxAndInverseDistance = vec3(uMaxVmax.xy, uvMinAndExtents.z);
v_vMaxAndInverseDistance = vec3(uMaxVmax.zw, uvMinAndExtents.w);
v_uvMinAndSphericalLongitudeRotation.xy = uvMinAndExtents.xy;
#endif // TEXTURE_COORDINATES
#ifdef PER_INSTANCE_COLOR
v_color = czm_batchTable_color(batchId);
#endif
gl_Position = czm_depthClamp(czm_modelViewProjectionRelativeToEye * position);
}
`,wI=`#ifdef VECTOR_TILE
uniform vec4 u_highlightColor;
#endif
void main(void)
{
#ifdef VECTOR_TILE
out_FragColor = czm_gammaCorrect(u_highlightColor);
#else
out_FragColor = vec4(1.0);
#endif
czm_writeDepthClamp();
}
`,Jk={TERRAIN:0,CESIUM_3D_TILE:1,BOTH:2};Jk.NUMBER_OF_CLASSIFICATION_TYPES=3;const Ui=Object.freeze(Jk),aie={NEVER:J.NEVER,LESS:J.LESS,EQUAL:J.EQUAL,LESS_OR_EQUAL:J.LEQUAL,GREATER:J.GREATER,NOT_EQUAL:J.NOTEQUAL,GREATER_OR_EQUAL:J.GEQUAL,ALWAYS:J.ALWAYS},lp=Object.freeze(aie);function cie(e,t){if(!c(e))throw new E("array is required.");if(!c(t)||t<1)throw new E("numberOfArrays must be greater than 0.");const n=[],i=e.length;let o=0;for(;o<i;){const r=Math.ceil((i-o)/t--);n.push(e.slice(o,o+r)),o+=r}return n}function uu(e,t,n){if(!c(e))throw new E("context is required");if(!c(t))throw new E("attributes is required");if(!c(n))throw new E("numberOfInstances is required");if(this._attributes=t,this._numberOfInstances=n,t.length===0)return;const i=lie(t),o=e.floatingPointTexture,r=i===Me.FLOAT&&!o,s=uie(t,r),a=die(s,t,r),l=Math.floor(pt.maximumTextureSize/a),u=Math.min(n,l),h=a*u,f=Math.ceil(n/u),_=1/h,g=_*.5,m=1/f,b=m*.5;this._textureDimensions=new H(h,f),this._textureStep=new te(_,g,m,b),this._pixelDatatype=r?Me.UNSIGNED_BYTE:i,this._packFloats=r,this._offsets=s,this._stride=a,this._texture=void 0;const T=4*h*f;this._batchValues=i===Me.FLOAT&&!r?new Float32Array(T):new Uint8Array(T),this._batchValuesDirty=!1}Object.defineProperties(uu.prototype,{attributes:{get:function(){return this._attributes}},numberOfInstances:{get:function(){return this._numberOfInstances}}});function lie(e){let t=!1;const n=e.length;for(let i=0;i<n;++i)if(e[i].componentDatatype!==Z.UNSIGNED_BYTE){t=!0;break}return t?Me.FLOAT:Me.UNSIGNED_BYTE}function eV(e,t){const n=e[t].componentsPerAttribute;return n===2?H:n===3?d:n===4?te:Number}function uie(e,t){const n=new Array(e.length);let i=0;const o=e.length;for(let r=0;r<o;++r){const a=e[r].componentDatatype;n[r]=i,a!==Z.UNSIGNED_BYTE&&t?i+=4:++i}return n}function die(e,t,n){const i=e.length,o=e[i-1];return t[i-1].componentDatatype!==Z.UNSIGNED_BYTE&&n?o+4:o+1}const dy=new te;function hie(e,t,n){let i=te.unpack(e,t,dy);const o=te.unpackFloat(i);i=te.unpack(e,t+4,dy);const r=te.unpackFloat(i);i=te.unpack(e,t+8,dy);const s=te.unpackFloat(i);i=te.unpack(e,t+12,dy);const a=te.unpackFloat(i);return te.fromElements(o,r,s,a,n)}function fie(e,t,n){let i=te.packFloat(e.x,dy);te.pack(i,t,n),i=te.packFloat(e.y,i),te.pack(i,t,n+4),i=te.packFloat(e.z,i),te.pack(i,t,n+8),i=te.packFloat(e.w,i),te.pack(i,t,n+12)}const WR=new te;uu.prototype.getBatchedAttribute=function(e,t,n){if(e<0||e>=this._numberOfInstances)throw new E("instanceIndex is out of range.");if(t<0||t>=this._attributes.length)throw new E("attributeIndex is out of range");const i=this._attributes,o=this._offsets[t],s=4*this._stride*e+4*o;let a;this._packFloats&&i[t].componentDatatype!==Me.UNSIGNED_BYTE?a=hie(this._batchValues,s,WR):a=te.unpack(this._batchValues,s,WR);const l=eV(i,t);return c(l.fromCartesian4)?l.fromCartesian4(a,n):c(l.clone)?l.clone(a,n):a.x};const pie=[void 0,void 0,new H,new d,new te],mie=new te;uu.prototype.setBatchedAttribute=function(e,t,n){if(e<0||e>=this._numberOfInstances)throw new E("instanceIndex is out of range.");if(t<0||t>=this._attributes.length)throw new E("attributeIndex is out of range");if(!c(n))throw new E("value is required.");const i=this._attributes,o=pie[i[t].componentsPerAttribute],r=this.getBatchedAttribute(e,t,o),s=eV(this._attributes,t);if(c(s.equals)?s.equals(r,n):r===n)return;const l=mie;l.x=c(n.x)?n.x:n,l.y=c(n.y)?n.y:0,l.z=c(n.z)?n.z:0,l.w=c(n.w)?n.w:0;const u=this._offsets[t],f=4*this._stride*e+4*u;this._packFloats&&i[t].componentDatatype!==Me.UNSIGNED_BYTE?fie(l,this._batchValues,f):te.pack(l,this._batchValues,f),this._batchValuesDirty=!0};function _ie(e,t){const n=e._textureDimensions;e._texture=new xt({context:t,pixelFormat:Ve.RGBA,pixelDatatype:e._pixelDatatype,width:n.x,height:n.y,sampler:un.NEAREST,flipY:!1})}function gie(e){const t=e._textureDimensions;e._texture.copyFrom({source:{width:t.x,height:t.y,arrayBufferView:e._batchValues}})}uu.prototype.update=function(e){c(this._texture)&&!this._batchValuesDirty||this._attributes.length===0||(this._batchValuesDirty=!1,c(this._texture)||_ie(this,e.context),gie
vec2 computeSt(float batchId)
{
float stepX = batchTextureStep.x;
float centerX = batchTextureStep.y;
float numberOfAttributes = float(${t});
return vec2(centerX + (batchId * numberOfAttributes * stepX), 0.5);
}
`:`uniform vec4 batchTextureStep;
uniform vec2 batchTextureDimensions;
vec2 computeSt(float batchId)
{
float stepX = batchTextureStep.x;
float centerX = batchTextureStep.y;
float stepY = batchTextureStep.z;
float centerY = batchTextureStep.w;
float numberOfAttributes = float(${t});
float xId = mod(batchId * numberOfAttributes, batchTextureDimensions.x);
float yId = floor(batchId * numberOfAttributes / batchTextureDimensions.x);
return vec2(centerX + (xId * stepX), centerY + (yId * stepY));
}
`}function bie(e){return e===1?"float":`vec${e}`}function Tie(e){return e===1?".x":e===2?".xy":e===3?".xyz":""}function Aie(e,t){const i=e._attributes[t],o=i.componentsPerAttribute,r=i.functionName,s=bie(o),a=Tie(o),l=e._offsets[t];let u=`${s} ${r}(float batchId)
{
vec2 st = computeSt(batchId);
st.x += batchTextureStep.x * float(${l});
`;return e._packFloats&&i.componentDatatype!==Me.UNSIGNED_BYTE?u+=`vec4 textureValue;
textureValue.x = czm_unpackFloat(texture(batchTexture, st));
textureValue.y = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x, 0.0)));
textureValue.z = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x * 2.0, 0.0)));
textureValue.w = czm_unpackFloat(texture(batchTexture, st + vec2(batchTextureStep.x * 3.0, 0.0)));
`:u+=` vec4 textureValue = texture(batchTexture, st);
`,u+=` ${s} value = textureValue${a};
`,e._pixelDatatype===Me.UNSIGNED_BYTE&&i.componentDatatype===Z.UNSIGNED_BYTE&&!i.normalize?u+=`value *= 255.0;
`:e._pixelDatatype===Me.FLOAT&&i.componentDatatype===Z.UNSIGNED_BYTE&&i.normalize&&(u+=`value /= 255.0;
`),u+=` return value;
}
`,u}uu.prototype.getVertexShaderCallback=function(){const e=this._attributes;if(e.length===0)return function(i){return i};let t=`uniform highp sampler2D batchTexture;
`;t+=`${yie(this)}
`;const n=e.length;for(let i=0;i<n;++i)t+=Aie(this,i);return function(i){const o=i.indexOf("void main"),r=i.substring(0,o),s=i.substring(o);return`${r}
${t}
${s}`}};uu.prototype.isDestroyed=function(){return!1};uu.prototype.destroy=function(){return this._texture=this._texture&&this._texture.destroy(),ve(this)};const kn={SCALAR:"SCALAR",VEC2:"VEC2",VEC3:"VEC3",VEC4:"VEC4",MAT2:"MAT2",MAT3:"MAT3",MAT4:"MAT4"};kn.getMathType=function(e){switch(e){case kn.SCALAR:return Number;case kn.VEC2:return H;case kn.VEC3:return d;case kn.VEC4:return te;case kn.MAT2:return Xe;case kn.MAT3:return $;case kn.MAT4:return L;default:throw new E("attributeType is not a valid value.")}};kn.getNumberOfComponents=function(e){switch(e){case kn.SCALAR:return 1;case kn.VEC2:return 2;case kn.VEC3:return 3;case kn.VEC4:case kn.MAT2:return 4;case kn.MAT3:return 9;case kn.MAT4:return 16;default:throw new E("attributeType is not a valid value.")}};kn.getAttributeLocationCount=function(e){switch(e){case kn.SCALAR:case kn.VEC2:case kn.VEC3:case kn.VEC4:return 1;case kn.MAT2:return 2;case kn.MAT3:return 3;case kn.MAT4:return 4;default:throw new E("attributeType is not a valid value.")}};kn.getGlslType=function(e){switch(A.typeOf.string("attributeType",e),e){case kn.SCALAR:return"float";case kn.VEC2:return"vec2";case kn.VEC3:return"vec3";case kn.VEC4:return"vec4";case kn.MAT2:return"mat2";case kn.MAT3:return"mat3";case kn.MAT4:return"mat4";default:throw new E("attributeType is not a valid value.")}};const qt=Object.freeze(kn),qR=1/256,YR=256,ii={};ii.octEncodeInRange=function(e,t,n){A.defined("vector",e),A.defined("result",n);const i=d.magnitudeSquared(e);if(Math.abs(i-1)>R.EPSILON6)throw new E("vector must be normalized.");if(n.x=e.x/(Math.abs(e.x)+Math.abs(e.y)+Math.abs(e.z)),n.y=e.y/(Math.abs(e.x)+Math.abs(e.y)+Math.abs(e.z)),e.z<0){const o=n.x,r=n.y;n.x=(1-Math.abs(r))*R.signNotZero(o),n.y=(1-Math.abs(o))*R.signNotZero(r)}return n.x=R.toSNorm(n.x,t),n.y=R.toSNorm(n.y,t),n};ii.octEncode=function(e,t){return ii.octEncodeInRange(e,255,t)};const xg=new H,$R=new Uint8Array(1);function Gb(e){return $R[0]=e,$R[0]}ii.octEncodeToCartesian4=function(e,t){return ii.octEncodeInRange(e,65535,xg),t.x=Gb(xg.x*qR),t.y=Gb(xg.x),t.z=Gb(xg.y*qR),t.w=Gb(xg.y),t};ii.octDecodeInRange=function(e,t,n,i){if(A.defined("result",i),e<0||e>n||t<0||t>n)throw new E(`x and y must be unsigned normalized integers between 0 and ${n}`);if(i.x=R.fromSNorm(e,n),i.y=R.fromSNorm(t,n),i.z=1-(Math.abs(i.x)+Math.abs(i.y)),i.z<0){const o=i.x;i.x=(1-Math.abs(i.y))*R.signNotZero(o),i.y=(1-Math.abs(o))*R.signNotZero(i.y)}return d.normalize(i,i)};ii.octDecode=function(e,t,n){return ii.octDecodeInRange(e,t,255,n)};ii.octDecodeFromCartesian4=function(e,t){A.typeOf.object("encoded",e),A.typeOf.object("result",t);const n=e.x,i=e.y,o=e.z,r=e.w;if(n<0||n>255||i<0||i>255||o<0||o>255||r<0||r>255)throw new E("x, y, z, and w must be unsigned normalized integers between 0 and 255");const s=n*YR+i,a=o*YR+r;return ii.octDecodeInRange(s,a,65535,t)};ii.octPackFloat=function(e){return A.defined("encoded",e),256*e.x+e.y};const SI=new H;ii.octEncodeFloat=function(e){return ii.octEncode(e,SI),ii.octPackFloat(SI)};ii.octDecodeFloat=function(e,t){A.defined("value",e);const n=e/256,i=Math.floor(n),o=(n-i)*256;return ii.octDecode(i,o,t)};ii.octPack=function(e,t,n,i){A.defined("v1",e),A.defined("v2",t),A.defined("v3",n),A.defined("result",i);const o=ii.octEncodeFloat(e),r=ii.octEncodeFloat(t),s=ii.octEncode(n,SI);return i.x=65536*s.x+o,i.y=65536*s.y+r,i};ii.octUnpack=function(e,t,n,i){A.defined("packed",e),A.defined("v1",t),A.defined("v2",n),A.defined("v3",i);let o=e.x/65536;const r=Math.floor(o),s=(o-r)*65536;o=e.y/65536;const a=Math.floor(o),l=(o-a)*65536;ii.octDecodeFloat(s,t),ii.octDecodeFloat(l,n),ii.octDecode(r,a,i)};ii.compressTextureCoordinates=function(e){A.defined("textureCoordinates",e);const t=e.x*4095|0,n=e.y*4095|0;return 4096*t+n};ii.decompressTextureCoordinates=function(e,t){A.defined("compressed",e),A.defined("result",t);const n=e/4096,i=Math.floor(n);return t.x=i/4095,t.y=(e-i*4096)/4095,t};function uw(e){return e>>1^-(e&1)}ii.zigZagDeltaDecode=function(e,t,n){A.defined("uBuffer",e),A.defined("vBuffer",t),A.typeOf.number.equals("uBuffer.length","vBuffer.lengt
`),c(e.rtcCenter)?(t=t.replace(/in\s+vec(?:3|4)\s+position3DHigh;/g,""),t=t.replace(/in\s+vec(?:3|4)\s+position3DLow;/g,""),o+=`uniform mat4 u_modifiedModelView;
`,r+=`in vec4 position;
`,s+=`${l}
{
return u_modifiedModelView * position;
}
`,t=t.replace(/czm_modelViewRelativeToEye\s+\*\s+/g,""),t=t.replace(/czm_modelViewProjectionRelativeToEye/g,"czm_projection")):n?s+=`${l}
{
return czm_translateRelativeToEye(${a}3DHigh, ${a}3DLow);
}
`:(r+=`in vec3 ${a}2DHigh;
in vec3 ${a}2DLow;
`,s+=`${l}
{
vec4 p;
if (czm_morphTime == 1.0)
{
p = czm_translateRelativeToEye(${a}3DHigh, ${a}3DLow);
}
else if (czm_morphTime == 0.0)
{
p = czm_translateRelativeToEye(${a}2DHigh.zxy, ${a}2DLow.zxy);
}
else
{
p = czm_columbusViewMorph(
czm_translateRelativeToEye(${a}2DHigh.zxy, ${a}2DLow.zxy),
czm_translateRelativeToEye(${a}3DHigh, ${a}3DLow),
czm_morphTime);
}
return p;
}
`)}return[o,r,t,s].join(`
`)};Mt._appendShowToShader=function(e,t){return c(e._batchTableAttributeIndices.show)?`${Oe.replaceMain(t,"czm_non_show_main")}
void main()
{
czm_non_show_main();
gl_Position *= czm_batchTable_show(batchId);
}`:t};Mt._updateColorAttribute=function(e,t,n){if(!c(e._batchTableAttributeIndices.color)&&!c(e._batchTableAttributeIndices.depthFailColor)||t.search(/in\s+vec4\s+color;/g)===-1)return t;if(n&&!c(e._batchTableAttributeIndices.depthFailColor))throw new E("A depthFailColor per-instance attribute is required when using a depth fail appearance that uses a color attribute.");let i=t;return i=i.replace(/in\s+vec4\s+color;/g,""),n?i=i.replace(/(\b)color(\b)/g,"$1czm_batchTable_depthFailColor(batchId)$2"):i=i.replace(/(\b)color(\b)/g,"$1czm_batchTable_color(batchId)$2"),i};function hN(e){return`${Oe.replaceMain(e,"czm_non_pick_main")}
out vec4 v_pickColor;
void main()
{
czm_non_pick_main();
v_pickColor = czm_batchTable_pickColor(batchId);
}`}function fN(e){return`in vec4 v_pickColor;
${e}`}Mt._updatePickColorAttribute=function(e){let t=e.replace(/in\s+vec4\s+pickColor;/g,"");return t=t.replace(/(\b)pickColor(\b)/g,"$1czm_batchTable_pickColor(batchId)$2"),t};Mt._appendOffsetToShader=function(e,t){if(!c(e._batchTableAttributeIndices.offset))return t;let n=`in float batchId;
`;n+="in float applyOffset;";let i=t.replace(/in\s+float\s+batchId;/g,n),o=`vec4 $1 = czm_computePosition();
`;return o+=` if (czm_sceneMode == czm_sceneMode3D)
`,o+=` {
`,o+=" $1 = $1 + vec4(czm_batchTable_offset(batchId) * applyOffset, 0.0);",o+=` }
`,o+=` else
`,o+=` {
`,o+=" $1 = $1 + vec4(czm_batchTable_offset2D(batchId) * applyOffset, 0.0);",o+=` }
`,i=i.replace(/vec4\s+([A-Za-z0-9_]+)\s+=\s+czm_computePosition\(\);/g,o),i};Mt._appendDistanceDisplayConditionToShader=function(e,t,n){if(!c(e._batchTableAttributeIndices.distanceDisplayCondition))return t;const i=Oe.replaceMain(t,"czm_non_distanceDisplayCondition_main");let o=`void main()
{
czm_non_distanceDisplayCondition_main();
vec2 distanceDisplayCondition = czm_batchTable_distanceDisplayCondition(batchId);
vec3 boundingSphereCenter3DHigh = czm_batchTable_boundingSphereCenter3DHigh(batchId);
vec3 boundingSphereCenter3DLow = czm_batchTable_boundingSphereCenter3DLow(batchId);
float boundingSphereRadius = czm_batchTable_boundingSphereRadius(batchId);
`;return n?o+=` vec4 centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);
`:o+=` vec3 boundingSphereCenter2DHigh = czm_batchTable_boundingSphereCenter2DHigh(batchId);
vec3 boundingSphereCenter2DLow = czm_batchTable_boundingSphereCenter2DLow(batchId);
vec4 centerRTE;
if (czm_morphTime == 1.0)
{
centerRTE = czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow);
}
else if (czm_morphTime == 0.0)
{
centerRTE = czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy);
}
else
{
centerRTE = czm_columbusViewMorph(
czm_translateRelativeToEye(boundingSphereCenter2DHigh.zxy, boundingSphereCenter2DLow.zxy),
czm_translateRelativeToEye(boundingSphereCenter3DHigh, boundingSphereCenter3DLow),
czm_morphTime);
}
`,o+=` float radiusSq = boundingSphereRadius * boundingSphereRadius;
float distanceSq;
if (czm_sceneMode == czm_sceneMode2D)
{
distanceSq = czm_eyeHeight2D.y - radiusSq;
}
else
{
distanceSq = dot(centerRTE.xyz, centerRTE.xyz) - radiusSq;
}
distanceSq = max(distanceSq, 0.0);
float nearSq = distanceDisplayCondition.x * distanceDisplayCondition.x;
float farSq = distanceDisplayCondition.y * distanceDisplayCondition.y;
float show = (distanceSq >= nearSq && distanceSq <= farSq) ? 1.0 : 0.0;
gl_Position *= show;
}`,`${i}
${o}`};function pN(e,t){if(!e.compressVertices)return t;const n=t.search(/in\s+vec3\s+normal;/g)!==-1,i=t.search(/in\s+vec2\s+st;/g)!==-1;if(!n&&!i)return t;const o=t.search(/in\s+vec3\s+tangent;/g)!==-1,r=t.search(/in\s+vec3\s+bitangent;/g)!==-1;let s=i&&n?2:1;s+=o||r?1:0;const a=s>1?`vec${s}`:"float",l="compressedAttributes",u=`in ${a} ${l};`;let h="",f="";if(i){h+=`vec2 st;
`;const m=s>1?`${l}.x`:l;f+=` st = czm_decompressTextureCoordinates(${m});
`}n&&o&&r?(h+=`vec3 normal;
vec3 tangent;
vec3 bitangent;
`,f+=` czm_octDecode(${l}.${i?"yz":"xy"}, normal, tangent, bitangent);
`):(n&&(h+=`vec3 normal;
`,f+=` normal = czm_octDecode(${l}${s>1?`.${i?"y":"x"}`:""});
`),o&&(h+=`vec3 tangent;
`,f+=` tangent = czm_octDecode(${l}.${i&&n?"z":"y"});
`),r&&(h+=`vec3 bitangent;
`,f+=` bitangent = czm_octDecode(${l}.${i&&n?"z":"y"});
`));let _=t;_=_.replace(/in\s+vec3\s+normal;/g,""),_=_.replace(/in\s+vec2\s+st;/g,""),_=_.replace(/in\s+vec3\s+tangent;/g,""),_=_.replace(/in\s+vec3\s+bitangent;/g,""),_=Oe.replaceMain(_,"czm_non_compressed_main");const g=`void main()
{
${f} czm_non_compressed_main();
}`;return[u,h,_,g].join(`
`)}function boe(e){let t=Oe.replaceMain(e,"czm_non_depth_clamp_main");return t+=`void main() {
czm_non_depth_clamp_main();
gl_Position = czm_depthClamp(gl_Position);}
`,t}function Toe(e){let t=Oe.replaceMain(e,"czm_non_depth_clamp_main");return t+=`void main() {
czm_non_depth_clamp_main();
#if defined(LOG_DEPTH)
czm_writeLogDepth();
#else
czm_writeDepthClamp();
#endif
}
`,t}function mN(e,t){const n=e.vertexAttributes;for(const i in n)if(n.hasOwnProperty(i)&&!c(t[i]))throw new E(`Appearance/Geometry mismatch. The appearance requires vertex shader attribute input '${i}', which was not computed as part of the Geometry. Use the appearance's vertexFormat property when constructing the geometry.`)}function Aoe(e,t){return function(){return e[t]}}const yw=Math.max(Yt.hardwareConcurrency-1,1);let Xb;const xoe=new Kn("combineGeometry");function Coe(e,t){let n,i,o,r;const s=e._instanceIds;if(e._state===Uo.READY){n=Array.isArray(e.geometryInstances)?e.geometryInstances:[e.geometryInstances];const a=e._numberOfInstances=n.length,l=[];let u=[];for(o=0;o<a;++o){if(i=n[o].geometry,s.push(n[o].id),c(i._workerName)&&c(i._workerPath)||!c(i._workerName)&&!c(i._workerPath))throw new E("Must define either _workerName or _workerPath for asynchronous geometry.");u.push({moduleName:i._workerName,modulePath:i._workerPath,geometry:i})}if(!c(Xb))for(Xb=new Array(yw),o=0;o<yw;o++)Xb[o]=new Kn("createGeometry");let h;for(u=cie(u,yw),o=0;o<u.length;o++){let f=0;const _=u[o],g=_.length;for(r=0;r<g;++r)h=_[r],i=h.geometry,c(i.constructor.pack)&&(h.offset=f,f+=y(i.constructor.packedLength,i.packedLength));let m;if(f>0){const b=new Float64Array(f);for(m=[b.buffer],r=0;r<g;++r)h=_[r],i=h.geometry,c(i.constructor.pack)&&(i.constructor.pack(i,b,h.offset),h.geometry=b)}l.push(Xb[o].scheduleTask({subTasks:u[o]},m))}e._state=Uo.CREATING,Promise.all(l).then(function(f){e._createGeometryResults=f,e._state=Uo.CREATED}).catch(function(f){Py(e,t,Uo.FAILED,f)})}else if(e._state===Uo.CREATED){const a=[];n=Array.isArray(e.geometryInstances)?e.geometryInstances:[e.geometryInstances];const l=t.scene3DOnly,u=t.mapProjection,h=xoe.scheduleTask(PI.packCombineGeometryParameters({createGeometryResults:e._createGeometryResults,instances:n,ellipsoid:u.ellipsoid,projection:u,elementIndexUintSupported:t.context.elementIndexUint,scene3DOnly:l,vertexCacheOptimize:e.vertexCacheOptimize,compressVertices:e.compressVertices,modelMatrix:e.modelMatrix,createPickOffsets:e._createPickOffsets},a),a);e._createGeometryResults=void 0,e._state=Uo.COMBINING,Promise.resolve(h).then(function(f){const _=PI.unpackCombineGeometryResults(f);e._geometries=_.geometries,e._attributeLocations=_.attributeLocations,e.modelMatrix=L.clone(_.modelMatrix,e.modelMatrix),e._pickOffsets=_.pickOffsets,e._offsetInstanceExtend=_.offsetInstanceExtend,e._instanceBoundingSpheres=_.boundingSpheres,e._instanceBoundingSpheresCV=_.boundingSpheresCV,c(e._geometries)&&e._geometries.length>0?(e._recomputeBoundingSpheres=!0,e._state=Uo.COMBINED):Py(e,t,Uo.FAILED,void 0)}).catch(function(f){Py(e,t,Uo.FAILED,f)})}}function Eoe(e,t){const n=Array.isArray(e.geometryInstances)?e.geometryInstances:[e.geometryInstances],i=e._numberOfInstances=n.length,o=new Array(i),r=e._instanceIds;let s,a,l=0;for(a=0;a<i;a++){s=n[a];const _=s.geometry;let g;c(_.attributes)&&c(_.primitiveType)?g=_oe(_):g=_.constructor.createGeometry(_),o[l++]=goe(s,g),r.push(s.id)}o.length=l;const u=t.scene3DOnly,h=t.mapProjection,f=PI.combineGeometry({instances:o,ellipsoid:h.ellipsoid,projection:h,elementIndexUintSupported:t.context.elementIndexUint,scene3DOnly:u,vertexCacheOptimize:e.vertexCacheOptimize,compressVertices:e.compressVertices,modelMatrix:e.modelMatrix,createPickOffsets:e._createPickOffsets});e._geometries=f.geometries,e._attributeLocations=f.attributeLocations,e.modelMatrix=L.clone(f.modelMatrix,e.modelMatrix),e._pickOffsets=f.pickOffsets,e._offsetInstanceExtend=f.offsetInstanceExtend,e._instanceBoundingSpheres=f.boundingSpheres,e._instanceBoundingSpheresCV=f.boundingSpheresCV,c(e._geometries)&&e._geometries.length>0?(e._recomputeBoundingSpheres=!0,e._state=Uo.COMBINED):Py(e,t,Uo.FAILED,void 0)}function woe(e,t){const n=e._batchTableAttributeIndices.offset;if(!e._recomputeBoundingSpheres||!c(n)){e._recomputeBoundingSpheres=!1;return}let i;const o=e._offsetInstanceExtend,r=e._instanceBoundingSpheres,s=r.length;let a=e._tempBoundingSpheres;if(!c(a)){for(a=new Array(s),i=0;i<s;i++)a[i]=new se;e._tempBoundingSpheres=a
#ifdef SPHERICAL
in vec4 v_sphericalExtents;
#else // SPHERICAL
in vec2 v_inversePlaneExtents;
in vec4 v_westPlane;
in vec4 v_southPlane;
#endif // SPHERICAL
in vec3 v_uvMinAndSphericalLongitudeRotation;
in vec3 v_uMaxAndInverseDistance;
in vec3 v_vMaxAndInverseDistance;
#endif // TEXTURE_COORDINATES
#ifdef PER_INSTANCE_COLOR
in vec4 v_color;
#endif
#ifdef NORMAL_EC
vec3 getEyeCoordinate3FromWindowCoordinate(vec2 fragCoord, float logDepthOrDepth) {
vec4 eyeCoordinate = czm_windowToEyeCoordinates(fragCoord, logDepthOrDepth);
return eyeCoordinate.xyz / eyeCoordinate.w;
}
vec3 vectorFromOffset(vec4 eyeCoordinate, vec2 positiveOffset) {
vec2 glFragCoordXY = gl_FragCoord.xy;
// Sample depths at both offset and negative offset
float upOrRightLogDepth = czm_unpackDepth(texture(czm_globeDepthTexture, (glFragCoordXY + positiveOffset) / czm_viewport.zw));
float downOrLeftLogDepth = czm_unpackDepth(texture(czm_globeDepthTexture, (glFragCoordXY - positiveOffset) / czm_viewport.zw));
// Explicitly evaluate both paths
// Necessary for multifrustum and for edges of the screen
bvec2 upOrRightInBounds = lessThan(glFragCoordXY + positiveOffset, czm_viewport.zw);
float useUpOrRight = float(upOrRightLogDepth > 0.0 && upOrRightInBounds.x && upOrRightInBounds.y);
float useDownOrLeft = float(useUpOrRight == 0.0);
vec3 upOrRightEC = getEyeCoordinate3FromWindowCoordinate(glFragCoordXY + positiveOffset, upOrRightLogDepth);
vec3 downOrLeftEC = getEyeCoordinate3FromWindowCoordinate(glFragCoordXY - positiveOffset, downOrLeftLogDepth);
return (upOrRightEC - (eyeCoordinate.xyz / eyeCoordinate.w)) * useUpOrRight + ((eyeCoordinate.xyz / eyeCoordinate.w) - downOrLeftEC) * useDownOrLeft;
}
#endif // NORMAL_EC
void main(void)
{
#ifdef REQUIRES_EC
float logDepthOrDepth = czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw));
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);
#endif
#ifdef REQUIRES_WC
vec4 worldCoordinate4 = czm_inverseView * eyeCoordinate;
vec3 worldCoordinate = worldCoordinate4.xyz / worldCoordinate4.w;
#endif
#ifdef TEXTURE_COORDINATES
vec2 uv;
#ifdef SPHERICAL
// Treat world coords as a sphere normal for spherical coordinates
vec2 sphericalLatLong = czm_approximateSphericalCoordinates(worldCoordinate);
sphericalLatLong.y += v_uvMinAndSphericalLongitudeRotation.z;
sphericalLatLong.y = czm_branchFreeTernary(sphericalLatLong.y < czm_pi, sphericalLatLong.y, sphericalLatLong.y - czm_twoPi);
uv.x = (sphericalLatLong.y - v_sphericalExtents.y) * v_sphericalExtents.w;
uv.y = (sphericalLatLong.x - v_sphericalExtents.x) * v_sphericalExtents.z;
#else // SPHERICAL
// Unpack planes and transform to eye space
uv.x = czm_planeDistance(v_westPlane, eyeCoordinate.xyz / eyeCoordinate.w) * v_inversePlaneExtents.x;
uv.y = czm_planeDistance(v_southPlane, eyeCoordinate.xyz / eyeCoordinate.w) * v_inversePlaneExtents.y;
#endif // SPHERICAL
#endif // TEXTURE_COORDINATES
#ifdef PICK
#ifdef CULL_FRAGMENTS
// When classifying translucent geometry, logDepthOrDepth == 0.0
// indicates a region that should not be classified, possibly due to there
// being opaque pixels there in another buffer.
// Check for logDepthOrDepth != 0.0 to make sure this should be classified.
if (0.0 <= uv.x && uv.x <= 1.0 && 0.0 <= uv.y && uv.y <= 1.0 || logDepthOrDepth != 0.0) {
out_FragColor.a = 1.0; // 0.0 alpha leads to discard from ShaderSource.createPickFragmentShaderSource
czm_writeDepthClamp();
}
#else // CULL_FRAGMENTS
out_FragColor.a = 1.0;
#endif // CULL_FRAGMENTS
#else // PICK
#ifdef CULL_FRAGMENTS
// When classifying translucent geometry, logDepthOrDepth == 0.0
// indicates a region that should not be classified, possibly due to there
// being opaque pixels there in another buffer.
if (uv.x <= 0.0 || 1.0 <= uv.x || uv.y <= 0.0 || 1.0 <= uv.y || logDepthOrDepth == 0.0) {
discard;
}
#endif
#ifdef NORMAL_EC
// Compute normal by sampling adjacent pixels in 2x2 block in screen space
vec3 downUp = vectorFromOffset(eyeCoordinate, vec2(0.0, 1.0));
vec3 leftRight = vectorFromOffset(eyeCoordinate, vec2(1.0, 0.0));
vec3 normalEC = normalize(cross(leftRight, downUp));
#endif
#ifdef PER_INSTANCE_COLOR
vec4 color = czm_gammaCorrect(v_color);
#ifdef FLAT
out_FragColor = color;
#else // FLAT
czm_materialInput materialInput;
materialInput.normalEC = normalEC;
materialInput.positionToEyeEC = -eyeCoordinate.xyz;
czm_material material = czm_getDefaultMaterial(materialInput);
material.diffuse = color.rgb;
material.alpha = color.a;
out_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);
#endif // FLAT
// Premultiply alpha. Required for classification primitives on translucent globe.
out_FragColor.rgb *= out_FragColor.a;
#else // PER_INSTANCE_COLOR
// Material support.
// USES_ is distinct from REQUIRES_, because some things are dependencies of each other or
// dependencies for culling but might not actually be used by the material.
czm_materialInput materialInput;
#ifdef USES_NORMAL_EC
materialInput.normalEC = normalEC;
#endif
#ifdef USES_POSITION_TO_EYE_EC
materialInput.positionToEyeEC = -eyeCoordinate.xyz;
#endif
#ifdef USES_TANGENT_TO_EYE
materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(worldCoordinate, normalEC);
#endif
#ifdef USES_ST
// Remap texture coordinates from computed (approximately aligned with cartographic space) to the desired
// texture coordinate system, which typically forms a tight oriented bounding box around the geometry.
// Shader is provided a set of reference points for remapping.
materialInput.st.x = czm_lineDistance(v_uvMinAndSphericalLongitudeRotation.xy, v_uMaxAndInverseDistance.xy, uv) * v_uMaxAndInverseDistance.z;
materialInput.st.y = czm_lineDistance(v_uvMinAndSphericalLongitudeRotation.xy, v_vMaxAndInverseDistance.xy, uv) * v_vMaxAndInverseDistance.z;
#endif
czm_material material = czm_getMaterial(materialInput);
#ifdef FLAT
out_FragColor = vec4(material.diffuse + material.emission, material.alpha);
#else // FLAT
out_FragColor = czm_phong(normalize(-eyeCoordinate.xyz), material, czm_lightDirectionEC);
#endif // FLAT
// Premultiply alpha. Required for classification primitives on translucent globe.
out_FragColor.rgb *= out_FragColor.a;
#endif // PER_INSTANCE_COLOR
czm_writeDepthClamp();
#endif // PICK
}
`;function Sr(e,t,n){A.typeOf.bool("extentsCulling",e),A.typeOf.bool("planarExtents",t),A.typeOf.object("appearance",n),this._projectionExtentDefines={eastMostYhighDefine:"",eastMostYlowDefine:"",westMostYhighDefine:"",westMostYlowDefine:""};const i=new OI;i.requiresTextureCoordinates=e,i.requiresEC=!n.flat;const o=new OI;if(o.requiresTextureCoordinates=e,n instanceof tn)i.requiresNormalEC=!n.flat;else{const r=`${n.material.shaderSource}
${n.fragmentShaderSource}`;i.normalEC=r.indexOf("materialInput.normalEC")!==-1||r.indexOf("czm_getDefaultMaterial")!==-1,i.positionToEyeEC=r.indexOf("materialInput.positionToEyeEC")!==-1,i.tangentToEyeMatrix=r.indexOf("materialInput.tangentToEyeMatrix")!==-1,i.st=r.indexOf("materialInput.st")!==-1}this._colorShaderDependencies=i,this._pickShaderDependencies=o,this._appearance=n,this._extentsCulling=e,this._planarExtents=t}Sr.prototype.createFragmentShader=function(e){A.typeOf.bool("columbusView2D",e);const t=this._appearance,n=this._colorShaderDependencies,i=[];!e&&!this._planarExtents&&i.push("SPHERICAL"),n.requiresEC&&i.push("REQUIRES_EC"),n.requiresWC&&i.push("REQUIRES_WC"),n.requiresTextureCoordinates&&i.push("TEXTURE_COORDINATES"),this._extentsCulling&&i.push("CULL_FRAGMENTS"),n.requiresNormalEC&&i.push("NORMAL_EC"),t instanceof tn&&i.push("PER_INSTANCE_COLOR"),n.normalEC&&i.push("USES_NORMAL_EC"),n.positionToEyeEC&&i.push("USES_POSITION_TO_EYE_EC"),n.tangentToEyeMatrix&&i.push("USES_TANGENT_TO_EYE"),n.st&&i.push("USES_ST"),t.flat&&i.push("FLAT");let o="";return t instanceof tn||(o=t.material.shaderSource),new Oe({defines:i,sources:[o,dV]})};Sr.prototype.createPickFragmentShader=function(e){A.typeOf.bool("columbusView2D",e);const t=this._pickShaderDependencies,n=["PICK"];return!e&&!this._planarExtents&&n.push("SPHERICAL"),t.requiresEC&&n.push("REQUIRES_EC"),t.requiresWC&&n.push("REQUIRES_WC"),t.requiresTextureCoordinates&&n.push("TEXTURE_COORDINATES"),this._extentsCulling&&n.push("CULL_FRAGMENTS"),new Oe({defines:n,sources:[dV],pickColorQualifier:"in"})};Sr.prototype.createVertexShader=function(e,t,n,i){return A.defined("defines",e),A.typeOf.string("vertexShaderSource",t),A.typeOf.bool("columbusView2D",n),A.defined("mapProjection",i),hV(this._colorShaderDependencies,this._planarExtents,n,e,t,this._appearance,i,this._projectionExtentDefines)};Sr.prototype.createPickVertexShader=function(e,t,n,i){return A.defined("defines",e),A.typeOf.string("vertexShaderSource",t),A.typeOf.bool("columbusView2D",n),A.defined("mapProjection",i),hV(this._pickShaderDependencies,this._planarExtents,n,e,t,void 0,i,this._projectionExtentDefines)};const TN=new d,AN=new he,xN={high:0,low:0};function hV(e,t,n,i,o,r,s,a){const l=i.slice();if(a.eastMostYhighDefine===""){const u=AN;u.longitude=R.PI,u.latitude=0,u.height=0;const h=s.project(u,TN);let f=rn.encode(h.x,xN);a.eastMostYhighDefine=`EAST_MOST_X_HIGH ${f.high.toFixed(`${f.high}`.length+1)}`,a.eastMostYlowDefine=`EAST_MOST_X_LOW ${f.low.toFixed(`${f.low}`.length+1)}`;const _=AN;_.longitude=-R.PI,_.latitude=0,_.height=0;const g=s.project(_,TN);f=rn.encode(g.x,xN),a.westMostYhighDefine=`WEST_MOST_X_HIGH ${f.high.toFixed(`${f.high}`.length+1)}`,a.westMostYlowDefine=`WEST_MOST_X_LOW ${f.low.toFixed(`${f.low}`.length+1)}`}return n&&(l.push(a.eastMostYhighDefine),l.push(a.eastMostYlowDefine),l.push(a.westMostYhighDefine),l.push(a.westMostYlowDefine)),c(r)&&r instanceof tn&&l.push("PER_INSTANCE_COLOR"),e.requiresTextureCoordinates&&(l.push("TEXTURE_COORDINATES"),t||n||l.push("SPHERICAL"),n&&l.push("COLUMBUS_VIEW_2D")),new Oe({defines:l,sources:[o]})}function OI(){this._requiresEC=!1,this._requiresWC=!1,this._requiresNormalEC=!1,this._requiresTextureCoordinates=!1,this._usesNormalEC=!1,this._usesPositionToEyeEC=!1,this._usesTangentToEyeMat=!1,this._usesSt=!1}Object.defineProperties(OI.prototype,{requiresEC:{get:function(){return this._requiresEC},set:function(e){this._requiresEC=e||this._requiresEC}},requiresWC:{get:function(){return this._requiresWC},set:function(e){this._requiresWC=e||this._requiresWC,this.requiresEC=this._requiresWC}},requiresNormalEC:{get:function(){return this._requiresNormalEC},set:function(e){this._requiresNormalEC=e||this._requiresNormalEC,this.requiresEC=this._requiresNormalEC}},requiresTextureCoordinates:{get:function(){return this._requiresTextureCoordinates},set:function(e){this._requiresTextureCoordinates=e||this._requiresTextureCoordinates,this.requiresWC=this._requiresTextureCoordinates}},normalEC:{set:function(e){this.requiresNormalEC=e,this._usesNormalEC=e},get:f
`,r=` extrudeDirection = czm_octDecode(${n}, 65535.0);
`;let s=t;s=s.replace(/in\s+vec3\s+extrudeDirection;/g,""),s=Oe.replaceMain(s,"czm_non_compressed_main");const a=`void main()
{
${r} czm_non_compressed_main();
}`;return[i,o,s,a].join(`
`)}}function ore(e,t){const n=t.context,i=e._primitive;let o=sie;o=e._primitive._batchTable.getVertexShaderCallback()(o),o=Mt._appendDistanceDisplayConditionToShader(i,o),o=Mt._modifyShaderPosition(e,o,t.scene3DOnly),o=Mt._updateColorAttribute(i,o);const r=e._hasPlanarExtentsAttributes,s=r||e._hasSphericalExtentsAttribute;e._extruded&&(o=ire(i,o));const a=e._extruded?"EXTRUDED_GEOMETRY":"";let l=new Oe({defines:[a],sources:[o]});const u=new Oe({sources:[wI]}),h=e._primitive._attributeLocations,f=new Sr(s,r,e.appearance);if(e._spStencil=Jt.replaceCache({context:n,shaderProgram:e._spStencil,vertexShaderSource:l,fragmentShaderSource:u,attributeLocations:h}),e._primitive.allowPicking){let m=Oe.createPickVertexShaderSource(o);m=Mt._appendShowToShader(i,m),m=Mt._updatePickColorAttribute(m);const b=f.createPickFragmentShader(!1),T=f.createPickVertexShader([a],m,!1,t.mapProjection);if(e._spPick=Jt.replaceCache({context:n,shaderProgram:e._spPick,vertexShaderSource:T,fragmentShaderSource:b,attributeLocations:h}),s){let x=n.shaderCache.getDerivedShaderProgram(e._spPick,"2dPick");if(!c(x)){const C=f.createPickFragmentShader(!0),w=f.createPickVertexShader([a],m,!0,t.mapProjection);x=n.shaderCache.createDerivedShaderProgram(e._spPick,"2dPick",{vertexShaderSource:w,fragmentShaderSource:C,attributeLocations:h})}e._spPick2D=x}}else e._spPick=Jt.fromCache({context:n,vertexShaderSource:l,fragmentShaderSource:u,attributeLocations:h});o=Mt._appendShowToShader(i,o),l=new Oe({defines:[a],sources:[o]}),e._sp=Jt.replaceCache({context:n,shaderProgram:e._sp,vertexShaderSource:l,fragmentShaderSource:u,attributeLocations:h});const _=f.createFragmentShader(!1),g=f.createVertexShader([a],o,!1,t.mapProjection);if(e._spColor=Jt.replaceCache({context:n,shaderProgram:e._spColor,vertexShaderSource:g,fragmentShaderSource:_,attributeLocations:h}),s){let m=n.shaderCache.getDerivedShaderProgram(e._spColor,"2dColor");if(!c(m)){const b=f.createFragmentShader(!0),T=f.createVertexShader([a],o,!0,t.mapProjection);m=n.shaderCache.createDerivedShaderProgram(e._spColor,"2dColor",{vertexShaderSource:T,fragmentShaderSource:b,attributeLocations:h})}e._spColor2D=m}}function rre(e,t){const n=e._primitive;let i=n._va.length*2;t.length=i;let o,r,s,a=0,l=n._batchTable.getUniformMapCallback()(e._uniformMap);const u=e._needs2DShader;for(o=0;o<i;o+=2){const g=n._va[a++];r=t[o],c(r)||(r=t[o]=new Ze({owner:e,primitiveType:n._primitiveType})),r.vertexArray=g,r.renderState=e._rsStencilDepthPass,r.shaderProgram=e._sp,r.uniformMap=l,r.pass=xe.TERRAIN_CLASSIFICATION,s=Ze.shallowClone(r,r.derivedCommands.tileset),s.renderState=e._rsStencilDepthPass3DTiles,s.pass=xe.CESIUM_3D_TILE_CLASSIFICATION,r.derivedCommands.tileset=s,r=t[o+1],c(r)||(r=t[o+1]=new Ze({owner:e,primitiveType:n._primitiveType})),r.vertexArray=g,r.renderState=e._rsColorPass,r.shaderProgram=e._spColor,r.pass=xe.TERRAIN_CLASSIFICATION;const b=e.appearance.material;if(c(b)&&(l=jt(l,b._uniforms)),r.uniformMap=l,s=Ze.shallowClone(r,r.derivedCommands.tileset),s.pass=xe.CESIUM_3D_TILE_CLASSIFICATION,r.derivedCommands.tileset=s,u){let T=Ze.shallowClone(r,r.derivedCommands.appearance2D);T.shaderProgram=e._spColor2D,r.derivedCommands.appearance2D=T,T=Ze.shallowClone(s,s.derivedCommands.appearance2D),T.shaderProgram=e._spColor2D,s.derivedCommands.appearance2D=T}}const h=e._commandsIgnoreShow,f=e._spStencil;let _=0;i=h.length=i/2;for(let g=0;g<i;++g){const m=h[g]=Ze.shallowClone(t[_],h[g]);m.shaderProgram=f,m.pass=xe.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW,_+=2}}function sre(e,t){const n=e._usePickOffsets,i=e._primitive;let o=i._va.length*2,r,s=0,a;n&&(r=i._pickOffsets,o=r.length*2),t.length=o;let l,u,h,f=0;const _=i._batchTable.getUniformMapCallback()(e._uniformMap),g=e._needs2DShader;for(l=0;l<o;l+=2){let m=i._va[f++];if(n&&(a=r[s++],m=i._va[a.index]),u=t[l],c(u)||(u=t[l]=new Ze({owner:e,primitiveType:i._primitiveType,pickOnly:!0})),u.vertexArray=m,u.renderState=e._rsStencilDepthPass,u.shaderProgram=e._sp,u.uniformMap=_,u.pass=xe.TERRAIN_CLASSIFICATION,n&&(u.offset=a.offset,u.count=a.count),h=Ze.shallowClone(u,u.derivedCommands
in vec4 v_endPlaneNormalEcAndBatchId;
in vec4 v_rightPlaneEC; // Technically can compute distance for this here
in vec4 v_endEcAndStartEcX;
in vec4 v_texcoordNormalizationAndStartEcYZ;
#ifdef PER_INSTANCE_COLOR
in vec4 v_color;
#endif
void main(void)
{
float logDepthOrDepth = czm_branchFreeTernary(czm_sceneMode == czm_sceneMode2D, gl_FragCoord.z, czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw)));
vec3 ecStart = vec3(v_endEcAndStartEcX.w, v_texcoordNormalizationAndStartEcYZ.zw);
// Discard for sky
if (logDepthOrDepth == 0.0) {
#ifdef DEBUG_SHOW_VOLUME
out_FragColor = vec4(1.0, 0.0, 0.0, 0.5);
return;
#else // DEBUG_SHOW_VOLUME
discard;
#endif // DEBUG_SHOW_VOLUME
}
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);
eyeCoordinate /= eyeCoordinate.w;
float halfMaxWidth = v_startPlaneNormalEcAndHalfWidth.w * czm_metersPerPixel(eyeCoordinate);
// Check distance of the eye coordinate against the right-facing plane
float widthwiseDistance = czm_planeDistance(v_rightPlaneEC, eyeCoordinate.xyz);
// Check eye coordinate against the mitering planes
float distanceFromStart = czm_planeDistance(v_startPlaneNormalEcAndHalfWidth.xyz, -dot(ecStart, v_startPlaneNormalEcAndHalfWidth.xyz), eyeCoordinate.xyz);
float distanceFromEnd = czm_planeDistance(v_endPlaneNormalEcAndBatchId.xyz, -dot(v_endEcAndStartEcX.xyz, v_endPlaneNormalEcAndBatchId.xyz), eyeCoordinate.xyz);
if (abs(widthwiseDistance) > halfMaxWidth || distanceFromStart < 0.0 || distanceFromEnd < 0.0) {
#ifdef DEBUG_SHOW_VOLUME
out_FragColor = vec4(1.0, 0.0, 0.0, 0.5);
return;
#else // DEBUG_SHOW_VOLUME
discard;
#endif // DEBUG_SHOW_VOLUME
}
// Check distance of the eye coordinate against start and end planes with normals in the right plane.
// For computing unskewed lengthwise texture coordinate.
// Can also be used for clipping extremely pointy miters, but in practice unnecessary because of miter breaking.
// aligned plane: cross the right plane normal with miter plane normal, then cross the result with right again to point it more "forward"
vec3 alignedPlaneNormal;
// start aligned plane
alignedPlaneNormal = cross(v_rightPlaneEC.xyz, v_startPlaneNormalEcAndHalfWidth.xyz);
alignedPlaneNormal = normalize(cross(alignedPlaneNormal, v_rightPlaneEC.xyz));
distanceFromStart = czm_planeDistance(alignedPlaneNormal, -dot(alignedPlaneNormal, ecStart), eyeCoordinate.xyz);
// end aligned plane
alignedPlaneNormal = cross(v_rightPlaneEC.xyz, v_endPlaneNormalEcAndBatchId.xyz);
alignedPlaneNormal = normalize(cross(alignedPlaneNormal, v_rightPlaneEC.xyz));
distanceFromEnd = czm_planeDistance(alignedPlaneNormal, -dot(alignedPlaneNormal, v_endEcAndStartEcX.xyz), eyeCoordinate.xyz);
#ifdef PER_INSTANCE_COLOR
out_FragColor = czm_gammaCorrect(v_color);
#else // PER_INSTANCE_COLOR
// Clamp - distance to aligned planes may be negative due to mitering,
// so fragment texture coordinate might be out-of-bounds.
float s = clamp(distanceFromStart / (distanceFromStart + distanceFromEnd), 0.0, 1.0);
s = (s * v_texcoordNormalizationAndStartEcYZ.x) + v_texcoordNormalizationAndStartEcYZ.y;
float t = (widthwiseDistance + halfMaxWidth) / (2.0 * halfMaxWidth);
czm_materialInput materialInput;
materialInput.s = s;
materialInput.st = vec2(s, t);
materialInput.str = vec3(s, t, 0.0);
czm_material material = czm_getMaterial(materialInput);
out_FragColor = vec4(material.diffuse + material.emission, material.alpha);
#endif // PER_INSTANCE_COLOR
// Premultiply alpha. Required for classification primitives on translucent globe.
out_FragColor.rgb *= out_FragColor.a;
czm_writeDepthClamp();
}
`,_se=`in vec3 v_forwardDirectionEC;
in vec3 v_texcoordNormalizationAndHalfWidth;
in float v_batchId;
#ifdef PER_INSTANCE_COLOR
in vec4 v_color;
#else
in vec2 v_alignedPlaneDistances;
in float v_texcoordT;
#endif
float rayPlaneDistanceUnsafe(vec3 origin, vec3 direction, vec3 planeNormal, float planeDistance) {
// We don't expect the ray to ever be parallel to the plane
return (-planeDistance - dot(planeNormal, origin)) / dot(planeNormal, direction);
}
void main(void)
{
vec4 eyeCoordinate = gl_FragCoord;
eyeCoordinate /= eyeCoordinate.w;
#ifdef PER_INSTANCE_COLOR
out_FragColor = czm_gammaCorrect(v_color);
#else // PER_INSTANCE_COLOR
// Use distances for planes aligned with segment to prevent skew in dashing
float distanceFromStart = rayPlaneDistanceUnsafe(eyeCoordinate.xyz, -v_forwardDirectionEC, v_forwardDirectionEC.xyz, v_alignedPlaneDistances.x);
float distanceFromEnd = rayPlaneDistanceUnsafe(eyeCoordinate.xyz, v_forwardDirectionEC, -v_forwardDirectionEC.xyz, v_alignedPlaneDistances.y);
// Clamp - distance to aligned planes may be negative due to mitering
distanceFromStart = max(0.0, distanceFromStart);
distanceFromEnd = max(0.0, distanceFromEnd);
float s = distanceFromStart / (distanceFromStart + distanceFromEnd);
s = (s * v_texcoordNormalizationAndHalfWidth.x) + v_texcoordNormalizationAndHalfWidth.y;
czm_materialInput materialInput;
materialInput.s = s;
materialInput.st = vec2(s, v_texcoordT);
materialInput.str = vec3(s, v_texcoordT, 0.0);
czm_material material = czm_getMaterial(materialInput);
out_FragColor = vec4(material.diffuse + material.emission, material.alpha);
#endif // PER_INSTANCE_COLOR
}
`,gse=`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
}
`,yse=`in vec3 position3DHigh;
in vec3 position3DLow;
// In 2D and in 3D, texture coordinate normalization component signs encodes:
// * X sign - sidedness relative to right plane
// * Y sign - is negative OR magnitude is greater than 1.0 if vertex is on bottom of volume
#ifndef COLUMBUS_VIEW_2D
in vec4 startHiAndForwardOffsetX;
in vec4 startLoAndForwardOffsetY;
in vec4 startNormalAndForwardOffsetZ;
in vec4 endNormalAndTextureCoordinateNormalizationX;
in vec4 rightNormalAndTextureCoordinateNormalizationY;
#else
in vec4 startHiLo2D;
in vec4 offsetAndRight2D;
in vec4 startEndNormals2D;
in vec2 texcoordNormalization2D;
#endif
in float batchId;
out vec4 v_startPlaneNormalEcAndHalfWidth;
out vec4 v_endPlaneNormalEcAndBatchId;
out vec4 v_rightPlaneEC;
out vec4 v_endEcAndStartEcX;
out vec4 v_texcoordNormalizationAndStartEcYZ;
// 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;
#endif
void main()
{
#ifdef COLUMBUS_VIEW_2D
vec3 ecStart = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(vec3(0.0, startHiLo2D.xy), vec3(0.0, startHiLo2D.zw))).xyz;
vec3 forwardDirectionEC = czm_normal * vec3(0.0, offsetAndRight2D.xy);
vec3 ecEnd = forwardDirectionEC + ecStart;
forwardDirectionEC = normalize(forwardDirectionEC);
// Right plane
v_rightPlaneEC.xyz = czm_normal * vec3(0.0, offsetAndRight2D.zw);
v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);
// start plane
vec4 startPlaneEC;
startPlaneEC.xyz = czm_normal * vec3(0.0, startEndNormals2D.xy);
startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);
// end plane
vec4 endPlaneEC;
endPlaneEC.xyz = czm_normal * vec3(0.0, startEndNormals2D.zw);
endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);
v_texcoordNormalizationAndStartEcYZ.x = abs(texcoordNormalization2D.x);
v_texcoordNormalizationAndStartEcYZ.y = texcoordNormalization2D.y;
#else // COLUMBUS_VIEW_2D
vec3 ecStart = (czm_modelViewRelativeToEye * czm_translateRelativeToEye(startHiAndForwardOffsetX.xyz, startLoAndForwardOffsetY.xyz)).xyz;
vec3 offset = czm_normal * vec3(startHiAndForwardOffsetX.w, startLoAndForwardOffsetY.w, startNormalAndForwardOffsetZ.w);
vec3 ecEnd = ecStart + offset;
vec3 forwardDirectionEC = normalize(offset);
// start plane
vec4 startPlaneEC;
startPlaneEC.xyz = czm_normal * startNormalAndForwardOffsetZ.xyz;
startPlaneEC.w = -dot(startPlaneEC.xyz, ecStart);
// end plane
vec4 endPlaneEC;
endPlaneEC.xyz = czm_normal * endNormalAndTextureCoordinateNormalizationX.xyz;
endPlaneEC.w = -dot(endPlaneEC.xyz, ecEnd);
// Right plane
v_rightPlaneEC.xyz = czm_normal * rightNormalAndTextureCoordinateNormalizationY.xyz;
v_rightPlaneEC.w = -dot(v_rightPlaneEC.xyz, ecStart);
v_texcoordNormalizationAndStartEcYZ.x = abs(endNormalAndTextureCoordinateNormalizationX.w);
v_texcoordNormalizationAndStartEcYZ.y = rightNormalAndTextureCoordinateNormalizationY.w;
#endif // COLUMBUS_VIEW_2D
v_endEcAndStartEcX.xyz = ecEnd;
v_endEcAndStartEcX.w = ecStart.x;
v_texcoordNormalizationAndStartEcYZ.zw = ecStart.yz;
#ifdef PER_INSTANCE_COLOR
v_color = czm_batchTable_color(batchId);
#endif // PER_INSTANCE_COLOR
// 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.
vec4 positionRelativeToEye = czm_computePosition();
// Check distance to the end plane and start plane, pick the plane that is closer
vec4 positionEC = czm_modelViewRelativeToEye * positionRelativeToEye; // w = 1.0, see czm_computePosition
float absStartPlaneDistance = abs(czm_planeDistance(startPlaneEC, positionEC.xyz));
float absEndPlaneDistance = abs(czm_planeDistance(endPlaneEC, positionEC.xyz));
vec3 planeDirection = czm_branchFreeTernary(absStartPlaneDistance < absEndPlaneDistance, startPlaneEC.xyz, endPlaneEC.xyz);
vec3 upOrDown = normalize(cross(v_rightPlaneEC.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.
// Extrude bottom vertices downward for far view distances, like for GroundPrimitives
upOrDown = cross(forwardDirectionEC, normalEC);
upOrDown = float(czm_sceneMode == czm_sceneMode3D) * upOrDown;
upOrDown = float(v_texcoordNormalizationAndStartEcYZ.y > 1.0 || v_texcoordNormalizationAndStartEcYZ.y < 0.0) * upOrDown;
upOrDown = min(GLOBE_MINIMUM_ALTITUDE, czm_geometricToleranceOverMeter * length(positionRelativeToEye.xyz)) * upOrDown;
positionEC.xyz += upOrDown;
v_texcoordNormalizationAndStartEcYZ.y = czm_branchFreeTernary(v_texcoordNormalizationAndStartEcYZ.y > 1.0, 0.0, abs(v_texcoordNormalizationAndStartEcYZ.y));
// Determine distance along normalEC to push for a volume of appropriate width.
// Make volumes about double pixel width for a conservative fit - in practice the
// extra cost here is minimal compared to the loose volume heights.
//
// N = normalEC (guaranteed "right-facing")
// R = rightEC
// p = angle between N and R
// w = distance to push along R if R == N
// d = distance to push along N
//
// N R
// { p| } * cos(p) = dot(N, R) = w / d
// d | |w * d = w / dot(N, R)
// { | }
// o---------- polyline segment ---->
//
float width = czm_batchTable_width(batchId);
#ifdef WIDTH_VARYING
v_width = width;
#endif
v_startPlaneNormalEcAndHalfWidth.xyz = startPlaneEC.xyz;
v_startPlaneNormalEcAndHalfWidth.w = width * 0.5;
v_endPlaneNormalEcAndBatchId.xyz = endPlaneEC.xyz;
v_endPlaneNormalEcAndBatchId.w = batchId;
width = width * max(0.0, czm_metersPerPixel(positionEC)); // width = distance to push along R
width = width / dot(normalEC, v_rightPlaneEC.xyz); // width = distance to push along N
// Determine if this vertex is on the "left" or "right"
#ifdef COLUMBUS_VIEW_2D
normalEC *= sign(texcoordNormalization2D.x);
#else
normalEC *= sign(endNormalAndTextureCoordinateNormalizationX.w);
#endif
positionEC.xyz += width * normalEC;
gl_Position = czm_depthClamp(czm_projection * positionEC);
#ifdef ANGLE_VARYING
// Approximate relative screen space direction of the line.
vec2 approxLineDirection = normalize(vec2(forwardDirectionEC.x, -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
}
`,bse=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec3 prevPosition3DHigh;
in vec3 prevPosition3DLow;
in vec3 nextPosition3DHigh;
in vec3 nextPosition3DLow;
in vec2 expandAndWidth;
in vec4 color;
in float batchId;
out vec4 v_color;
void main()
{
float expandDir = expandAndWidth.x;
float width = abs(expandAndWidth.y) + 0.5;
bool usePrev = expandAndWidth.y < 0.0;
vec4 p = czm_computePosition();
vec4 prev = czm_computePrevPosition();
vec4 next = czm_computeNextPosition();
float angle;
vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);
gl_Position = czm_viewportOrthographic * positionWC;
v_color = color;
}
`,M0=`void clipLineSegmentToNearPlane(
vec3 p0,
vec3 p1,
out vec4 positionWC,
out bool clipped,
out bool culledByNearPlane,
out vec4 clippedPositionEC)
{
culledByNearPlane = false;
clipped = false;
vec3 p0ToP1 = p1 - p0;
float magnitude = length(p0ToP1);
vec3 direction = normalize(p0ToP1);
// Distance that p0 is behind the near plane. Negative means p0 is
// in front of the near plane.
float endPoint0Distance = czm_currentFrustum.x + p0.z;
// Camera looks down -Z.
// When moving a point along +Z: LESS VISIBLE
// * Points in front of the camera move closer to the camera.
// * Points behind the camrea move farther away from the camera.
// When moving a point along -Z: MORE VISIBLE
// * Points in front of the camera move farther away from the camera.
// * Points behind the camera move closer to the camera.
// Positive denominator: -Z, becoming more visible
// Negative denominator: +Z, becoming less visible
// Nearly zero: parallel to near plane
float denominator = -direction.z;
if (endPoint0Distance > 0.0 && abs(denominator) < czm_epsilon7)
{
// p0 is behind the near plane and the line to p1 is nearly parallel to
// the near plane, so cull the segment completely.
culledByNearPlane = true;
}
else if (endPoint0Distance > 0.0)
{
// p0 is behind the near plane, and the line to p1 is moving distinctly
// toward or away from it.
// t = (-plane distance - dot(plane normal, ray origin)) / dot(plane normal, ray direction)
float t = endPoint0Distance / denominator;
if (t < 0.0 || t > magnitude)
{
// Near plane intersection is not between the two points.
// We already confirmed p0 is behind the naer plane, so now
// we know the entire segment is behind it.
culledByNearPlane = true;
}
else
{
// Segment crosses the near plane, update p0 to lie exactly on it.
p0 = p0 + t * direction;
// Numerical noise might put us a bit on the wrong side of the near plane.
// Don't let that happen.
p0.z = min(p0.z, -czm_currentFrustum.x);
clipped = true;
}
}
clippedPositionEC = vec4(p0, 1.0);
positionWC = czm_eyeToWindowCoordinates(clippedPositionEC);
}
vec4 getPolylineWindowCoordinatesEC(vec4 positionEC, vec4 prevEC, vec4 nextEC, float expandDirection, float width, bool usePrevious, out float angle)
{
// expandDirection +1 is to the _left_ when looking from positionEC toward nextEC.
#ifdef POLYLINE_DASH
// Compute the window coordinates of the points.
vec4 positionWindow = czm_eyeToWindowCoordinates(positionEC);
vec4 previousWindow = czm_eyeToWindowCoordinates(prevEC);
vec4 nextWindow = czm_eyeToWindowCoordinates(nextEC);
// Determine the relative screen space direction of the line.
vec2 lineDir;
if (usePrevious) {
lineDir = normalize(positionWindow.xy - previousWindow.xy);
}
else {
lineDir = normalize(nextWindow.xy - positionWindow.xy);
}
angle = atan(lineDir.x, lineDir.y) - 1.570796327; // precomputed atan(1,0)
// Quantize the angle so it doesn't change rapidly between segments.
angle = floor(angle / czm_piOverFour + 0.5) * czm_piOverFour;
#endif
vec4 clippedPrevWC, clippedPrevEC;
bool prevSegmentClipped, prevSegmentCulled;
clipLineSegmentToNearPlane(prevEC.xyz, positionEC.xyz, clippedPrevWC, prevSegmentClipped, prevSegmentCulled, clippedPrevEC);
vec4 clippedNextWC, clippedNextEC;
bool nextSegmentClipped, nextSegmentCulled;
clipLineSegmentToNearPlane(nextEC.xyz, positionEC.xyz, clippedNextWC, nextSegmentClipped, nextSegmentCulled, clippedNextEC);
bool segmentClipped, segmentCulled;
vec4 clippedPositionWC, clippedPositionEC;
clipLineSegmentToNearPlane(positionEC.xyz, usePrevious ? prevEC.xyz : nextEC.xyz, clippedPositionWC, segmentClipped, segmentCulled, clippedPositionEC);
if (segmentCulled)
{
return vec4(0.0, 0.0, 0.0, 1.0);
}
vec2 directionToPrevWC = normalize(clippedPrevWC.xy - clippedPositionWC.xy);
vec2 directionToNextWC = normalize(clippedNextWC.xy - clippedPositionWC.xy);
// If a segment was culled, we can't use the corresponding direction
// computed above. We should never see both of these be true without
// \`segmentCulled\` above also being true.
if (prevSegmentCulled)
{
directionToPrevWC = -directionToNextWC;
}
else if (nextSegmentCulled)
{
directionToNextWC = -directionToPrevWC;
}
vec2 thisSegmentForwardWC, otherSegmentForwardWC;
if (usePrevious)
{
thisSegmentForwardWC = -directionToPrevWC;
otherSegmentForwardWC = directionToNextWC;
}
else
{
thisSegmentForwardWC = directionToNextWC;
otherSegmentForwardWC = -directionToPrevWC;
}
vec2 thisSegmentLeftWC = vec2(-thisSegmentForwardWC.y, thisSegmentForwardWC.x);
vec2 leftWC = thisSegmentLeftWC;
float expandWidth = width * 0.5;
// When lines are split at the anti-meridian, the position may be at the
// same location as the next or previous position, and we need to handle
// that to avoid producing NaNs.
if (!czm_equalsEpsilon(prevEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1) && !czm_equalsEpsilon(nextEC.xyz - positionEC.xyz, vec3(0.0), czm_epsilon1))
{
vec2 otherSegmentLeftWC = vec2(-otherSegmentForwardWC.y, otherSegmentForwardWC.x);
vec2 leftSumWC = thisSegmentLeftWC + otherSegmentLeftWC;
float leftSumLength = length(leftSumWC);
leftWC = leftSumLength < czm_epsilon6 ? thisSegmentLeftWC : (leftSumWC / leftSumLength);
// The sine of the angle between the two vectors is given by the formula
// |a x b| = |a||b|sin(theta)
// which is
// float sinAngle = length(cross(vec3(leftWC, 0.0), vec3(-thisSegmentForwardWC, 0.0)));
// Because the z components of both vectors are zero, the x and y coordinate will be zero.
// Therefore, the sine of the angle is just the z component of the cross product.
vec2 u = -thisSegmentForwardWC;
vec2 v = leftWC;
float sinAngle = abs(u.x * v.y - u.y * v.x);
expandWidth = clamp(expandWidth / sinAngle, 0.0, width * 2.0);
}
vec2 offset = leftWC * expandDirection * expandWidth * czm_pixelRatio;
return vec4(clippedPositionWC.xy + offset, -clippedPositionWC.z, 1.0) * (czm_projection * clippedPositionEC).w;
}
vec4 getPolylineWindowCoordinates(vec4 position, vec4 previous, vec4 next, float expandDirection, float width, bool usePrevious, out float angle)
{
vec4 positionEC = czm_modelViewRelativeToEye * position;
vec4 prevEC = czm_modelViewRelativeToEye * previous;
vec4 nextEC = czm_modelViewRelativeToEye * next;
return getPolylineWindowCoordinatesEC(positionEC, prevEC, nextEC, expandDirection, width, usePrevious, angle);
}
`;let MI=`${M0}
${bse}`;const Tse=jk;Yt.isInternetExplorer()||(MI=`#define CLIP_POLYLINE
${MI}`);function ds(e){e=y(e,y.EMPTY_OBJECT);const t=y(e.translucent,!0),n=!1,i=ds.VERTEX_FORMAT;this.material=void 0,this.translucent=t,this._vertexShaderSource=y(e.vertexShaderSource,MI),this._fragmentShaderSource=y(e.fragmentShaderSource,Tse),this._renderState=Lo.getDefaultRenderState(t,n,e.renderState),this._closed=n,this._vertexFormat=i}Object.defineProperties(ds.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}}});ds.VERTEX_FORMAT=Ee.POSITION_ONLY;ds.prototype.getFragmentShaderSource=Lo.prototype.getFragmentShaderSource;ds.prototype.isTranslucent=Lo.prototype.isTranslucent;ds.prototype.getRenderState=Lo.prototype.getRenderState;const Ase=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec3 prevPosition3DHigh;
in vec3 prevPosition3DLow;
in vec3 nextPosition3DHigh;
in vec3 nextPosition3DLow;
in vec2 expandAndWidth;
in vec2 st;
in float batchId;
out float v_width;
out vec2 v_st;
out float v_polylineAngle;
void main()
{
float expandDir = expandAndWidth.x;
float width = abs(expandAndWidth.y) + 0.5;
bool usePrev = expandAndWidth.y < 0.0;
vec4 p = czm_computePosition();
vec4 prev = czm_computePrevPosition();
vec4 next = czm_computeNextPosition();
float angle;
vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, angle);
gl_Position = czm_viewportOrthographic * positionWC;
v_width = width;
v_st.s = st.s;
v_st.t = czm_writeNonPerspective(st.t, gl_Position.w);
v_polylineAngle = angle;
}
`,IV=`#ifdef VECTOR_TILE
uniform vec4 u_highlightColor;
#endif
in vec2 v_st;
void main()
{
czm_materialInput materialInput;
vec2 st = v_st;
st.t = czm_readNonPerspective(st.t, gl_FragCoord.w);
materialInput.s = st.s;
materialInput.st = st;
materialInput.str = vec3(st, 0.0);
czm_material material = czm_getMaterial(materialInput);
out_FragColor = vec4(material.diffuse + material.emission, material.alpha);
#ifdef VECTOR_TILE
out_FragColor *= u_highlightColor;
#endif
czm_writeLogDepth();
}
`;let FI=`${M0}
${Ase}`;const xse=IV;Yt.isInternetExplorer()||(FI=`#define CLIP_POLYLINE
${FI}`);function Ur(e){e=y(e,y.EMPTY_OBJECT);const t=y(e.translucent,!0),n=!1,i=Ur.VERTEX_FORMAT;this.material=c(e.material)?e.material:Se.fromType(Se.ColorType),this.translucent=t,this._vertexShaderSource=y(e.vertexShaderSource,FI),this._fragmentShaderSource=y(e.fragmentShaderSource,xse),this._renderState=Lo.getDefaultRenderState(t,n,e.renderState),this._closed=n,this._vertexFormat=i}Object.defineProperties(Ur.prototype,{vertexShaderSource:{get:function(){let e=this._vertexShaderSource;return this.material.shaderSource.search(/in\s+float\s+v_polylineAngle;/g)!==-1&&(e=`#define POLYLINE_DASH
${e}`),e}},fragmentShaderSource:{get:function(){return this._fragmentShaderSource}},renderState:{get:function(){return this._renderState}},closed:{get:function(){return this._closed}},vertexFormat:{get:function(){return this._vertexFormat}}});Ur.VERTEX_FORMAT=Ee.POSITION_AND_ST;Ur.prototype.getFragmentShaderSource=Lo.prototype.getFragmentShaderSource;Ur.prototype.isTranslucent=Lo.prototype.isTranslucent;Ur.prototype.getRenderState=Lo.prototype.getRenderState;function Sc(e){e=y(e,y.EMPTY_OBJECT),this.geometryInstances=e.geometryInstances,this._hasPerInstanceColors=!0;let t=e.appearance;c(t)||(t=new Ur),this.appearance=t,this.show=y(e.show,!0),this.classificationType=y(e.classificationType,Ui.BOTH),this.debugShowBoundingVolume=y(e.debugShowBoundingVolume,!1),this._debugShowShadowVolume=y(e.debugShowShadowVolume,!1),this._primitiveOptions={geometryInstances:void 0,appearance:void 0,vertexCacheOptimize:!1,interleave:y(e.interleave,!1),releaseGeometryInstances:y(e.releaseGeometryInstances,!0),allowPicking:y(e.allowPicking,!0),asynchronous:y(e.asynchronous,!0),compressVertices:!1,_createShaderProgramFunction:void 0,_createCommandsFunction:void 0,_updateAndQueueCommandsFunction:void 0},this._zIndex=void 0,this._ready=!1,this._primitive=void 0,this._sp=void 0,this._sp2D=void 0,this._spMorph=void 0,this._renderState=ZN(!1),this._renderState3DTiles=ZN(!0),this._renderStateMorph=Ue.fromCache({cull:{enabled:!0,face:Qi.FRONT},depthTest:{enabled:!0},blending:Zn.PRE_MULTIPLIED_ALPHA_BLEND,depthMask:!1})}Object.defineProperties(Sc.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}},debugShowShadowVolume:{get:function(){return this._debugShowShadowVolume}}});Sc.initializeTerrainHeights=function(){return Ti.initialize()};function Cse(e,t,n){const i=t.context,o=e._primitive,r=o._attributeLocations;let s=o._batchTable.getVertexShaderCallback()(yse);s=Mt._appendShowToShader(o,s),s=Mt._appendDistanceDisplayConditionToShader(o,s),s=Mt._modifyShaderPosition(e,s,t.scene3DOnly);let a=o._batchTable.getVertexShaderCallback()(gse);a=Mt._appendShowToShader(o,a),a=Mt._appendDistanceDisplayConditionToShader(o,a),a=Mt._modifyShaderPosition(e,a,t.scene3DOnly);let l=o._batchTable.getVertexShaderCallback()(mse);const u=[`GLOBE_MINIMUM_ALTITUDE ${t.mapProjection.ellipsoid.minimumRadius.toFixed(1)}`];let h="",f="";c(n.material)?(f=c(n.material)?n.material.shaderSource:"",f.search(/in\s+float\s+v_polylineAngle;/g)!==-1&&u.push("ANGLE_VARYING"),f.search(/in\s+float\s+v_width;/g)!==-1&&u.push("WIDTH_VARYING")):h="PER_INSTANCE_COLOR",u.push(h);const _=e.debugShowShadowVolume?["DEBUG_SHOW_VOLUME",h]:[h],g=new Oe({defines:u,sources:[s]}),m=new Oe({defines:_,sources:[f,l]});e._sp=Jt.replaceCache({context:i,shaderProgram:o._sp,vertexShaderSource:g,fragmentShaderSource:m,attributeLocations:r});let b=i.shaderCache.getDerivedShaderProgram(e._sp,"2dColor");if(!c(b)){const x=new Oe({defines:u.concat(["COLUMBUS_VIEW_2D"]),sources:[s]});b=i.shaderCache.createDerivedShaderProgram(e._sp,"2dColor",{context:i,shaderProgram:e._sp2D,vertexShaderSource:x,fragmentShaderSource:m,attributeLocations:r})}e._sp2D=b;let T=i.shaderCache.getDerivedShaderProgram(e._sp,"MorphColor");if(!c(T)){const x=new Oe({defines:u.concat([`MAX_TERRAIN_HEIGHT ${Ti._defaultMaxTerrainHeight.toFixed(1)}`]),sources:[a]});l=o._batchTable.getVertexShaderCallback()(_se);const C=new Oe({defines:_,sources:[f,l]});T=i.shaderCache.createDerivedShaderProgram(e._sp,"MorphColor",{context:i,shaderProgram:e._spMorph,vertexShaderSource:x,fragmentShaderSource:C,attributeLocations:r})}e._spMorph=T}function ZN(e){return Ue.fromCache({cull:{enabled:!0},blending:Zn.PRE_MULTIPLIED_ALPHA_BLEND,depthMask:!1,stencilTest:{enabled:e,frontFunction:Pn.EQUAL,frontOperation:{fail:nt.KEEP,zFail:nt.KEEP,zPass:nt.KEEP},backFu
`+Ys),fe&&eT([S,D,p],$s=>{Ys=vg(Ys,$s," ")}),w&&We?w.createHTML(Ys):Ys},t.setConfig=function(){let Et=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ln(Et),we=!0},t.clearConfig=function(){fr=null,we=!1},t.isValidAttribute=function(Et,be,Ge){fr||Ln({});const wt=ri(Et),ln=ri(be);return Ya(wt,ln,Ge)},t.addHook=function(Et,be){typeof be=="function"&&(B[Et]=B[Et]||[],Sg(B[Et],be))},t.removeHook=function(Et){if(B[Et])return tM(B[Et])},t.removeHooks=function(Et){B[Et]&&(B[Et]=[])},t.removeAllHooks=function(){B={}},t}var yae=HV();let bae=0;const zw={};function Wt(e,t){A.typeOf.string("html",e);let n;const i=e;c(zw[i])?n=zw[i]:(n=bae++,zw[i]=n),t=y(t,!1),this._id=n,this._html=e,this._showOnScreen=t,this._element=void 0}Object.defineProperties(Wt.prototype,{html:{get:function(){return this._html}},id:{get:function(){return this._id}},showOnScreen:{get:function(){return this._showOnScreen},set:function(e){this._showOnScreen=e}},element:{get:function(){if(!c(this._element)){const e=yae.sanitize(this._html),t=document.createElement("div");t._creditId=this._id,t.style.display="inline",t.innerHTML=e;const n=t.querySelectorAll("a");for(let i=0;i<n.length;i++)n[i].setAttribute("target","_blank");this._element=t}return this._element}}});Wt.equals=function(e,t){return e===t||c(e)&&c(t)&&e._id===t._id&&e._showOnScreen===t._showOnScreen};Wt.prototype.equals=function(e){return Wt.equals(this,e)};Wt.prototype.isIon=function(){return this.html.indexOf("ion-credit.png")!==-1};Wt.getIonCredit=function(e){const t=c(e.collapsible)&&!e.collapsible;return new Wt(e.html,t)};Wt.clone=function(e){if(c(e))return new Wt(e.html,e.showOnScreen)};const Tae=`in vec2 v_textureCoordinates;
uniform float originalSize;
uniform sampler2D texture0;
uniform sampler2D texture1;
uniform sampler2D texture2;
uniform sampler2D texture3;
uniform sampler2D texture4;
uniform sampler2D texture5;
const float yMipLevel1 = 1.0 - (1.0 / pow(2.0, 1.0));
const float yMipLevel2 = 1.0 - (1.0 / pow(2.0, 2.0));
const float yMipLevel3 = 1.0 - (1.0 / pow(2.0, 3.0));
const float yMipLevel4 = 1.0 - (1.0 / pow(2.0, 4.0));
void main()
{
vec2 uv = v_textureCoordinates;
vec2 textureSize = vec2(originalSize * 1.5 + 2.0, originalSize);
vec2 pixel = 1.0 / textureSize;
float mipLevel = 0.0;
if (uv.x - pixel.x > (textureSize.y / textureSize.x))
{
mipLevel = 1.0;
if (uv.y - pixel.y > yMipLevel1)
{
mipLevel = 2.0;
if (uv.y - pixel.y * 3.0 > yMipLevel2)
{
mipLevel = 3.0;
if (uv.y - pixel.y * 5.0 > yMipLevel3)
{
mipLevel = 4.0;
if (uv.y - pixel.y * 7.0 > yMipLevel4)
{
mipLevel = 5.0;
}
}
}
}
}
if (mipLevel > 0.0)
{
float scale = pow(2.0, mipLevel);
uv.y -= (pixel.y * (mipLevel - 1.0) * 2.0);
uv.x *= ((textureSize.x - 2.0) / textureSize.y);
uv.x -= 1.0 + pixel.x;
uv.y -= (1.0 - (1.0 / pow(2.0, mipLevel - 1.0)));
uv *= scale;
}
else
{
uv.x *= (textureSize.x / textureSize.y);
}
if(mipLevel == 0.0)
{
out_FragColor = texture(texture0, uv);
}
else if(mipLevel == 1.0)
{
out_FragColor = texture(texture1, uv);
}
else if(mipLevel == 2.0)
{
out_FragColor = texture(texture2, uv);
}
else if(mipLevel == 3.0)
{
out_FragColor = texture(texture3, uv);
}
else if(mipLevel == 4.0)
{
out_FragColor = texture(texture4, uv);
}
else if(mipLevel == 5.0)
{
out_FragColor = texture(texture5, uv);
}
else
{
out_FragColor = vec4(0.0);
}
}
`,Aae=`in vec3 v_cubeMapCoordinates;
uniform samplerCube cubeMap;
void main()
{
vec4 rgba = czm_textureCube(cubeMap, v_cubeMapCoordinates);
#ifdef RGBA_NORMALIZED
out_FragColor = vec4(rgba.rgb, 1.0);
#else
float m = rgba.a * 16.0;
vec3 r = rgba.rgb * m;
out_FragColor = vec4(r * r, 1.0);
#endif
}
`,xae=`in vec4 position;
in vec3 cubeMapCoordinates;
out vec3 v_cubeMapCoordinates;
void main()
{
gl_Position = position;
v_cubeMapCoordinates = cubeMapCoordinates;
}
`;function yl(e){this._url=e,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=!1,this._ready=!1,this._errorEvent=new Le}Object.defineProperties(yl.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}}});yl.isSupported=function(e){return e.colorBufferHalfFloat&&e.halfFloatingPointTexture||e.floatingPointTexture&&e.colorBufferFloat};const Cae=new d(1,0,0),Eae=new d(0,0,1),wae=new d(-1,0,0),Sae=new d(0,0,-1),iT=new d(0,1,0),vae=new d(0,-1,0),GV=[iT,wae,Eae,vae,Cae,iT,Sae,iT,iT],jV=GV.length,WV=new Float32Array(jV*3);let lM=0;for(let e=0;e<jV;++e,lM+=3)d.pack(GV[e],WV,lM);const Iae=new Float32Array([-1,1,-1,0,0,1,0,0,1,0,1,1,0,-1,-1,-1,1,-1]),Dae=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 Pae(e){const t=ct.createVertexBuffer({context:e,typedArray:Iae,usage:ke.STATIC_DRAW}),n=ct.createVertexBuffer({context:e,typedArray:WV,usage:ke.STATIC_DRAW}),i=ct.createIndexBuffer({context:e,typedArray:Dae,usage:ke.STATIC_DRAW,indexDatatype:je.UNSIGNED_SHORT}),o=[{index:0,vertexBuffer:t,componentsPerAttribute:2,componentDatatype:Z.FLOAT},{index:1,vertexBuffer:n,componentsPerAttribute:3,componentDatatype:Z.FLOAT}];return new Ci({context:e,attributes:o,indexBuffer:i})}function uM(e){return function(){return e}}function HI(e){e._va=e._va&&e._va.destroy(),e._sp=e._sp&&e._sp.destroy();let t,n;const i=e._cubeMaps;if(c(i))for(n=i.length,t=0;t<n;++t)i[t].destroy();const o=e._mipTextures;if(c(o))for(n=o.length,t=0;t<n;++t)o[t].destroy();e._va=void 0,e._sp=void 0,e._cubeMaps=void 0,e._cubeMapBuffers=void 0,e._mipTextures=void 0}yl.prototype.update=function(e){const t=e.context;if(!yl.isSupported(t)||(c(this._texture)&&c(this._va)&&HI(this),c(this._texture)))return;if(!c(this._texture)&&!this._loading){const g=e.context.textureCache.getTexture(this._url);c(g)&&(HI(this),this._texture=g,this._maximumMipmapLevel=this._texture.maximumMipmapLevel,this._ready=!0)}const n=this._cubeMapBuffers;if(!c(n)&&!this._loading){const g=this;Op(this._url).then(function(m){g._cubeMapBuffers=m,g._loading=!1}).catch(function(m){g.isDestroyed()||g._errorEvent.raiseEvent(m)}),this._loading=!0}if(!c(this._cubeMapBuffers))return;const i=[];let o=n[0].positiveX.pixelDatatype;c(o)?i.push("RGBA_NORMALIZED"):o=t.halfFloatingPointTexture?Me.HALF_FLOAT:Me.FLOAT;const r=Ve.RGBA,s=new Oe({defines:i,sources:[Aae]});this._va=Pae(t),this._sp=Jt.fromCache({context:t,vertexShaderSource:xae,fragmentShaderSource:s,attributeLocations:{position:0,cubeMapCoordinates:1}});const a=Math.min(n.length,6);this._maximumMipmapLevel=a-1;const l=this._cubeMaps=new Array(a),u=this._mipTextures=new Array(a),h=n[0].positiveX.width*2,f={originalSize:function(){return h}};for(let g=0;g<a;++g){const m=n[g].positiveY;n[g].positiveY=n[g].negativeY,n[g].negativeY=m;const b=l[g]=new Sl({context:t,source:n[g],pixelDatatype:o}),T=l[g].width*2,x=u[g]=new xt({context:t,width:T,height:T,pixelDatatype:o,pixelFormat:r}),C=new A_({vertexArray:this._va,shaderProgram:this._sp,uniformMap:{cubeMap:uM(b)},outputTexture:x,persists:!0,owner:this});e.commandList.push(C),f[`texture${g}`]=uM(x)}this._texture=new xt({context:t,width:h*1.5+2,height:h,pixelDatatype:o,pixelFormat:r}),this._texture.maximumMipmapLevel=this._maximumMipmapLevel,t.textureCache.addTexture(this._url,this._texture);const _=new A_({fragmentShaderSource:Tae,uniformMap:f,outputTexture:this._texture,persists:!1,owner:this});e.commandList.push(_),this._ready=!0};yl.prototype.isDestroyed=function(){return!1};yl.prototype.destroy=function(){return HI(this),this._texture=this._texture&&this._texture.destroy(),ve(this)};function G_(e){e=y(e,y.EMPTY_OBJECT);const t=c(e.imageBasedLightingFactor)?H.clone(e.imageBasedLightingFactor):new H(1,1);A.typeOf.object("options.imageBasedLightingFactor",t),A.typeOf.numb
vec2 computeSt(float batchId)
{
float stepX = tile_textureStep.x;
float centerX = tile_textureStep.y;
return vec2(centerX + (batchId * stepX), 0.5);
}
`:`uniform vec4 tile_textureStep;
uniform vec2 tile_textureDimensions;
vec2 computeSt(float batchId)
{
float stepX = tile_textureStep.x;
float centerX = tile_textureStep.y;
float stepY = tile_textureStep.z;
float centerY = tile_textureStep.w;
float xId = mod(batchId, tile_textureDimensions.x);
float yId = floor(batchId / tile_textureDimensions.x);
return vec2(centerX + (xId * stepX), centerY + (yId * stepY));
}
`}Hn.prototype.getVertexShaderCallback=function(e,t,n){if(this.featuresLength===0)return;const i=this;return function(o){const r=JV(o,n,!1);let s;return pt.maximumVertexTextureImageUnits>0?(s="",e&&(s+=`uniform bool tile_translucentCommand;
`),s+=`uniform sampler2D tile_batchTexture;
out vec4 tile_featureColor;
out vec2 tile_featureSt;
void main()
{
vec2 st = computeSt(${t});
vec4 featureProperties = texture(tile_batchTexture, st);
tile_color(featureProperties);
float show = ceil(featureProperties.a);
gl_Position *= show;
`,e&&(s+=` bool isStyleTranslucent = (featureProperties.a != 1.0);
if (czm_pass == czm_passTranslucent)
{
if (!isStyleTranslucent && !tile_translucentCommand)
{
gl_Position *= 0.0;
}
}
else
{
if (isStyleTranslucent)
{
gl_Position *= 0.0;
}
}
`),s+=` tile_featureColor = featureProperties;
tile_featureSt = st;
}`):s=`out vec2 tile_featureSt;
void main()
{
tile_color(vec4(1.0));
tile_featureSt = computeSt(${t});
}`,`${r}
${oce(i)}${s}`}};function dM(e,t){return e=Oe.replaceMain(e,"tile_main"),t?`${e}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);
}
`:`${e}void tile_color(vec4 tile_featureColor)
{
tile_main();
}
`}function rce(e,t){const n=`texture(${t}`;let i=0,o=e.indexOf(n,i),r;for(;o>-1;){let s=0;for(let u=o;u<e.length;++u){const h=e.charAt(u);if(h==="(")++s;else if(h===")"&&(--s,s===0)){r=u+1;break}}const l=`tile_diffuse_final(${e.slice(o,r)}, tile_diffuse)`;e=e.slice(0,o)+l+e.slice(r),i=o+l.length,o=e.indexOf(n,i)}return e}function JV(e,t,n){if(!c(t))return dM(e,n);let i=new RegExp(`(uniform|attribute|in)\\s+(vec[34]|sampler2D)\\s+${t};`);const o=e.match(i);if(!c(o))return dM(e,n);const r=o[0],s=o[2];e=Oe.replaceMain(e,"tile_main"),e=e.replace(r,"");const a=`bool isWhite(vec3 color)
{
return all(greaterThan(color, vec3(1.0 - czm_epsilon3)));
}
vec4 tile_diffuse_final(vec4 sourceDiffuse, vec4 tileDiffuse)
{
vec4 blendDiffuse = mix(sourceDiffuse, tileDiffuse, tile_colorBlend);
vec4 diffuse = isWhite(tileDiffuse.rgb) ? sourceDiffuse : blendDiffuse;
return vec4(diffuse.rgb, sourceDiffuse.a);
}
`,l=` 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);
`;let u;if(s==="vec3"||s==="vec4"){const h=s==="vec3"?`vec4(${t}, 1.0)`:t,f=s==="vec3"?"tile_diffuse.xyz":"tile_diffuse";i=new RegExp(t,"g"),e=e.replace(i,f),u=` vec4 source = ${h};
tile_diffuse = tile_diffuse_final(source, tile_featureColor);
tile_main();
`}else s==="sampler2D"&&(e=rce(e,t),u=` tile_diffuse = tile_featureColor;
tile_main();
`);return e=`uniform float tile_colorBlend;
vec4 tile_diffuse = vec4(1.0);
${a}${r}
${e}
void tile_color(vec4 tile_featureColor)
{
${u}`,n&&(e+=l),e+=`}
`,e}Hn.prototype.getFragmentShaderCallback=function(e,t,n){if(this.featuresLength!==0)return function(i){return i=JV(i,t,!0),pt.maximumVertexTextureImageUnits>0?(i+=`uniform sampler2D tile_pickTexture;
in vec2 tile_featureSt;
in vec4 tile_featureColor;
void main()
{
tile_color(tile_featureColor);
`,n&&(i+=` out_FragColor.rgb *= out_FragColor.a;
`),i+="}"):(e&&(i+=`uniform bool tile_translucentCommand;
`),i+=`uniform sampler2D tile_pickTexture;
uniform sampler2D tile_batchTexture;
in vec2 tile_featureSt;
void main()
{
vec4 featureProperties = texture(tile_batchTexture, tile_featureSt);
if (featureProperties.a == 0.0) {
discard;
}
`,e&&(i+=` bool isStyleTranslucent = (featureProperties.a != 1.0);
if (czm_pass == czm_passTranslucent)
{
if (!isStyleTranslucent && !tile_translucentCommand)
{
discard;
}
}
else
{
if (isStyleTranslucent)
{
discard;
}
}
`),i+=` tile_color(featureProperties);
`,n&&(i+=` out_FragColor.rgb *= out_FragColor.a;
`),i+=`}
`),i}};Hn.prototype.getClassificationFragmentShaderCallback=function(){if(this.featuresLength!==0)return function(e){return e=Oe.replaceMain(e,"tile_main"),pt.maximumVertexTextureImageUnits>0?e+=`uniform sampler2D tile_pickTexture;
in vec2 tile_featureSt;
in vec4 tile_featureColor;
void main()
{
tile_main();
out_FragColor = tile_featureColor;
out_FragColor.rgb *= out_FragColor.a;
}`:e+=`uniform sampler2D tile_batchTexture;
uniform sampler2D tile_pickTexture;
in vec2 tile_featureSt;
void main()
{
tile_main();
vec4 featureProperties = texture(tile_batchTexture, tile_featureSt);
if (featureProperties.a == 0.0) {
discard;
}
out_FragColor = featureProperties;
out_FragColor.rgb *= out_FragColor.a;
}
`,e}};function sce(e){const t=e._content.tileset,n=t.colorBlendMode,i=t.colorBlendAmount;if(n===HA.HIGHLIGHT)return 0;if(n===HA.REPLACE)return 1;if(n===HA.MIX)return R.clamp(i,R.EPSILON4,1);throw new E(`Invalid color blend mode "${n}".`)}Hn.prototype.getUniformMapCallback=function(){if(this.featuresLength===0)return;const e=this;return function(t){return jt(t,{tile_batchTexture:function(){return y(e._batchTexture.batchTexture,e._batchTexture.defaultTexture)},tile_textureDimensions:function(){return e._batchTexture.textureDimensions},tile_textureStep:function(){return e._batchTexture.textureStep},tile_colorBlend:function(){return sce(e)},tile_pickTexture:function(){return e._batchTexture.pickTexture}})}};Hn.prototype.getPickId=function(){return"texture(tile_pickTexture, tile_featureSt)"};const sh={ALL_OPAQUE:0,ALL_TRANSLUCENT:1,OPAQUE_AND_TRANSLUCENT:2};Hn.prototype.addDerivedCommands=function(e,t){const n=e.commandList,i=n.length,o=this._content._tile,r=o._finalResolution,s=o.tileset,a=s.isSkippingLevelOfDetail&&s.hasMixedContent&&e.context.stencilBuffer,l=ace(this);for(let u=t;u<i;++u){const h=n[u];if(h.pass===xe.COMPUTE)continue;let f=h.derivedCommands.tileset;(!c(f)||h.dirty)&&(f={},h.derivedCommands.tileset=f,f.originalCommand=cce(h),h.dirty=!1);const _=f.originalCommand;l!==sh.ALL_OPAQUE&&h.pass!==xe.TRANSLUCENT&&(c(f.translucent)||(f.translucent=lce(_))),l!==sh.ALL_TRANSLUCENT&&h.pass!==xe.TRANSLUCENT&&(c(f.opaque)||(f.opaque=uce(_)),a&&(r||(c(f.zback)||(f.zback=hce(e.context,_)),s._backfaceCommands.push(f.zback)),(!c(f.stencil)||o._selectionDepth!==pce(f.stencil))&&(h.renderState.depthMask?f.stencil=fce(_,o._selectionDepth):f.stencil=f.opaque)));const g=a?f.stencil:f.opaque,m=f.translucent;h.pass!==xe.TRANSLUCENT?(l===sh.ALL_OPAQUE&&(n[u]=g),l===sh.ALL_TRANSLUCENT&&(n[u]=m),l===sh.OPAQUE_AND_TRANSLUCENT&&(n[u]=g,n.push(m))):n[u]=_}};function ace(e){const t=e._batchTexture.translucentFeaturesLength;return t===0?sh.ALL_OPAQUE:t===e.featuresLength?sh.ALL_TRANSLUCENT:sh.OPAQUE_AND_TRANSLUCENT}function cce(e){const t=Ze.shallowClone(e),n=t.pass===xe.TRANSLUCENT;return t.uniformMap=c(t.uniformMap)?t.uniformMap:{},t.uniformMap.tile_translucentCommand=function(){return n},t}function lce(e){const t=Ze.shallowClone(e);return t.pass=xe.TRANSLUCENT,t.renderState=mce(e.renderState),t}function uce(e){const t=Ze.shallowClone(e);return t.renderState=_ce(e.renderState),t}function dce(e,t){let n=e.shaderCache.getDerivedShaderProgram(t,"zBackfaceLogDepth");if(!c(n)){const i=t.fragmentShaderSource.clone();i.defines=c(i.defines)?i.defines.slice(0):[],i.defines.push("POLYGON_OFFSET"),n=e.shaderCache.createDerivedShaderProgram(t,"zBackfaceLogDepth",{vertexShaderSource:t.vertexShaderSource,fragmentShaderSource:i,attributeLocations:t._attributeLocations})}return n}function hce(e,t){const n=Ze.shallowClone(t),i=Je(n.renderState,!0);i.cull.enabled=!0,i.cull.face=Qi.FRONT,i.colorMask={red:!1,green:!1,blue:!1,alpha:!1},i.polygonOffset={enabled:!0,factor:5,units:5},i.stencilTest=At.setCesium3DTileBit(),i.stencilMask=At.CESIUM_3D_TILE_MASK,n.renderState=Ue.fromCache(i),n.castShadows=!1,n.receiveShadows=!1,n.uniformMap=Je(t.uniformMap);const o=new H(5,5);return n.uniformMap.u_polygonOffset=function(){return o},n.shaderProgram=dce(e,t.shaderProgram),n}function fce(e,t){const n=Ze.shallowClone(e),i=Je(n.renderState,!0);return i.stencilTest.enabled=!0,i.stencilTest.mask=At.SKIP_LOD_MASK,i.stencilTest.reference=At.CESIUM_3D_TILE_MASK|t<<At.SKIP_LOD_BIT_SHIFT,i.stencilTest.frontFunction=Pn.GREATER_OR_EQUAL,i.stencilTest.frontOperation.zPass=nt.REPLACE,i.stencilTest.backFunction=Pn.GREATER_OR_EQUAL,i.stencilTest.backOperation.zPass=nt.REPLACE,i.stencilMask=At.CESIUM_3D_TILE_MASK|At.SKIP_LOD_MASK,n.renderState=Ue.fromCache(i),n}function pce(e){return(e.renderState.stencilTest.reference&At.SKIP_LOD_MASK)>>>At.SKIP_LOD_BIT_SHIFT}function mce(e){const t=Je(e,!0);return t.cull.enabled=!1,t.depthTest.enabled=!0,t.depthMask=!1,t.blending=Zn.ALPHA_BLEND,t.stencilTest=At.setCesium3DTileBit(),t.stencilMask=At.CESIUM_3D_TILE_MASK,Ue.fromCache(t)}function _ce(e)
in float a_batchId;
uniform mat4 u_modifiedModelViewProjection;
void main()
{
gl_Position = czm_depthClamp(u_modifiedModelViewProjection * vec4(position, 1.0));
}
`;function Ir(e,t){this._content=e,this._batchId=t,this._color=void 0}Object.defineProperties(Ir.prototype,{show:{get:function(){return this._content.batchTable.getShow(this._batchId)},set:function(e){this._content.batchTable.setShow(this._batchId,e)}},color:{get:function(){return c(this._color)||(this._color=new z),this._content.batchTable.getColor(this._batchId,this._color)},set:function(e){this._content.batchTable.setColor(this._batchId,e)}},polylinePositions:{get:function(){if(!!c(this._content.getPolylinePositions))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)}}});Ir.prototype.hasProperty=function(e){return this._content.batchTable.hasProperty(this._batchId,e)};Ir.prototype.getPropertyIds=function(e){return this._content.batchTable.getPropertyIds(this._batchId,e)};Ir.prototype.getProperty=function(e){return this._content.batchTable.getProperty(this._batchId,e)};Ir.getPropertyInherited=function(e,t,n){const i=e.batchTable;if(c(i)){if(i.hasPropertyBySemantic(t,n))return i.getPropertyBySemantic(t,n);if(i.hasProperty(t,n))return i.getProperty(t,n)}const o=e.metadata;if(c(o)){if(o.hasPropertyBySemantic(n))return o.getPropertyBySemantic(n);if(o.hasProperty(n))return o.getProperty(n)}const r=e.tile,s=r.metadata;if(c(s)){if(s.hasPropertyBySemantic(n))return s.getPropertyBySemantic(n);if(s.hasProperty(n))return s.getProperty(n)}let a;if(c(r.implicitSubtree)&&(a=r.implicitSubtree.metadata),c(a)){if(a.hasPropertyBySemantic(n))return a.getPropertyBySemantic(n);if(a.hasProperty(n))return a.getProperty(n)}const l=c(e.group)?e.group.metadata:void 0;if(c(l)){if(l.hasPropertyBySemantic(n))return l.getPropertyBySemantic(n);if(l.hasProperty(n))return l.getProperty(n)}const u=e.tileset.metadata;if(c(u)){if(u.hasPropertyBySemantic(n))return u.getPropertyBySemantic(n);if(u.hasProperty(n))return u.getProperty(n)}};Ir.prototype.getPropertyInherited=function(e){return Ir.getPropertyInherited(this._content,this._batchId,e)};Ir.prototype.setProperty=function(e,t){this._content.batchTable.setProperty(this._batchId,e,t),this._content.featurePropertiesDirty=!0};Ir.prototype.isExactClass=function(e){return this._content.batchTable.isExactClass(this._batchId,e)};Ir.prototype.isClass=function(e){return this._content.batchTable.isClass(this._batchId,e)};Ir.prototype.getExactClassName=function(){return this._content.batchTable.getExactClassName(this._batchId)};class gce{add(t,n,i){if(typeof arguments[0]!="string")for(let o in arguments[0])this.add(o,arguments[0][o],arguments[1]);else(Array.isArray(t)?t:[t]).forEach(function(o){this[o]=this[o]||[],n&&this[o][i?"unshift":"push"](n)},this)}run(t,n){this[t]=this[t]||[],this[t].forEach(function(i){i.call(n&&n.context?n.context:n,n)})}}class yce{constructor(t){this.jsep=t,this.registered={}}register(...t){t.forEach(n=>{if(typeof n!="object"||!n.name||!n.init)throw new Error("Invalid JSEP plugin format");this.registered[n.name]||(n.init(this.jsep),this.registered[n.name]=n)})}}class De{static get version(){return"1.3.8"}static toString(){return"JavaScript Expression Parser (JSEP) v"+De.version}static addUnaryOp(t){return De.max_unop_len=Math.max(t.length,De.max_unop_len),De.unary_ops[t]=1,De}static addBinaryOp(t,n,i){return De.max_binop_len=Math.max(t.length,De.max_binop_len),De.binary_ops[t]=n,i?De.right_associative.add(t):De.right_associative.delete(t),De}static addIdentifierChar(t){return De.additional_identifier_chars.add(t),De}static addLiteral(t,n){return De.literals[t]=n,De}static removeUnaryOp(t){return delete De.unary_ops[t],t.length===De.max_unop_len&&(De.max_unop_len=De.getMaxKeyLen(De.unary_ops)),De}static removeAllUnaryOps(){return De.unary_ops={},De.max_unop_len=0,De}static removeIdentifierChar(t){return De.additional_identifier_chars.delete(t),De}static removeBinaryOp(t){return delete De.binar
`;break;case"r":t+="\r";break;case"t":t+=" ";break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="\v";break;default:t+=r}else t+=r}return o||this.throwError('Unclosed quote after "'+t+'"'),{type:De.LITERAL,value:t,raw:this.expr.substring(n,this.index)}}gobbleIdentifier(){let t=this.code,n=this.index;for(De.isIdentifierStart(t)?this.index++:this.throwError("Unexpected "+this.char);this.index<this.expr.length&&(t=this.code,De.isIdentifierPart(t));)this.index++;return{type:De.IDENTIFIER,name:this.expr.slice(n,this.index)}}gobbleArguments(t){const n=[];let i=!1,o=0;for(;this.index<this.expr.length;){this.gobbleSpaces();let r=this.code;if(r===t){i=!0,this.index++,t===De.CPAREN_CODE&&o&&o>=n.length&&this.throwError("Unexpected token "+String.fromCharCode(t));break}else if(r===De.COMMA_CODE){if(this.index++,o++,o!==n.length){if(t===De.CPAREN_CODE)this.throwError("Unexpected token ,");else if(t===De.CBRACK_CODE)for(let s=n.length;s<o;s++)n.push(null)}}else if(n.length!==o&&o!==0)this.throwError("Expected comma");else{const s=this.gobbleExpression();(!s||s.type===De.COMPOUND)&&this.throwError("Expected comma"),n.push(s)}}return i||this.throwError("Expected "+String.fromCharCode(t)),n}gobbleGroup(){this.index++;let t=this.gobbleExpressions(De.CPAREN_CODE);if(this.code===De.CPAREN_CODE)return this.index++,t.length===1?t[0]:t.length?{type:De.SEQUENCE_EXP,expressions:t}:!1;this.throwError("Unclosed (")}gobbleArray(){return this.index++,{type:De.ARRAY_EXP,elements:this.gobbleArguments(De.CBRACK_CODE)}}}const bce=new gce;Object.assign(De,{hooks:bce,plugins:new yce(De),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:new Set,additional_identifier_chars:new Set(["$","_"]),literals:{true:!0,false:!1,null:null},this_str:"this"});De.max_unop_len=De.getMaxKeyLen(De.unary_ops);De.max_binop_len=De.getMaxKeyLen(De.binary_ops);const ep=e=>new De(e).parse(),Tce=Object.getOwnPropertyNames(De);Tce.forEach(e=>{ep[e]===void 0&&e!=="prototype"&&(ep[e]=De[e])});ep.Jsep=De;const Ace="ConditionalExpression";var xce={name:"ternary",init(e){e.hooks.add("after-expression",function(n){if(n.node&&this.code===e.QUMARK_CODE){this.index++;const i=n.node,o=this.gobbleExpression();if(o||this.throwError("Expected expression"),this.gobbleSpaces(),this.code===e.COLON_CODE){this.index++;const r=this.gobbleExpression();if(r||this.throwError("Expected expression"),n.node={type:Ace,test:i,consequent:o,alternate:r},i.operator&&e.binary_ops[i.operator]<=.9){let s=i;for(;s.right.operator&&e.binary_ops[s.right.operator]<=.9;)s=s.right;n.node.test=s.right,s.right=n.node,n.node=i}}else this.throwError("Expected :")}})}};ep.plugins.register(xce);const Cce={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},$e=Object.freeze(Cce);function bl(e,t){A.typeOf.string("expression",e),this._expression=e,e=Fce(e,t),e=zce(Bce(e)),ep.addBinaryOp("=~",0),ep.addBinaryOp("!~",0);let n;try{n=ep(e)}catch(i){throw new Te(i)}this._runtimeAst=yn(this,n)}Object.defineProperties(bl.prototype,{expression:{get:function(){return this._expression}}});const Vt={arrayIndex:0,arrayArray:[[]],cartesian2Index:0,cartesian3Index:0,cartesian4Index:0,cartesian2Array:[new H],cartesian3Array:[new d],cartesian4Array:[new te],reset:function(){this.arrayIndex=0
{
return ${o};
}
`,o};bl.prototype.getShaderExpression=function(e,t){return this._runtimeAst.getShaderExpression(e,t)};bl.prototype.getVariables=function(){let e=[];return this._runtimeAst.getVariables(e),e=e.filter(function(t,n,i){return i.indexOf(t)===n}),e};const Ece=["!","-","+"],fM=["+","-","*","/","%","===","!==",">",">=","<","<=","&&","||","!~","=~"],Ox=/\${(.*?)}/g,wce=/\\/g,Sce="@#%",vce=/@#%/g,CC=new z,EC={abs:Jo(Math.abs),sqrt:Jo(Math.sqrt),cos:Jo(Math.cos),sin:Jo(Math.sin),tan:Jo(Math.tan),acos:Jo(Math.acos),asin:Jo(Math.asin),atan:Jo(Math.atan),radians:Jo(R.toRadians),degrees:Jo(R.toDegrees),sign:Jo(R.sign),floor:Jo(Math.floor),ceil:Jo(Math.ceil),round:Jo(Math.round),exp:Jo(Math.exp),exp2:Jo(Dce),log:Jo(Math.log),log2:Jo(Pce),fract:Jo(Ice),length:Oce,normalize:Lce},wC={atan2:oT(Math.atan2,!1),pow:oT(Math.pow,!1),min:oT(Math.min,!0),max:oT(Math.max,!0),distance:Rce,dot:Nce,cross:Mce},sO={clamp:pM(R.clamp,!0),mix:pM(R.lerp,!0)};function Ice(e){return e-Math.floor(e)}function Dce(e){return Math.pow(2,e)}function Pce(e){return R.log2(e)}function Jo(e){return function(t,n){if(typeof n=="number")return e(n);if(n instanceof H)return H.fromElements(e(n.x),e(n.y),Vt.getCartesian2());if(n instanceof d)return d.fromElements(e(n.x),e(n.y),e(n.z),Vt.getCartesian3());if(n instanceof te)return te.fromElements(e(n.x),e(n.y),e(n.z),e(n.w),Vt.getCartesian4());throw new Te(`Function "${t}" requires a vector or number argument. Argument is ${n}.`)}}function oT(e,t){return function(n,i,o){if(t&&typeof o=="number"){if(typeof i=="number")return e(i,o);if(i instanceof H)return H.fromElements(e(i.x,o),e(i.y,o),Vt.getCartesian2());if(i instanceof d)return d.fromElements(e(i.x,o),e(i.y,o),e(i.z,o),Vt.getCartesian3());if(i instanceof te)return te.fromElements(e(i.x,o),e(i.y,o),e(i.z,o),e(i.w,o),Vt.getCartesian4())}if(typeof i=="number"&&typeof o=="number")return e(i,o);if(i instanceof H&&o instanceof H)return H.fromElements(e(i.x,o.x),e(i.y,o.y),Vt.getCartesian2());if(i instanceof d&&o instanceof d)return d.fromElements(e(i.x,o.x),e(i.y,o.y),e(i.z,o.z),Vt.getCartesian3());if(i instanceof te&&o instanceof te)return te.fromElements(e(i.x,o.x),e(i.y,o.y),e(i.z,o.z),e(i.w,o.w),Vt.getCartesian4());throw new Te(`Function "${n}" requires vector or number arguments of matching types. Arguments are ${i} and ${o}.`)}}function pM(e,t){return function(n,i,o,r){if(t&&typeof r=="number"){if(typeof i=="number"&&typeof o=="number")return e(i,o,r);if(i instanceof H&&o instanceof H)return H.fromElements(e(i.x,o.x,r),e(i.y,o.y,r),Vt.getCartesian2());if(i instanceof d&&o instanceof d)return d.fromElements(e(i.x,o.x,r),e(i.y,o.y,r),e(i.z,o.z,r),Vt.getCartesian3());if(i instanceof te&&o instanceof te)return te.fromElements(e(i.x,o.x,r),e(i.y,o.y,r),e(i.z,o.z,r),e(i.w,o.w,r),Vt.getCartesian4())}if(typeof i=="number"&&typeof o=="number"&&typeof r=="number")return e(i,o,r);if(i instanceof H&&o instanceof H&&r instanceof H)return H.fromElements(e(i.x,o.x,r.x),e(i.y,o.y,r.y),Vt.getCartesian2());if(i instanceof d&&o instanceof d&&r instanceof d)return d.fromElements(e(i.x,o.x,r.x),e(i.y,o.y,r.y),e(i.z,o.z,r.z),Vt.getCartesian3());if(i instanceof te&&o instanceof te&&r instanceof te)return te.fromElements(e(i.x,o.x,r.x),e(i.y,o.y,r.y),e(i.z,o.z,r.z),e(i.w,o.w,r.w),Vt.getCartesian4());throw new Te(`Function "${n}" requires vector or number arguments of matching types. Arguments are ${i}, ${o}, and ${r}.`)}}function Oce(e,t){if(typeof t=="number")return Math.abs(t);if(t instanceof H)return H.magnitude(t);if(t instanceof d)return d.magnitude(t);if(t instanceof te)return te.magnitude(t);throw new Te(`Function "${e}" requires a vector or number argument. Argument is ${t}.`)}function Lce(e,t){if(typeof t=="number")return 1;if(t instanceof H)return H.normalize(t,Vt.getCartesian2());if(t instanceof d)return d.normalize(t,Vt.getCartesian3());if(t instanceof te)return te.normalize(t,Vt.getCartesian4());throw new Te(`Function "${e}" requires a vector or number argument. Argument is ${t}.`)}function Rce(e,t,n){if(typeof t=="number"&&typeof n=="number")return Math.abs(t-n);if(t instanceof H&&
{
czm_non_pick_main();
out_FragColor = ${o};
}
`,e._spPick=Jt.fromCache({context:t,vertexShaderSource:r,fragmentShaderSource:s,attributeLocations:i});return}const a=n.getVertexShaderCallback(!1,"a_batchId",void 0)(hM);let l=n.getFragmentShaderCallback(!1,void 0,!0)(wI);o=n.getPickId();let u=new Oe({sources:[a]}),h=new Oe({defines:["VECTOR_TILE"],sources:[l]});e._sp=Jt.fromCache({context:t,vertexShaderSource:u,fragmentShaderSource:h,attributeLocations:i}),u=new Oe({sources:[hM]}),h=new Oe({defines:["VECTOR_TILE"],sources:[wI]}),e._spStencil=Jt.fromCache({context:t,vertexShaderSource:u,fragmentShaderSource:h,attributeLocations:i}),l=Oe.replaceMain(l,"czm_non_pick_main"),l=`${l}
void main()
{
czm_non_pick_main();
out_FragColor = ${o};
}
`;const f=new Oe({sources:[a]}),_=new Oe({defines:["VECTOR_TILE"],sources:[l]});e._spPick=Jt.fromCache({context:t,vertexShaderSource:f,fragmentShaderSource:_,attributeLocations:i})}function bM(e){const t=e?Pn.EQUAL:Pn.ALWAYS;return{colorMask:{red:!1,green:!1,blue:!1,alpha:!1},stencilTest:{enabled:!0,frontFunction:t,frontOperation:{fail:nt.KEEP,zFail:nt.DECREMENT_WRAP,zPass:nt.KEEP},backFunction:t,backOperation:{fail:nt.KEEP,zFail:nt.INCREMENT_WRAP,zPass:nt.KEEP},reference:At.CESIUM_3D_TILE_MASK,mask:At.CESIUM_3D_TILE_MASK},stencilMask:At.CLASSIFICATION_MASK,depthTest:{enabled:!0,func:lp.LESS_OR_EQUAL},depthMask:!1}}const ile={stencilTest:{enabled:!0,frontFunction:Pn.NOT_EQUAL,frontOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},backFunction:Pn.NOT_EQUAL,backOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},reference:0,mask:At.CLASSIFICATION_MASK},stencilMask:At.CLASSIFICATION_MASK,depthTest:{enabled:!1},depthMask:!1,blending:Zn.PRE_MULTIPLIED_ALPHA_BLEND},ole={stencilTest:{enabled:!0,frontFunction:Pn.NOT_EQUAL,frontOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},backFunction:Pn.NOT_EQUAL,backOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},reference:0,mask:At.CLASSIFICATION_MASK},stencilMask:At.CLASSIFICATION_MASK,depthTest:{enabled:!1},depthMask:!1};function rle(e){c(e._rsStencilDepthPass)||(e._rsStencilDepthPass=Ue.fromCache(bM(!1)),e._rsStencilDepthPass3DTiles=Ue.fromCache(bM(!0)),e._rsColorPass=Ue.fromCache(ile),e._rsPickPass=Ue.fromCache(ole))}const _f=new L,TM=new d;function sle(e,t){if(c(e._uniformMap))return;const n={u_modifiedModelViewProjection:function(){const i=t.uniformState.view,o=t.uniformState.projection;return L.clone(i,_f),L.multiplyByPoint(_f,e._center,TM),L.setTranslation(_f,TM,_f),L.multiply(o,_f,_f),_f},u_highlightColor:function(){return e._highlightColor}};e._uniformMap=e._batchTable.getUniformMapCallback()(n)}function Gw(e,t,n,i,o,r,s){const a=e.constructor.BYTES_PER_ELEMENT,l=r.length;for(let u=0;u<l;++u){const h=r[u],f=s[h],_=i[f],g=o[f],m=new e.constructor(e.buffer,a*_,g);t.set(m,n),i[f]=n,n+=g}return n}function ale(e,t){const n=e._indices,i=e._indexOffsets,o=e._indexCounts,r=e._batchIdLookUp,s=new n.constructor(n.length);let a=t.pop();const l=[a];let u=Gw(n,s,0,i,o,a.batchIds,r);for(a.offset=0,a.count=u;t.length>0;){const h=t.pop();if(z.equals(h.color,a.color))u=Gw(n,s,u,i,o,h.batchIds,r),a.batchIds=a.batchIds.concat(h.batchIds),a.count=u-a.offset;else{const f=u;u=Gw(n,s,u,i,o,h.batchIds,r),h.offset=f,h.count=u-f,l.push(h),a=h}}e._va.indexBuffer.copyFromArrayView(s),e._indices=s,e._batchedIndices=l}function jw(e,t,n,i,o,r,s){const a=e.bytesPerIndex,l=r.length;for(let u=0;u<l;++u){const h=r[u],f=s[h],_=i[f],g=o[f];t.copyFromBuffer(e,_*a,n*a,g*a),i[f]=n,n+=g}return n}function cle(e,t){const n=e._indexOffsets,i=e._indexCounts,o=e._batchIdLookUp;let r=t.pop();const s=[r],a=e._va.indexBuffer,l=e._vaSwap.indexBuffer;let u=jw(a,l,0,n,i,r.batchIds,o);for(r.offset=0,r.count=u;t.length>0;){const f=t.pop();if(z.equals(f.color,r.color))u=jw(a,l,u,n,i,f.batchIds,o),r.batchIds=r.batchIds.concat(f.batchIds),r.count=u-r.offset;else{const _=u;u=jw(a,l,u,n,i,f.batchIds,o),f.offset=_,f.count=u-_,s.push(f),r=f}}const h=e._va;e._va=e._vaSwap,e._vaSwap=h,e._batchedIndices=s}function lle(e,t){return t.color.toRgba()-e.color.toRgba()}function ule(e,t){if(!e._batchDirty)return!1;const n=e._batchedIndices,i=n.length;let o=!1;const r={};for(let s=0;s<i;++s){const l=n[s].color.toRgba();if(c(r[l])){o=!0;break}else r[l]=!0}if(!o)return e._batchDirty=!1,!1;if(o&&!e.forceRebatch&&e._framesSinceLastRebatch<120){++e._framesSinceLastRebatch;return}return n.sort(lle),t.webgl2?cle(e,n):ale(e,n),e._framesSinceLastRebatch=0,e._batchDirty=!1,e._pickCommandsDirty=!0,e._wireframeDirty=!0,!0}function dle(e,t){const n=ule(e,t),i=e._commands,o=e._batchedIndices,r=o.length,s=r*2;if(c(i)&&!n&&i.length===s)return;i.length=s;const a=e._va,l=e._sp,u=y(e._modelMatrix,L.IDENTITY),h=e._uniformMap,f=e._boundingVolume;for(let _=0;_<r;++_){const g=o[_].offset,m=o[_].count;let b=i[_*2];c(b)||(b=i[_*2]=new Ze({owner:e})),b.vertexArr
${t.message}`);const n=new Te(e);return c(t)&&(n.stack=`Original stack:
${t.stack}
Handler stack:
${n.stack}`),n};wo.prototype.isDestroyed=function(){return!1};wo.prototype.destroy=function(){return this.unload(),ve(this)};const pue={UNLOADED:0,LOADING:1,LOADED:2,PROCESSING:3,READY:4,FAILED:5},ut=Object.freeze(pue);function hl(e){e=y(e,y.EMPTY_OBJECT);const t=e.typedArray,n=e.resource,i=e.cacheKey;if(c(t)===c(n))throw new E("One of options.typedArray and options.resource must be defined.");this._typedArray=t,this._resource=n,this._cacheKey=i,this._state=ut.UNLOADED,this._promise=void 0}c(Object.create)&&(hl.prototype=Object.create(wo.prototype),hl.prototype.constructor=hl);Object.defineProperties(hl.prototype,{cacheKey:{get:function(){return this._cacheKey}},typedArray:{get:function(){return this._typedArray}}});hl.prototype.load=async function(){return c(this._promise)?this._promise:c(this._typedArray)?(this._promise=Promise.resolve(this),this._promise):(this._promise=mue(this),this._promise)};async function mue(e){const t=e._resource;e._state=ut.LOADING;try{const n=await hl._fetchArrayBuffer(t);return e.isDestroyed()?void 0:(e._typedArray=new Uint8Array(n),e._state=ut.READY,e)}catch(n){if(e.isDestroyed())return;e._state=ut.FAILED;const i=`Failed to load external buffer: ${t.url}`;throw e.getError(i,n)}}hl._fetchArrayBuffer=function(e){return e.fetchArrayBuffer()};hl.prototype.unload=function(){this._typedArray=void 0};(function(){var e="b9H79TebbbeJq9Geueu9Geub9Gbb9Gvuuuuueu9Gduueu9Gluuuueu9Gvuuuuub9Gouuuuuub9Gluuuub9GiuuueuiKLdilevlevlooroowwvwbDDbelve9Weiiviebeoweuec:W;kekr;RiOo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8A9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWVbe8F9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWV9c9V919U9KbdE9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949wWV79P9V9UbiY9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWVbl8E9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWV9c9V919U9Kbv8A9TW79O9V9Wt9FW9U9J9V9KW69U9KW949wWV79P9V9UboE9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JWbra9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JW9c9V919U9KbwL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9p9JtbDK9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9r919HtbqL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWVT949WbkE9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OWbPa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OW9ttV9P9Wbsa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94SWt9J9O9sW9T9H9WbzK9TW79O9V9Wt9F79W9Ht9P9H29t9VVt9sW9T9H9WbHl79IV9RbODwebcekdQXq:g9sLdbk;3keYu8Jjjjjbcjo9Rgv8Kjjjjbcbhodnalcefae0mbabcbRb:S:kjjbc:GeV86bbavcjdfcbcjdzNjjjb8AdnaiTmbavcjdfadalz:tjjjb8Akabaefhrabcefhwavalfcbcbcjdal9RalcFe0EzNjjjb8Aavavcjdfalz:tjjjbhDcj;abal9UhodndndndndnalTmbaoc;WFbGgecjdaecjd6Ehqcbhkdninakai9pmiaDcjlfcbcjdzNjjjb8Aaqaiak9Rakaqfai6Egxcsfgecl4cifcd4hmadakal2fhPdndndndndnaec9WGgsTmbcbhzcehHaPhOawhAxekdnaxTmbcbhAcehHaPhCinaDaAfRbbhXaDcjlfheaChoaxhQinaeaoRbbgLaX9RgXcetaX;acr4786bbaoalfhoaecefheaLhXaQcufgQmbkaraw9Ram6miawcbamzNjjjbgeTmiaCcefhCaeamfhwaAcefgAal6hHaAal9hmbxvkkaraw9Ram6mvawcbamzNjjjb8AceheinawgXamfhwalaegoSmldnaraw9Ram6mbaocefheawcbamzNjjjb8AaXmekkaoal6hHxekindnaxTmbaDazfRbbhXaDcjlfheaOhoaxhQinaeaoRbbgLaX9RgXcetaX;acr4786bbaoalfhoaecefheaLhXaQcufgQmbkkaraA9Ram6mearaAcbamzNjjjbgKamfgw9RcK6mdcbhYaDcjlfhAinaDcjlfaYfh8AcwhCczhLcehQindndnaQce9hmbcuhoa8ARbbmecbhodninaogecsSmeaecefhoaAaefcefRbbTmbkkcucbaecs6EhoxekaQcetc;:FFFeGhocuaQtcu7cFeGhXcbheinaoaXaAaefRbb9nfhoaecefgecz9hmbkkaoaLaoaL6geEhLaQaCaeEhCaQcetgQcw6mbkdndndndnaCcufPdiebkaKaYco4fgeaeRbbcdciaCclSEaYci4coGtV86bbaCcw9hmeawa8A8Pbb83bbawcwfa8Acwf8Pbb83bbawczfhwxdkaKaYco4fgeaeRbbceaYci4coGtV86bbkdncwaC9TgEmbinawcb86bbawcefhwxbkkcuaCtcu7h8Acbh3aAh5ina5heaEhQcbhoinaeRbbgLa8AcFeGgXaLaX6EaoaCtVhoaecefheaQcufgQmbkawao86bba5aEfh5awcefhwa3aEfg3cz6mbkcbheindnaAaefRbbgoaX6mbawao86bbawcefhwkaecefgecz9hmbkkdnaYczfgYas9pmbaAczfhAaraw9RcL0mekkaYas6meawTmeaOcefhOazcefgzal6hHawhAazalSmixbkkcbhwaHceGTmexikcbhwaHceGmdkaDaPaxcufal2falz:tjjjb8AaxakfhkawmbkcbhoxokcbhoxvkaiTmekcbhoaraw9Ralcaalca0E6mialc8F9nmexdkcbhoaecufca6mdkawcbcaal9RgezNjjjbaefhwkawaDcjdfalz:tjjjbalfab9Rhokavcjof8Kjjjjbaok9heeuaecaaeca0Eabcj;abae9Uc;WFbGgdcjdadcjd6Egdfcufad9Uae2adcl4cifcd4adV2fcefkmbcbabBd:S:kjjbk;rse3u8Jjjjjbc;ae9Rgl8Kjjjjbcbhvdnaici9UgocHfae0mbabcbyd:C:kjjbgrc;GeV86bbalc;abfcFecjezNjjjb8AalcUfgw9cu83ibalc8WfgD9c
${n.message}`);const o=new Te(i);return c(n)&&(o.stack=`Original stack:
${n.stack}
Handler stack:
${o.stack}`),o};Lt.getNodeTransform=function(e){return c(e.matrix)?e.matrix:L.fromTranslationQuaternionRotationScale(c(e.translation)?e.translation:d.ZERO,c(e.rotation)?e.rotation:_e.IDENTITY,c(e.scale)?e.scale:d.ONE)};Lt.getAttributeBySemantic=function(e,t,n){const i=e.attributes,o=i.length;for(let r=0;r<o;++r){const s=i[r],a=c(n)?s.setIndex===n:!0;if(s.semantic===t&&a)return s}};Lt.getAttributeByName=function(e,t){const n=e.attributes,i=n.length;for(let o=0;o<i;++o){const r=n[o];if(r.name===t)return r}};Lt.getFeatureIdsByLabel=function(e,t){for(let n=0;n<e.length;n++){const i=e[n];if(i.positionalLabel===t||i.label===t)return i}};Lt.hasQuantizedAttributes=function(e){if(!c(e))return!1;for(let t=0;t<e.length;t++){const n=e[t];if(c(n.quantization))return!0}return!1};Lt.getAttributeInfo=function(e){const t=e.semantic,n=e.setIndex;let i,o=!1;c(t)?(i=ht.getVariableName(t,n),o=!0):(i=e.name,i=i.replace(/^_/,""),i=i.toLowerCase());const r=/^color_\d+$/.test(i),s=e.type;let a=qt.getGlslType(s);r&&(a="vec4");const l=c(e.quantization);let u;return l&&(u=r?"vec4":qt.getGlslType(e.quantization.type)),{attribute:e,isQuantized:l,variableName:i,hasSemantic:o,glslType:a,quantizedGlslType:u}};const Rde=new d,Nde=new d;Lt.getPositionMinMax=function(e,t,n){const i=Lt.getAttributeBySemantic(e,"POSITION");let o=i.max,r=i.min;return c(n)&&c(t)&&(r=d.add(r,t,Nde),o=d.add(o,n,Rde)),{min:r,max:o}};Lt.getAxisCorrectionMatrix=function(e,t,n){return n=L.clone(L.IDENTITY,n),e===Cr.Y?n=L.clone(Cr.Y_UP_TO_Z_UP,n):e===Cr.X&&(n=L.clone(Cr.X_UP_TO_Z_UP,n)),t===Cr.Z&&(n=L.multiplyTransformation(n,Cr.Z_UP_TO_X_UP,n)),n};const Mde=new $;Lt.getCullFace=function(e,t){if(!ze.isTriangles(t))return Qi.BACK;const n=L.getMatrix3(e,Mde);return $.determinant(n)<0?Qi.FRONT:Qi.BACK};Lt.sanitizeGlslIdentifier=function(e){let t=e.replaceAll(/[^A-Za-z0-9]+/g,"_");return t=t.replace(/^gl_/,""),/^\d/.test(t)&&(t=`_${t}`),t};Lt.supportedExtensions={AGI_articulations:!0,CESIUM_primitive_outline:!0,CESIUM_RTC:!0,EXT_feature_metadata:!0,EXT_instance_features:!0,EXT_mesh_features:!0,EXT_mesh_gpu_instancing:!0,EXT_meshopt_compression:!0,EXT_structural_metadata:!0,EXT_texture_webp:!0,KHR_blend:!0,KHR_draco_mesh_compression:!0,KHR_techniques_webgl:!0,KHR_materials_common:!0,KHR_materials_pbrSpecularGlossiness:!0,KHR_materials_unlit:!0,KHR_mesh_quantization:!0,KHR_texture_basisu:!0,KHR_texture_transform:!0,WEB3D_quantized_attributes:!0};Lt.checkSupportedExtensions=function(e){const t=e.length;for(let n=0;n<t;n++){const i=e[n];if(!Lt.supportedExtensions[i])throw new Te(`Unsupported glTF Extension: ${i}`)}};function ed(e){e=y(e,y.EMPTY_OBJECT);const t=e.resourceCache,n=e.gltfResource,i=e.baseResource,o=e.typedArray,r=e.gltfJson,s=e.cacheKey;A.typeOf.func("options.resourceCache",t),A.typeOf.object("options.gltfResource",n),A.typeOf.object("options.baseResource",i),this._resourceCache=t,this._gltfResource=n,this._baseResource=i,this._typedArray=o,this._gltfJson=r,this._cacheKey=s,this._gltf=void 0,this._bufferLoaders=[],this._state=ut.UNLOADED,this._promise=void 0}c(Object.create)&&(ed.prototype=Object.create(wo.prototype),ed.prototype.constructor=ed);Object.defineProperties(ed.prototype,{cacheKey:{get:function(){return this._cacheKey}},gltf:{get:function(){return this._gltf}}});ed.prototype.load=async function(){return c(this._promise)?this._promise:(this._state=ut.LOADING,c(this._gltfJson)?(this._promise=w4(this,this._gltfJson),this._promise):c(this._typedArray)?(this._promise=S4(this,this._typedArray),this._promise):(this._promise=Fde(this),this._promise))};async function Fde(e){let t;try{const n=await e._fetchGltf();if(e.isDestroyed())return;t=new Uint8Array(n)}catch(n){if(e.isDestroyed())return;gO(e,n)}return S4(e,t)}function gO(e,t){e.unload(),e._state=ut.FAILED;const n=`Failed to load glTF: ${e._gltfResource.url}`;throw e.getError(n,t)}async function Bde(e,t){if(c(t.asset)&&t.asset.version==="2.0"&&!cr(t,"KHR_techniques_webgl")&&!cr(t,"KHR_materials_common"))return Promise.resolve();const n=[];me.buffer(t,function(i){if(!c(i.extras._pipeline.source)&&c(i.uri)){const o=e._baseR
uniform int u_polygonsLength;
uniform int u_extentsLength;
uniform highp sampler2D u_polygonTexture;
uniform highp sampler2D u_extentsTexture;
int getPolygonIndex(float dimension, vec2 coord) {
vec2 uv = coord.xy * dimension;
return int(floor(uv.y) * dimension + floor(uv.x));
}
vec2 getLookupUv(ivec2 dimensions, int i) {
int pixY = i / dimensions.x;
int pixX = i - (pixY * dimensions.x);
float pixelWidth = 1.0 / float(dimensions.x);
float pixelHeight = 1.0 / float(dimensions.y);
float u = (float(pixX) + 0.5) * pixelWidth; // sample from center of pixel
float v = (float(pixY) + 0.5) * pixelHeight;
return vec2(u, v);
}
vec4 getExtents(int i) {
return texture(u_extentsTexture, getLookupUv(textureSize(u_extentsTexture, 0), i));
}
ivec2 getPositionsLengthAndExtentsIndex(int i) {
vec2 uv = getLookupUv(textureSize(u_polygonTexture, 0), i);
vec4 value = texture(u_polygonTexture, uv);
return ivec2(int(value.x), int(value.y));
}
vec2 getPolygonPosition(int i) {
vec2 uv = getLookupUv(textureSize(u_polygonTexture, 0), i);
return texture(u_polygonTexture, uv).xy;
}
vec2 getCoordinates(vec2 textureCoordinates, vec4 extents) {
float latitude = mix(extents.x, extents.x + 1.0 / extents.z, textureCoordinates.y);
float longitude = mix(extents.y, extents.y + 1.0 / extents.w, textureCoordinates.x);
return vec2(latitude, longitude);
}
void main() {
int lastPolygonIndex = 0;
out_FragColor = vec4(1.0);
// Get the relevant region of the texture
float dimension = float(u_extentsLength);
if (u_extentsLength > 2) {
dimension = ceil(log2(float(u_extentsLength)));
}
int regionIndex = getPolygonIndex(dimension, v_textureCoordinates);
for (int polygonIndex = 0; polygonIndex < u_polygonsLength; polygonIndex++) {
ivec2 positionsLengthAndExtents = getPositionsLengthAndExtentsIndex(lastPolygonIndex);
int positionsLength = positionsLengthAndExtents.x;
int polygonExtentsIndex = positionsLengthAndExtents.y;
lastPolygonIndex += 1;
// Only compute signed distance for the relevant part of the atlas
if (polygonExtentsIndex == regionIndex) {
float clipAmount = czm_infinity;
vec4 extents = getExtents(polygonExtentsIndex);
vec2 textureOffset = vec2(mod(float(polygonExtentsIndex), dimension), floor(float(polygonExtentsIndex) / dimension)) / dimension;
vec2 p = getCoordinates((v_textureCoordinates - textureOffset) * dimension, extents);
float s = 1.0;
// Check each edge for absolute distance
for (int i = 0, j = positionsLength - 1; i < positionsLength; j = i, i++) {
vec2 a = getPolygonPosition(lastPolygonIndex + i);
vec2 b = getPolygonPosition(lastPolygonIndex + j);
vec2 ab = b - a;
vec2 pa = p - a;
float t = dot(pa, ab) / dot(ab, ab);
t = clamp(t, 0.0, 1.0);
vec2 pq = pa - t * ab;
float d = length(pq);
// Inside / outside computation to determine sign
bvec3 cond = bvec3(p.y >= a.y,
p.y < b.y,
ab.x * pa.y > ab.y * pa.x);
if (all(cond) || all(not(cond))) s = -s;
if (abs(d) < abs(clipAmount)) {
clipAmount = d;
}
}
// Normalize the range to [0,1]
vec4 result = (s * vec4(clipAmount * length(extents.zw))) / 2.0 + 0.5;
// In the case where we've iterated through multiple polygons, take the minimum
out_FragColor = min(out_FragColor, result);
}
lastPolygonIndex += positionsLength;
}
}`;function Di(e){e=y(e,y.EMPTY_OBJECT),this._polygons=[],this._totalPositions=0,this.enabled=y(e.enabled,!0),this.inverse=y(e.inverse,!1),this.polygonAdded=new Le,this.polygonRemoved=new Le,this._owner=void 0,this._float32View=void 0,this._extentsFloat32View=void 0,this._extentsCount=0,this._polygonsTexture=void 0,this._extentsTexture=void 0,this._signedDistanceTexture=void 0,this._signedDistanceComputeCommand=void 0;const t=e.polygons;if(c(t)){const n=t.length;for(let i=0;i<n;++i)this._polygons.push(t[i])}}Object.defineProperties(Di.prototype,{length:{get:function(){return this._polygons.length}},totalPositions:{get:function(){return this._totalPositions}},extentsTexture:{get:function(){return this._extentsTexture}},extentsCount:{get:function(){return this._extentsCount}},pixelsNeededForExtents:{get:function(){return this.length}},pixelsNeededForPolygonPositions:{get:function(){return this.totalPositions+this.length}},clippingTexture:{get:function(){return this._signedDistanceTexture}},owner:{get:function(){return this._owner}},clippingPolygonsState:{get:function(){return this.inverse?-this.extentsCount:this.extentsCount}}});Di.prototype.add=function(e){A.typeOf.object("polygon",e);const t=this._polygons.length;return this._polygons.push(e),this.polygonAdded.raiseEvent(e,t),e};Di.prototype.get=function(e){return A.typeOf.number("index",e),this._polygons[e]};Di.prototype.contains=function(e){return A.typeOf.object("polygon",e),this._polygons.some(t=>Nh.equals(t,e))};Di.prototype.remove=function(e){A.typeOf.object("polygon",e);const t=this._polygons,n=t.findIndex(i=>Nh.equals(i,e));return n===-1?!1:(t.splice(n,1),this.polygonRemoved.raiseEvent(e,n),!0)};const bpe=new ce;function Tpe(e){const t=[],n=[],i=e.length;for(let r=0;r<i;++r){const a=e[r].computeSphericalExtents();let l=Math.max(a.height*2.5,.001),u=Math.max(a.width*2.5,.001),h=ce.clone(a);h.south-=l,h.west-=u,h.north+=l,h.east+=u,h.south=Math.max(h.south,-Math.PI),h.west=Math.max(h.west,-Math.PI),h.north=Math.min(h.north,Math.PI),h.east=Math.min(h.east,Math.PI);const f=[r];for(let _=0;_<t.length;++_){const g=t[_];if(c(g)&&c(ce.simpleIntersection(g,h))&&!ce.equals(g,h)){const m=n[_];f.push(...m),m.reduce((b,T)=>ce.union(e[T].computeSphericalExtents(bpe),b,b),a),t[_]=void 0,n[_]=void 0,l=Math.max(a.height*2.5,.001),u=Math.max(a.width*2.5,.001),h=ce.clone(a,h),h.south-=l,h.west-=u,h.north+=l,h.east+=u,h.south=Math.max(h.south,-Math.PI),h.west=Math.max(h.west,-Math.PI),h.north=Math.min(h.north,Math.PI),h.east=Math.min(h.east,Math.PI),_=-1}}t.push(h),n.push(f)}const o=new Map;return n.filter(c).forEach((r,s)=>r.forEach(a=>o.set(a,s))),{extentsList:t.filter(c),extentsIndexByPolygon:o}}Di.prototype.removeAll=function(){const e=this._polygons,t=e.length;for(let n=0;n<t;++n){const i=e[n];this.polygonRemoved.raiseEvent(i,n)}this._polygons=[]};function Ape(e){const t=e._float32View,n=e._extentsFloat32View,i=e._polygons,{extentsList:o,extentsIndexByPolygon:r}=Tpe(i);let s=0;for(const[l,u]of i.entries()){const h=u.length;t[s++]=h,t[s++]=r.get(l);for(let f=0;f<h;++f){const _=u.positions[f],g=Math.hypot(_.x,_.y),m=R.fastApproximateAtan2(g,_.z),b=R.fastApproximateAtan2(_.x,_.y);t[s++]=m,t[s++]=b}}let a=0;for(const l of o){const u=1/(l.east-l.west),h=1/(l.north-l.south);n[a++]=l.south,n[a++]=l.west,n[a++]=h,n[a++]=u}e._extentsCount=o.length}const Kw=new H;Di.prototype.update=function(e){const t=e.context;if(!Di.isSupported(e))throw new Te("ClippingPolygonCollections are only supported for WebGL 2.");const n=this._polygons.reduce((s,a)=>s+a.length,0);if(n===this.totalPositions||(this._totalPositions=n,this.length===0))return;c(this._signedDistanceComputeCommand)&&(this._signedDistanceComputeCommand.canceled=!0,this._signedDistanceComputeCommand=void 0);let i=this._polygonsTexture,o=this._extentsTexture,r=this._signedDistanceTexture;if(c(i)){const s=i.width*i.height;(s<this.pixelsNeededForPolygonPositions||this.pixelsNeededForPolygonPositions<.25*s)&&(i.destroy(),i=void 0,this._polygonsTexture=void 0)}if(!c(i)){const s=Di.getTextureResolution(i,this.pixelsNeededForPolygonPositions
uniform sampler2D u_pointCloud_depthGBuffer;
uniform vec2 u_distanceAndEdlStrength;
in vec2 v_textureCoordinates;
vec2 neighborContribution(float log2Depth, vec2 offset)
{
float dist = u_distanceAndEdlStrength.x;
vec2 texCoordOrig = v_textureCoordinates + offset * dist;
vec2 texCoord0 = v_textureCoordinates + offset * floor(dist);
vec2 texCoord1 = v_textureCoordinates + offset * ceil(dist);
float depthOrLogDepth0 = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, texCoord0));
float depthOrLogDepth1 = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, texCoord1));
// ignore depth values that are the clear depth
if (depthOrLogDepth0 == 0.0 || depthOrLogDepth1 == 0.0) {
return vec2(0.0);
}
// interpolate the two adjacent depth values
float depthMix = mix(depthOrLogDepth0, depthOrLogDepth1, fract(dist));
vec4 eyeCoordinate = czm_windowToEyeCoordinates(texCoordOrig, depthMix);
return vec2(max(0.0, log2Depth - log2(-eyeCoordinate.z / eyeCoordinate.w)), 1.0);
}
void main()
{
float depthOrLogDepth = czm_unpackDepth(texture(u_pointCloud_depthGBuffer, v_textureCoordinates));
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, depthOrLogDepth);
eyeCoordinate /= eyeCoordinate.w;
float log2Depth = log2(-eyeCoordinate.z);
if (depthOrLogDepth == 0.0) // 0.0 is the clear value for the gbuffer
{
discard;
}
vec4 color = texture(u_pointCloud_colorGBuffer, v_textureCoordinates);
// sample from neighbors left, right, down, up
vec2 texelSize = 1.0 / czm_viewport.zw;
vec2 responseAndCount = vec2(0.0);
responseAndCount += neighborContribution(log2Depth, vec2(-texelSize.x, 0.0));
responseAndCount += neighborContribution(log2Depth, vec2(+texelSize.x, 0.0));
responseAndCount += neighborContribution(log2Depth, vec2(0.0, -texelSize.y));
responseAndCount += neighborContribution(log2Depth, vec2(0.0, +texelSize.y));
float response = responseAndCount.x / responseAndCount.y;
float strength = u_distanceAndEdlStrength.y;
float shade = exp(-response * 300.0 * strength);
color.rgb *= shade;
out_FragColor = vec4(color);
// Input and output depth are the same.
gl_FragDepth = depthOrLogDepth;
}
`;function Jh(){this._framebuffer=new on({colorAttachmentsLength:2,depth:!0,supportsDepthTexture:!0}),this._drawCommand=void 0,this._clearCommand=void 0,this._strength=1,this._radius=1}Object.defineProperties(Jh.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 S_e(e){e._framebuffer.destroy(),e._drawCommand=void 0,e._clearCommand=void 0}const tS=new H;function v_e(e,t){const n=new Oe({defines:["LOG_DEPTH_WRITE"],sources:[w_e]}),i={u_pointCloud_colorGBuffer:function(){return e.colorGBuffer},u_pointCloud_depthGBuffer:function(){return e.depthGBuffer},u_distanceAndEdlStrength:function(){return tS.x=e._radius,tS.y=e._strength,tS}},o=Ue.fromCache({blending:Zn.ALPHA_BLEND,depthMask:!0,depthTest:{enabled:!0},stencilTest:At.setCesium3DTileBit(),stencilMask:At.CESIUM_3D_TILE_MASK});e._drawCommand=t.createViewportQuadCommand(n,{uniformMap:i,renderState:o,pass:xe.CESIUM_3D_TILE,owner:e}),e._clearCommand=new bi({framebuffer:e.framebuffer,color:new z(0,0,0,0),depth:1,renderState:Ue.fromCache(),pass:xe.CESIUM_3D_TILE,owner:e})}function I_e(e,t){const n=t.drawingBufferWidth,i=t.drawingBufferHeight;e._framebuffer.update(t,n,i),v_e(e,t)}function xH(e){return e.drawBuffers&&e.fragmentDepth}Jh.isSupported=xH;function D_e(e,t){let n=e.shaderCache.getDerivedShaderProgram(t,"EC");if(!c(n)){const i=t._attributeLocations,o=t.fragmentShaderSource.clone();o.sources.splice(0,0,`layout (location = 0) out vec4 out_FragData_0;
layout (location = 1) out vec4 out_FragData_1;`),o.sources=o.sources.map(function(r){return r=Oe.replaceMain(r,"czm_point_cloud_post_process_main"),r=r.replaceAll(/out_FragColor/g,"out_FragData_0"),r}),o.sources.push(`void main()
{
czm_point_cloud_post_process_main();
#ifdef LOG_DEPTH
czm_writeLogDepth();
out_FragData_1 = czm_packDepth(gl_FragDepth);
#else
out_FragData_1 = czm_packDepth(gl_FragCoord.z);
#endif
}`),n=e.shaderCache.createDerivedShaderProgram(t,"EC",{vertexShaderSource:t.vertexShaderSource,fragmentShaderSource:o,attributeLocations:i})}return n}Jh.prototype.update=function(e,t,n,i){if(!xH(e.context))return;this._strength=n.eyeDomeLightingStrength,this._radius=n.eyeDomeLightingRadius*e.pixelRatio,I_e(this,e.context);let o;const r=e.commandList,s=r.length;for(o=t;o<s;++o){const u=r[o];if(u.primitiveType!==ze.POINTS||u.pass===xe.TRANSLUCENT)continue;let h,f,_=u.derivedCommands.pointCloudProcessor;c(_)&&(h=_.command,f=_.originalShaderProgram),(!c(h)||u.dirty||f!==u.shaderProgram||h.framebuffer!==this.framebuffer)&&(h=Ze.shallowClone(u,h),h.framebuffer=this.framebuffer,h.shaderProgram=D_e(e.context,u.shaderProgram),h.castShadows=!1,h.receiveShadows=!1,c(_)||(_={command:h,originalShaderProgram:u.shaderProgram},u.derivedCommands.pointCloudProcessor=_),_.originalShaderProgram=u.shaderProgram),r[o]=h}const a=this._clearCommand,l=this._drawCommand;l.boundingVolume=i,r.push(l),r.push(a)};Jh.prototype.isDestroyed=function(){return!1};Jh.prototype.destroy=function(){return S_e(this),ve(this)};function q0(e){const t=y(e,{});this.attenuation=y(t.attenuation,!1),this.geometricErrorScale=y(t.geometricErrorScale,1),this.maximumAttenuation=t.maximumAttenuation,this.baseResolution=t.baseResolution,this.eyeDomeLighting=y(t.eyeDomeLighting,!0),this.eyeDomeLightingStrength=y(t.eyeDomeLightingStrength,1),this.eyeDomeLightingRadius=y(t.eyeDomeLightingRadius,1),this.backFaceCulling=y(t.backFaceCulling,!1),this.normalShading=y(t.normalShading,!0)}q0.isSupported=function(e){return Jh.isSupported(e.context)};const zr={},P_e=new te(0,0,0,1);let Zr=new te;const O_e=new Re,nS=new H,iS=new H;zr.wgs84ToWindowCoordinates=function(e,t,n){return zr.wgs84WithEyeOffsetToWindowCoordinates(e,t,d.ZERO,n)};const tF=new te,nF=new d;function Og(e,t,n,i){const o=n.viewMatrix,r=L.multiplyByVector(o,te.fromElements(e.x,e.y,e.z,1,tF),tF),s=d.multiplyComponents(t,d.normalize(r,nF),nF);return r.x+=t.x+s.x,r.y+=t.y+s.y,r.z+=s.z,L.multiplyByVector(n.frustum.projectionMatrix,r,i)}const L_e=new he(Math.PI,R.PI_OVER_TWO),R_e=new d,N_e=new d;zr.wgs84WithEyeOffsetToWindowCoordinates=function(e,t,n,i){if(!c(e))throw new E("scene is required.");if(!c(t))throw new E("position is required.");const o=e.frameState,r=zr.computeActualWgs84Position(o,t,P_e);if(!c(r))return;const s=e.canvas,a=O_e;a.x=0,a.y=0,a.width=s.clientWidth,a.height=s.clientHeight;const l=e.camera;let u=!1;if(o.mode===oe.SCENE2D){const h=e.mapProjection,f=L_e,_=h.project(f,R_e),g=d.clone(l.position,N_e),m=l.frustum.clone(),b=L.computeViewportTransformation(a,0,1,new L),T=l.frustum.projectionMatrix,x=l.positionWC.y,C=d.fromElements(R.sign(x)*_.x-x,0,-l.positionWC.x),w=zt.pointToGLWindowCoordinates(T,b,C);if(x===0||w.x<=0||w.x>=s.clientWidth)u=!0;else{if(w.x>s.clientWidth*.5){a.width=w.x,l.frustum.right=_.x-x,Zr=Og(r,n,l,Zr),zr.clipToGLWindowCoordinates(a,Zr,nS),a.x+=w.x,l.position.x=-l.position.x;const v=l.frustum.right;l.frustum.right=-l.frustum.left,l.frustum.left=-v,Zr=Og(r,n,l,Zr),zr.clipToGLWindowCoordinates(a,Zr,iS)}else{a.x+=w.x,a.width-=w.x,l.frustum.left=-_.x-x,Zr=Og(r,n,l,Zr),zr.clipToGLWindowCoordinates(a,Zr,nS),a.x=a.x-a.width,l.position.x=-l.position.x;const v=l.frustum.left;l.frustum.left=-l.frustum.right,l.frustum.right=-v,Zr=Og(r,n,l,Zr),zr.clipToGLWindowCoordinates(a,Zr,iS)}d.clone(g,l.position),l.frustum=m.clone(),i=H.clone(nS,i),(i.x<0||i.x>s.clientWidth)&&(i.x=iS.x)}}if(o.mode!==oe.SCENE2D||u){if(Zr=Og(r,n,l,Zr),Zr.z<0&&!(l.frustum instanceof It)&&!(l.frustum instanceof Ki))return;i=zr.clipToGLWindowCoordinates(a,Zr,i)}return i.y=s.clientHeight-i.y,i};zr.wgs84ToDrawingBufferCoordinates=function(e,t,n){if(n=zr.wgs84ToWindowCoordinates(e,t,n),!!c(n))return zr.transformWindowToDrawingBuffer(e,n,n)};const Pu=new d,M_e=new he;zr.computeActualWgs84Position=function(e,t,n){const i=e.mode;if(i===oe.SCENE3D)return d.clone(t,n);const o=e.mapProjection,r=o.ellipsoid.cartesianToCartographic(t,M_e);if(!c(r))return;if(o.project(r,Pu),i===oe.COLUMBUS_VIEW)return d.fromElements(Pu.z,Pu.x,Pu.y,n);if(i===o
precision highp float;
czm_modelMaterial defaultModelMaterial()
{
czm_modelMaterial material;
material.diffuse = vec3(0.0);
material.specular = vec3(1.0);
material.roughness = 1.0;
material.occlusion = 1.0;
material.normalEC = vec3(0.0, 0.0, 1.0);
material.emissive = vec3(0.0);
material.alpha = 1.0;
return material;
}
vec4 handleAlpha(vec3 color, float alpha)
{
#ifdef ALPHA_MODE_MASK
if (alpha < u_alphaCutoff) {
discard;
}
#endif
return vec4(color, alpha);
}
SelectedFeature selectedFeature;
void main()
{
#ifdef HAS_MODEL_SPLITTER
modelSplitterStage();
#endif
czm_modelMaterial material = defaultModelMaterial();
ProcessedAttributes attributes;
geometryStage(attributes);
FeatureIds featureIds;
featureIdStage(featureIds, attributes);
Metadata metadata;
MetadataClass metadataClass;
MetadataStatistics metadataStatistics;
metadataStage(metadata, metadataClass, metadataStatistics, attributes);
#ifdef HAS_SELECTED_FEATURE_ID
selectedFeatureIdStage(selectedFeature, featureIds);
#endif
#ifndef CUSTOM_SHADER_REPLACE_MATERIAL
materialStage(material, attributes, selectedFeature);
#endif
#ifdef HAS_CUSTOM_FRAGMENT_SHADER
customShaderStage(material, attributes, featureIds, metadata, metadataClass, metadataStatistics);
#endif
lightingStage(material, attributes);
#ifdef HAS_SELECTED_FEATURE_ID
cpuStylingStage(material, selectedFeature);
#endif
#ifdef HAS_MODEL_COLOR
modelColorStage(material);
#endif
#ifdef HAS_PRIMITIVE_OUTLINE
primitiveOutlineStage(material);
#endif
vec4 color = handleAlpha(material.diffuse, material.alpha);
#ifdef HAS_CLIPPING_PLANES
modelClippingPlanesStage(color);
#endif
#ifdef ENABLE_CLIPPING_POLYGONS
modelClippingPolygonsStage();
#endif
#if defined(HAS_SILHOUETTE) && defined(HAS_NORMALS)
silhouetteStage(color);
#endif
#ifdef HAS_ATMOSPHERE
atmosphereStage(color, attributes);
#endif
out_FragColor = color;
}
`,Lge=`precision highp float;
czm_modelVertexOutput defaultVertexOutput(vec3 positionMC) {
czm_modelVertexOutput vsOutput;
vsOutput.positionMC = positionMC;
vsOutput.pointSize = 1.0;
return vsOutput;
}
void main()
{
// Initialize the attributes struct with all
// attributes except quantized ones.
ProcessedAttributes attributes;
initializeAttributes(attributes);
// Dequantize the quantized ones and add them to the
// attributes struct.
#ifdef USE_DEQUANTIZATION
dequantizationStage(attributes);
#endif
#ifdef HAS_MORPH_TARGETS
morphTargetsStage(attributes);
#endif
#ifdef HAS_SKINNING
skinningStage(attributes);
#endif
#ifdef HAS_PRIMITIVE_OUTLINE
primitiveOutlineStage();
#endif
// Compute the bitangent according to the formula in the glTF spec.
// Normal and tangents can be affected by morphing and skinning, so
// the bitangent should not be computed until their values are finalized.
#ifdef HAS_BITANGENTS
attributes.bitangentMC = normalize(cross(attributes.normalMC, attributes.tangentMC) * attributes.tangentSignMC);
#endif
FeatureIds featureIds;
featureIdStage(featureIds, attributes);
#ifdef HAS_SELECTED_FEATURE_ID
SelectedFeature feature;
selectedFeatureIdStage(feature, featureIds);
// Handle any show properties that come from the style.
cpuStylingStage(attributes.positionMC, feature);
#endif
#if defined(USE_2D_POSITIONS) || defined(USE_2D_INSTANCING)
// The scene mode 2D pipeline stage and instancing stage add a different
// model view matrix to accurately project the model to 2D. However, the
// output positions and normals should be transformed by the 3D matrices
// to keep the data the same for the fragment shader.
mat4 modelView = czm_modelView3D;
mat3 normal = czm_normal3D;
#else
// These are used for individual model projection because they will
// automatically change based on the scene mode.
mat4 modelView = czm_modelView;
mat3 normal = czm_normal;
#endif
// Update the position for this instance in place
#ifdef HAS_INSTANCING
// The legacy instance stage is used when rendering i3dm models that
// encode instances transforms in world space, as opposed to glTF models
// that use EXT_mesh_gpu_instancing, where instance transforms are encoded
// in object space.
#ifdef USE_LEGACY_INSTANCING
mat4 instanceModelView;
mat3 instanceModelViewInverseTranspose;
legacyInstancingStage(attributes, instanceModelView, instanceModelViewInverseTranspose);
modelView = instanceModelView;
normal = instanceModelViewInverseTranspose;
#else
instancingStage(attributes);
#endif
#ifdef USE_PICKING
v_pickColor = a_pickColor;
#endif
#endif
Metadata metadata;
MetadataClass metadataClass;
MetadataStatistics metadataStatistics;
metadataStage(metadata, metadataClass, metadataStatistics, attributes);
#ifdef HAS_VERTICAL_EXAGGERATION
verticalExaggerationStage(attributes);
#endif
#ifdef HAS_CUSTOM_VERTEX_SHADER
czm_modelVertexOutput vsOutput = defaultVertexOutput(attributes.positionMC);
customShaderStage(vsOutput, attributes, featureIds, metadata, metadataClass, metadataStatistics);
#endif
// Compute the final position in each coordinate system needed.
// This returns the value that will be assigned to gl_Position.
vec4 positionClip = geometryStage(attributes, modelView, normal);
// This must go after the geometry stage as it needs v_positionWC
#ifdef HAS_ATMOSPHERE
atmosphereStage(attributes);
#endif
#ifdef ENABLE_CLIPPING_POLYGONS
modelClippingPolygonsStage(attributes);
#endif
#ifdef HAS_SILHOUETTE
silhouetteStage(attributes, positionClip);
#endif
#ifdef HAS_POINT_CLOUD_SHOW_STYLE
float show = pointCloudShowStylingStage(attributes, metadata);
#else
float show = 1.0;
#endif
#ifdef HAS_POINT_CLOUD_BACK_FACE_CULLING
show *= pointCloudBackFaceCullingStage();
#endif
#ifdef HAS_POINT_CLOUD_COLOR_STYLE
v_pointCloudColor = pointCloudColorStylingStage(attributes, metadata);
#endif
#ifdef PRIMITIVE_TYPE_POINTS
#ifdef HAS_CUSTOM_VERTEX_SHADER
gl_PointSize = vsOutput.pointSize;
#elif defined(HAS_POINT_CLOUD_POINT_SIZE_STYLE) || defined(HAS_POINT_CLOUD_ATTENUATION)
gl_PointSize = pointCloudPointSizeStylingStage(attributes, metadata);
#else
gl_PointSize = 1.0;
#endif
gl_PointSize *= show;
#endif
gl_Position = show * positionClip;
}
`;function PO(e){e=y(e,y.EMPTY_OBJECT);const t=e.command,n=e.primitiveRenderResources;A.typeOf.object("options.command",t),A.typeOf.object("options.primitiveRenderResources",n);const i=n.model;this._command=t,this._model=i,this._runtimePrimitive=n.runtimePrimitive,this._modelMatrix=t.modelMatrix,this._boundingVolume=t.boundingVolume,this._cullFace=t.renderState.cull.face;const o=i.classificationType;this._classificationType=o,this._classifiesTerrain=o!==Ui.CESIUM_3D_TILE,this._classifies3DTiles=o!==Ui.TERRAIN,this._useDebugWireframe=i._enableDebugWireframe&&i.debugWireframe,this._pickId=n.pickId,this._commandListTerrain=[],this._commandList3DTiles=[],this._commandListIgnoreShow=[],this._commandListDebugWireframe=[],this._commandListTerrainPicking=[],this._commandList3DTilesPicking=[],Fge(this)}function Rge(e){return{colorMask:{red:!1,green:!1,blue:!1,alpha:!1},stencilTest:{enabled:!0,frontFunction:e,frontOperation:{fail:nt.KEEP,zFail:nt.DECREMENT_WRAP,zPass:nt.KEEP},backFunction:e,backOperation:{fail:nt.KEEP,zFail:nt.INCREMENT_WRAP,zPass:nt.KEEP},reference:At.CESIUM_3D_TILE_MASK,mask:At.CESIUM_3D_TILE_MASK},stencilMask:At.CLASSIFICATION_MASK,depthTest:{enabled:!0,func:lp.LESS_OR_EQUAL},depthMask:!1}}const Nge={stencilTest:{enabled:!0,frontFunction:Pn.NOT_EQUAL,frontOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},backFunction:Pn.NOT_EQUAL,backOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},reference:0,mask:At.CLASSIFICATION_MASK},stencilMask:At.CLASSIFICATION_MASK,depthTest:{enabled:!1},depthMask:!1,blending:Zn.PRE_MULTIPLIED_ALPHA_BLEND},Mge={stencilTest:{enabled:!0,frontFunction:Pn.NOT_EQUAL,frontOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},backFunction:Pn.NOT_EQUAL,backOperation:{fail:nt.ZERO,zFail:nt.ZERO,zPass:nt.ZERO},reference:0,mask:At.CLASSIFICATION_MASK},stencilMask:At.CLASSIFICATION_MASK,depthTest:{enabled:!1},depthMask:!1},MH=[];function Fge(e){const t=e._command,n=MH;if(e._useDebugWireframe){t.pass=xe.OPAQUE,n.length=0,n.push(t),e._commandListDebugWireframe=Oy(e,n,e._commandListDebugWireframe);const r=e._commandListDebugWireframe,s=r.length;for(let a=0;a<s;a++){const l=r[a];l.count*=2,l.offset*=2}return}const o=e.model.allowPicking;if(e._classifiesTerrain){const r=xe.TERRAIN_CLASSIFICATION,s=tD(t,r),a=lF(t,r);n.length=0,n.push(s,a),e._commandListTerrain=Oy(e,n,e._commandListTerrain),o&&(e._commandListTerrainPicking=uF(e,n,e._commandListTerrainPicking))}if(e._classifies3DTiles){const r=xe.CESIUM_3D_TILE_CLASSIFICATION,s=tD(t,r),a=lF(t,r);n.length=0,n.push(s,a),e._commandList3DTiles=Oy(e,n,e._commandList3DTiles),o&&(e._commandList3DTilesPicking=uF(e,n,e._commandList3DTilesPicking))}}function Oy(e,t,n){const i=e._runtimePrimitive,o=i.batchLengths,r=i.batchOffsets,s=o.length,a=t.length;for(let l=0;l<s;l++){const u=o[l],h=r[l];for(let f=0;f<a;f++){const _=t[f],g=Ze.shallowClone(_);g.count=u,g.offset=h,n.push(g)}}return n}function tD(e,t){const n=Ze.shallowClone(e);n.cull=!1,n.pass=t;const i=t===xe.TERRAIN_CLASSIFICATION?Pn.ALWAYS:Pn.EQUAL,o=Rge(i);return n.renderState=Ue.fromCache(o),n}function lF(e,t){const n=Ze.shallowClone(e);return n.cull=!1,n.pass=t,n.renderState=Ue.fromCache(Nge),n}const Bge=[];function uF(e,t,n){const i=Ue.fromCache(Mge),o=t[0],r=t[1],s=Ze.shallowClone(o);s.cull=!0,s.pickOnly=!0;const a=Ze.shallowClone(r);a.cull=!0,a.pickOnly=!0,a.renderState=i,a.pickId=e._pickId;const l=Bge;return l.length=0,l.push(s,a),Oy(e,l,n)}Object.defineProperties(PO.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(e){this._modelMatrix=L.clone(e,this._modelMatrix);const t=this._runtimePrimitive.boundingSphere;this._boundingVolume=se.transform(t,this._modelMatrix,this._boundingVolume)}},boundingVolume:{get
// https://github.com/0xfaded/ellipse_demo/issues/1
// https://stackoverflow.com/questions/22959698/distance-from-given-point-to-given-ellipse
//
// This version uses only a single iteration for best performance. For fog
// rendering, the difference is negligible.
vec2 nearestPointOnEllipseFast(vec2 pos, vec2 radii) {
vec2 p = abs(pos);
vec2 inverseRadii = 1.0 / radii;
vec2 evoluteScale = (radii.x * radii.x - radii.y * radii.y) * vec2(1.0, -1.0) * inverseRadii;
// We describe the ellipse parametrically: v = radii * vec2(cos(t), sin(t))
// but store the cos and sin of t in a vec2 for efficiency.
// Initial guess: t = cos(pi/4)
vec2 tTrigs = vec2(0.70710678118);
vec2 v = radii * tTrigs;
// Find the evolute of the ellipse (center of curvature) at v.
vec2 evolute = evoluteScale * tTrigs * tTrigs * tTrigs;
// Find the (approximate) intersection of p - evolute with the ellipsoid.
vec2 q = normalize(p - evolute) * length(v - evolute);
// Update the estimate of t.
tTrigs = (q + evolute) * inverseRadii;
tTrigs = normalize(clamp(tTrigs, 0.0, 1.0));
v = radii * tTrigs;
return v * sign(pos);
}
vec3 computeEllipsoidPositionWC(vec3 positionMC) {
// Get the world-space position and project onto a meridian plane of
// the ellipsoid
vec3 positionWC = (czm_model * vec4(positionMC, 1.0)).xyz;
vec2 positionEllipse = vec2(length(positionWC.xy), positionWC.z);
vec2 nearestPoint = nearestPointOnEllipseFast(positionEllipse, czm_ellipsoidRadii.xz);
// Reconstruct a 3D point in world space
return vec3(nearestPoint.x * normalize(positionWC.xy), nearestPoint.y);
}
void applyFog(inout vec4 color, vec4 groundAtmosphereColor, vec3 lightDirection, float distanceToCamera) {
vec3 fogColor = groundAtmosphereColor.rgb;
// If there is dynamic lighting, apply that to the fog.
const float NONE = 0.0;
if (czm_atmosphereDynamicLighting != NONE) {
float darken = clamp(dot(normalize(czm_viewerPositionWC), lightDirection), czm_fogMinimumBrightness, 1.0);
fogColor *= darken;
}
// Tonemap if HDR rendering is disabled
#ifndef HDR
fogColor.rgb = czm_acesTonemapping(fogColor.rgb);
fogColor.rgb = czm_inverseGamma(fogColor.rgb);
#endif
// Matches the constant in GlobeFS.glsl. This makes the fog falloff
// more gradual.
const float fogModifier = 0.15;
vec3 withFog = czm_fog(distanceToCamera, color.rgb, fogColor, fogModifier);
color = vec4(withFog, color.a);
}
void atmosphereStage(inout vec4 color, in ProcessedAttributes attributes) {
vec3 rayleighColor;
vec3 mieColor;
float opacity;
vec3 positionWC;
vec3 lightDirection;
// When the camera is in space, compute the position per-fragment for
// more accurate ground atmosphere. All other cases will use
//
// The if condition will be added in https://github.com/CesiumGS/cesium/issues/11717
if (false) {
positionWC = computeEllipsoidPositionWC(attributes.positionMC);
lightDirection = czm_getDynamicAtmosphereLightDirection(positionWC, czm_atmosphereDynamicLighting);
// The fog color is derived from the ground atmosphere color
czm_computeGroundAtmosphereScattering(
positionWC,
lightDirection,
rayleighColor,
mieColor,
opacity
);
} else {
positionWC = attributes.positionWC;
lightDirection = czm_getDynamicAtmosphereLightDirection(positionWC, czm_atmosphereDynamicLighting);
rayleighColor = v_atmosphereRayleighColor;
mieColor = v_atmosphereMieColor;
opacity = v_atmosphereOpacity;
}
//color correct rayleigh and mie colors
const bool ignoreBlackPixels = true;
rayleighColor = czm_applyHSBShift(rayleighColor, czm_atmosphereHsbShift, ignoreBlackPixels);
mieColor = czm_applyHSBShift(mieColor, czm_atmosphereHsbShift, ignoreBlackPixels);
vec4 groundAtmosphereColor = czm_computeAtmosphereColor(positionWC, lightDirection, rayleighColor, mieColor, opacity);
if (u_isInFog) {
float distanceToCamera = length(attributes.positionEC);
applyFog(color, groundAtmosphereColor, lightDirection, distanceToCamera);
} else {
// Ground atmosphere
}
}
`,iye=`void atmosphereStage(ProcessedAttributes attributes) {
vec3 lightDirection = czm_getDynamicAtmosphereLightDirection(v_positionWC, czm_atmosphereDynamicLighting);
czm_computeGroundAtmosphereScattering(
// This assumes the geometry stage came before this.
v_positionWC,
lightDirection,
v_atmosphereRayleighColor,
v_atmosphereMieColor,
v_atmosphereOpacity
);
}
`,zH={name:"AtmospherePipelineStage"};zH.process=function(e,t,n){const i=e.shaderBuilder;i.addDefine("HAS_ATMOSPHERE",void 0,ge.BOTH),i.addDefine("COMPUTE_POSITION_WC_ATMOSPHERE",void 0,ge.BOTH),i.addVarying("vec3","v_atmosphereRayleighColor"),i.addVarying("vec3","v_atmosphereMieColor"),i.addVarying("float","v_atmosphereOpacity"),i.addVertexLines([iye]),i.addFragmentLines([nye]),i.addUniform("bool","u_isInFog",ge.FRAGMENT),e.uniformMap.u_isInFog=function(){const o=d.distance(n.camera.positionWC,t.boundingSphere.center);return R.fog(o,n.fog.density)>R.EPSILON3}};const oye=zH,rye=`vec3 proceduralIBL(
vec3 positionEC,
vec3 normalEC,
vec3 lightDirectionEC,
vec3 lightColorHdr,
czm_pbrParameters pbrParameters
) {
vec3 v = -positionEC;
vec3 positionWC = vec3(czm_inverseView * vec4(positionEC, 1.0));
vec3 vWC = -normalize(positionWC);
vec3 l = normalize(lightDirectionEC);
vec3 n = normalEC;
vec3 r = normalize(czm_inverseViewRotation * normalize(reflect(v, n)));
float NdotL = clamp(dot(n, l), 0.001, 1.0);
float NdotV = abs(dot(n, v)) + 0.001;
// Figure out if the reflection vector hits the ellipsoid
float vertexRadius = length(positionWC);
float horizonDotNadir = 1.0 - min(1.0, czm_ellipsoidRadii.x / vertexRadius);
float reflectionDotNadir = dot(r, normalize(positionWC));
// Flipping the X vector is a cheap way to get the inverse of czm_temeToPseudoFixed, since that's a rotation about Z.
r.x = -r.x;
r = -normalize(czm_temeToPseudoFixed * r);
r.x = -r.x;
vec3 diffuseColor = pbrParameters.diffuseColor;
float roughness = pbrParameters.roughness;
vec3 specularColor = pbrParameters.f0;
float inverseRoughness = 1.04 - roughness;
inverseRoughness *= inverseRoughness;
vec3 sceneSkyBox = czm_textureCube(czm_environmentMap, r).rgb * inverseRoughness;
float atmosphereHeight = 0.05;
float blendRegionSize = 0.1 * ((1.0 - inverseRoughness) * 8.0 + 1.1 - horizonDotNadir);
float blendRegionOffset = roughness * -1.0;
float farAboveHorizon = clamp(horizonDotNadir - blendRegionSize * 0.5 + blendRegionOffset, 1.0e-10 - blendRegionSize, 0.99999);
float aroundHorizon = clamp(horizonDotNadir + blendRegionSize * 0.5, 1.0e-10 - blendRegionSize, 0.99999);
float farBelowHorizon = clamp(horizonDotNadir + blendRegionSize * 1.5, 1.0e-10 - blendRegionSize, 0.99999);
float smoothstepHeight = smoothstep(0.0, atmosphereHeight, horizonDotNadir);
vec3 belowHorizonColor = mix(vec3(0.1, 0.15, 0.25), vec3(0.4, 0.7, 0.9), smoothstepHeight);
vec3 nadirColor = belowHorizonColor * 0.5;
vec3 aboveHorizonColor = mix(vec3(0.9, 1.0, 1.2), belowHorizonColor, roughness * 0.5);
vec3 blueSkyColor = mix(vec3(0.18, 0.26, 0.48), aboveHorizonColor, reflectionDotNadir * inverseRoughness * 0.5 + 0.75);
vec3 zenithColor = mix(blueSkyColor, sceneSkyBox, smoothstepHeight);
vec3 blueSkyDiffuseColor = vec3(0.7, 0.85, 0.9);
float diffuseIrradianceFromEarth = (1.0 - horizonDotNadir) * (reflectionDotNadir * 0.25 + 0.75) * smoothstepHeight;
float diffuseIrradianceFromSky = (1.0 - smoothstepHeight) * (1.0 - (reflectionDotNadir * 0.25 + 0.25));
vec3 diffuseIrradiance = blueSkyDiffuseColor * clamp(diffuseIrradianceFromEarth + diffuseIrradianceFromSky, 0.0, 1.0);
float notDistantRough = (1.0 - horizonDotNadir * roughness * 0.8);
vec3 specularIrradiance = mix(zenithColor, aboveHorizonColor, smoothstep(farAboveHorizon, aroundHorizon, reflectionDotNadir) * notDistantRough);
specularIrradiance = mix(specularIrradiance, belowHorizonColor, smoothstep(aroundHorizon, farBelowHorizon, reflectionDotNadir) * inverseRoughness);
specularIrradiance = mix(specularIrradiance, nadirColor, smoothstep(farBelowHorizon, 1.0, reflectionDotNadir) * inverseRoughness);
// Luminance model from page 40 of http://silviojemma.com/public/papers/lighting/spherical-harmonic-lighting.pdf
#ifdef USE_SUN_LUMINANCE
// Angle between sun and zenith
float LdotZenith = clamp(dot(normalize(czm_inverseViewRotation * l), vWC), 0.001, 1.0);
float S = acos(LdotZenith);
// Angle between zenith and current pixel
float NdotZenith = clamp(dot(normalize(czm_inverseViewRotation * n), vWC), 0.001, 1.0);
// Angle between sun and current pixel
float gamma = acos(NdotL);
float numerator = ((0.91 + 10.0 * exp(-3.0 * gamma) + 0.45 * pow(NdotL, 2.0)) * (1.0 - exp(-0.32 / NdotZenith)));
float denominator = (0.91 + 10.0 * exp(-3.0 * S) + 0.45 * pow(LdotZenith,2.0)) * (1.0 - exp(-0.32));
float luminance = model_luminanceAtZenith * (numerator / denominator);
#endif
vec2 brdfLut = texture(czm_brdfLut, vec2(NdotV, roughness)).rg;
vec3 iblColor = (diffuseIrradiance * diffuseColor * model_iblFactor.x) + (specularIrradiance * czm_srgbToLinear(specularColor * brdfLut.x + brdfLut.y) * model_iblFactor.y);
float maximumComponent = max(max(lightColorHdr.x, lightColorHdr.y), lightColorHdr.z);
vec3 lightColor = lightColorHdr / max(maximumComponent, 1.0);
iblColor *= lightColor;
#ifdef USE_SUN_LUMINANCE
iblColor *= luminance;
#endif
return iblColor;
}
#if defined(DIFFUSE_IBL) || defined(SPECULAR_IBL)
vec3 textureIBL(
vec3 positionEC,
vec3 normalEC,
vec3 lightDirectionEC,
czm_pbrParameters pbrParameters
) {
vec3 diffuseColor = pbrParameters.diffuseColor;
float roughness = pbrParameters.roughness;
vec3 specularColor = pbrParameters.f0;
vec3 v = -positionEC;
vec3 n = normalEC;
vec3 l = normalize(lightDirectionEC);
vec3 h = normalize(v + l);
float NdotV = abs(dot(n, v)) + 0.001;
float VdotH = clamp(dot(v, h), 0.0, 1.0);
const mat3 yUpToZUp = mat3(
-1.0, 0.0, 0.0,
0.0, 0.0, -1.0,
0.0, 1.0, 0.0
);
vec3 cubeDir = normalize(yUpToZUp * model_iblReferenceFrameMatrix * normalize(reflect(-v, n)));
#ifdef DIFFUSE_IBL
#ifdef CUSTOM_SPHERICAL_HARMONICS
vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, model_sphericalHarmonicCoefficients);
#else
vec3 diffuseIrradiance = czm_sphericalHarmonics(cubeDir, czm_sphericalHarmonicCoefficients);
#endif
#else
vec3 diffuseIrradiance = vec3(0.0);
#endif
#ifdef SPECULAR_IBL
vec3 r0 = specularColor.rgb;
float reflectance = max(max(r0.r, r0.g), r0.b);
vec3 r90 = vec3(clamp(reflectance * 25.0, 0.0, 1.0));
vec3 F = fresnelSchlick2(r0, r90, VdotH);
vec2 brdfLut = texture(czm_brdfLut, vec2(NdotV, roughness)).rg;
#ifdef CUSTOM_SPECULAR_IBL
vec3 specularIBL = czm_sampleOctahedralProjection(model_specularEnvironmentMaps, model_specularEnvironmentMapsSize, cubeDir, roughness * model_specularEnvironmentMapsMaximumLOD, model_specularEnvironmentMapsMaximumLOD);
#else
vec3 specularIBL = czm_sampleOctahedralProjection(czm_specularEnvironmentMaps, czm_specularEnvironmentMapSize, cubeDir, roughness * czm_specularEnvironmentMapsMaximumLOD, czm_specularEnvironmentMapsMaximumLOD);
#endif
specularIBL *= F * brdfLut.x + brdfLut.y;
#else
vec3 specularIBL = vec3(0.0);
#endif
return diffuseColor * diffuseIrradiance + specularColor * specularIBL;
}
#endif
vec3 imageBasedLightingStage(
vec3 positionEC,
vec3 normalEC,
vec3 lightDirectionEC,
vec3 lightColorHdr,
czm_pbrParameters pbrParameters
) {
#if defined(DIFFUSE_IBL) || defined(SPECULAR_IBL)
// Environment maps were provided, use them for IBL
return textureIBL(
positionEC,
normalEC,
lightDirectionEC,
pbrParameters
);
#else
// Use the procedural IBL if there are no environment maps
return proceduralIBL(
positionEC,
normalEC,
lightDirectionEC,
lightColorHdr,
pbrParameters
);
#endif
}`,UH={name:"ImageBasedLightingPipelineStage"};UH.process=function(e,t,n){const i=t.imageBasedLighting,o=e.shaderBuilder;o.addDefine("USE_IBL_LIGHTING",void 0,ge.FRAGMENT),o.addUniform("vec2","model_iblFactor",ge.FRAGMENT),yl.isSupported(n.context)&&((i.useSphericalHarmonics||i.useSpecularEnvironmentMaps||i.enabled)&&o.addUniform("mat3","model_iblReferenceFrameMatrix",ge.FRAGMENT),c(i.sphericalHarmonicCoefficients)?(o.addDefine("DIFFUSE_IBL",void 0,ge.FRAGMENT),o.addDefine("CUSTOM_SPHERICAL_HARMONICS",void 0,ge.FRAGMENT),o.addUniform("vec3","model_sphericalHarmonicCoefficients[9]",ge.FRAGMENT)):i.useDefaultSphericalHarmonics&&o.addDefine("DIFFUSE_IBL",void 0,ge.FRAGMENT),c(i.specularEnvironmentMapAtlas)&&i.specularEnvironmentMapAtlas.ready?(o.addDefine("SPECULAR_IBL",void 0,ge.FRAGMENT),o.addDefine("CUSTOM_SPECULAR_IBL",void 0,ge.FRAGMENT),o.addUniform("sampler2D","model_specularEnvironmentMaps",ge.FRAGMENT),o.addUniform("vec2","model_specularEnvironmentMapsSize",ge.FRAGMENT),o.addUniform("float","model_specularEnvironmentMapsMaximumLOD",ge.FRAGMENT)):t.useDefaultSpecularMaps&&o.addDefine("SPECULAR_IBL",void 0,ge.FRAGMENT)),c(i.luminanceAtZenith)&&(o.addDefine("USE_SUN_LUMINANCE",void 0,ge.FRAGMENT),o.addUniform("float","model_luminanceAtZenith",ge.FRAGMENT)),o.addFragmentLines(rye);const r={model_iblFactor:function(){return i.imageBasedLightingFactor},model_iblReferenceFrameMatrix:function(){return t._iblReferenceFrameMatrix},model_luminanceAtZenith:function(){return i.luminanceAtZenith},model_sphericalHarmonicCoefficients:function(){return i.sphericalHarmonicCoefficients},model_specularEnvironmentMaps:function(){return i.specularEnvironmentMapAtlas.texture},model_specularEnvironmentMapsSize:function(){return i.specularEnvironmentMapAtlas.texture.dimensions},model_specularEnvironmentMapsMaximumLOD:function(){return i.specularEnvironmentMapAtlas.maximumMipmapLevel}};e.uniformMap=jt(r,e.uniformMap)};const sye=UH,aye=R.EPSILON16;function OO(e){e=y(e,y.EMPTY_OBJECT);const t=e.stage,n=e.runtimeArticulation;A.typeOf.object("options.stage",t),A.typeOf.object("options.runtimeArticulation",n),this._stage=t,this._runtimeArticulation=n,this._name=t.name,this._type=t.type,this._minimumValue=t.minimumValue,this._maximumValue=t.maximumValue,this._currentValue=t.initialValue}Object.defineProperties(OO.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(e){A.typeOf.number("value",e),e=R.clamp(e,this.minimumValue,this.maximumValue),R.equalsEpsilon(this._currentValue,e,aye)||(this._currentValue=e,this.runtimeArticulation._dirty=!0)}}});const cye=new d,oS=new $;OO.prototype.applyStageToMatrix=function(e){A.typeOf.object("result",e);const t=this.type,n=this.currentValue,i=cye;let o;switch(t){case Zc.XROTATE:o=$.fromRotationX(R.toRadians(n),oS),e=L.multiplyByMatrix3(e,o,e);break;case Zc.YROTATE:o=$.fromRotationY(R.toRadians(n),oS),e=L.multiplyByMatrix3(e,o,e);break;case Zc.ZROTATE:o=$.fromRotationZ(R.toRadians(n),oS),e=L.multiplyByMatrix3(e,o,e);break;case Zc.XTRANSLATE:i.x=n,i.y=0,i.z=0,e=L.multiplyByTranslation(e,i,e);break;case Zc.YTRANSLATE:i.x=0,i.y=n,i.z=0,e=L.multiplyByTranslation(e,i,e);break;case Zc.ZTRANSLATE:i.x=0,i.y=0,i.z=n,e=L.multiplyByTranslation(e,i,e);break;case Zc.XSCALE:i.x=n,i.y=1,i.z=1,e=L.multiplyByScale(e,i,e);break;case Zc.YSCALE:i.x=1,i.y=n,i.z=1,e=L.multiplyByScale(e,i,e);break;case Zc.ZSCALE:i.x=1,i.y=1,i.z=n,e=L.multiplyByScale(e,i,e);break;case Zc.UNIFORMSCALE:e=L.multiplyByUniformScale(e,n,e);break}return e};function BC(e){e=y(e,y.EMPTY_OBJECT);const t=e.articulation,n=e.sceneGraph;A.typeOf.object("options.articulation",t),A.typeOf.object("options.sceneGraph",n),this._articulation=t,this._sceneGraph=n,this._name=t.name,this._runtimeStages=[],this._runtimeStagesByName={},this._r
{
material.diffuse = mix(material.diffuse, model_color.rgb, model_colorBlend);
float highlight = ceil(model_colorBlend);
material.diffuse *= mix(model_color.rgb, vec3(1.0), highlight);
material.alpha *= model_color.a;
}
`,zm={name:"ModelColorPipelineStage",COLOR_UNIFORM_NAME:"model_color",COLOR_BLEND_UNIFORM_NAME:"model_colorBlend"};zm.process=function(e,t,n){const i=e.shaderBuilder;i.addDefine("HAS_MODEL_COLOR",void 0,ge.FRAGMENT),i.addFragmentLines(hye);const o={},r=t.color;r.alpha===0&&!t.hasSilhouette(n)&&(e.renderStateOptions.colorMask={red:!1,green:!1,blue:!1,alpha:!1}),r.alpha<1&&(e.alphaOptions.pass=xe.TRANSLUCENT),i.addUniform("vec4",zm.COLOR_UNIFORM_NAME,ge.FRAGMENT),o[zm.COLOR_UNIFORM_NAME]=function(){return t.color},i.addUniform("float",zm.COLOR_BLEND_UNIFORM_NAME,ge.FRAGMENT),o[zm.COLOR_BLEND_UNIFORM_NAME]=function(){return RC.getColorBlend(t.colorBlendMode,t.colorBlendAmount)},e.uniformMap=jt(o,e.uniformMap)};const nD=zm,fye=`#ifdef USE_CLIPPING_PLANES_FLOAT_TEXTURE
vec4 getClippingPlane(
highp sampler2D packedClippingPlanes,
int clippingPlaneNumber,
mat4 transform
) {
int pixY = clippingPlaneNumber / CLIPPING_PLANES_TEXTURE_WIDTH;
int pixX = clippingPlaneNumber - (pixY * CLIPPING_PLANES_TEXTURE_WIDTH);
float pixelWidth = 1.0 / float(CLIPPING_PLANES_TEXTURE_WIDTH);
float pixelHeight = 1.0 / float(CLIPPING_PLANES_TEXTURE_HEIGHT);
float u = (float(pixX) + 0.5) * pixelWidth; // sample from center of pixel
float v = (float(pixY) + 0.5) * pixelHeight;
vec4 plane = texture(packedClippingPlanes, vec2(u, v));
return czm_transformPlane(plane, transform);
}
#else
// Handle uint8 clipping texture instead
vec4 getClippingPlane(
highp sampler2D packedClippingPlanes,
int clippingPlaneNumber,
mat4 transform
) {
int clippingPlaneStartIndex = clippingPlaneNumber * 2; // clipping planes are two pixels each
int pixY = clippingPlaneStartIndex / CLIPPING_PLANES_TEXTURE_WIDTH;
int pixX = clippingPlaneStartIndex - (pixY * CLIPPING_PLANES_TEXTURE_WIDTH);
float pixelWidth = 1.0 / float(CLIPPING_PLANES_TEXTURE_WIDTH);
float pixelHeight = 1.0 / float(CLIPPING_PLANES_TEXTURE_HEIGHT);
float u = (float(pixX) + 0.5) * pixelWidth; // sample from center of pixel
float v = (float(pixY) + 0.5) * pixelHeight;
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 + pixelWidth, v)));
return czm_transformPlane(plane, transform);
}
#endif
float clip(vec4 fragCoord, sampler2D clippingPlanes, mat4 clippingPlanesMatrix) {
vec4 position = czm_windowToEyeCoordinates(fragCoord);
vec3 clipNormal = vec3(0.0);
vec3 clipPosition = vec3(0.0);
float pixelWidth = czm_metersPerPixel(position);
#ifdef UNION_CLIPPING_REGIONS
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.
#else
float clipAmount = 0.0;
bool clipped = true;
#endif
for (int i = 0; i < CLIPPING_PLANES_LENGTH; ++i) {
vec4 clippingPlane = getClippingPlane(clippingPlanes, i, clippingPlanesMatrix);
clipNormal = clippingPlane.xyz;
clipPosition = -clippingPlane.w * clipNormal;
float amount = dot(clipNormal, (position.xyz - clipPosition)) / pixelWidth;
#ifdef UNION_CLIPPING_REGIONS
clipAmount = czm_branchFreeTernary(i == 0, amount, min(amount, clipAmount));
if (amount <= 0.0) {
discard;
}
#else
clipAmount = max(amount, clipAmount);
clipped = clipped && (amount <= 0.0);
#endif
}
#ifndef UNION_CLIPPING_REGIONS
if (clipped) {
discard;
}
#endif
return clipAmount;
}
void modelClippingPlanesStage(inout vec4 color)
{
float clipDistance = clip(gl_FragCoord, model_clippingPlanes, model_clippingPlanesMatrix);
vec4 clippingPlanesEdgeColor = vec4(1.0);
clippingPlanesEdgeColor.rgb = model_clippingPlanesEdgeStyle.rgb;
float clippingPlanesEdgeWidth = model_clippingPlanesEdgeStyle.a;
if (clipDistance > 0.0 && clipDistance < clippingPlanesEdgeWidth) {
color = clippingPlanesEdgeColor;
}
}
`,kH={name:"ModelClippingPlanesPipelineStage"},pye=new H;kH.process=function(e,t,n){const i=t.clippingPlanes,o=n.context,r=e.shaderBuilder;r.addDefine("HAS_CLIPPING_PLANES",void 0,ge.FRAGMENT),r.addDefine("CLIPPING_PLANES_LENGTH",i.length,ge.FRAGMENT),i.unionClippingRegions&&r.addDefine("UNION_CLIPPING_REGIONS",void 0,ge.FRAGMENT),Li.useFloatTexture(o)&&r.addDefine("USE_CLIPPING_PLANES_FLOAT_TEXTURE",void 0,ge.FRAGMENT);const s=Li.getTextureResolution(i,o,pye);r.addDefine("CLIPPING_PLANES_TEXTURE_WIDTH",s.x,ge.FRAGMENT),r.addDefine("CLIPPING_PLANES_TEXTURE_HEIGHT",s.y,ge.FRAGMENT),r.addUniform("sampler2D","model_clippingPlanes",ge.FRAGMENT),r.addUniform("vec4","model_clippingPlanesEdgeStyle",ge.FRAGMENT),r.addUniform("mat4","model_clippingPlanesMatrix",ge.FRAGMENT),r.addFragmentLines(fye);const a={model_clippingPlanes:function(){return i.texture},model_clippingPlanesEdgeStyle:function(){const l=z.clone(i.edgeColor);return l.alpha=i.edgeWidth,l},model_clippingPlanesMatrix:function(){return t._clippingPlanesMatrix}};e.uniformMap=jt(a,e.uniformMap)};const mye=kH,_ye=`void modelClippingPolygonsStage(ProcessedAttributes attributes)
{
vec2 sphericalLatLong = czm_approximateSphericalCoordinates(v_positionWC);
sphericalLatLong.y = czm_branchFreeTernary(sphericalLatLong.y < czm_pi, sphericalLatLong.y, sphericalLatLong.y - czm_twoPi);
vec2 minDistance = vec2(czm_infinity);
v_regionIndex = -1;
v_clippingPosition = vec2(czm_infinity);
for (int regionIndex = 0; regionIndex < CLIPPING_POLYGON_REGIONS_LENGTH; regionIndex++) {
vec4 extents = czm_unpackClippingExtents(model_clippingExtents, regionIndex);
vec2 rectUv = (sphericalLatLong.yx - extents.yx) * extents.wz;
vec2 clamped = clamp(rectUv, vec2(0.0), vec2(1.0));
vec2 distance = abs(rectUv - clamped) * extents.wz;
if (minDistance.x > distance.x || minDistance.y > distance.y) {
minDistance = distance;
v_clippingPosition = rectUv;
}
float threshold = 0.01;
if (rectUv.x > threshold && rectUv.y > threshold && rectUv.x < 1.0 - threshold && rectUv.y < 1.0 - threshold) {
v_regionIndex = regionIndex;
}
}
}
`,gye=`void modelClippingPolygonsStage()
{
vec2 clippingPosition = v_clippingPosition;
int regionIndex = v_regionIndex;
czm_clipPolygons(model_clippingDistance, CLIPPING_POLYGON_REGIONS_LENGTH, clippingPosition, regionIndex);
}
`,VH={name:"ModelClippingPolygonsPipelineStage"};VH.process=function(e,t,n){const i=t.clippingPolygons,o=e.shaderBuilder;o.addDefine("ENABLE_CLIPPING_POLYGONS",void 0,ge.BOTH),i.inverse&&o.addDefine("CLIPPING_INVERSE",void 0,ge.FRAGMENT),o.addDefine("CLIPPING_POLYGON_REGIONS_LENGTH",i.extentsCount,ge.BOTH),o.addUniform("sampler2D","model_clippingDistance",ge.FRAGMENT),o.addUniform("sampler2D","model_clippingExtents",ge.VERTEX),o.addVarying("vec2","v_clippingPosition"),o.addVarying("int","v_regionIndex","flat"),o.addVertexLines(_ye),o.addFragmentLines(gye);const r={model_clippingDistance:function(){return i.clippingTexture},model_clippingExtents:function(){return i.extentsTexture}};e.uniformMap=jt(r,e.uniformMap)};const yye=VH;function HH(e,t){A.typeOf.object("model",e),A.typeOf.object("runtimeNode",t),this._model=e,this._runtimeNode=t}Object.defineProperties(HH.prototype,{name:{get:function(){return this._runtimeNode._name}},id:{get:function(){return this._runtimeNode._id}},show:{get:function(){return this._runtimeNode.show},set:function(e){this._runtimeNode.show=e}},matrix:{get:function(){return this._runtimeNode.transform},set:function(e){c(e)?(this._runtimeNode.transform=e,this._runtimeNode.userAnimated=!0,this._model._userAnimationDirty=!0):(this._runtimeNode.transform=this.originalMatrix,this._runtimeNode.userAnimated=!1)}},originalMatrix:{get:function(){return this._runtimeNode.originalTransform}}});const bye=`mat4 getInstancingTransform()
{
mat4 instancingTransform;
#ifdef HAS_INSTANCE_MATRICES
instancingTransform = mat4(
a_instancingTransformRow0.x, a_instancingTransformRow1.x, a_instancingTransformRow2.x, 0.0, // Column 1
a_instancingTransformRow0.y, a_instancingTransformRow1.y, a_instancingTransformRow2.y, 0.0, // Column 2
a_instancingTransformRow0.z, a_instancingTransformRow1.z, a_instancingTransformRow2.z, 0.0, // Column 3
a_instancingTransformRow0.w, a_instancingTransformRow1.w, a_instancingTransformRow2.w, 1.0 // Column 4
);
#else
vec3 translation = vec3(0.0, 0.0, 0.0);
vec3 scale = vec3(1.0, 1.0, 1.0);
#ifdef HAS_INSTANCE_TRANSLATION
translation = a_instanceTranslation;
#endif
#ifdef HAS_INSTANCE_SCALE
scale = a_instanceScale;
#endif
instancingTransform = mat4(
scale.x, 0.0, 0.0, 0.0,
0.0, scale.y, 0.0, 0.0,
0.0, 0.0, scale.z, 0.0,
translation.x, translation.y, translation.z, 1.0
);
#endif
return instancingTransform;
}
#ifdef USE_2D_INSTANCING
mat4 getInstancingTransform2D()
{
mat4 instancingTransform2D;
#ifdef HAS_INSTANCE_MATRICES
instancingTransform2D = mat4(
a_instancingTransform2DRow0.x, a_instancingTransform2DRow1.x, a_instancingTransform2DRow2.x, 0.0, // Column 1
a_instancingTransform2DRow0.y, a_instancingTransform2DRow1.y, a_instancingTransform2DRow2.y, 0.0, // Column 2
a_instancingTransform2DRow0.z, a_instancingTransform2DRow1.z, a_instancingTransform2DRow2.z, 0.0, // Column 3
a_instancingTransform2DRow0.w, a_instancingTransform2DRow1.w, a_instancingTransform2DRow2.w, 1.0 // Column 4
);
#else
vec3 translation2D = vec3(0.0, 0.0, 0.0);
vec3 scale = vec3(1.0, 1.0, 1.0);
#ifdef HAS_INSTANCE_TRANSLATION
translation2D = a_instanceTranslation2D;
#endif
#ifdef HAS_INSTANCE_SCALE
scale = a_instanceScale;
#endif
instancingTransform2D = mat4(
scale.x, 0.0, 0.0, 0.0,
0.0, scale.y, 0.0, 0.0,
0.0, 0.0, scale.z, 0.0,
translation2D.x, translation2D.y, translation2D.z, 1.0
);
#endif
return instancingTransform2D;
}
#endif
`,Tye=`void instancingStage(inout ProcessedAttributes attributes)
{
vec3 positionMC = attributes.positionMC;
mat4 instancingTransform = getInstancingTransform();
attributes.positionMC = (instancingTransform * vec4(positionMC, 1.0)).xyz;
#ifdef HAS_NORMALS
vec3 normalMC = attributes.normalMC;
attributes.normalMC = (instancingTransform * vec4(normalMC, 0.0)).xyz;
#endif
#ifdef USE_2D_INSTANCING
mat4 instancingTransform2D = getInstancingTransform2D();
attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;
#endif
}
`,Aye=`void legacyInstancingStage(
inout ProcessedAttributes attributes,
out mat4 instanceModelView,
out mat3 instanceModelViewInverseTranspose)
{
vec3 positionMC = attributes.positionMC;
mat4 instancingTransform = getInstancingTransform();
mat4 instanceModel = instancingTransform * u_instance_nodeTransform;
instanceModelView = u_instance_modifiedModelView;
instanceModelViewInverseTranspose = mat3(u_instance_modifiedModelView * instanceModel);
attributes.positionMC = (instanceModel * vec4(positionMC, 1.0)).xyz;
#ifdef USE_2D_INSTANCING
mat4 instancingTransform2D = getInstancingTransform2D();
attributes.position2D = (instancingTransform2D * vec4(positionMC, 1.0)).xyz;
#endif
}
`,gT=new L,xye=new L,Cye=new L,GH={name:"InstancingPipelineStage",_getInstanceTransformsAsMatrices:$H,_transformsToTypedArray:iD};GH.process=function(e,t,n){const i=t.instances,o=i.attributes[0].count,r=e.shaderBuilder;r.addDefine("HAS_INSTANCING"),r.addVertexLines(bye);const s=e.model,a=s.sceneGraph,l=e.runtimeNode,u=n.mode!==oe.SCENE3D&&!n.scene3DOnly&&s._projectTo2D,h=s._enablePick&&!n.context.webgl2,f=[];Mye(e,n,i,f,u,h),zye(e,n,i,f);const _={};if(i.transformInWorldSpace?(r.addDefine("USE_LEGACY_INSTANCING",void 0,ge.VERTEX),r.addUniform("mat4","u_instance_modifiedModelView",ge.VERTEX),r.addUniform("mat4","u_instance_nodeTransform",ge.VERTEX),_.u_instance_modifiedModelView=function(){let g=L.multiplyTransformation(s.modelMatrix,a.components.transform,gT);return u?L.multiplyTransformation(n.context.uniformState.view3D,g,gT):(n.mode!==oe.SCENE3D&&(g=zt.basisTo2D(n.mapProjection,g,gT)),L.multiplyTransformation(n.context.uniformState.view,g,gT))},_.u_instance_nodeTransform=function(){return L.multiplyTransformation(a.axisCorrectionMatrix,l.computedTransform,xye)},r.addVertexLines(Aye)):r.addVertexLines(Tye),u){r.addDefine("USE_2D_INSTANCING",void 0,ge.VERTEX),r.addUniform("mat4","u_modelView2D",ge.VERTEX);const g=n.context,m=L.fromTranslation(l.instancingReferencePoint2D,new L);_.u_modelView2D=function(){return L.multiplyTransformation(g.uniformState.view,m,Cye)}}e.uniformMap=jt(_,e.uniformMap),e.instanceCount=o,e.attributes.push.apply(e.attributes,f)};const Ly=new L,Eye=new d;function wye(e,t,n,i,o){let r=L.multiplyTransformation(t,e,Ly);return r=L.multiplyTransformation(r,n,Ly),o=zt.basisTo2D(i.mapProjection,r,o),o}function Sye(e,t,n,i,o){const r=L.fromTranslation(e,Ly);let s=L.multiplyTransformation(t,r,Ly);s=L.multiplyTransformation(s,n,Ly);const a=L.getTranslation(s,Eye);return o=Ao.computeActualWgs84Position(i,a,o),o}function jH(e,t,n){const i=e.model,o=i.sceneGraph;e.runtimeNode.node.instances.transformInWorldSpace?(t=L.multiplyTransformation(i.modelMatrix,o.components.transform,t),n=L.multiplyTransformation(o.axisCorrectionMatrix,e.runtimeNode.computedTransform,n)):(t=L.clone(o.computedModelMatrix,t),t=L.multiplyTransformation(t,e.runtimeNode.computedTransform,t),n=L.clone(L.IDENTITY,n))}const WH=new L,qH=new L,vye=new L,Iye=new d;function Dye(e,t,n,i){const o=WH,r=qH;jH(t,o,r);const a=t.runtimeNode.instancingReferencePoint2D,l=e.length;for(let u=0;u<l;u++){const h=e[u],f=wye(h,o,r,n,vye),_=L.getTranslation(f,Iye),g=d.subtract(_,a,_);i[u]=L.setTranslation(f,g,i[u])}return i}function Pye(e,t,n,i){const o=WH,r=qH;jH(t,o,r);const a=t.runtimeNode.instancingReferencePoint2D,l=e.length;for(let u=0;u<l;u++){const h=e[u],f=Sye(h,o,r,n,h);i[u]=d.subtract(f,a,i[u])}return i}const Oye=new d,Lye=new d;function YH(e,t){const n=e.runtimeNode,i=e.model.sceneGraph.computedModelMatrix,o=L.multiplyByPoint(i,n.instancingTranslationMin,Oye),r=Ao.computeActualWgs84Position(t,o,o),s=L.multiplyByPoint(i,n.instancingTranslationMax,Lye),a=Ao.computeActualWgs84Position(t,s,s);n.instancingReferencePoint2D=d.lerp(r,a,.5,new d)}function iD(e){const n=e.length,i=new Float32Array(n*12);for(let o=0;o<n;o++){const r=e[o],s=12*o;i[s+0]=r[0],i[s+1]=r[4],i[s+2]=r[8],i[s+3]=r[12],i[s+4]=r[1],i[s+5]=r[5],i[s+6]=r[9],i[s+7]=r[13],i[s+8]=r[2],i[s+9]=r[6],i[s+10]=r[10],i[s+11]=r[14]}return i}function Rye(e){const n=e.length,i=new Float32Array(n*3);for(let o=0;o<n;o++){const r=e[o],s=3*o;i[s+0]=r[0],i[s+1]=r[4],i[s+2]=r[8]}return i}new d;new _e;new d;function $H(e,t,n){const i=new Array(t),o=Lt.getAttributeBySemantic(e,hs.TRANSLATION),r=Lt.getAttributeBySemantic(e,hs.ROTATION),s=Lt.getAttributeBySemantic(e,hs.SCALE),a=new d(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=new d(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),u=c(o),h=c(r),f=c(s),_=u?o.typedArray:new Float32Array(t*3);let g=h?r.typedArray:new Float32Array(t*4);h&&r.normalized&&(g=En.dequantize(g,r.componentDatatype,r.type,t));let m;f?m=s.typedArray:(m=new Float32Array(t*3),m.fill(1));for(let T=0;T<t;T++){const x=new d(_[T*3],_[T*3+1],_[T*3+2]);d.maximumByComponent(a,x,a),d.mi
{
bool styleTranslucent = (featureColor.a != 1.0);
// Only render translucent features in the translucent pass (if the style or the original command has translucency).
if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)
{
// If the model has a translucent silhouette, it needs to render during the silhouette color command,
// (i.e. the command where model_silhouettePass = true), even if the model isn't translucent.
#ifdef HAS_SILHOUETTE
positionMC *= float(model_silhouettePass);
#else
positionMC *= 0.0;
#endif
}
// If the current pass is not the translucent pass and the style is not translucent, don't render the feature.
else if (czm_pass != czm_passTranslucent && styleTranslucent)
{
positionMC *= 0.0;
}
}
void cpuStylingStage(inout vec3 positionMC, inout SelectedFeature feature)
{
float show = ceil(feature.color.a);
positionMC *= show;
#if defined(HAS_SELECTED_FEATURE_ID_ATTRIBUTE) && !defined(HAS_CLASSIFICATION)
filterByPassType(positionMC, feature.color);
#endif
}
`,$ye=`void filterByPassType(vec4 featureColor)
{
bool styleTranslucent = (featureColor.a != 1.0);
// Only render translucent features in the translucent pass (if the style or the original command has translucency).
if (czm_pass == czm_passTranslucent && !styleTranslucent && !model_commandTranslucent)
{
// If the model has a translucent silhouette, it needs to render during the silhouette color command,
// (i.e. the command where model_silhouettePass = true), even if the model isn't translucent.
#ifdef HAS_SILHOUETTE
if(!model_silhouettePass) {
discard;
}
#else
discard;
#endif
}
// If the current pass is not the translucent pass and the style is not translucent, don't render the feature.
else if (czm_pass != czm_passTranslucent && styleTranslucent)
{
discard;
}
}
void cpuStylingStage(inout czm_modelMaterial material, SelectedFeature feature)
{
vec4 featureColor = feature.color;
if (featureColor.a == 0.0)
{
discard;
}
// If a feature ID vertex attribute is used, the pass type filter is applied in the vertex shader.
// So, we only apply in in the fragment shader if the feature ID texture is used.
#if defined(HAS_SELECTED_FEATURE_ID_TEXTURE) && !defined(HAS_CLASSIFICATION)
filterByPassType(featureColor);
#endif
featureColor = czm_gammaCorrect(featureColor);
// Classification models compute the diffuse differently.
#ifdef HAS_CLASSIFICATION
material.diffuse = featureColor.rgb * featureColor.a;
#else
float highlight = ceil(model_colorBlend);
material.diffuse *= mix(featureColor.rgb, vec3(1.0), highlight);
#endif
material.alpha *= featureColor.a;
}
`,n5={name:"CPUStylingPipelineStage"};n5.process=function(e,t,n){const i=e.model,o=e.shaderBuilder;o.addVertexLines(Yye),o.addFragmentLines($ye),o.addDefine("USE_CPU_STYLING",void 0,ge.BOTH),c(i.color)||(o.addUniform("float",nD.COLOR_BLEND_UNIFORM_NAME,ge.FRAGMENT),e.uniformMap[nD.COLOR_BLEND_UNIFORM_NAME]=function(){return RC.getColorBlend(i.colorBlendMode,i.colorBlendAmount)}),o.addUniform("bool","model_commandTranslucent",ge.BOTH),e.uniformMap.model_commandTranslucent=function(){return e.alphaOptions.pass===xe.TRANSLUCENT}};const Xye=n5,i5={MODIFY_MATERIAL:"MODIFY_MATERIAL",REPLACE_MATERIAL:"REPLACE_MATERIAL"};i5.getDefineName=function(e){return`CUSTOM_SHADER_${e}`};const RO=Object.freeze(i5),Qye=`void customShaderStage(
inout czm_modelVertexOutput vsOutput,
inout ProcessedAttributes attributes,
FeatureIds featureIds,
Metadata metadata,
MetadataClass metadataClass,
MetadataStatistics metadataStatistics
) {
// VertexInput and initializeInputStruct() are dynamically generated in JS,
// see CustomShaderPipelineStage.js
VertexInput vsInput;
initializeInputStruct(vsInput, attributes);
vsInput.featureIds = featureIds;
vsInput.metadata = metadata;
vsInput.metadataClass = metadataClass;
vsInput.metadataStatistics = metadataStatistics;
vertexMain(vsInput, vsOutput);
attributes.positionMC = vsOutput.positionMC;
}
`,Kye=`void customShaderStage(
inout czm_modelMaterial material,
ProcessedAttributes attributes,
FeatureIds featureIds,
Metadata metadata,
MetadataClass metadataClass,
MetadataStatistics metadataStatistics
) {
// FragmentInput and initializeInputStruct() are dynamically generated in JS,
// see CustomShaderPipelineStage.js
FragmentInput fsInput;
initializeInputStruct(fsInput, attributes);
fsInput.featureIds = featureIds;
fsInput.metadata = metadata;
fsInput.metadataClass = metadataClass;
fsInput.metadataStatistics = metadataStatistics;
fragmentMain(fsInput, material);
}
`,Zye=`void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes) {
initializeFeatureIds(featureIds, attributes);
initializeFeatureIdAliases(featureIds);
}
`,Jye=`void featureIdStage(out FeatureIds featureIds, ProcessedAttributes attributes)
{
initializeFeatureIds(featureIds, attributes);
initializeFeatureIdAliases(featureIds);
setFeatureIdVaryings();
}
`,Sn={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()"};Sn.process=function(e,t,n){const i=e.shaderBuilder;e0e(i);const o=e.runtimeNode.node.instances;c(o)&&t0e(e,o,n),n0e(e,t,n),i.addVertexLines(Jye),i.addFragmentLines(Zye)};function e0e(e){e.addStruct(Sn.STRUCT_ID_FEATURE_IDS_VS,Sn.STRUCT_NAME_FEATURE_IDS,ge.VERTEX),e.addStruct(Sn.STRUCT_ID_FEATURE_IDS_FS,Sn.STRUCT_NAME_FEATURE_IDS,ge.FRAGMENT),e.addFunction(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,Sn.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS,ge.VERTEX),e.addFunction(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,Sn.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_IDS,ge.FRAGMENT),e.addFunction(Sn.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_VS,Sn.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES,ge.VERTEX),e.addFunction(Sn.FUNCTION_ID_INITIALIZE_FEATURE_ID_ALIASES_FS,Sn.FUNCTION_SIGNATURE_INITIALIZE_FEATURE_ID_ALIASES,ge.FRAGMENT),e.addFunction(Sn.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,Sn.FUNCTION_SIGNATURE_SET_FEATURE_ID_VARYINGS,ge.VERTEX)}function t0e(e,t,n){const i=t.featureIds,o=t.attributes[0].count;for(let r=0;r<i.length;r++){const s=i[r],a=s.positionalLabel;s instanceof yt.FeatureIdAttribute?i0e(e,s,a):o5(e,s,a,o,1,n);const l=s.label;c(l)&&r5(e,a,l,ge.BOTH)}}function n0e(e,t,n){const i=t.featureIds,r=Lt.getAttributeBySemantic(t,ht.POSITION).count;for(let s=0;s<i.length;s++){const a=i[s],l=a.positionalLabel;let u=ge.BOTH;a instanceof yt.FeatureIdAttribute?o0e(e,a,l):a instanceof yt.FeatureIdImplicitRange?o5(e,a,l,r,void 0,n):(r0e(e,a,l,s,n),u=ge.FRAGMENT);const h=a.label;c(h)&&r5(e,l,h,u)}}function i0e(e,t,n){const i=e.shaderBuilder;i.addStructField(Sn.STRUCT_ID_FEATURE_IDS_VS,"int",n),i.addStructField(Sn.STRUCT_ID_FEATURE_IDS_FS,"int",n);const o=t.setIndex,r=n.replace(/_\d+$/,"_"),s=`a_${r}${o}`,a=`v_${r}${o}`,l=`featureIds.${n} = int(czm_round(${s}));`,u=`featureIds.${n} = int(czm_round(${a}));`;i.addFunctionLines(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,[l]),i.addFunctionLines(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,[u]),i.addVarying("float",a),i.addFunctionLines(Sn.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,[`${a} = ${s};`])}function o0e(e,t,n){const i=e.shaderBuilder;i.addStructField(Sn.STRUCT_ID_FEATURE_IDS_VS,"int",n),i.addStructField(Sn.STRUCT_ID_FEATURE_IDS_FS,"int",n);const o=t.setIndex,r=n.replace(/_\d+$/,"_"),s=[`featureIds.${n} = int(czm_round(attributes.${r}${o}));`];i.addFunctionLines(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,s),i.addFunctionLines(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,s)}function o5(e,t,n,i,o,r){s0e(e,t,i,o,r);const s=e.shaderBuilder,a=`a_implicit_${n}`;s.addAttribute("float",a);const l=`v_implicit_${n}`;s.addVarying("float",l),s.addStructField(Sn.STRUCT_ID_FEATURE_IDS_VS,"int",n),s.addStructField(Sn.STRUCT_ID_FEATURE_IDS_FS,"int",n),s.addFunctionLines(Sn.FUNCTION_ID_SET_FEATURE_ID_VARYINGS,[`${l} = ${a};`]),s.addFunctionLines(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_VS,[`featureIds.${n} = int(czm_round(${a}));`]),s.addFunctionLines(Sn.FUNCTION_ID_INITIALIZE_FEATURE_IDS_FS,[`featureIds.${n} = int(czm_round(${l}));`])}function r0e(e,t,n,i,o){const r=`u_featureIdTexture_${i}`,s=e.uniformMap,a=t.textureReader;s[r]=function(){return y(a.texture,o.context.defaultTexture)};const l=a.channels,u=e.shaderBuilder;u.addStructField(Sn.STRUCT_ID_FEATURE_IDS_FS,"int",n),u.addUniform("sampler2D",r,ge.FRAGMENT);const f=`v_texCoord_${a.texCo
out Metadata metadata,
out MetadataClass metadataClass,
out MetadataStatistics metadataStatistics,
ProcessedAttributes attributes
)
{
initializeMetadata(metadata, metadataClass, metadataStatistics, attributes);
}
`,l0e=`void metadataStage(
out Metadata metadata,
out MetadataClass metadataClass,
out MetadataStatistics metadataStatistics,
ProcessedAttributes attributes
)
{
initializeMetadata(metadata, metadataClass, metadataStatistics, attributes);
setMetadataVaryings();
}
`,bn={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"}]};bn.process=function(e,t,n){var f;const{shaderBuilder:i,model:o}=e,{structuralMetadata:r={},content:s}=o,a=(f=s==null?void 0:s.tileset.metadataExtension)==null?void 0:f.statistics,l=u0e(r.propertyAttributes,t,a),u=h0e(r.propertyTextures,a),h=l.concat(u);p0e(i,h),g0e(i),i.addVertexLines(l0e),i.addFragmentLines(c0e);for(let _=0;_<l.length;_++){const g=l[_];y0e(e,g)}for(let _=0;_<u.length;_++){const g=u[_];T0e(e,g)}};function u0e(e,t,n){return c(e)?e.flatMap(i=>d0e(i,t,n)):[]}function d0e(e,t,n){const{getAttributeByName:i,getAttributeInfo:o,sanitizeGlslIdentifier:r}=Lt,s=e.class.id,a=n==null?void 0:n.classes[s],l=Object.entries(e.properties),u=new Array(l.length);for(let h=0;h<l.length;h++){const[f,_]=l[h],g=i(t,_.attribute),{glslType:m,variableName:b}=o(g);u[h]={metadataVariable:r(f),property:_,type:_.classProperty.type,glslType:m,variableName:b,propertyStatistics:a==null?void 0:a.properties[f],shaderDestination:ge.BOTH}}return u}function h0e(e,t){return c(e)?e.flatMap(n=>f0e(n,t)):[]}function f0e(e,t){const{sanitizeGlslIdentifier:n}=Lt,i=e.class.id,o=t==null?void 0:t.classes[i],r=Object.entries(e.properties).filter(([a,l])=>l.isGpuCompatible()),s=new Array(r.length);for(let a=0;a<r.length;a++){const[l,u]=r[a];s[a]={metadataVariable:n(l),property:u,type:u.classProperty.type,glslType:u.getGlslType(),propertyStatistics:o==null?void 0:o.properties[l],shaderDestination:ge.FRAGMENT}}return s}function p0e(e,t){const n=new Set,i=new Set;for(let a=0;a<t.length;a++){const{type:l,glslType:u,propertyStatistics:h}=t[a];n.add(u),!!c(h)&&l!==bt.ENUM&&i.add(u)}const o=bn.METADATA_CLASS_FIELDS;for(const a of n){const l=`${a}MetadataClass`;s(l,a,o)}const r=bn.METADATA_STATISTICS_FIELDS;for(const a of i){const l=`${a}MetadataStatistics`;s(l,a,r)}function s(a,l,u){e.addStruct(a,a,ge.BOTH);for(let h=0;h<u.length;h++){const{shaderName:f}=u[h],_=u[h].type==="float"?_0e(l):l;e.addStructField(a,_,f)}}}const m0e={int:"float",ivec2:"vec2",ivec3:"vec3",ivec4:"vec4"};function _0e(e){const t=m0e[e];return c(t)?t:e}function g0e(e){e.addStruct(bn.STRUCT_ID_METADATA_VS,bn.STRUCT_NAME_METADATA,ge.VERTEX),e.addStruct(bn.STRUCT_ID_METADATA_FS,bn.STRUCT_NAME_METADATA,ge.FRAGMENT),e.addStruct(bn.STRUCT_ID_METADATA_CLASS_VS,bn.STRUCT_NAME_METADATA_CLASS,ge.VERTEX),e.addStruct(bn.STRUCT_ID_METADATA_CLASS_FS,bn.STRUCT_NAME_METADATA_CLASS,ge.FRAGMENT),e.addStruct(bn.STRUCT_ID_METADATA_STATISTICS_VS,bn.STRUCT_NAME_METADATA_STATISTICS,ge.VERTEX),e.addStruct(bn.STRUCT_ID_METADATA_STATISTICS_FS,bn.STRUCT_NAME_METADATA_STATISTICS,ge.FRAGMENT),e.addFunction(bn.FUNCTION_ID_INITIALIZE_METADATA_VS,bn.FUNCTION_SIGNATURE_INITIALIZE_METADATA,ge.VERTEX),e.addFunction(bn.FUNCTI
{
attributes.positionMC = v_positionMC;
attributes.positionEC = v_positionEC;
#if defined(COMPUTE_POSITION_WC_CUSTOM_SHADER) || defined(COMPUTE_POSITION_WC_STYLE) || defined(COMPUTE_POSITION_WC_ATMOSPHERE)
attributes.positionWC = v_positionWC;
#endif
#ifdef HAS_NORMALS
// renormalize after interpolation
attributes.normalEC = normalize(v_normalEC);
#endif
#ifdef HAS_TANGENTS
attributes.tangentEC = normalize(v_tangentEC);
#endif
#ifdef HAS_BITANGENTS
attributes.bitangentEC = normalize(v_bitangentEC);
#endif
// Everything else is dynamically generated in GeometryPipelineStage
setDynamicVaryings(attributes);
}
`,H0e=`vec4 geometryStage(inout ProcessedAttributes attributes, mat4 modelView, mat3 normal)
{
vec4 computedPosition;
// Compute positions in different coordinate systems
vec3 positionMC = attributes.positionMC;
v_positionMC = positionMC;
v_positionEC = (modelView * vec4(positionMC, 1.0)).xyz;
#if defined(USE_2D_POSITIONS) || defined(USE_2D_INSTANCING)
vec3 position2D = attributes.position2D;
vec3 positionEC = (u_modelView2D * vec4(position2D, 1.0)).xyz;
computedPosition = czm_projection * vec4(positionEC, 1.0);
#else
computedPosition = czm_projection * vec4(v_positionEC, 1.0);
#endif
// Sometimes the custom shader and/or style needs this
#if defined(COMPUTE_POSITION_WC_CUSTOM_SHADER) || defined(COMPUTE_POSITION_WC_STYLE) || defined(COMPUTE_POSITION_WC_ATMOSPHERE) || defined(ENABLE_CLIPPING_POLYGONS)
// Note that this is a 32-bit position which may result in jitter on small
// scales.
v_positionWC = (czm_model * vec4(positionMC, 1.0)).xyz;
#endif
#ifdef HAS_NORMALS
v_normalEC = normalize(normal * attributes.normalMC);
#endif
#ifdef HAS_TANGENTS
v_tangentEC = normalize(normal * attributes.tangentMC);
#endif
#ifdef HAS_BITANGENTS
v_bitangentEC = normalize(normal * attributes.bitangentMC);
#endif
// All other varyings need to be dynamically generated in
// GeometryPipelineStage
setDynamicVaryings(attributes);
return computedPosition;
}
`,fF=`vec2 computeSt(float featureId)
{
float stepX = model_textureStep.x;
float centerX = model_textureStep.y;
#ifdef MULTILINE_BATCH_TEXTURE
float stepY = model_textureStep.z;
float centerY = model_textureStep.w;
float xId = mod(featureId, model_textureDimensions.x);
float yId = floor(featureId / model_textureDimensions.x);
return vec2(centerX + (xId * stepX), centerY + (yId * stepY));
#else
return vec2(centerX + (featureId * stepX), 0.5);
#endif
}
void selectedFeatureIdStage(out SelectedFeature feature, FeatureIds featureIds)
{
int featureId = featureIds.SELECTED_FEATURE_ID;
if (featureId < model_featuresLength)
{
vec2 featureSt = computeSt(float(featureId));
feature.id = featureId;
feature.st = featureSt;
feature.color = texture(model_batchTexture, featureSt);
}
// Floating point comparisons can be unreliable in GLSL, so we
// increment the feature ID to make sure it's always greater
// then the model_featuresLength - a condition we check for in the
// pick ID, to avoid sampling the pick texture if the feature ID is
// greater than the number of features.
else
{
feature.id = model_featuresLength + 1;
feature.st = vec2(0.0);
feature.color = vec4(1.0);
}
#ifdef HAS_NULL_FEATURE_ID
if (featureId == model_nullFeatureId) {
feature.id = featureId;
feature.st = vec2(0.0);
feature.color = vec4(1.0);
}
#endif
}
`,Ny={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)"};Ny.process=function(e,t,n){const i=e.shaderBuilder;e.hasPropertyTable=!0;const o=e.model,r=e.runtimeNode.node,s=G0e(o,r,t),a=s.shaderDestination;i.addDefine("HAS_SELECTED_FEATURE_ID",void 0,a),i.addDefine("SELECTED_FEATURE_ID",s.variableName,a),i.addDefine(s.featureIdDefine,void 0,a),j0e(i);const l=s.featureIds.nullFeatureId,u=e.uniformMap;c(l)&&(i.addDefine("HAS_NULL_FEATURE_ID",void 0,a),i.addUniform("int","model_nullFeatureId",a),u.model_nullFeatureId=function(){return l}),s.shaderDestination===ge.BOTH&&i.addVertexLines(fF),i.addFragmentLines(fF)};function pF(e){return e instanceof yt.FeatureIdTexture?"HAS_SELECTED_FEATURE_ID_TEXTURE":"HAS_SELECTED_FEATURE_ID_ATTRIBUTE"}function mF(e){return e instanceof yt.FeatureIdTexture?ge.FRAGMENT:ge.BOTH}function G0e(e,t,n){let i,o;return c(t.instances)&&(o=Lt.getFeatureIdsByLabel(t.instances.featureIds,e.instanceFeatureIdLabel),c(o))?(i=y(o.label,o.positionalLabel),{featureIds:o,variableName:i,shaderDestination:mF(o),featureIdDefine:pF(o)}):(o=Lt.getFeatureIdsByLabel(n.featureIds,e.featureIdLabel),i=y(o.label,o.positionalLabel),{featureIds:o,variableName:i,shaderDestination:mF(o),featureIdDefine:pF(o)})}function j0e(e){e.addStructField(Ny.STRUCT_ID_SELECTED_FEATURE,"int","id"),e.addStructField(Ny.STRUCT_ID_SELECTED_FEATURE,"vec2","st"),e.addStructField(Ny.STRUCT_ID_SELECTED_FEATURE,"vec4","color")}const sD=Ny,nr={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)"};nr.process=function(e,t,n){const i=e.shaderBuilder,o=e.model;i.addStruct(nr.STRUCT_ID_PROCESSED_ATTRIBUTES_VS,"ProcessedAttributes",ge.VERTEX),i.addStruct(nr.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,"ProcessedAttributes",ge.FRAGMENT),i.addStruct(sD.STRUCT_ID_SELECTED_FEATURE,sD.STRUCT_NAME_SELECTED_FEATURE,ge.BOTH),i.addFunction(nr.FUNCTION_ID_INITIALIZE_ATTRIBUTES,nr.FUNCTION_SIGNATURE_INITIALIZE_ATTRIBUTES,ge.VERTEX),i.addVarying("vec3","v_positionWC"),i.addVarying("vec3","v_positionEC"),i.addStructField(nr.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,"vec3","positionWC"),i.addStructField(nr.STRUCT_ID_PROCESSED_ATTRIBUTES_FS,"vec3","positionEC"),i.addFunction(nr.FUNCTION_ID_SET_DYNAMIC_VARYINGS_VS,nr.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS,ge.VERTEX),i.addFunction(nr.FUNCTION_ID_SET_DYNAMIC_VARYINGS_FS,nr.FUNCTION_SIGNATURE_SET_DYNAMIC_VARYINGS,ge.FRAGMENT),o.type===bs.TILE_PNTS&&i.addDefine("HAS_SRGB_COLOR",void 0,ge.FRAGMENT);const s=n.mode!==oe.SCENE3D&&!n.scene3DOnly&&o._projectTo2D,a=c(e.runtimeNode.node.instances),l=s&&!a,u=t.attributes.length;for(let h=0;h<u;h++){const f=t.attributes[h],_=qt.getAttributeLocationCount(f.type);if(!c(f.buffer)&&!c(f.constant))throw new E("Attributes must be provided as a Buffer or constant value");const g=f.semantic===ht.POSITION;let m;_>1?(m=e.attributeIndex,e.attributeIndex+=_):g&&!l?m=0:m=e.attributeIndex++,W0e(e,f,m,_,s,a)}ebe(i,t.attributes),t.primitiveType===ze.POINTS&&i.addDefine("PRIMITIVE_TYPE_POINTS"),i.addVertexLines(H0e),i.addFragmentLines(V0e)};function W0e(e,t,n,i,o,r){const s=e.shaderBuilder,a=Lt.getAttributeInfo(t),l=o&&!r;i>1?$0e(e,t,n,i):Y0e(e,t,n,l),Q0e(s,a,l),X0e(s,a),c(t.semantic)&&q0e(s,t),K0e(s,a,o),Z0e(s,a,l),J0e(s,a)}function q0e(e,t){const n=t.semantic,i=t.setIndex;switch(n){case ht.NORMAL:e.addDefine("HAS_NORMAL
vec3 computePbrLighting(czm_modelMaterial inputMaterial, ProcessedAttributes attributes)
{
czm_pbrParameters pbrParameters;
pbrParameters.diffuseColor = inputMaterial.diffuse;
pbrParameters.f0 = inputMaterial.specular;
pbrParameters.roughness = inputMaterial.roughness;
#ifdef USE_CUSTOM_LIGHT_COLOR
vec3 lightColorHdr = model_lightColorHdr;
#else
vec3 lightColorHdr = czm_lightColorHdr;
#endif
vec3 color = inputMaterial.diffuse;
#ifdef HAS_NORMALS
color = czm_pbrLighting(
attributes.positionEC,
inputMaterial.normalEC,
czm_lightDirectionEC,
lightColorHdr,
pbrParameters
);
#ifdef USE_IBL_LIGHTING
color += imageBasedLightingStage(
attributes.positionEC,
inputMaterial.normalEC,
czm_lightDirectionEC,
lightColorHdr,
pbrParameters
);
#endif
#endif
color *= inputMaterial.occlusion;
color += inputMaterial.emissive;
// In HDR mode, the frame buffer is in linear color space. The
// post-processing stages (see PostProcessStageCollection) will handle
// tonemapping. However, if HDR is not enabled, we must tonemap else large
// values may be clamped to 1.0
#ifndef HDR
color = czm_acesTonemapping(color);
#endif
return color;
}
#endif
void lightingStage(inout czm_modelMaterial material, ProcessedAttributes attributes)
{
// Even though the lighting will only set the diffuse color,
// pass all other properties so further stages have access to them.
vec3 color = vec3(0.0);
#ifdef LIGHTING_PBR
color = computePbrLighting(material, attributes);
#else // unlit
color = material.diffuse;
#endif
#ifdef HAS_POINT_CLOUD_COLOR_STYLE
// The colors resulting from point cloud styles are adjusted differently.
color = czm_gammaCorrect(color);
#elif !defined(HDR)
// If HDR is not enabled, the frame buffer stores sRGB colors rather than
// linear colors so the linear value must be converted.
color = czm_linearToSrgb(color);
#endif
material.diffuse = color;
}
`,ibe={UNLIT:0,PBR:1},Gx=Object.freeze(ibe),f5={name:"LightingPipelineStage"};f5.process=function(e,t){const n=e.model,i=e.lightingOptions,o=e.shaderBuilder;if(c(n.lightColor)){o.addDefine("USE_CUSTOM_LIGHT_COLOR",void 0,ge.FRAGMENT),o.addUniform("vec3","model_lightColorHdr",ge.FRAGMENT);const s=e.uniformMap;s.model_lightColorHdr=function(){return n.lightColor}}i.lightingModel===Gx.PBR?o.addDefine("LIGHTING_PBR",void 0,ge.FRAGMENT):o.addDefine("LIGHTING_UNLIT",void 0,ge.FRAGMENT),o.addFragmentLines(nbe)};const obe=f5,rbe=`// If the style color is white, it implies the feature has not been styled.
bool isDefaultStyleColor(vec3 color)
{
return all(greaterThan(color, vec3(1.0 - czm_epsilon3)));
}
vec3 blend(vec3 sourceColor, vec3 styleColor, float styleColorBlend)
{
vec3 blendColor = mix(sourceColor, styleColor, styleColorBlend);
vec3 color = isDefaultStyleColor(styleColor.rgb) ? sourceColor : blendColor;
return color;
}
vec2 computeTextureTransform(vec2 texCoord, mat3 textureTransform)
{
return vec2(textureTransform * vec3(texCoord, 1.0));
}
#ifdef HAS_NORMALS
vec3 computeNormal(ProcessedAttributes attributes)
{
// Geometry normal. This is already normalized
vec3 ng = attributes.normalEC;
vec3 normal = ng;
#if defined(HAS_NORMAL_TEXTURE) && !defined(HAS_WIREFRAME)
vec2 normalTexCoords = TEXCOORD_NORMAL;
#ifdef HAS_NORMAL_TEXTURE_TRANSFORM
normalTexCoords = computeTextureTransform(normalTexCoords, u_normalTextureTransform);
#endif
// If HAS_BITANGENTS is set, then HAS_TANGENTS is also set
#ifdef HAS_BITANGENTS
vec3 t = attributes.tangentEC;
vec3 b = attributes.bitangentEC;
mat3 tbn = mat3(t, b, ng);
vec3 n = texture(u_normalTexture, normalTexCoords).rgb;
normal = normalize(tbn * (2.0 * n - 1.0));
#elif (__VERSION__ == 300 || defined(GL_OES_standard_derivatives))
// If derivatives are available (not IE 10), compute tangents
vec3 positionEC = attributes.positionEC;
vec3 pos_dx = dFdx(positionEC);
vec3 pos_dy = dFdy(positionEC);
vec3 tex_dx = dFdx(vec3(normalTexCoords,0.0));
vec3 tex_dy = dFdy(vec3(normalTexCoords,0.0));
vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t);
t = normalize(t - ng * dot(ng, t));
vec3 b = normalize(cross(ng, t));
mat3 tbn = mat3(t, b, ng);
vec3 n = texture(u_normalTexture, normalTexCoords).rgb;
normal = normalize(tbn * (2.0 * n - 1.0));
#endif
#endif
#ifdef HAS_DOUBLE_SIDED_MATERIAL
if (czm_backFacing()) {
normal = -normal;
}
#endif
return normal;
}
#endif
void materialStage(inout czm_modelMaterial material, ProcessedAttributes attributes, SelectedFeature feature)
{
#ifdef HAS_NORMALS
material.normalEC = computeNormal(attributes);
#endif
vec4 baseColorWithAlpha = vec4(1.0);
// Regardless of whether we use PBR, set a base color
#ifdef HAS_BASE_COLOR_TEXTURE
vec2 baseColorTexCoords = TEXCOORD_BASE_COLOR;
#ifdef HAS_BASE_COLOR_TEXTURE_TRANSFORM
baseColorTexCoords = computeTextureTransform(baseColorTexCoords, u_baseColorTextureTransform);
#endif
baseColorWithAlpha = czm_srgbToLinear(texture(u_baseColorTexture, baseColorTexCoords));
#ifdef HAS_BASE_COLOR_FACTOR
baseColorWithAlpha *= u_baseColorFactor;
#endif
#elif defined(HAS_BASE_COLOR_FACTOR)
baseColorWithAlpha = u_baseColorFactor;
#endif
#ifdef HAS_POINT_CLOUD_COLOR_STYLE
baseColorWithAlpha = v_pointCloudColor;
#elif defined(HAS_COLOR_0)
vec4 color = attributes.color_0;
// .pnts files store colors in the sRGB color space
#ifdef HAS_SRGB_COLOR
color = czm_srgbToLinear(color);
#endif
baseColorWithAlpha *= color;
#endif
material.diffuse = baseColorWithAlpha.rgb;
material.alpha = baseColorWithAlpha.a;
#ifdef USE_CPU_STYLING
material.diffuse = blend(material.diffuse, feature.color.rgb, model_colorBlend);
#endif
#ifdef HAS_OCCLUSION_TEXTURE
vec2 occlusionTexCoords = TEXCOORD_OCCLUSION;
#ifdef HAS_OCCLUSION_TEXTURE_TRANSFORM
occlusionTexCoords = computeTextureTransform(occlusionTexCoords, u_occlusionTextureTransform);
#endif
material.occlusion = texture(u_occlusionTexture, occlusionTexCoords).r;
#endif
#ifdef HAS_EMISSIVE_TEXTURE
vec2 emissiveTexCoords = TEXCOORD_EMISSIVE;
#ifdef HAS_EMISSIVE_TEXTURE_TRANSFORM
emissiveTexCoords = computeTextureTransform(emissiveTexCoords, u_emissiveTextureTransform);
#endif
vec3 emissive = czm_srgbToLinear(texture(u_emissiveTexture, emissiveTexCoords).rgb);
#ifdef HAS_EMISSIVE_FACTOR
emissive *= u_emissiveFactor;
#endif
material.emissive = emissive;
#elif defined(HAS_EMISSIVE_FACTOR)
material.emissive = u_emissiveFactor;
#endif
#if defined(LIGHTING_PBR) && defined(USE_SPECULAR_GLOSSINESS)
#ifdef HAS_SPECULAR_GLOSSINESS_TEXTURE
vec2 specularGlossinessTexCoords = TEXCOORD_SPECULAR_GLOSSINESS;
#ifdef HAS_SPECULAR_GLOSSINESS_TEXTURE_TRANSFORM
specularGlossinessTexCoords = computeTextureTransform(specularGlossinessTexCoords, u_specularGlossinessTextureTransform);
#endif
vec4 specularGlossiness = czm_srgbToLinear(texture(u_specularGlossinessTexture, specularGlossinessTexCoords));
vec3 specular = specularGlossiness.rgb;
float glossiness = specularGlossiness.a;
#ifdef HAS_SPECULAR_FACTOR
specular *= u_specularFactor;
#endif
#ifdef HAS_GLOSSINESS_FACTOR
glossiness *= u_glossinessFactor;
#endif
#else
#ifdef HAS_SPECULAR_FACTOR
vec3 specular = clamp(u_specularFactor, vec3(0.0), vec3(1.0));
#else
vec3 specular = vec3(1.0);
#endif
#ifdef HAS_GLOSSINESS_FACTOR
float glossiness = clamp(u_glossinessFactor, 0.0, 1.0);
#else
float glossiness = 1.0;
#endif
#endif
#ifdef HAS_DIFFUSE_TEXTURE
vec2 diffuseTexCoords = TEXCOORD_DIFFUSE;
#ifdef HAS_DIFFUSE_TEXTURE_TRANSFORM
diffuseTexCoords = computeTextureTransform(diffuseTexCoords, u_diffuseTextureTransform);
#endif
vec4 diffuse = czm_srgbToLinear(texture(u_diffuseTexture, diffuseTexCoords));
#ifdef HAS_DIFFUSE_FACTOR
diffuse *= u_diffuseFactor;
#endif
#elif defined(HAS_DIFFUSE_FACTOR)
vec4 diffuse = clamp(u_diffuseFactor, vec4(0.0), vec4(1.0));
#else
vec4 diffuse = vec4(1.0);
#endif
czm_pbrParameters parameters = czm_pbrSpecularGlossinessMaterial(
diffuse.rgb,
specular,
glossiness
);
material.diffuse = parameters.diffuseColor;
// the specular glossiness extension's alpha overrides anything set
// by the base material.
material.alpha = diffuse.a;
material.specular = parameters.f0;
material.roughness = parameters.roughness;
#elif defined(LIGHTING_PBR)
#ifdef HAS_METALLIC_ROUGHNESS_TEXTURE
vec2 metallicRoughnessTexCoords = TEXCOORD_METALLIC_ROUGHNESS;
#ifdef HAS_METALLIC_ROUGHNESS_TEXTURE_TRANSFORM
metallicRoughnessTexCoords = computeTextureTransform(metallicRoughnessTexCoords, u_metallicRoughnessTextureTransform);
#endif
vec3 metallicRoughness = texture(u_metallicRoughnessTexture, metallicRoughnessTexCoords).rgb;
float metalness = clamp(metallicRoughness.b, 0.0, 1.0);
float roughness = clamp(metallicRoughness.g, 0.04, 1.0);
#ifdef HAS_METALLIC_FACTOR
metalness *= u_metallicFactor;
#endif
#ifdef HAS_ROUGHNESS_FACTOR
roughness *= u_roughnessFactor;
#endif
#else
#ifdef HAS_METALLIC_FACTOR
float metalness = clamp(u_metallicFactor, 0.0, 1.0);
#else
float metalness = 1.0;
#endif
#ifdef HAS_ROUGHNESS_FACTOR
float roughness = clamp(u_roughnessFactor, 0.04, 1.0);
#else
float roughness = 1.0;
#endif
#endif
czm_pbrParameters parameters = czm_pbrMetallicRoughnessMaterial(
material.diffuse,
metalness,
roughness
);
material.diffuse = parameters.diffuseColor;
material.specular = parameters.f0;
material.roughness = parameters.roughness;
#endif
}
`,sbe=yt.Material,aS=yt.MetallicRoughness,cS=yt.SpecularGlossiness,p5={name:"MaterialPipelineStage",_processTexture:Eh,_processTextureTransform:m5};p5.process=function(e,t,n){const i=t.material,o=e.model,r=c(o.classificationType),s=r,a=e.uniformMap,l=e.shaderBuilder,u=n.context.defaultTexture,h=n.context.defaultNormalTexture,f=n.context.defaultEmissiveTexture;abe(i,a,l,u,h,f,s),c(i.specularGlossiness)?cbe(i,a,l,u,s):lbe(i,a,l,u,s);const _=Lt.getAttributeBySemantic(t,ht.NORMAL),g=e.lightingOptions;i.unlit||!_||r?g.lightingModel=Gx.UNLIT:g.lightingModel=Gx.PBR;const m=o.backFaceCulling&&!i.doubleSided;e.renderStateOptions.cull.enabled=m;const b=e.alphaOptions;i.alphaMode===Mx.BLEND?b.pass=xe.TRANSLUCENT:i.alphaMode===Mx.MASK&&(b.alphaCutoff=i.alphaCutoff),l.addFragmentLines(rbe),i.doubleSided&&l.addDefine("HAS_DOUBLE_SIDED_MATERIAL",void 0,ge.BOTH)};function m5(e,t,n,i,o){const r=`HAS_${o}_TEXTURE_TRANSFORM`;e.addDefine(r,void 0,ge.FRAGMENT);const s=`${i}Transform`;e.addUniform("mat3",s,ge.FRAGMENT),t[s]=function(){return n.transform}}function Eh(e,t,n,i,o,r){e.addUniform("sampler2D",i,ge.FRAGMENT),t[i]=function(){return y(n.texture,r)};const s=`HAS_${o}_TEXTURE`;e.addDefine(s,void 0,ge.FRAGMENT);const l=`v_texCoord_${n.texCoord}`,u=`TEXCOORD_${o}`;e.addDefine(u,l,ge.FRAGMENT);const h=n.transform;c(h)&&!$.equals(h,$.IDENTITY)&&m5(e,t,n,i,o)}function abe(e,t,n,i,o,r,s){const a=e.emissiveFactor;if(c(a)&&!d.equals(a,sbe.DEFAULT_EMISSIVE_FACTOR)){n.addUniform("vec3","u_emissiveFactor",ge.FRAGMENT),t.u_emissiveFactor=function(){return e.emissiveFactor},n.addDefine("HAS_EMISSIVE_FACTOR",void 0,ge.FRAGMENT);const h=e.emissiveTexture;c(h)&&!s&&Eh(n,t,h,"u_emissiveTexture","EMISSIVE",r)}const l=e.normalTexture;c(l)&&!s&&Eh(n,t,l,"u_normalTexture","NORMAL",o);const u=e.occlusionTexture;c(u)&&!s&&Eh(n,t,u,"u_occlusionTexture","OCCLUSION",i)}function cbe(e,t,n,i,o){const r=e.specularGlossiness;n.addDefine("USE_SPECULAR_GLOSSINESS",void 0,ge.FRAGMENT);const s=r.diffuseTexture;c(s)&&!o&&Eh(n,t,s,"u_diffuseTexture","DIFFUSE",i);const a=r.diffuseFactor;c(a)&&!te.equals(a,cS.DEFAULT_DIFFUSE_FACTOR)&&(n.addUniform("vec4","u_diffuseFactor",ge.FRAGMENT),t.u_diffuseFactor=function(){return r.diffuseFactor},n.addDefine("HAS_DIFFUSE_FACTOR",void 0,ge.FRAGMENT));const l=r.specularGlossinessTexture;c(l)&&!o&&Eh(n,t,l,"u_specularGlossinessTexture","SPECULAR_GLOSSINESS",i);const u=r.specularFactor;c(u)&&!d.equals(u,cS.DEFAULT_SPECULAR_FACTOR)&&(n.addUniform("vec3","u_specularFactor",ge.FRAGMENT),t.u_specularFactor=function(){return r.specularFactor},n.addDefine("HAS_SPECULAR_FACTOR",void 0,ge.FRAGMENT));const h=r.glossinessFactor;c(h)&&h!==cS.DEFAULT_GLOSSINESS_FACTOR&&(n.addUniform("float","u_glossinessFactor",ge.FRAGMENT),t.u_glossinessFactor=function(){return r.glossinessFactor},n.addDefine("HAS_GLOSSINESS_FACTOR",void 0,ge.FRAGMENT))}function lbe(e,t,n,i,o){const r=e.metallicRoughness;n.addDefine("USE_METALLIC_ROUGHNESS",void 0,ge.FRAGMENT);const s=r.baseColorTexture;c(s)&&!o&&Eh(n,t,s,"u_baseColorTexture","BASE_COLOR",i);const a=r.baseColorFactor;c(a)&&!te.equals(a,aS.DEFAULT_BASE_COLOR_FACTOR)&&(n.addUniform("vec4","u_baseColorFactor",ge.FRAGMENT),t.u_baseColorFactor=function(){return r.baseColorFactor},n.addDefine("HAS_BASE_COLOR_FACTOR",void 0,ge.FRAGMENT));const l=r.metallicRoughnessTexture;c(l)&&!o&&Eh(n,t,l,"u_metallicRoughnessTexture","METALLIC_ROUGHNESS",i);const u=r.metallicFactor;c(u)&&u!==aS.DEFAULT_METALLIC_FACTOR&&(n.addUniform("float","u_metallicFactor",ge.FRAGMENT),t.u_metallicFactor=function(){return r.metallicFactor},n.addDefine("HAS_METALLIC_FACTOR",void 0,ge.FRAGMENT));const h=r.roughnessFactor;c(h)&&h!==aS.DEFAULT_ROUGHNESS_FACTOR&&(n.addUniform("float","u_roughnessFactor",ge.FRAGMENT),t.u_roughnessFactor=function(){return r.roughnessFactor},n.addDefine("HAS_ROUGHNESS_FACTOR",void 0,ge.FRAGMENT))}const ube=p5,dbe=`void morphTargetsStage(inout ProcessedAttributes attributes)
{
vec3 positionMC = attributes.positionMC;
attributes.positionMC = getMorphedPosition(positionMC);
#ifdef HAS_NORMALS
vec3 normalMC = attributes.normalMC;
attributes.normalMC = getMorphedNormal(normalMC);
#endif
#ifdef HAS_TANGENTS
vec3 tangentMC = attributes.tangentMC;
attributes.tangentMC = getMorphedTangent(tangentMC);
#endif
}`,Fr={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)"};Fr.process=function(e,t){const n=e.shaderBuilder;n.addDefine("HAS_MORPH_TARGETS",void 0,ge.VERTEX),gbe(n);const i=t.morphTargets.length;for(let a=0;a<i;a++){const l=t.morphTargets[a].attributes,u=l.length;for(let h=0;h<u;h++){const f=l[h],_=f.semantic;_!==ht.POSITION&&_!==ht.NORMAL&&_!==ht.TANGENT||(fbe(e,f,e.attributeIndex,a),e.attributeIndex++)}}ybe(n);const r=e.runtimeNode.morphWeights.length;n.addUniform("float",`u_morphWeights[${r}]`,ge.VERTEX),n.addVertexLines(dbe);const s={u_morphWeights:function(){return e.runtimeNode.morphWeights}};e.uniformMap=jt(s,e.uniformMap)};const hbe={attributeString:void 0,functionId:void 0};function fbe(e,t,n,i){const o=e.shaderBuilder;pbe(e,t,n);const r=mbe(t,hbe);_be(o,r,i)}function pbe(e,t,n){const i={index:n,value:c(t.buffer)?void 0:t.constant,vertexBuffer:t.buffer,componentsPerAttribute:qt.getNumberOfComponents(t.type),componentDatatype:t.componentDatatype,offsetInBytes:t.byteOffset,strideInBytes:t.byteStride,normalize:t.normalized};e.attributes.push(i)}function mbe(e,t){switch(e.semantic){case ht.POSITION:t.attributeString="Position",t.functionId=Fr.FUNCTION_ID_GET_MORPHED_POSITION;break;case ht.NORMAL:t.attributeString="Normal",t.functionId=Fr.FUNCTION_ID_GET_MORPHED_NORMAL;break;case ht.TANGENT:t.attributeString="Tangent",t.functionId=Fr.FUNCTION_ID_GET_MORPHED_TANGENT;break}return t}function _be(e,t,n){const i=t.attributeString,o=`a_target${i}_${n}`,r=`morphed${i} += u_morphWeights[${n}] * a_target${i}_${n};`;e.addAttribute("vec3",o),e.addFunctionLines(t.functionId,[r])}function gbe(e){e.addFunction(Fr.FUNCTION_ID_GET_MORPHED_POSITION,Fr.FUNCTION_SIGNATURE_GET_MORPHED_POSITION,ge.VERTEX);const t="vec3 morphedPosition = position;";e.addFunctionLines(Fr.FUNCTION_ID_GET_MORPHED_POSITION,[t]),e.addFunction(Fr.FUNCTION_ID_GET_MORPHED_NORMAL,Fr.FUNCTION_SIGNATURE_GET_MORPHED_NORMAL,ge.VERTEX);const n="vec3 morphedNormal = normal;";e.addFunctionLines(Fr.FUNCTION_ID_GET_MORPHED_NORMAL,[n]),e.addFunction(Fr.FUNCTION_ID_GET_MORPHED_TANGENT,Fr.FUNCTION_SIGNATURE_GET_MORPHED_TANGENT,ge.VERTEX);const i="vec3 morphedTangent = tangent;";e.addFunctionLines(Fr.FUNCTION_ID_GET_MORPHED_TANGENT,[i])}function ybe(e){const t="return morphedPosition;";e.addFunctionLines(Fr.FUNCTION_ID_GET_MORPHED_POSITION,[t]);const n="return morphedNormal;";e.addFunctionLines(Fr.FUNCTION_ID_GET_MORPHED_NORMAL,[n]);const i="return morphedTangent;";e.addFunctionLines(Fr.FUNCTION_ID_GET_MORPHED_TANGENT,[i])}const bbe=Fr,_5={name:"PickingPipelineStage"};_5.process=function(e,t,n){const i=n.context,o=e.runtimeNode,r=e.shaderBuilder,s=e.model,a=o.node.instances;if(e.hasPropertyTable)Tbe(e,t,a);else if(c(a))Abe(e,i);else{const l=g5(e),u=i.createPickId(l);s._pipelineResources.push(u),s._pickIds.push(u),r.addUniform("vec4","czm_pickColor",ge.FRAGMENT);const h=e.uniformMap;h.czm_pickColor=function(){return u.color},e.pickId="czm_pickColor"}};function g5(e,t){const n=e.model;if(c(n.pickObject))return n.pickObject;const i={model:n,node:e.runtimeNode,primitive:e.runtimePrimitive};let o;if(bs.is3DTiles(n.type)){const r=n.content;o={content:r,primitive:r.tileset,detail:i}}else o={primitive:n,detail:i};return o.id=n.id,c(t)&&(o.instanceId=t),o}function Tbe(e,t,n){const i=e.model;let o,r;const s=i.featureIdLabel,a=i.instanceFeatureIdLabel;c(i.featureTableId)?o=i.featureTableId:c(n)?(r=Lt.getFeatureIdsByLabel(n.featureIds,a),o=r.propertyTableId):(r=Lt.getFeatureIdsByLabel(t.featureIds,s),o=r.propertyTableId);const l=i.featureTables[o];e.shaderBuilder.addUniform("sampler2D","model_pickTexture",ge.FRAGMENT);const h=l.batchTexture;e.uniformMap.model_pickTexture=function(){return y(h.pickTexture,h.default
// Variables are packed into a single vector to minimize gl.uniformXXX() calls
float pointSize = model_pointCloudParameters.x;
float geometricError = model_pointCloudParameters.y;
float depthMultiplier = model_pointCloudParameters.z;
float depth = -positionEC.z;
return min((geometricError / depth) * depthMultiplier, pointSize);
}
#ifdef HAS_POINT_CLOUD_SHOW_STYLE
float pointCloudShowStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {
float tiles3d_tileset_time = model_pointCloudParameters.w;
return float(getShowFromStyle(attributes, metadata, tiles3d_tileset_time));
}
#endif
#ifdef HAS_POINT_CLOUD_COLOR_STYLE
vec4 pointCloudColorStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {
float tiles3d_tileset_time = model_pointCloudParameters.w;
return getColorFromStyle(attributes, metadata, tiles3d_tileset_time);
}
#endif
#ifdef HAS_POINT_CLOUD_POINT_SIZE_STYLE
float pointCloudPointSizeStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {
float tiles3d_tileset_time = model_pointCloudParameters.w;
return float(getPointSizeFromStyle(attributes, metadata, tiles3d_tileset_time));
}
#elif defined(HAS_POINT_CLOUD_ATTENUATION)
float pointCloudPointSizeStylingStage(in ProcessedAttributes attributes, in Metadata metadata) {
return getPointSizeFromAttenuation(v_positionEC);
}
#endif
#ifdef HAS_POINT_CLOUD_BACK_FACE_CULLING
float pointCloudBackFaceCullingStage() {
#if defined(HAS_NORMALS) && !defined(HAS_DOUBLE_SIDED_MATERIAL)
// This needs to be computed in eye coordinates so we can't use attributes.normalMC
return step(-v_normalEC.z, 0.0);
#else
return 1.0;
#endif
}
#endif`,wbe=new te,y5={name:"PointCloudStylingPipelineStage"};y5.process=function(e,t,n){const i=e.shaderBuilder,o=e.model,r=o.style,s=o.structuralMetadata,a=c(s)?s.propertyAttributes:void 0,l=c(o.featureTableId)&&o.featureTables[o.featureTableId].featuresLength>0,u=!c(a)&&l;if(c(r)&&!u){const b=Dbe(a),T=Pbe(r,b);Obe(i,T);const C=Lbe(T).indexOf("normalMC")>=0,w=Lt.getAttributeBySemantic(t,ht.NORMAL);if(C&&!w)throw new Te("Style references the NORMAL semantic but the point cloud does not have normals");i.addDefine("COMPUTE_POSITION_WC_STYLE",void 0,ge.VERTEX),T.styleTranslucent&&(e.alphaOptions.pass=xe.TRANSLUCENT)}const h=o.pointCloudShading;h.attenuation&&i.addDefine("HAS_POINT_CLOUD_ATTENUATION",void 0,ge.VERTEX),h.backFaceCulling&&i.addDefine("HAS_POINT_CLOUD_BACK_FACE_CULLING",void 0,ge.VERTEX);let f,_,g;bs.is3DTiles(o.type)&&(_=!0,f=o.content,g=f.tile.refine===Vr.ADD),i.addUniform("vec4","model_pointCloudParameters",ge.VERTEX),i.addVertexLines(Ebe);const m=e.uniformMap;m.model_pointCloudParameters=function(){const b=wbe;let T=1;_&&(T=g?5:f.tileset.memoryAdjustedScreenSpaceError),b.x=y(h.maximumAttenuation,T),b.x*=n.pixelRatio;const x=Sbe(e,t,h,f);b.y=x*h.geometricErrorScale;const C=n.context,w=n.camera.frustum;let v;return n.mode===oe.SCENE2D||w instanceof It?v=Number.POSITIVE_INFINITY:v=C.drawingBufferHeight/n.camera.frustum.sseDenominator,b.z=v,_&&(b.w=f.tileset.timeSinceLoad),b}};const _F=new d;function Sbe(e,t,n,i){if(c(i)){const h=i.tile.geometricError;if(h>0)return h}if(c(n.baseResolution))return n.baseResolution;const o=Lt.getAttributeBySemantic(t,ht.POSITION),r=o.count,s=e.runtimeNode.transform;let a=d.subtract(o.max,o.min,_F);a=L.multiplyByPointAsVector(s,a,_F);const l=a.x*a.y*a.z;return R.cbrt(l/r)}const vbe={colorStyleFunction:void 0,showStyleFunction:void 0,pointSizeStyleFunction:void 0,styleTranslucent:!1},Ibe={POSITION:"attributes.positionMC",POSITION_ABSOLUTE:"v_positionWC",COLOR:"attributes.color_0",NORMAL:"attributes.normalMC"};function Dbe(e){const t=Je(Ibe);if(!c(e))return t;for(let n=0;n<e.length;n++){const o=e[n].properties;for(const r in o)o.hasOwnProperty(r)&&(t[r]=`metadata.${r}`)}return t}const lS="ProcessedAttributes attributes, Metadata metadata, float tiles3d_tileset_time";function Pbe(e,t){const n=vbe,i={translucent:!1};return n.colorStyleFunction=e.getColorShaderFunction(`getColorFromStyle(${lS})`,t,i),n.showStyleFunction=e.getShowShaderFunction(`getShowFromStyle(${lS})`,t,i),n.pointSizeStyleFunction=e.getPointSizeShaderFunction(`getPointSizeFromStyle(${lS})`,t,i),n.styleTranslucent=c(n.colorStyleFunction)&&i.translucent,n}function Obe(e,t){const n=t.colorStyleFunction;c(n)&&(e.addDefine("HAS_POINT_CLOUD_COLOR_STYLE",void 0,ge.BOTH),e.addVertexLines(n),e.addVarying("vec4","v_pointCloudColor"));const i=t.showStyleFunction;c(i)&&(e.addDefine("HAS_POINT_CLOUD_SHOW_STYLE",void 0,ge.VERTEX),e.addVertexLines(i));const o=t.pointSizeStyleFunction;c(o)&&(e.addDefine("HAS_POINT_CLOUD_POINT_SIZE_STYLE",void 0,ge.VERTEX),e.addVertexLines(o))}function uS(e,t){const n=/attributes\.(\w+)/g;let i=n.exec(e);for(;i!==null;){const o=i[1];t.indexOf(o)===-1&&t.push(o),i=n.exec(e)}}function Lbe(e){const t=e.colorStyleFunction,n=e.showStyleFunction,i=e.pointSizeStyleFunction,o=[];return c(t)&&uS(t,o),c(n)&&uS(n,o),c(i)&&uS(i,o),o}const Rbe=y5,Nbe=`void primitiveOutlineStage() {
v_outlineCoordinates = a_outlineCoordinates;
}
`,Mbe=`void primitiveOutlineStage(inout czm_modelMaterial material) {
if (!model_showOutline) {
return;
}
float outlineX =
texture(model_outlineTexture, vec2(v_outlineCoordinates.x, 0.5)).r;
float outlineY =
texture(model_outlineTexture, vec2(v_outlineCoordinates.y, 0.5)).r;
float outlineZ =
texture(model_outlineTexture, vec2(v_outlineCoordinates.z, 0.5)).r;
float outlineness = max(outlineX, max(outlineY, outlineZ));
material.diffuse = mix(material.diffuse, model_outlineColor.rgb, model_outlineColor.a * outlineness);
}
`,b5={name:"PrimitiveOutlinePipelineStage"};b5.process=function(e,t,n){const i=e.shaderBuilder,o=e.uniformMap;i.addDefine("HAS_PRIMITIVE_OUTLINE",void 0,ge.BOTH),i.addAttribute("vec3","a_outlineCoordinates"),i.addVarying("vec3","v_outlineCoordinates");const r=t.outlineCoordinates,s={index:e.attributeIndex++,vertexBuffer:r.buffer,componentsPerAttribute:qt.getNumberOfComponents(r.type),componentDatatype:r.componentDatatype,offsetInBytes:r.byteOffset,strideInBytes:r.byteStride,normalize:r.normalized};e.attributes.push(s),i.addUniform("sampler2D","model_outlineTexture",ge.FRAGMENT);const a=W0.createTexture(n.context);o.model_outlineTexture=function(){return a};const l=e.model;i.addUniform("vec4","model_outlineColor",ge.FRAGMENT),o.model_outlineColor=function(){return l.outlineColor},i.addUniform("bool","model_showOutline",ge.FRAGMENT),o.model_showOutline=function(){return l.showOutline},i.addVertexLines(Nbe),i.addFragmentLines(Mbe)};const Fbe=b5,T5={name:"PrimitiveStatisticsPipelineStage",_countGeometry:A5,_count2DPositions:x5,_countMorphTargetAttributes:C5,_countMaterialTextures:E5,_countFeatureIdTextures:w5,_countBinaryMetadata:S5};T5.process=function(e,t,n){const i=e.model,o=i.statistics;A5(o,t),x5(o,e.runtimePrimitive),C5(o,t),E5(o,t.material),w5(o,t.featureIds),S5(o,i)};function A5(e,t){const n=c(t.indices)?t.indices.count:Lt.getAttributeBySemantic(t,"POSITION").count,i=t.primitiveType;i===ze.POINTS?e.pointsLength+=n:ze.isTriangles(i)&&(e.trianglesLength+=Bbe(i,n));const o=t.attributes,r=o.length;for(let l=0;l<r;l++){const u=o[l];if(c(u.buffer)){const h=c(u.typedArray);e.addBuffer(u.buffer,h)}}const s=t.outlineCoordinates;c(s)&&c(s.buffer)&&e.addBuffer(s.buffer,!1);const a=t.indices;if(c(a)&&c(a.buffer)){const l=c(a.typedArray);e.addBuffer(a.buffer,l)}}function Bbe(e,t){switch(e){case ze.TRIANGLES:return t/3;case ze.TRIANGLE_STRIP:case ze.TRIANGLE_FAN:return Math.max(t-2,0);default:return 0}}function x5(e,t){const n=t.positionBuffer2D;c(n)&&e.addBuffer(n,!0)}function C5(e,t){const n=t.morphTargets;if(!c(n))return;const i=!1,o=n.length;for(let r=0;r<o;r++){const s=n[r].attributes,a=s.length;for(let l=0;l<a;l++){const u=s[l];c(u.buffer)&&e.addBuffer(u.buffer,i)}}}function E5(e,t){const n=zbe(t),i=n.length;for(let o=0;o<i;o++){const r=n[o];c(r)&&c(r.texture)&&e.addTexture(r.texture)}}function zbe(e){const t=e.metallicRoughness,n=[e.emissiveTexture,e.normalTexture,e.occlusionTexture,t.baseColorTexture,t.metallicRoughnessTexture],i=e.specularGlossiness;return c(i)&&(n.push(i.diffuseTexture),n.push(i.specularGlossinessTexture)),n}function w5(e,t){const n=t.length;for(let i=0;i<n;i++){const o=t[i];if(o instanceof yt.FeatureIdTexture){const r=o.textureReader;c(r.texture)&&e.addTexture(r.texture)}}}function S5(e,t){const n=t.structuralMetadata;c(n)&&(Ube(e,n),e.propertyTablesByteLength+=n.propertyTablesByteLength);const i=t.featureTables;if(!c(i))return;const o=i.length;for(let r=0;r<o;r++){const s=i[r];e.addBatchTexture(s.batchTexture)}}function Ube(e,t){const n=t.propertyTextures;if(!c(n))return;const i=n.length;for(let o=0;o<i;o++){const s=n[o].properties;for(const a in s)if(s.hasOwnProperty(a)){const u=s[a].textureReader;c(u.texture)&&e.addTexture(u.texture)}}}const kbe=T5,Vbe=new L,Hbe=new L,v5={name:"SceneMode2DPipelineStage"};v5.process=function(e,t,n){const i=Lt.getAttributeBySemantic(t,ht.POSITION),o=e.shaderBuilder,r=e.model,s=r.sceneGraph.computedModelMatrix,a=e.runtimeNode.computedTransform,l=L.multiplyTransformation(s,a,Vbe),u=Wbe(e,l,n),h=e.runtimePrimitive;h.boundingSphere2D=u;const f=e.runtimeNode.node.instances;if(c(f))return;if(c(i.typedArray)){const b=$be(i,l,u,n);h.positionBuffer2D=b,r._modelResources.push(b),i.typedArray=void 0}o.addDefine("USE_2D_POSITIONS",void 0,ge.VERTEX),o.addUniform("mat4","u_modelView2D",ge.VERTEX);const _=L.fromTranslation(u.center,new L),g=n.context,m={u_modelView2D:function(){return L.multiplyTransformation(g.uniformState.view,_,Hbe)}};e.uniformMap=jt(m,e.uniformMap)};const Gbe=new d,jbe=new d;function Wbe(e,t,n){const i=L.multiplyByPoint(t,e.positionMin,Gbe),o=Ao.computeActualWgs
{
mat4 skinningMatrix = getSkinningMatrix();
mat3 skinningMatrixMat3 = mat3(skinningMatrix);
vec4 positionMC = vec4(attributes.positionMC, 1.0);
attributes.positionMC = vec3(skinningMatrix * positionMC);
#ifdef HAS_NORMALS
vec3 normalMC = attributes.normalMC;
attributes.normalMC = skinningMatrixMat3 * normalMC;
#endif
#ifdef HAS_TANGENTS
vec3 tangentMC = attributes.tangentMC;
attributes.tangentMC = skinningMatrixMat3 * tangentMC;
#endif
}`,kf={name:"SkinningPipelineStage",FUNCTION_ID_GET_SKINNING_MATRIX:"getSkinningMatrix",FUNCTION_SIGNATURE_GET_SKINNING_MATRIX:"mat4 getSkinningMatrix()"};kf.process=function(e,t){const n=e.shaderBuilder;n.addDefine("HAS_SKINNING",void 0,ge.VERTEX),Zbe(n,t);const i=e.runtimeNode,o=i.computedJointMatrices;n.addUniform("mat4",`u_jointMatrices[${o.length}]`,ge.VERTEX),n.addVertexLines(Qbe);const r={u_jointMatrices:function(){return i.computedJointMatrices}};e.uniformMap=jt(r,e.uniformMap)};function Kbe(e){let t=-1;const n=e.attributes,i=n.length;for(let o=0;o<i;o++){const r=n[o];(r.semantic===ht.JOINTS||r.semantic===ht.WEIGHTS)&&(t=Math.max(t,r.setIndex))}return t}function Zbe(e,t){e.addFunction(kf.FUNCTION_ID_GET_SKINNING_MATRIX,kf.FUNCTION_SIGNATURE_GET_SKINNING_MATRIX,ge.VERTEX);const n="mat4 skinnedMatrix = mat4(0);";e.addFunctionLines(kf.FUNCTION_ID_GET_SKINNING_MATRIX,[n]);let i,o;const r=["x","y","z","w"],s=Kbe(t);for(i=0;i<=s;i++)for(o=0;o<=3;o++){const l=r[o],u=`skinnedMatrix += a_weights_${i}.${l} * u_jointMatrices[int(a_joints_${i}.${l})];`;e.addFunctionLines(kf.FUNCTION_ID_GET_SKINNING_MATRIX,[u])}const a="return skinnedMatrix;";e.addFunctionLines(kf.FUNCTION_ID_GET_SKINNING_MATRIX,[a])}const Jbe=kf,eTe=`void verticalExaggerationStage(
inout ProcessedAttributes attributes
) {
// Compute the distance from the camera to the local center of curvature.
vec4 vertexPositionENU = czm_modelToEnu * vec4(attributes.positionMC, 1.0);
vec2 vertexAzimuth = normalize(vertexPositionENU.xy);
// Curvature = 1 / radius of curvature.
float azimuthalCurvature = dot(vertexAzimuth * vertexAzimuth, czm_eyeEllipsoidCurvature);
float eyeToCenter = 1.0 / azimuthalCurvature + czm_eyeHeight;
// Compute the approximate ellipsoid normal at the vertex position.
// Uses a circular approximation for the Earth curvature along the geodesic.
vec3 vertexPositionEC = (czm_modelView * vec4(attributes.positionMC, 1.0)).xyz;
vec3 centerToVertex = eyeToCenter * czm_eyeEllipsoidNormalEC + vertexPositionEC;
vec3 vertexNormal = normalize(centerToVertex);
// Estimate the (sine of the) angle between the camera direction and the vertex normal
float verticalDistance = dot(vertexPositionEC, czm_eyeEllipsoidNormalEC);
float horizontalDistance = length(vertexPositionEC - verticalDistance * czm_eyeEllipsoidNormalEC);
float sinTheta = horizontalDistance / (eyeToCenter + verticalDistance);
bool isSmallAngle = clamp(sinTheta, 0.0, 0.05) == sinTheta;
// Approximate the change in height above the ellipsoid, from camera to vertex position.
float exactVersine = 1.0 - dot(czm_eyeEllipsoidNormalEC, vertexNormal);
float smallAngleVersine = 0.5 * sinTheta * sinTheta;
float versine = isSmallAngle ? smallAngleVersine : exactVersine;
float dHeight = dot(vertexPositionEC, vertexNormal) - eyeToCenter * versine;
float vertexHeight = czm_eyeHeight + dHeight;
// Transform the approximate vertex normal to model coordinates.
vec3 vertexNormalMC = (czm_inverseModelView * vec4(vertexNormal, 0.0)).xyz;
vertexNormalMC = normalize(vertexNormalMC);
// Compute the exaggeration and apply it along the approximate vertex normal.
float stretch = u_verticalExaggerationAndRelativeHeight.x;
float shift = u_verticalExaggerationAndRelativeHeight.y;
float exaggeration = (vertexHeight - shift) * (stretch - 1.0);
attributes.positionMC += exaggeration * vertexNormalMC;
}
`,D5={name:"VerticalExaggerationPipelineStage"},tTe=new H;D5.process=function(e,t,n){const{shaderBuilder:i,uniformMap:o}=e;i.addVertexLines(eTe),i.addDefine("HAS_VERTICAL_EXAGGERATION",void 0,ge.VERTEX),i.addUniform("vec2","u_verticalExaggerationAndRelativeHeight",ge.VERTEX),o.u_verticalExaggerationAndRelativeHeight=function(){return H.fromElements(n.verticalExaggeration,n.verticalExaggerationRelativeHeight,tTe)}};const nTe=D5,MO={};function iTe(e){const t=je.createTypedArray(e,e*2),n=e;let i=0;for(let o=0;o<n;o+=3)t[i++]=o,t[i++]=o+1,t[i++]=o+1,t[i++]=o+2,t[i++]=o+2,t[i++]=o;return t}function oTe(e,t){const n=t.length,i=je.createTypedArray(e,n*2);let o=0;for(let r=0;r<n;r+=3){const s=t[r],a=t[r+1],l=t[r+2];i[o++]=s,i[o++]=a,i[o++]=a,i[o++]=l,i[o++]=l,i[o++]=s}return i}function rTe(e){const t=e-2,n=2+t*4,i=je.createTypedArray(e,n);let o=0;i[o++]=0,i[o++]=1;for(let r=0;r<t;r++)i[o++]=r+1,i[o++]=r+2,i[o++]=r+2,i[o++]=r;return i}function sTe(e,t){const i=t.length-2,o=2+i*4,r=je.createTypedArray(e,o);let s=0;r[s++]=t[0],r[s++]=t[1];for(let a=0;a<i;a++){const l=t[a],u=t[a+1],h=t[a+2];r[s++]=u,r[s++]=h,r[s++]=h,r[s++]=l}return r}function aTe(e){const t=e-2,n=2+t*4,i=je.createTypedArray(e,n);let o=0;i[o++]=0,i[o++]=1;for(let r=0;r<t;r++)i[o++]=r+1,i[o++]=r+2,i[o++]=r+2,i[o++]=0;return i}function cTe(e,t){const i=t.length-2,o=2+i*4,r=je.createTypedArray(e,o);let s=0;const a=t[0];r[s++]=a,r[s++]=t[1];for(let l=0;l<i;l++){const u=t[l+1],h=t[l+2];r[s++]=u,r[s++]=h,r[s++]=h,r[s++]=a}return r}MO.createWireframeIndices=function(e,t,n){const i=c(n);if(e===ze.TRIANGLES)return i?oTe(t,n):iTe(t);if(e===ze.TRIANGLE_STRIP)return i?sTe(t,n):rTe(t);if(e===ze.TRIANGLE_FAN)return i?cTe(t,n):aTe(t)};MO.getWireframeIndicesCount=function(e,t){return e===ze.TRIANGLES?t*2:e===ze.TRIANGLE_STRIP||e===ze.TRIANGLE_FAN?2+(t-2)*4:t};const P5=MO,O5={name:"WireframePipelineStage"};O5.process=function(e,t,n){e.shaderBuilder.addDefine("HAS_WIREFRAME",void 0,ge.FRAGMENT);const o=e.model,r=lTe(t,e.indices,n);o._pipelineResources.push(r),e.wireframeIndexBuffer=r;const s=!1;o.statistics.addBuffer(r,s);const a=e.primitiveType,l=e.count;e.primitiveType=ze.LINES,e.count=P5.getWireframeIndicesCount(a,l)};function lTe(e,t,n){const o=Lt.getAttributeBySemantic(e,ht.POSITION).count,r=n.context.webgl2;let s;if(c(t)){const h=t.buffer,f=t.count;c(h)&&r?(s=h.sizeInBytes===f?new Uint8Array(f):je.createTypedArray(o,f),h.getBufferData(s)):s=t.typedArray}const a=e.primitiveType,l=P5.createWireframeIndices(a,o,s),u=je.fromSizeInBytes(l.BYTES_PER_ELEMENT);return ct.createIndexBuffer({context:n.context,typedArray:l,usage:ke.STATIC_DRAW,indexDatatype:u})}const uTe=O5;function L5(e){e=y(e,y.EMPTY_OBJECT);const t=e.primitive,n=e.node,i=e.model;A.typeOf.object("options.primitive",t),A.typeOf.object("options.node",n),A.typeOf.object("options.model",i),this.primitive=t,this.node=n,this.model=i,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=[]}L5.prototype.configurePipeline=function(e){const t=this.pipelineStages;t.length=0;const n=this.primitive,i=this.node,o=this.model,r=o.customShader,s=o.style,a=e.context.webgl2,u=e.mode!==oe.SCENE3D&&!e.scene3DOnly&&o._projectTo2D,h=e.verticalExaggeration!==1,f=c(n.morphTargets)&&n.morphTargets.length>0,_=c(i.skin),g=c(r),b=!(g&&c(r.fragmentShaderText))||r.mode!==RO.REPLACE_MATERIAL,T=Lt.hasQuantizedAttributes(n.attributes),x=o.debugWireframe&&ze.isTriangles(n.primitiveType)&&(o._enableDebugWireframe||a),C=o.pointCloudShading,w=c(C)&&C.attenuation,v=c(C)&&C.backFaceCulling,P=n.primitiveType===ze.POINTS&&(c(s)||w||v),N=o._enableShowOutline&&c(n.outlineCoordinates),k=dTe(o,i,n),M=c(o.classificationType);u&&t.push(Xbe),t.push(tbe),x&&t.push(uTe),M&&t.push(qye),f&&t.push(bbe),_&&t.push(Jbe),P&&t.push(Rbe),T&&t.push(k0e),b&&t.push(ube),t.push(NO),t.push(op),k.hasPropertyTable&&(t.push(sD),t.push(jye),t.push(Xye)),h&&t.push(nTe),g&&t.push(M0e),t.push(obe),o.allowPicking&&t.push(xbe),N&&t.push(Fbe),t.push(
if(model_silhouettePass) {
color = czm_gammaCorrect(model_silhouetteColor);
}
}`,_Te=`void silhouetteStage(in ProcessedAttributes attributes, inout vec4 positionClip) {
#ifdef HAS_NORMALS
if(model_silhouettePass) {
vec3 normal = normalize(czm_normal3D * attributes.normalMC);
normal.x *= czm_projection[0][0];
normal.y *= czm_projection[1][1];
positionClip.xy += normal.xy * positionClip.w * model_silhouetteSize * czm_pixelRatio / czm_viewport.z;
}
#endif
}
`,jx={name:"ModelSilhouettePipelineStage"};jx.silhouettesLength=0;jx.process=function(e,t,n){c(t._silhouetteId)||(t._silhouetteId=++jx.silhouettesLength);const i=e.shaderBuilder;i.addDefine("HAS_SILHOUETTE",void 0,ge.BOTH),i.addVertexLines(_Te),i.addFragmentLines(mTe),i.addUniform("vec4","model_silhouetteColor",ge.FRAGMENT),i.addUniform("float","model_silhouetteSize",ge.VERTEX),i.addUniform("bool","model_silhouettePass",ge.BOTH);const o={model_silhouetteColor:function(){return t.silhouetteColor},model_silhouetteSize:function(){return t.silhouetteSize},model_silhouettePass:function(){return!1}};e.uniformMap=jt(o,e.uniformMap),e.hasSilhouette=!0};const gTe=jx,yTe=`void modelSplitterStage()
{
// Don't split when rendering the shadow map, because it is rendered from
// the perspective of a totally different camera.
#ifndef SHADOW_MAP
if (model_splitDirection < 0.0 && gl_FragCoord.x > czm_splitPosition) discard;
if (model_splitDirection > 0.0 && gl_FragCoord.x < czm_splitPosition) discard;
#endif
}
`,WA={name:"ModelSplitterPipelineStage",SPLIT_DIRECTION_UNIFORM_NAME:"model_splitDirection"};WA.process=function(e,t,n){const i=e.shaderBuilder;i.addDefine("HAS_MODEL_SPLITTER",void 0,ge.FRAGMENT),i.addFragmentLines(yTe);const o={};i.addUniform("float",WA.SPLIT_DIRECTION_UNIFORM_NAME,ge.FRAGMENT),o[WA.SPLIT_DIRECTION_UNIFORM_NAME]=function(){return t.splitDirection},e.uniformMap=jt(o,e.uniformMap)};const bTe=WA;function TTe(e,t){A.typeOf.object("modelRenderResources",e),A.typeOf.object("runtimeNode",t),this.model=e.model,this.shaderBuilder=e.shaderBuilder.clone(),this.uniformMap=Je(e.uniformMap),this.alphaOptions=Je(e.alphaOptions),this.renderStateOptions=Je(e.renderStateOptions,!0),this.hasSilhouette=e.hasSilhouette,this.hasSkipLevelOfDetail=e.hasSkipLevelOfDetail,this.runtimeNode=t,this.attributes=[],this.attributeIndex=1,this.featureIdVertexAttributeSetIndex=0,this.instanceCount=0}function ATe(e){e=y(e,y.EMPTY_OBJECT),this.lightingModel=y(e.lightingModel,Gx.UNLIT)}function xTe(e,t){A.typeOf.object("nodeRenderResources",e),A.typeOf.object("runtimePrimitive",t),this.model=e.model,this.runtimeNode=e.runtimeNode,this.attributes=e.attributes.slice(),this.attributeIndex=e.attributeIndex,this.featureIdVertexAttributeSetIndex=e.featureIdVertexAttributeSetIndex,this.uniformMap=Je(e.uniformMap),this.alphaOptions=Je(e.alphaOptions),this.renderStateOptions=Je(e.renderStateOptions,!0),this.hasSilhouette=e.hasSilhouette,this.hasSkipLevelOfDetail=e.hasSkipLevelOfDetail,this.shaderBuilder=e.shaderBuilder.clone(),this.instanceCount=e.instanceCount,this.runtimePrimitive=t;const n=t.primitive;this.count=c(n.indices)?n.indices.count:Lt.getAttributeBySemantic(n,"POSITION").count,this.hasPropertyTable=!1,this.indices=n.indices,this.wireframeIndexBuffer=void 0,this.primitiveType=n.primitiveType;const i=Lt.getPositionMinMax(n,this.runtimeNode.instancingTranslationMin,this.runtimeNode.instancingTranslationMax);this.positionMin=d.clone(i.min,new d),this.positionMax=d.clone(i.max,new d),this.boundingSphere=se.fromCornerPoints(this.positionMin,this.positionMax,new se),this.lightingOptions=new ATe,this.pickId=void 0}function Ha(e){e=y(e,y.EMPTY_OBJECT);const t=e.modelComponents;A.typeOf.object("options.model",e.model),A.typeOf.object("options.modelComponents",t),this._model=e.model,this._components=t,this._pipelineStages=[],this._updateStages=[],this._runtimeNodes=[],this._rootNodes=[],this._skinnedNodes=[],this._runtimeSkins=[],this.modelPipelineStages=[],this._boundingSphere=void 0,this._boundingSphere2D=void 0,this._computedModelMatrix=L.clone(L.IDENTITY),this._computedModelMatrix2D=L.clone(L.IDENTITY),this._axisCorrectionMatrix=Lt.getAxisCorrectionMatrix(t.upAxis,t.forwardAxis,new L),this._runtimeArticulations={},CTe(this)}Object.defineProperties(Ha.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 CTe(e){const t=e._components,n=t.scene,o=e._model.modelMatrix;N5(e,o);const r=t.articulations,s=r.length,a=e._runtimeArticulations;for(let C=0;C<s;C++){const w=r[C],v=new BC({articulation:w,sceneGraph:e}),P=v.name;a[P]=v}const l=t.nodes,u=l.length;e._runtimeNodes=new Array(u);const f=n.nodes.length,_=L.IDENTITY;for(let C=0;C<f;C++){const w=n.nodes[C],v=M5(e,w,_);e._rootNodes.push(v)}const g=t.skins,m=e._runtimeSkins,b=g.length;for(let C=0;C<b;C++){const w=g[C];m.push(new FO({skin:w,sceneGraph:e}))}const T=e._skinnedNodes,x=T.length;for(let C=0;C<x;C++){const w=T[C],v=e._runtimeNodes[w],N=l[w].skin.index;v._runtimeSkin=m[N],v.updateJointMatrices()}e.applyArticulations()}function N5(e,t){const n=e._components,i=e._model;e._computedModelMatrix=L.multiplyTransformation(t,n.transform,e._computedModelMatrix),e._computedModelMatrix=L.multiplyTransformation(e._computedModelMatrix,e._axisCorrectionMatrix,e._computedModelMatrix),e._computedModelMatrix=L.multiplyByUniformScale(e._computedModelMatrix,i.computedScale,e._computedModelM
#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
}
`,txe=`#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;
}
`;function St(e,t){if(e=y(e,y.EMPTY_OBJECT),c(e.disableDepthTestDistance)&&e.disableDepthTestDistance<0)throw new E("disableDepthTestDistance must be greater than or equal to 0.0.");let n=e.translucencyByDistance,i=e.pixelOffsetScaleByDistance,o=e.scaleByDistance,r=e.distanceDisplayCondition;if(c(n)){if(n.far<=n.near)throw new E("translucencyByDistance.far must be greater than translucencyByDistance.near.");n=vt.clone(n)}if(c(i)){if(i.far<=i.near)throw new E("pixelOffsetScaleByDistance.far must be greater than pixelOffsetScaleByDistance.near.");i=vt.clone(i)}if(c(o)){if(o.far<=o.near)throw new E("scaleByDistance.far must be greater than scaleByDistance.near.");o=vt.clone(o)}if(c(r)){if(r.far<=r.near)throw new E("distanceDisplayCondition.far must be greater than distanceDisplayCondition.near.");r=Pt.clone(r)}this._show=y(e.show,!0),this._position=d.clone(y(e.position,d.ZERO)),this._actualPosition=d.clone(this._position),this._pixelOffset=H.clone(y(e.pixelOffset,H.ZERO)),this._translate=new H(0,0),this._eyeOffset=d.clone(y(e.eyeOffset,d.ZERO)),this._heightReference=y(e.heightReference,gt.NONE),this._verticalOrigin=y(e.verticalOrigin,si.CENTER),this._horizontalOrigin=y(e.horizontalOrigin,Fs.CENTER),this._scale=y(e.scale,1),this._color=z.clone(y(e.color,z.WHITE)),this._rotation=y(e.rotation,0),this._alignedAxis=d.clone(y(e.alignedAxis,d.ZERO)),this._width=e.width,this._height=e.height,this._scaleByDistance=o,this._translucencyByDistance=n,this._pixelOffsetScaleByDistance=i,this._sizeInMeters=y(e.sizeInMeters,!1),this._distanceDisplayCondition=r,this._disableDepthTestDistance=e.disableDepthTestDistance,this._id=e.id,this._collection=y(e.collection,t),this._pickId=void 0,this._pickPrimitive=y(e._pickPrimitive,this),this._billboardCollection=t,this._dirty=!1,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 s=e.image;let a=e.imageId;c(s)&&(c(a)||(typeof s=="string"?a=s:c(s.src)?a=s.src:a=Wr()),this._imageId=a,this._image=s),c(e.imageSubRegion)&&(this._imageId=a,this._imageSubRegion=e.imageSubRegion),c(this._billboardCollection._textureAtlas)&&this._loadImage(),this._actualClampedPosition=void 0,this._removeCallbackFunc=void 0,this._mode=oe.SCENE3D,this._clusterShow=!0,this._outlineColor=z.clone(y(e.outlineColor,z.BLACK)),this._outlineWidth=y(e.outlineWidth,0),this._updateClamping()}const TF=St.SHOW_INDEX=0,qA=St.POSITION_INDEX=1,G5=St.PIXEL_OFFSET_INDEX=2,nxe=St.EYE_OFFSET_INDEX=3,ixe=St.HORIZONTAL_ORIGIN_INDEX=4,oxe=St.VERTICAL_ORIGIN_INDEX=5,rxe=St.SCALE_INDEX=6,YA=St.IMAGE_INDEX_INDEX=7,AF=St.COLOR_INDEX=8,sxe=St.ROTATION_INDEX=9,axe=St.ALIGNED_AXIS_INDEX=10,cxe=St.SCALE_BY_DISTANCE_INDEX=11,lxe=St.TRANSLUCENCY_BY_DISTANCE_INDEX=12,uxe=St.PIXEL_OFFSET_SCALE_BY_DISTANCE_INDEX=13,dxe=St.DISTANCE_DISPLAY_CONDITION=14,hxe=St.DISABLE_DEPTH_DISTANCE=15;St.TEXTURE_COORDINATE_BOUNDS=16;const xF=St.SDF_INDEX=17;St.NUMBER_OF_PROPERTIES=18;function mi(e,t){const n=e._billboardCollection;c(n)&&(n._updateBillboard(e,t),e._dirty=!0)}Object.defineProperties(St.prototype,{show:{get:function(){return this._show},set:function(e){A.typeOf.bool("value",e),this._show!==e&&(this._show=e,mi(this,TF))}},position:{get:function(){return this._position},set:function(e){A.typeOf.object("value",e);const t=this._position;d.equals(t,e)||(d.clone(e,t),d.clone(e,this._actualPosition),this._updateClamping(),mi(this,qA))}},heightReference:{get:function(){return this._heightReference},set:function(e){A.typeOf.number("value",e);const t=this._heightReference;e!==t&&(this._heightReference=e,this._updateClamping(),mi(this,qA))}},pixelOffset:{get:function(){return this._pixelOffset},set:function(e){A.typeOf.object("value",e);const t=this._pixelOffset;H.equals(t,e)||(H.clone(e,t),mi(this,G5))}},scaleByDistance:{get:function(){return this._scaleByDistance},set:function(e){if(c(e)&&(A.typeOf.object("value",e),e.far<=
in vec2 v_textureCoordinates;
void main()
{
out_FragColor = texture(billboard_texture, v_textureCoordinates);
}
`,i=t.createViewportQuadCommand(n,{uniformMap:{billboard_texture:function(){return e._textureAtlas.texture}}});return i.pass=xe.OVERLAY,i}const kxe=[];Ts.prototype.update=function(e){if(zO(this),!this.show)return;let t=this._billboards,n=t.length;const i=e.context;this._instanced=i.instancedArrays,ni=this._instanced?Sxe:wxe,mS=this._instanced?Ixe:vxe;let o=this._textureAtlas;if(!c(o)){o=this._textureAtlas=new ou({context:i});for(let M=0;M<n;++M)t[M]._loadImage()}const r=o.textureCoordinates;if(r.length===0)return;Bxe(this,e),t=this._billboards,n=t.length;const s=this._billboardsToUpdate,a=this._billboardsToUpdateIndex,l=this._propertiesChanged,u=o.guid,h=this._createVertexArray||this._textureAtlasGUID!==u;this._textureAtlasGUID=u;let f;const _=e.passes,g=_.pick;if(h||!g&&this.computeNewBuffersUsage()){this._createVertexArray=!1;for(let M=0;M<BO;++M)l[M]=0;if(this._vaf=this._vaf&&this._vaf.destroy(),n>0){this._vaf=Pxe(i,n,this._buffersUsage,this._instanced,this._batchTable,this._sdf),f=this._vaf.writers;for(let M=0;M<n;++M){const U=this._billboards[M];U._dirty=!1,Fxe(this,e,r,f,U)}this._vaf.commit(mS(i))}this._billboardsToUpdateIndex=0}else if(a>0){const M=kxe;M.length=0,(l[My]||l[Axe]||l[Txe])&&M.push(n8),(l[Rg]||l[Y5]||l[yxe]||l[bxe]||l[gxe])&&(M.push(c8),this._instanced&&M.push(lD)),(l[Rg]||l[xxe]||l[K5])&&(M.push(l8),M.push(cD)),(l[Rg]||l[X5])&&M.push(cD),l[$5]&&M.push(lD),l[Q5]&&M.push(u8),l[Z5]&&M.push(d8),(l[J5]||l[Cxe]||l[Rg]||l[My])&&M.push(h8),(l[Rg]||l[My])&&M.push(f8),l[e8]&&M.push(p8);const U=M.length;if(f=this._vaf.writers,a/n>.1){for(let B=0;B<a;++B){const S=s[B];S._dirty=!1;for(let D=0;D<U;++D)M[D](this,e,r,f,S)}this._vaf.commit(mS(i))}else{for(let B=0;B<a;++B){const S=s[B];S._dirty=!1;for(let D=0;D<U;++D)M[D](this,e,r,f,S);this._instanced?this._vaf.subCommit(S._index,1):this._vaf.subCommit(S._index*4,4)}this._vaf.endSubCommits()}this._billboardsToUpdateIndex=0}if(a>n*1.5&&(s.length=n),!c(this._vaf)||!c(this._vaf.va))return;this._boundingVolumeDirty&&(this._boundingVolumeDirty=!1,se.transform(this._baseVolume,this.modelMatrix,this._baseVolumeWC));let m,b=L.IDENTITY;e.mode===oe.SCENE3D?(b=this.modelMatrix,m=se.clone(this._baseVolumeWC,this._boundingVolume)):m=se.clone(this._baseVolume2D,this._boundingVolume),zxe(this,e,m);const T=this._blendOption!==this.blendOption;if(this._blendOption=this.blendOption,T){this._blendOption===io.OPAQUE||this._blendOption===io.OPAQUE_AND_TRANSLUCENT?this._rsOpaque=Ue.fromCache({depthTest:{enabled:!0,func:J.LESS},depthMask:!0}):this._rsOpaque=void 0;const M=this._blendOption===io.TRANSLUCENT;this._blendOption===io.TRANSLUCENT||this._blendOption===io.OPAQUE_AND_TRANSLUCENT?this._rsTranslucent=Ue.fromCache({depthTest:{enabled:!0,func:M?J.LEQUAL:J.LESS},depthMask:M,blending:Zn.ALPHA_BLEND}):this._rsTranslucent=void 0}this._shaderDisableDepthDistance=this._shaderDisableDepthDistance||e.minimumDisableDepthTestDistance!==0;let x,C,w,v,P;const N=pt.maximumVertexTextureImageUnits>0;if(T||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){x=txe,C=exe,P=[],c(this._batchTable)&&(P.push("VECTOR_TILE"),x=this._batchTable.getVertexShaderCallback(!1,"a_batchId",void 0)(x),C=this._batchTable.getFragmentShaderCallback(!1,void 0)(C)),w=new Oe({defines:P,sources:[x]}),this._instanced&&w.defines.push("INSTANCED"),this._shaderRotation&&w.defines.push("ROTATION"),this._shaderAlignedAxis&&w.defines.push("ALIGNED_AXIS"),this._shaderScaleByDistance&&w.defines.push("EYE_DISTANCE_SCALING"),this._shaderTranslucencyByDistance&&w.defines.push("EYE_DISTANCE_TRAN
`);let n="";for(let i=0;i<t.length;i++){const o=t[i],r=IF.test(o.charAt(0)),s=Qxe(o,IF);let a=0,l="";for(let u=0;u<s.length;++u){const h=s[u],f=h.Type===vo.BRACKETS?Zxe(h.Word):Kxe(h.Word);r?h.Type===vo.RTL?(l=f+l,a=0):h.Type===vo.LTR?(l=Fg(l,a,h.Word),a+=h.Word.length):(h.Type===vo.WEAK||h.Type===vo.BRACKETS)&&(h.Type===vo.WEAK&&s[u-1].Type===vo.BRACKETS?l=f+l:s[u-1].Type===vo.RTL?(l=f+l,a=0):s.length>u+1?s[u+1].Type===vo.RTL?(l=f+l,a=0):(l=Fg(l,a,h.Word),a+=h.Word.length):l=Fg(l,0,f)):h.Type===vo.RTL?l=Fg(l,a,f):h.Type===vo.LTR?(l+=h.Word,a=l.length):(h.Type===vo.WEAK||h.Type===vo.BRACKETS)&&(u>0&&s[u-1].Type===vo.RTL?s.length>u+1?s[u+1].Type===vo.RTL?l=Fg(l,a,f):(l+=h.Word,a=l.length):l+=h.Word:(l+=h.Word,a=l.length))}n+=l,i<t.length-1&&(n+=`
`)}return n}var g8={exports:{}};(function(e){function t(){var n=0,i=1,o=2,r=3,s=4,a=5,l=6,u=7,h=8,f=9,_=10,g=11,m=12,b=13,T=14,x=15,C=16,w=17,v=0,P=1,N=2,k=3,M=4;function U(p,I){return 55296<=p.charCodeAt(I)&&p.charCodeAt(I)<=56319&&56320<=p.charCodeAt(I+1)&&p.charCodeAt(I+1)<=57343}function B(p,I){I===void 0&&(I=0);var O=p.charCodeAt(I);if(55296<=O&&O<=56319&&I<p.length-1){var F=O,V=p.charCodeAt(I+1);return 56320<=V&&V<=57343?(F-55296)*1024+(V-56320)+65536:F}if(56320<=O&&O<=57343&&I>=1){var F=p.charCodeAt(I-1),V=O;return 55296<=F&&F<=56319?(F-55296)*1024+(V-56320)+65536:V}return O}function S(p,I,O){var F=[p].concat(I).concat([O]),V=F[F.length-2],G=O,j=F.lastIndexOf(T);if(j>1&&F.slice(1,j).every(function(q){return q==r})&&[r,b,w].indexOf(p)==-1)return N;var W=F.lastIndexOf(s);if(W>0&&F.slice(1,W).every(function(q){return q==s})&&[m,s].indexOf(V)==-1)return F.filter(function(q){return q==s}).length%2==1?k:M;if(V==n&&G==i)return v;if(V==o||V==n||V==i)return G==T&&I.every(function(q){return q==r})?N:P;if(G==o||G==n||G==i)return P;if(V==l&&(G==l||G==u||G==f||G==_))return v;if((V==f||V==u)&&(G==u||G==h))return v;if((V==_||V==h)&&G==h)return v;if(G==r||G==x)return v;if(G==a)return v;if(V==m)return v;var X=F.indexOf(r)!=-1?F.lastIndexOf(r)-1:F.length-2;return[b,w].indexOf(F[X])!=-1&&F.slice(X+1,-1).every(function(q){return q==r})&&G==T||V==x&&[C,w].indexOf(G)!=-1?v:I.indexOf(s)!=-1?N:V==s&&G==s?v:P}this.nextBreak=function(p,I){if(I===void 0&&(I=0),I<0)return 0;if(I>=p.length-1)return p.length;for(var O=D(B(p,I)),F=[],V=I+1;V<p.length;V++)if(!U(p,V-1)){var G=D(B(p,V));if(S(O,F,G))return V;F.push(G)}return p.length},this.splitGraphemes=function(p){for(var I=[],O=0,F;(F=this.nextBreak(p,O))<p.length;)I.push(p.slice(O,F)),O=F;return O<p.length&&I.push(p.slice(O)),I},this.iterateGraphemes=function(p){var I=0,O={next:function(){var F,V;return(V=this.nextBreak(p,I))<p.length?(F=p.slice(I,V),I=V,{value:F,done:!1}):I<p.length?(F=p.slice(I),I=p.length,{value:F,done:!1}):{value:void 0,done:!0}}.bind(this)};return typeof Symbol<"u"&&Symbol.iterator&&(O[Symbol.iterator]=function(){return O}),O},this.countGraphemes=function(p){for(var I=0,O=0,F;(F=this.nextBreak(p,O))<p.length;)O=F,I++;return O<p.length&&I++,I};function D(p){return 1536<=p&&p<=1541||p==1757||p==1807||p==2274||p==3406||p==69821||70082<=p&&p<=70083||p==72250||72326<=p&&p<=72329||p==73030?m:p==13?n:p==10?i:0<=p&&p<=9||11<=p&&p<=12||14<=p&&p<=31||127<=p&&p<=159||p==173||p==1564||p==6158||p==8203||8206<=p&&p<=8207||p==8232||p==8233||8234<=p&&p<=8238||8288<=p&&p<=8292||p==8293||8294<=p&&p<=8303||55296<=p&&p<=57343||p==65279||65520<=p&&p<=65528||65529<=p&&p<=65531||113824<=p&&p<=113827||119155<=p&&p<=119162||p==917504||p==917505||917506<=p&&p<=917535||917632<=p&&p<=917759||918e3<=p&&p<=921599?o:768<=p&&p<=879||1155<=p&&p<=1159||1160<=p&&p<=1161||1425<=p&&p<=1469||p==1471||1473<=p&&p<=1474||1476<=p&&p<=1477||p==1479||1552<=p&&p<=1562||1611<=p&&p<=1631||p==1648||1750<=p&&p<=1756||1759<=p&&p<=1764||1767<=p&&p<=1768||1770<=p&&p<=1773||p==1809||1840<=p&&p<=1866||1958<=p&&p<=1968||2027<=p&&p<=2035||2070<=p&&p<=2073||2075<=p&&p<=2083||2085<=p&&p<=2087||2089<=p&&p<=2093||2137<=p&&p<=2139||2260<=p&&p<=2273||2275<=p&&p<=2306||p==2362||p==2364||2369<=p&&p<=2376||p==2381||2385<=p&&p<=2391||2402<=p&&p<=2403||p==2433||p==2492||p==2494||2497<=p&&p<=2500||p==2509||p==2519||2530<=p&&p<=2531||2561<=p&&p<=2562||p==2620||2625<=p&&p<=2626||2631<=p&&p<=2632||2635<=p&&p<=2637||p==2641||2672<=p&&p<=2673||p==2677||2689<=p&&p<=2690||p==2748||2753<=p&&p<=2757||2759<=p&&p<=2760||p==2765||2786<=p&&p<=2787||2810<=p&&p<=2815||p==2817||p==2876||p==2878||p==2879||2881<=p&&p<=2884||p==2893||p==2902||p==2903||2914<=p&&p<=2915||p==2946||p==3006||p==3008||p==3021||p==3031||p==3072||3134<=p&&p<=3136||3142<=p&&p<=3144||3146<=p&&p<=3149||3157<=p&&p<=3158||3170<=p&&p<=3171||p==3201||p==3260||p==3263||p==3266||p==3270||3276<=p&&p<=3277||3285<=p&&p<=3286||3298<=p&&p<=3299||3328<=p&&p<=3329||3387<=p&&p<=3388||p==3390||3393<=p&&p<=3396||p==3405||p==3415||3426<=p&&p<=3427||p==3530||p==3535||3538<=p&&p<=3540||p==3542||p==3551|
`).join("").length>0;let f=t._backgroundBillboard;const _=e._backgroundBillboardCollection;h?(c(f)||(f=_.add({collection:e,image:y8,imageSubRegion:sCe}),t._backgroundBillboard=f),f.color=t._backgroundColor,f.show=t._show,f.position=t._position,f.eyeOffset=t._eyeOffset,f.pixelOffset=t._pixelOffset,f.horizontalOrigin=Fs.LEFT,f.verticalOrigin=t._verticalOrigin,f.heightReference=t._heightReference,f.scale=t.totalScale,f.pickPrimitive=t,f.id=t._id,f.translucencyByDistance=t._translucencyByDistance,f.pixelOffsetScaleByDistance=t._pixelOffsetScaleByDistance,f.scaleByDistance=t._scaleByDistance,f.distanceDisplayCondition=t._distanceDisplayCondition,f.disableDepthTestDistance=t._disableDepthTestDistance,f.clusterShow=t.clusterShow):c(f)&&(_.remove(f),t._backgroundBillboard=f=void 0);const g=e._glyphTextureCache;for(u=0;u<o;++u){const m=i[u],b=t._verticalOrigin,T=JSON.stringify([m,t._fontFamily,t._fontStyle,t._fontWeight,+b]);let x=g[T];if(!c(x)){const C=`${t._fontStyle} ${t._fontWeight} ${Aa.FONT_SIZE}px ${t._fontFamily}`,w=cCe(m,C,z.WHITE,z.WHITE,0,dl.FILL,b);if(x=new oCe(e,-1,w.dimensions),g[T]=x,w.width>0&&w.height>0){const v=jxe(w,{cutoff:Aa.CUTOFF,radius:Aa.RADIUS}),P=w.getContext("2d"),N=w.width,k=w.height,M=P.getImageData(0,0,N,k);for(let U=0;U<N;U++)for(let B=0;B<k;B++){const S=B*N+U,D=v[S]*255,p=S*4;M.data[p+0]=D,M.data[p+1]=D,M.data[p+2]=D,M.data[p+3]=D}P.putImageData(M,0,0),m!==" "&&lCe(e._textureAtlas,T,w,x)}}if(a=r[u],c(a)?x.index===-1?dD(e,a):c(a.textureInfo)&&(a.textureInfo=void 0):(a=new iCe,r[u]=a),a.textureInfo=x,a.dimensions=x.dimensions,x.index!==-1){let C=a.billboard;const w=e._spareBillboards;c(C)||(w.length>0?C=w.pop():(C=e._billboardCollection.add({collection:e}),C._labelDimensions=new H,C._labelTranslate=new H),a.billboard=C),C.show=t._show,C.position=t._position,C.eyeOffset=t._eyeOffset,C.pixelOffset=t._pixelOffset,C.horizontalOrigin=Fs.LEFT,C.verticalOrigin=t._verticalOrigin,C.heightReference=t._heightReference,C.scale=t.totalScale,C.pickPrimitive=t,C.id=t._id,C.image=T,C.translucencyByDistance=t._translucencyByDistance,C.pixelOffsetScaleByDistance=t._pixelOffsetScaleByDistance,C.scaleByDistance=t._scaleByDistance,C.distanceDisplayCondition=t._distanceDisplayCondition,C.disableDepthTestDistance=t._disableDepthTestDistance,C._batchIndex=t._batchIndex,C.outlineColor=t.outlineColor,t.style===dl.FILL_AND_OUTLINE?(C.color=t._fillColor,C.outlineWidth=t.outlineWidth):t.style===dl.FILL?(C.color=t._fillColor,C.outlineWidth=0):t.style===dl.OUTLINE&&(C.color=z.TRANSPARENT,C.outlineWidth=t.outlineWidth)}}t._repositionAllGlyphs=!0}function DF(e,t,n){return t===Fs.CENTER?-e/2:t===Fs.RIGHT?-(e+n.x):n.x}const Mi=new H,hCe=new H;function fCe(e){const t=e._glyphs,n=e._renderedText;let i,o,r=0,s=0;const a=[];let l=Number.NEGATIVE_INFINITY,u=0,h=1,f;const _=t.length,g=e._backgroundBillboard,m=H.clone(c(g)?e._backgroundPadding:H.ZERO,hCe);for(m.x/=e._relativeSize,m.y/=e._relativeSize,f=0;f<_;++f)n.charAt(f)===`
`?(a.push(r),++h,r=0):(i=t[f],o=i.dimensions,u=Math.max(u,o.height-o.descent),l=Math.max(l,o.descent),r+=o.width-o.minx,f<_-1&&(r+=t[f+1].dimensions.minx),s=Math.max(s,r));a.push(r);const b=u+l,T=e.totalScale,x=e._horizontalOrigin,C=e._verticalOrigin;let w=0,v=a[w],P=DF(v,x,m);const N=(c(e._lineHeight)?e._lineHeight:rCe*e._fontSize)/e._relativeSize,k=N*(h-1);let M=s,U=b+k;c(g)&&(M+=m.x*2,U+=m.y*2,g._labelHorizontalOrigin=x),Mi.x=P*T,Mi.y=0;let B=!0,S=0;for(f=0;f<_;++f)if(n.charAt(f)===`
`)++w,S+=N,v=a[w],P=DF(v,x,m),Mi.x=P*T,B=!0;else if(i=t[f],o=i.dimensions,C===si.TOP?(Mi.y=o.height-u-m.y,Mi.y+=Aa.PADDING):C===si.CENTER?Mi.y=(k+o.height-u)/2:C===si.BASELINE?(Mi.y=k,Mi.y-=Aa.PADDING):(Mi.y=k+l+m.y,Mi.y-=Aa.PADDING),Mi.y=(Mi.y-o.descent-S)*T,B&&(Mi.x-=Aa.PADDING*T,B=!1),c(i.billboard)&&(i.billboard._setTranslate(Mi),i.billboard._labelDimensions.x=M,i.billboard._labelDimensions.y=U,i.billboard._labelHorizontalOrigin=x),f<_-1){const D=t[f+1];Mi.x+=(o.width-o.minx+D.dimensions.minx)*T}if(c(g)&&n.split(`
`).join("").length>0&&(x===Fs.CENTER?P=-s/2-m.x:x===Fs.RIGHT?P=-(s+m.x*2):P=0,Mi.x=P*T,C===si.TOP?Mi.y=b-u-l:C===si.CENTER?Mi.y=(b-u)/2-l:C===si.BASELINE?Mi.y=-m.y-l:Mi.y=0,Mi.y=Mi.y*T,g.width=M,g.height=U,g._setTranslate(Mi),g._labelTranslate=H.clone(Mi,g._labelTranslate)),Np(e.heightReference))for(f=0;f<_;++f){i=t[f];const D=i.billboard;c(D)&&(D._labelTranslate=H.clone(Mi,D._labelTranslate))}}function b8(e,t){const n=t._glyphs;for(let i=0,o=n.length;i<o;++i)dD(e,n[i]);c(t._backgroundBillboard)&&(e._backgroundBillboardCollection.remove(t._backgroundBillboard),t._backgroundBillboard=void 0),t._labelCollection=void 0,c(t._removeCallbackFunc)&&t._removeCallbackFunc(),ve(t)}function Ga(e){e=y(e,y.EMPTY_OBJECT),this._scene=e.scene,this._batchTable=e.batchTable,this._textureAtlas=void 0,this._backgroundTextureAtlas=void 0,this._backgroundBillboardCollection=new Ts({scene:this._scene}),this._backgroundBillboardCollection.destroyTextureAtlas=!1,this._billboardCollection=new Ts({scene:this._scene,batchTable:this._batchTable}),this._billboardCollection.destroyTextureAtlas=!1,this._billboardCollection._sdf=!0,this._spareBillboards=[],this._glyphTextureCache={},this._labels=[],this._labelsToUpdate=[],this._totalGlyphCount=0,this._highlightColor=z.clone(z.WHITE),this.show=y(e.show,!0),this.modelMatrix=L.clone(y(e.modelMatrix,L.IDENTITY)),this.debugShowBoundingVolume=y(e.debugShowBoundingVolume,!1),this.blendOption=y(e.blendOption,io.OPAQUE_AND_TRANSLUCENT)}Object.defineProperties(Ga.prototype,{length:{get:function(){return this._labels.length}}});Ga.prototype.add=function(e){const t=new Tl(e,this);return this._labels.push(t),this._labelsToUpdate.push(t),t};Ga.prototype.remove=function(e){if(c(e)&&e._labelCollection===this){const t=this._labels.indexOf(e);if(t!==-1)return this._labels.splice(t,1),b8(this,e),!0}return!1};Ga.prototype.removeAll=function(){const e=this._labels;for(let t=0,n=e.length;t<n;++t)b8(this,e[t]);e.length=0};Ga.prototype.contains=function(e){return c(e)&&e._labelCollection===this};Ga.prototype.get=function(e){if(!c(e))throw new E("index is required.");return this._labels[e]};Ga.prototype.update=function(e){if(!this.show)return;const t=this._billboardCollection,n=this._backgroundBillboardCollection;t.modelMatrix=this.modelMatrix,t.debugShowBoundingVolume=this.debugShowBoundingVolume,n.modelMatrix=this.modelMatrix,n.debugShowBoundingVolume=this.debugShowBoundingVolume;const i=e.context;c(this._textureAtlas)||(this._textureAtlas=new ou({context:i}),t.textureAtlas=this._textureAtlas),c(this._backgroundTextureAtlas)||(this._backgroundTextureAtlas=new ou({context:i,initialSize:uD}),n.textureAtlas=this._backgroundTextureAtlas,aCe(this._backgroundTextureAtlas));const o=this._labelsToUpdate.length;for(let s=0;s<o;++s){const a=this._labelsToUpdate[s];if(a.isDestroyed())continue;const l=a._glyphs.length;a._rebindAllGlyphs&&(dCe(this,a),a._rebindAllGlyphs=!1),a._repositionAllGlyphs&&(fCe(a),a._repositionAllGlyphs=!1);const u=a._glyphs.length-l;this._totalGlyphCount+=u}const r=n.length>0?io.TRANSLUCENT:this.blendOption;t.blendOption=r,n.blendOption=r,t._highlightColor=this._highlightColor,n._highlightColor=this._highlightColor,this._labelsToUpdate.length=0,n.update(e),t.update(e)};Ga.prototype.isDestroyed=function(){return!1};Ga.prototype.destroy=function(){return 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(),ve(this)};const pCe=`in vec3 position3DHigh;
in vec3 position3DLow;
in vec3 position2DHigh;
in vec3 position2DLow;
in vec3 prevPosition3DHigh;
in vec3 prevPosition3DLow;
in vec3 prevPosition2DHigh;
in vec3 prevPosition2DLow;
in vec3 nextPosition3DHigh;
in vec3 nextPosition3DLow;
in vec3 nextPosition2DHigh;
in vec3 nextPosition2DLow;
in vec4 texCoordExpandAndBatchIndex;
out vec2 v_st;
out float v_width;
out vec4 v_pickColor;
out float v_polylineAngle;
void main()
{
float texCoord = texCoordExpandAndBatchIndex.x;
float expandDir = texCoordExpandAndBatchIndex.y;
bool usePrev = texCoordExpandAndBatchIndex.z < 0.0;
float batchTableIndex = texCoordExpandAndBatchIndex.w;
vec2 widthAndShow = batchTable_getWidthAndShow(batchTableIndex);
float width = widthAndShow.x + 0.5;
float show = widthAndShow.y;
if (width < 1.0)
{
show = 0.0;
}
vec4 pickColor = batchTable_getPickColor(batchTableIndex);
vec4 p, prev, next;
if (czm_morphTime == 1.0)
{
p = czm_translateRelativeToEye(position3DHigh.xyz, position3DLow.xyz);
prev = czm_translateRelativeToEye(prevPosition3DHigh.xyz, prevPosition3DLow.xyz);
next = czm_translateRelativeToEye(nextPosition3DHigh.xyz, nextPosition3DLow.xyz);
}
else if (czm_morphTime == 0.0)
{
p = czm_translateRelativeToEye(position2DHigh.zxy, position2DLow.zxy);
prev = czm_translateRelativeToEye(prevPosition2DHigh.zxy, prevPosition2DLow.zxy);
next = czm_translateRelativeToEye(nextPosition2DHigh.zxy, nextPosition2DLow.zxy);
}
else
{
p = czm_columbusViewMorph(
czm_translateRelativeToEye(position2DHigh.zxy, position2DLow.zxy),
czm_translateRelativeToEye(position3DHigh.xyz, position3DLow.xyz),
czm_morphTime);
prev = czm_columbusViewMorph(
czm_translateRelativeToEye(prevPosition2DHigh.zxy, prevPosition2DLow.zxy),
czm_translateRelativeToEye(prevPosition3DHigh.xyz, prevPosition3DLow.xyz),
czm_morphTime);
next = czm_columbusViewMorph(
czm_translateRelativeToEye(nextPosition2DHigh.zxy, nextPosition2DLow.zxy),
czm_translateRelativeToEye(nextPosition3DHigh.xyz, nextPosition3DLow.xyz),
czm_morphTime);
}
#ifdef DISTANCE_DISPLAY_CONDITION
vec3 centerHigh = batchTable_getCenterHigh(batchTableIndex);
vec4 centerLowAndRadius = batchTable_getCenterLowAndRadius(batchTableIndex);
vec3 centerLow = centerLowAndRadius.xyz;
float radius = centerLowAndRadius.w;
vec2 distanceDisplayCondition = batchTable_getDistanceDisplayCondition(batchTableIndex);
float lengthSq;
if (czm_sceneMode == czm_sceneMode2D)
{
lengthSq = czm_eyeHeight2D.y;
}
else
{
vec4 center = czm_translateRelativeToEye(centerHigh.xyz, centerLow.xyz);
lengthSq = max(0.0, dot(center.xyz, center.xyz) - radius * radius);
}
float nearSq = distanceDisplayCondition.x * distanceDisplayCondition.x;
float farSq = distanceDisplayCondition.y * distanceDisplayCondition.y;
if (lengthSq < nearSq || lengthSq > farSq)
{
show = 0.0;
}
#endif
float polylineAngle;
vec4 positionWC = getPolylineWindowCoordinates(p, prev, next, expandDir, width, usePrev, polylineAngle);
gl_Position = czm_viewportOrthographic * positionWC * show;
v_st.s = texCoord;
v_st.t = czm_writeNonPerspective(clamp(expandDir, 0.0, 1.0), gl_Position.w);
v_width = width;
v_pickColor = pickColor;
v_polylineAngle = polylineAngle;
}
`,ks={};ks.numberOfPoints=function(e,t,n){const i=d.distance(e,t);return Math.ceil(i/n)};ks.numberOfPointsRhumbLine=function(e,t,n){const i=Math.pow(e.longitude-t.longitude,2)+Math.pow(e.latitude-t.latitude,2);return Math.max(1,Math.ceil(Math.sqrt(i/(n*n))))};const mCe=new he;ks.extractHeights=function(e,t){const n=e.length,i=new Array(n);for(let o=0;o<n;o++){const r=e[o];i[o]=t.cartesianToCartographic(r,mCe).height}return i};const _Ce=new L,gCe=new d,PF=new d,yCe=new _t(d.UNIT_X,0),OF=new d,bCe=new _t(d.UNIT_X,0),TCe=new d,ACe=new d,UO=[];function T8(e,t,n){const i=UO;i.length=e;let o;if(t===n){for(o=0;o<e;o++)i[o]=t;return i}const s=(n-t)/e;for(o=0;o<e;o++){const a=t+o*s;i[o]=a}return i}const UC=new he,Wx=new he,Mh=new d,kO=new d,xCe=new d,bS=new Mp;let Bg=new vr;function CCe(e,t,n,i,o,r,s,a){const l=i.scaleToGeodeticSurface(e,kO),u=i.scaleToGeodeticSurface(t,xCe),h=ks.numberOfPoints(e,t,n),f=i.cartesianToCartographic(l,UC),_=i.cartesianToCartographic(u,Wx),g=T8(h,o,r);bS.setEndPoints(f,_);const m=bS.surfaceDistance/h;let b=a;f.height=o;let T=i.cartographicToCartesian(f,Mh);d.pack(T,s,b),b+=3;for(let x=1;x<h;x++){const C=bS.interpolateUsingSurfaceDistance(x*m,Wx);C.height=g[x],T=i.cartographicToCartesian(C,Mh),d.pack(T,s,b),b+=3}return b}function ECe(e,t,n,i,o,r,s,a){const l=i.cartesianToCartographic(e,UC),u=i.cartesianToCartographic(t,Wx),h=ks.numberOfPointsRhumbLine(l,u,n);l.height=0,u.height=0;const f=T8(h,o,r);Bg.ellipsoid.equals(i)||(Bg=new vr(void 0,void 0,i)),Bg.setEndPoints(l,u);const _=Bg.surfaceDistance/h;let g=a;l.height=o;let m=i.cartographicToCartesian(l,Mh);d.pack(m,s,g),g+=3;for(let b=1;b<h;b++){const T=Bg.interpolateUsingSurfaceDistance(b*_,Wx);T.height=f[b],m=i.cartographicToCartesian(T,Mh),d.pack(m,s,g),g+=3}return g}ks.wrapLongitude=function(e,t){const n=[],i=[];if(c(e)&&e.length>0){t=y(t,L.IDENTITY);const o=L.inverseTransformation(t,_Ce),r=L.multiplyByPoint(o,d.ZERO,gCe),s=d.normalize(L.multiplyByPointAsVector(o,d.UNIT_Y,PF),PF),a=_t.fromPointNormal(r,s,yCe),l=d.normalize(L.multiplyByPointAsVector(o,d.UNIT_X,OF),OF),u=_t.fromPointNormal(r,l,bCe);let h=1;n.push(d.clone(e[0]));let f=n[0];const _=e.length;for(let g=1;g<_;++g){const m=e[g];if(_t.getPointDistance(u,f)<0||_t.getPointDistance(u,m)<0){const b=Ei.lineSegmentPlane(f,m,a,TCe);if(c(b)){const T=d.multiplyByScalar(s,5e-9,ACe);_t.getPointDistance(a,f)<0&&d.negate(T,T),n.push(d.add(b,T,new d)),i.push(h+1),d.negate(T,T),n.push(d.add(b,T,new d)),h=1}}n.push(d.clone(e[g])),h++,f=m}i.push(h)}return{positions:n,lengths:i}};ks.generateArc=function(e){c(e)||(e={});const t=e.positions;if(!c(t))throw new E("options.positions is required.");const n=t.length,i=y(e.ellipsoid,ae.WGS84);let o=y(e.height,0);const r=Array.isArray(o);if(n<1)return[];if(n===1){const b=i.scaleToGeodeticSurface(t[0],kO);if(o=r?o[0]:o,o!==0){const T=i.geodeticSurfaceNormal(b,Mh);d.multiplyByScalar(T,o,T),d.add(b,T,b)}return[b.x,b.y,b.z]}let s=e.minDistance;if(!c(s)){const b=y(e.granularity,R.RADIANS_PER_DEGREE);s=R.chordLength(b,i.maximumRadius)}let a=0,l;for(l=0;l<n-1;l++)a+=ks.numberOfPoints(t[l],t[l+1],s);const u=(a+1)*3,h=new Array(u);let f=0;for(l=0;l<n-1;l++){const b=t[l],T=t[l+1],x=r?o[l]:o,C=r?o[l+1]:o;f=CCe(b,T,s,i,x,C,h,f)}UO.length=0;const _=t[n-1],g=i.cartesianToCartographic(_,UC);g.height=r?o[n-1]:o;const m=i.cartographicToCartesian(g,Mh);return d.pack(m,h,u-3),h};const LF=new he,wCe=new he;ks.generateRhumbArc=function(e){c(e)||(e={});const t=e.positions;if(!c(t))throw new E("options.positions is required.");const n=t.length,i=y(e.ellipsoid,ae.WGS84);let o=y(e.height,0);const r=Array.isArray(o);if(n<1)return[];if(n===1){const x=i.scaleToGeodeticSurface(t[0],kO);if(o=r?o[0]:o,o!==0){const C=i.geodeticSurfaceNormal(x,Mh);d.multiplyByScalar(C,o,C),d.add(x,C,x)}return[x.x,x.y,x.z]}const s=y(e.granularity,R.RADIANS_PER_DEGREE);let a=0,l,u=i.cartesianToCartographic(t[0],LF),h;for(l=0;l<n-1;l++)h=i.cartesianToCartographic(t[l+1],wCe),a+=ks.numberOfPointsRhumbLine(u,h,s),u=he.clone(h,LF);const f=(a+1)*3,_=new Array(f);let g=0;for(l=0;l<n-1;l++){const x=t[l],C=t[l+1],w=r?o[l]:o,v=
`,this.material.shaderSource,IV]}),r=t.getVertexShaderCallback()(pCe),s=new Oe({defines:i,sources:[M0,r]});this.shaderProgram=Jt.fromCache({context:e,vertexShaderSource:s,fragmentShaderSource:o,attributeLocations:Js})};function D8(e){return d.dot(d.UNIT_X,e._boundingVolume.center)<0||e._boundingVolume.intersectPlane(_t.ORIGIN_ZX_PLANE)===Bt.INTERSECTING}bu.prototype.getPolylinePositionsLength=function(e){let t;if(this.mode===oe.SCENE3D||!D8(e))return t=e._actualPositions.length,t*4-4;let n=0;const i=e._segments.lengths;t=i.length;for(let o=0;o<t;++o)n+=i[o]*4-4;return n};const Bo=new d,lc=new d,uc=new d,qx=new d,VCe=new te,HCe=new H;bu.prototype.write=function(e,t,n,i,o,r,s,a){const l=this.mode,u=a.ellipsoid.maximumRadius*R.PI,h=this.polylines,f=h.length;for(let _=0;_<f;++_){const g=h[_],m=g.width,b=g.show&&m>0,T=g._index,x=this.getSegments(g,a),C=x.positions,w=x.lengths,v=C.length,P=g.getPickId(s).color;let N=0,k=0,M;for(let V=0;V<v;++V){V===0?g._loop?M=C[v-2]:(M=qx,d.subtract(C[0],C[1],M),d.add(C[0],M,M)):M=C[V-1],d.clone(M,lc),d.clone(C[V],Bo),V===v-1?g._loop?M=C[1]:(M=qx,d.subtract(C[v-1],C[v-2],M),d.add(C[v-1],M,M)):M=C[V+1],d.clone(M,uc);const G=w[N];V===k+G&&(k+=G,++N);const j=V-k===0,W=V===k+w[N]-1;l===oe.SCENE2D&&(lc.z=0,Bo.z=0,uc.z=0),(l===oe.SCENE2D||l===oe.MORPHING)&&(j||W)&&u-Math.abs(Bo.x)<1&&((Bo.x<0&&lc.x>0||Bo.x>0&&lc.x<0)&&d.clone(Bo,lc),(Bo.x<0&&uc.x>0||Bo.x>0&&uc.x<0)&&d.clone(Bo,uc));const X=j?2:0,q=W?2:4;for(let ee=X;ee<q;++ee){rn.writeElements(Bo,e,n),rn.writeElements(lc,e,n+6),rn.writeElements(uc,e,n+12);const Y=ee-2<0?-1:1;t[o]=V/(v-1),t[o+1]=2*(ee%2)-1,t[o+2]=Y,t[o+3]=T,n+=6*3,o+=4}}const U=VCe;U.x=z.floatToByte(P.red),U.y=z.floatToByte(P.green),U.z=z.floatToByte(P.blue),U.w=z.floatToByte(P.alpha);const B=HCe;B.x=m,B.y=b?1:0;const S=l===oe.SCENE2D?g._boundingVolume2D:g._boundingVolumeWC,D=rn.fromCartesian(S.center,E8),p=D.high,I=te.fromElements(D.low.x,D.low.y,D.low.z,S.radius,w8),O=S8;O.x=0,O.y=Number.MAX_VALUE;const F=g.distanceDisplayCondition;c(F)&&(O.x=F.near,O.y=F.far),r.setBatchedAttribute(T,0,B),r.setBatchedAttribute(T,1,U),r.attributes.length>2&&(r.setBatchedAttribute(T,2,p),r.setBatchedAttribute(T,3,I),r.setBatchedAttribute(T,4,O))}};const GCe=new d,jCe=new d,WCe=new d,BF=new d;bu.prototype.writeForMorph=function(e,t){const n=this.modelMatrix,i=this.polylines,o=i.length;for(let r=0;r<o;++r){const s=i[r],a=s._segments.positions,l=s._segments.lengths,u=a.length;let h=0,f=0;for(let _=0;_<u;++_){let g;_===0?s._loop?g=a[u-2]:(g=BF,d.subtract(a[0],a[1],g),d.add(a[0],g,g)):g=a[_-1],g=L.multiplyByPoint(n,g,jCe);const m=L.multiplyByPoint(n,a[_],GCe);let b;_===u-1?s._loop?b=a[1]:(b=BF,d.subtract(a[u-1],a[u-2],b),d.add(a[u-1],b,b)):b=a[_+1],b=L.multiplyByPoint(n,b,WCe);const T=l[h];_===f+T&&(f+=T,++h);const x=_-f===0,C=_===f+l[h]-1,w=x?2:0,v=C?2:4;for(let P=w;P<v;++P)rn.writeElements(m,e,t),rn.writeElements(g,e,t+6),rn.writeElements(b,e,t+12),t+=6*3}}};const qCe=new Array(1);bu.prototype.updateIndices=function(e,t,n,i){let o=n.length-1,r=new TS(0,i,this);n[o].push(r);let s=0,a=e[e.length-1],l=0;a.length>0&&(l=a[a.length-1]+1);const u=this.polylines,h=u.length;for(let f=0;f<h;++f){const _=u[f];_._locatorBuckets=[];let g;if(this.mode===oe.SCENE3D){g=qCe;const b=_._actualPositions.length;if(b>0)g[0]=b;else continue}else g=_._segments.lengths;const m=g.length;if(m>0){let b=0;for(let T=0;T<m;++T){const x=g[T]-1;for(let C=0;C<x;++C)l+4>R.SIXTY_FOUR_KILOBYTES&&(_._locatorBuckets.push({locator:r,count:b}),b=0,t.push(4),a=[],e.push(a),l=0,r.count=s,s=0,i=0,r=new TS(0,0,this),n[++o]=[r]),a.push(l,l+2,l+1),a.push(l+1,l+2,l+3),b+=6,s+=6,i+=6,l+=4}_._locatorBuckets.push({locator:r,count:b}),l+4>R.SIXTY_FOUR_KILOBYTES&&(t.push(0),a=[],e.push(a),l=0,r.count=s,i=0,s=0,r=new TS(0,0,this),n[++o]=[r])}_._clean()}return r.count=s,i};bu.prototype.getPolylineStartIndex=function(e){const t=this.polylines;let n=0;const i=t.length;for(let o=0;o<i;++o){const r=t[o];if(r===e)break;n+=r._actualLength}return n};const mm={positions:void 0,lengths:void 0},zF=new Array(1),YCe=new d,$Ce=new he;bu.prototype.getSegments=function(
in vec4 previousPosition;
in vec4 nextPosition;
in vec2 expandAndWidth;
in float a_batchId;
uniform mat4 u_modifiedModelView;
void main()
{
float expandDir = expandAndWidth.x;
float width = abs(expandAndWidth.y) + 0.5;
bool usePrev = expandAndWidth.y < 0.0;
vec4 p = u_modifiedModelView * currentPosition;
vec4 prev = u_modifiedModelView * previousPosition;
vec4 next = u_modifiedModelView * nextPosition;
float angle;
vec4 positionWC = getPolylineWindowCoordinatesEC(p, prev, next, expandDir, width, usePrev, angle);
gl_Position = czm_viewportOrthographic * positionWC;
}
`;function Pc(e){this._positions=e.positions,this._widths=e.widths,this._counts=e.counts,this._batchIds=e.batchIds,this._ellipsoid=y(e.ellipsoid,ae.WGS84),this._minimumHeight=e.minimumHeight,this._maximumHeight=e.maximumHeight,this._center=e.center,this._rectangle=e.rectangle,this._boundingVolume=e.boundingVolume,this._batchTable=e.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=e.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=z.clone(z.WHITE),this._highlightColor=this._constantColor,this._trianglesLength=0,this._geometryByteLength=0,this._ready=!1,this._promise=void 0,this._error=void 0}Object.defineProperties(Pc.prototype,{trianglesLength:{get:function(){return this._trianglesLength}},geometryByteLength:{get:function(){return this._geometryByteLength}},ready:{get:function(){return this._ready}}});function fEe(e){const t=e._rectangle,n=e._minimumHeight,i=e._maximumHeight,o=e._ellipsoid,r=e._center,s=2+ce.packedLength+ae.packedLength+d.packedLength,a=new Float64Array(s);let l=0;return a[l++]=n,a[l++]=i,ce.pack(t,a,l),l+=ce.packedLength,ae.pack(o,a,l),l+=ae.packedLength,d.pack(r,a,l),a}const pEe=new Kn("createVectorTilePolylines",5),km={previousPosition:0,currentPosition:1,nextPosition:2,expandAndWidth:3,a_batchId:4};function mEe(e,t){if(c(e._va))return;let n=e._positions,i=e._widths,o=e._counts,r=e._transferrableBatchIds,s=e._packedBuffer;c(s)||(n=e._positions=n.slice(),i=e._widths=i.slice(),o=e._counts=o.slice(),r=e._transferrableBatchIds=e._batchIds.slice(),s=e._packedBuffer=fEe(e));const a=[n.buffer,i.buffer,o.buffer,r.buffer,s.buffer],l={positions:n.buffer,widths:i.buffer,counts:o.buffer,batchIds:r.buffer,packedBuffer:s.buffer,keepDecodedPositions:e._keepDecodedPositions},u=pEe.scheduleTask(l,a);if(!!c(u))return u.then(function(h){if(e.isDestroyed())return;e._keepDecodedPositions&&(e._decodedPositions=new Float64Array(h.decodedPositions),e._decodedPositionOffsets=new Uint32Array(h.decodedPositionOffsets)),e._currentPositions=new Float32Array(h.currentPositions),e._previousPositions=new Float32Array(h.previousPositions),e._nextPositions=new Float32Array(h.nextPositions),e._expandAndWidth=new Float32Array(h.expandAndWidth),e._vertexBatchIds=new Uint16Array(h.batchIds);const f=h.indexDatatype;e._indices=f===je.UNSIGNED_SHORT?new Uint16Array(h.indices):new Uint32Array(h.indices),_Ee(e,t),e._ready=!0}).catch(h=>{e.isDestroyed()||(e._error=h)})}function _Ee(e,t){if(!c(e._va)){const n=e._currentPositions,i=e._previousPositions,o=e._nextPositions,r=e._expandAndWidth,s=e._vertexBatchIds,a=e._indices;let l=i.byteLength+n.byteLength+o.byteLength;l+=r.byteLength+s.byteLength+a.byteLength,e._trianglesLength=a.length/3,e._geometryByteLength=l;const u=ct.createVertexBuffer({context:t,typedArray:i,usage:ke.STATIC_DRAW}),h=ct.createVertexBuffer({context:t,typedArray:n,usage:ke.STATIC_DRAW}),f=ct.createVertexBuffer({context:t,typedArray:o,usage:ke.STATIC_DRAW}),_=ct.createVertexBuffer({context:t,typedArray:r,usage:ke.STATIC_DRAW}),g=ct.createVertexBuffer({context:t,typedArray:s,usage:ke.STATIC_DRAW}),m=ct.createIndexBuffer({context:t,typedArray:a,usage:ke.STATIC_DRAW,indexDatatype:a.BYTES_PER_ELEMENT===2?je.UNSIGNED_SHORT:je.UNSIGNED_INT}),b=[{index:km.previousPosition,vertexBuffer:u,componentDatatype:Z.FLOAT,componentsPerAttribute:3},{index:km.currentPosition,vertexBuffer:h,componentDatatype:Z.FLOAT,componentsPerAttribute:3},{index:km.nextPosition,vertexBuffer:f,componentDatatype:Z.FLOAT,componentsPerAttribute:3},{index:km.expandAndWidth,vertexBuffer:_,componentDatatype:Z.FLOAT,componentsPerAttribute:2},{index:km.a_batchId,vertexBuffer:g,componentDatatype:Z.UNSIGNED_SHORT,componentsPerAttribute:1}];e._va=new Ci({context:t,attributes:b,indexBuffer:m}),e._positions=void 0,
void main()
{
out_FragColor = u_highlightColor;
}
`;function TEe(e,t){if(c(e._sp))return;const n=e._batchTable,i=n.getVertexShaderCallback(!1,"a_batchId",void 0)(hEe),o=n.getFragmentShaderCallback(!1,void 0,!1)(bEe),r=new Oe({defines:["VECTOR_TILE",Yt.isInternetExplorer()?"":"CLIP_POLYLINE"],sources:[M0,i]}),s=new Oe({defines:["VECTOR_TILE"],sources:[o]});e._sp=Jt.fromCache({context:t,vertexShaderSource:r,fragmentShaderSource:s,attributeLocations:km})}function AEe(e,t){if(!c(e._command)){const n=e._batchTable.getUniformMapCallback()(e._uniformMap);e._command=new Ze({owner:e,vertexArray:e._va,renderState:e._rs,shaderProgram:e._sp,uniformMap:n,boundingVolume:e._boundingVolume,pass:xe.TRANSLUCENT,pickId:e._batchTable.getPickId()})}t.commandList.push(e._command)}Pc.getPolylinePositions=function(e,t){const n=e._batchIds,i=e._decodedPositions,o=e._decodedPositionOffsets;if(!c(n)||!c(i))return;let r,s;const a=n.length;let l=0,u=0;for(r=0;r<a;++r)n[r]===t&&(l+=o[r+1]-o[r]);if(l===0)return;const h=new Float64Array(l*3);for(r=0;r<a;++r)if(n[r]===t){const f=o[r],_=o[r+1]-f;for(s=0;s<_;++s){const g=(f+s)*3;h[u++]=i[g],h[u++]=i[g+1],h[u++]=i[g+2]}}return h};Pc.prototype.getPositions=function(e){return Pc.getPolylinePositions(this,e)};Pc.prototype.createFeatures=function(e,t){const n=this._batchIds,i=n.length;for(let o=0;o<i;++o){const r=n[o];t[r]=new Ir(e,r)}};Pc.prototype.applyDebugSettings=function(e,t){this._highlightColor=e?t:this._constantColor};function xEe(e,t){const n=e._batchIds,i=n.length;for(let o=0;o<i;++o){const r=n[o],s=t[r];s.show=!0,s.color=z.WHITE}}const CEe=new z,EEe=z.WHITE,wEe=!0;Pc.prototype.applyStyle=function(e,t){if(!c(e)){xEe(this,t);return}const n=this._batchIds,i=n.length;for(let o=0;o<i;++o){const r=n[o],s=t[r];s.color=c(e.color)?e.color.evaluateColor(s,CEe):EEe,s.show=c(e.show)?e.show.evaluate(s):wEe}};Pc.prototype.update=function(e){const t=e.context;if(!this._ready){if(c(this._promise)||(this._promise=mEe(this,t)),c(this._error)){const i=this._error;throw this._error=void 0,i}return}gEe(this,t),TEe(this,t),yEe(this);const n=e.passes;(n.render||n.pick)&&AEe(this,e)};Pc.prototype.isDestroyed=function(){return!1};Pc.prototype.destroy=function(){return this._va=this._va&&this._va.destroy(),this._sp=this._sp&&this._sp.destroy(),ve(this)};const SEe=`in vec3 startEllipsoidNormal;
in vec3 endEllipsoidNormal;
in vec4 startPositionAndHeight;
in vec4 endPositionAndHeight;
in vec4 startFaceNormalAndVertexCorner;
in vec4 endFaceNormalAndHalfWidth;
in float a_batchId;
uniform mat4 u_modifiedModelView;
uniform vec2 u_minimumMaximumVectorHeights;
out vec4 v_startPlaneEC;
out vec4 v_endPlaneEC;
out vec4 v_rightPlaneEC;
out float v_halfWidth;
out vec3 v_volumeUpEC;
void main()
{
// vertex corner IDs
// 3-----------7
// /| left /|
// / | 1 / |
// 2-----------6 5 end
// | / | /
// start |/ right |/
// 0-----------4
//
float isEnd = floor(startFaceNormalAndVertexCorner.w * 0.251); // 0 for front, 1 for end
float isTop = floor(startFaceNormalAndVertexCorner.w * mix(0.51, 0.19, isEnd)); // 0 for bottom, 1 for top
vec3 forward = endPositionAndHeight.xyz - startPositionAndHeight.xyz;
vec3 right = normalize(cross(forward, startEllipsoidNormal));
vec4 position = vec4(startPositionAndHeight.xyz, 1.0);
position.xyz += forward * isEnd;
v_volumeUpEC = czm_normal * normalize(cross(right, forward));
// Push for volume height
float offset;
vec3 ellipsoidNormal = mix(startEllipsoidNormal, endEllipsoidNormal, isEnd);
// offset height to create volume
offset = mix(startPositionAndHeight.w, endPositionAndHeight.w, isEnd);
offset = mix(u_minimumMaximumVectorHeights.y, u_minimumMaximumVectorHeights.x, isTop) - offset;
position.xyz += offset * ellipsoidNormal;
// move from RTC to EC
position = u_modifiedModelView * position;
right = czm_normal * right;
// Push for width in a direction that is in the start or end plane and in a plane with right
// N = normalEC ("right-facing" direction for push)
// R = right
// p = angle between N and R
// w = distance to push along R if R == N
// d = distance to push along N
//
// N R
// { p| } * cos(p) = dot(N, R) = w / d
// d | |w * d = w / dot(N, R)
// { | }
// o---------- polyline segment ---->
//
vec3 scratchNormal = mix(-startFaceNormalAndVertexCorner.xyz, endFaceNormalAndHalfWidth.xyz, isEnd);
scratchNormal = cross(scratchNormal, mix(startEllipsoidNormal, endEllipsoidNormal, isEnd));
vec3 miterPushNormal = czm_normal * normalize(scratchNormal);
offset = 2.0 * endFaceNormalAndHalfWidth.w * max(0.0, czm_metersPerPixel(position)); // offset = widthEC
offset = offset / dot(miterPushNormal, right);
position.xyz += miterPushNormal * (offset * sign(0.5 - mod(startFaceNormalAndVertexCorner.w, 2.0)));
gl_Position = czm_depthClamp(czm_projection * position);
position = u_modifiedModelView * vec4(startPositionAndHeight.xyz, 1.0);
vec3 startNormalEC = czm_normal * startFaceNormalAndVertexCorner.xyz;
v_startPlaneEC = vec4(startNormalEC, -dot(startNormalEC, position.xyz));
v_rightPlaneEC = vec4(right, -dot(right, position.xyz));
position = u_modifiedModelView * vec4(endPositionAndHeight.xyz, 1.0);
vec3 endNormalEC = czm_normal * endFaceNormalAndHalfWidth.xyz;
v_endPlaneEC = vec4(endNormalEC, -dot(endNormalEC, position.xyz));
v_halfWidth = endFaceNormalAndHalfWidth.w;
}
`,vEe=`in vec4 v_startPlaneEC;
in vec4 v_endPlaneEC;
in vec4 v_rightPlaneEC;
in float v_halfWidth;
in vec3 v_volumeUpEC;
uniform vec4 u_highlightColor;
void main()
{
float logDepthOrDepth = czm_branchFreeTernary(czm_sceneMode == czm_sceneMode2D, gl_FragCoord.z, czm_unpackDepth(texture(czm_globeDepthTexture, gl_FragCoord.xy / czm_viewport.zw)));
// Discard for sky
if (logDepthOrDepth == 0.0) {
#ifdef DEBUG_SHOW_VOLUME
out_FragColor = vec4(0.0, 0.0, 1.0, 0.5);
return;
#else // DEBUG_SHOW_VOLUME
discard;
#endif // DEBUG_SHOW_VOLUME
}
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);
eyeCoordinate /= eyeCoordinate.w;
float halfMaxWidth = v_halfWidth * czm_metersPerPixel(eyeCoordinate);
// Expand halfMaxWidth if direction to camera is almost perpendicular with the volume's up direction
halfMaxWidth += halfMaxWidth * (1.0 - dot(-normalize(eyeCoordinate.xyz), v_volumeUpEC));
// Check distance of the eye coordinate against the right-facing plane
float widthwiseDistance = czm_planeDistance(v_rightPlaneEC, eyeCoordinate.xyz);
// Check eye coordinate against the mitering planes
float distanceFromStart = czm_planeDistance(v_startPlaneEC, eyeCoordinate.xyz);
float distanceFromEnd = czm_planeDistance(v_endPlaneEC, eyeCoordinate.xyz);
if (abs(widthwiseDistance) > halfMaxWidth || distanceFromStart < 0.0 || distanceFromEnd < 0.0) {
#ifdef DEBUG_SHOW_VOLUME
out_FragColor = vec4(logDepthOrDepth, 0.0, 0.0, 0.5);
return;
#else // DEBUG_SHOW_VOLUME
discard;
#endif // DEBUG_SHOW_VOLUME
}
out_FragColor = u_highlightColor;
czm_writeDepthClamp();
}
`;function xd(e){this._positions=e.positions,this._widths=e.widths,this._counts=e.counts,this._batchIds=e.batchIds,this._ellipsoid=y(e.ellipsoid,ae.WGS84),this._minimumHeight=e.minimumHeight,this._maximumHeight=e.maximumHeight,this._center=e.center,this._rectangle=e.rectangle,this._batchTable=e.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 H(Ti._defaultMinTerrainHeight,Ti._defaultMaxTerrainHeight),this._boundingVolume=Ct.fromRectangle(e.rectangle,Ti._defaultMinTerrainHeight,Ti._defaultMaxTerrainHeight,this._ellipsoid),this._classificationType=e.classificationType,this._keepDecodedPositions=e.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=z.clone(z.WHITE),this._highlightColor=this._constantColor,this._trianglesLength=0,this._geometryByteLength=0,this._ready=!1,this._promise=void 0,this._error=void 0}Object.defineProperties(xd.prototype,{trianglesLength:{get:function(){return this._trianglesLength}},geometryByteLength:{get:function(){return this._geometryByteLength}},ready:{get:function(){return this._ready}}});function IEe(e,t,n){const i=Ti.getMinimumMaximumHeights(t,n),o=i.minimumTerrainHeight,r=i.maximumTerrainHeight,s=e._minimumMaximumVectorHeights;s.x=o,s.y=r;const a=e._boundingVolume,l=e._rectangle;Ct.fromRectangle(l,o,r,n,a)}function DEe(e){const t=e._rectangle,n=e._minimumHeight,i=e._maximumHeight,o=e._ellipsoid,r=e._center,s=2+ce.packedLength+ae.packedLength+d.packedLength,a=new Float64Array(s);let l=0;return a[l++]=n,a[l++]=i,ce.pack(t,a,l),l+=ce.packedLength,ae.pack(o,a,l),l+=ae.packedLength,d.pack(r,a,l),a}const PEe=new Kn("createVectorTileClampedPolylines"),th={startEllipsoidNormal:0,endEllipsoidNormal:1,startPositionAndHeight:2,endPositionAndHeight:3,startFaceNormalAndVertexCorner:4,endFaceNormalAndHalfWidth:5,a_batchId:6};function OEe(e,t){if(c(e._va))return;let n=e._positions,i=e._widths,o=e._counts,r=e._transferrableBatchIds,s=e._packedBuffer;c(s)||(n=e._positions=n.slice(),i=e._widths=i.slice(),o=e._counts=o.slice(),r=e._transferrableBatchIds=e._batchIds.slice(),s=e._packedBuffer=DEe(e));const a=[n.buffer,i.buffer,o.buffer,r.buffer,s.buffer],l={positions:n.buffer,widths:i.buffer,counts:o.buffer,batchIds:r.buffer,packedBuffer:s.buffer,keepDecodedPositions:e._keepDecodedPositions},u=PEe.scheduleTask(l,a);if(!!c(u))return u.then(function(h){if(e.isDestroyed())return;e._keepDecodedPositions&&(e._decodedPositions=new Float64Array(h.decodedPositions),e._decodedPositionOffsets=new Uint32Array(h.decodedPositionOffsets)),e._startEllipsoidNormals=new Float32Array(h.startEllipsoidNormals),e._endEllipsoidNormals=new Float32Array(h.endEllipsoidNormals),e._startPositionAndHeights=new Float32Array(h.startPositionAndHeights),e._startFaceNormalAndVertexCornerIds=new Float32Array(h.startFaceNormalAndVertexCornerIds),e._endPositionAndHeights=new Float32Array(h.endPositionAndHeights),e._endFaceNormalAndHalfWidths=new Float32Array(h.endFaceNormalAndHalfWidths),e._vertexBatchIds=new Uint16Array(h.vertexBatchIds);const f=h.indexDatatype;e._indices=f===je.UNSIGNED_SHORT?new Uint16Array(h.indices):new Uint32Array(h.indices),LEe(e,t),e._ready=!0}).catch(h=>{e.isDestroyed()||(e._error=h)})}function LEe(e,t){if(!c(e._va)){const n=e._startEllipsoidNormals,i=e._endEllipsoidNormals,o=e._startPositionAndHeights,r=e._endPositionAndHeights,s=e._startFaceNormalAndVertexCornerIds,a=e._endFaceNormalAndHalfWidths,l=e._vertexBatchIds,u=e._indices;let h=n.byteLength+i.byteLength;h+=o.byteLength+r.byteLength,h+=s.byteLength+a.byteLength,h+=l.byteLength+u.byteLength,e._trianglesLength=u.length/3,e._geometryByteLength=h;const f=ct.createVertexBuffer({context:t,ty
The tileset will be rendered with a larger screen space error (see memoryAdjustedScreenSpaceError).
Consider using larger values for cacheBytes and maximumCacheOverflowBytes.`),e._memoryAdjustedScreenSpaceError*=1.02;const t=e._processingQueue;for(let n=0;n<t.length;++n)t[n].updatePriority();t.sort(sG)}function rve(e){e._memoryAdjustedScreenSpaceError=Math.max(e.memoryAdjustedScreenSpaceError/1.02,e.maximumScreenSpaceError)}const IT=new d,sve={maximumFractionDigits:3};function s2(e){const t=e/1048576;return t<1?t.toLocaleString(void 0,sve):Math.round(t).toLocaleString()}function zS(e){const{halfAxes:t,radius:n,center:i}=e.boundingVolume.boundingVolume;let o=d.clone(i,IT);if(c(t))o.x+=.75*(t[0]+t[3]+t[6]),o.y+=.75*(t[1]+t[4]+t[7]),o.z+=.75*(t[2]+t[5]+t[8]);else if(c(n)){let r=d.normalize(i,IT);r=d.multiplyByScalar(r,.75*n,IT),o=d.add(r,i,IT)}return o}function US(e,t,n){let i="",o=0;if(t.debugShowGeometricError&&(i+=`
Geometric error: ${e.geometricError}`,o++),t.debugShowRenderingStatistics&&(i+=`
Commands: ${e.commandsLength}`,o++,e.content.pointsLength>0&&(i+=`
Points: ${e.content.pointsLength}`,o++),e.content.trianglesLength>0&&(i+=`
Triangles: ${e.content.trianglesLength}`,o++),i+=`
Features: ${e.content.featuresLength}`,o++),t.debugShowMemoryUsage&&(i+=`
Texture Memory: ${s2(e.content.texturesByteLength)}`,i+=`
Geometry Memory: ${s2(e.content.geometryByteLength)}`,o+=2),t.debugShowUrl)if(e.hasMultipleContents){i+=`
Urls:`;const s=e.content.innerContentUrls;for(let a=0;a<s.length;a++)i+=`
- ${s[a]}`;o+=s.length}else i+=`
Url: ${e._contentHeader.uri}`,o++;const r={text:i.substring(1),position:n,font:`${19-o}px sans-serif`,showBackground:!0,disableDepthTestDistance:Number.POSITIVE_INFINITY};return t._tileDebugLabels.add(r)}function ave(e,t){const n=e._selectedTiles,i=n.length,o=e._emptyTiles,r=o.length;if(e._tileDebugLabels.removeAll(),e.debugPickedTileLabelOnly){if(c(e.debugPickedTile)){const s=c(e.debugPickPosition)?e.debugPickPosition:zS(e.debugPickedTile),a=US(e.debugPickedTile,e,s);a.pixelOffset=new H(15,-15)}}else{for(let s=0;s<i;++s){const a=n[s];US(a,e,zS(a))}for(let s=0;s<r;++s){const a=o[s];(a.hasTilesetContent||a.hasImplicitContent)&&US(a,e,zS(a))}}e._tileDebugLabels.update(t)}function cve(e,t,n){e._styleEngine.applyStyle(e),e._styleApplied=!0;const{commandList:i,context:o}=t,r=i.length,s=e._selectedTiles,a=e.isSkippingLevelOfDetail&&e._hasMixedContent&&o.stencilBuffer&&s.length>0;e._backfaceCommands.length=0,a&&(c(e._stencilClearCommand)||(e._stencilClearCommand=new bi({stencil:0,pass:xe.CESIUM_3D_TILE,renderState:Ue.fromCache({stencilMask:At.SKIP_LOD_MASK})})),i.push(e._stencilClearCommand));const{statistics:l,tileVisible:u}=e,h=n.isRender,f=i.length;for(let m=0;m<s.length;++m){const b=s[m];h&&u.raiseEvent(b),nve(e,b,t),b.update(e,t,n),l.incrementSelectionCounts(b.content),++l.selected}const _=e._emptyTiles;for(let m=0;m<_.length;++m)_[m].update(e,t,n);let g=i.length-f;if(e._backfaceCommands.trim(),a){const m=e._backfaceCommands.values,b=m.length;i.length+=b;for(let T=g-1;T>=0;--T)i[f+b+T]=i[f+T];for(let T=0;T<b;++T)i[f+T]=m[T]}g=i.length-r,l.numberOfCommands=g,h&&(e.pointCloudShading.attenuation&&e.pointCloudShading.eyeDomeLighting&&g>0&&e._pointCloudEyeDomeLighting.update(t,r,e.pointCloudShading,e.boundingSphere),e.debugShowGeometricError||e.debugShowRenderingStatistics||e.debugShowMemoryUsage||e.debugShowUrl?(c(e._tileDebugLabels)||(e._tileDebugLabels=new Ga),ave(e,t)):e._tileDebugLabels=e._tileDebugLabels&&e._tileDebugLabels.destroy())}const cG=[];function lve(e,t){const n=t,i=cG;for(i.push(t);i.length>0;){t=i.pop();const o=t.children;for(let r=0;r<o.length;++r)i.push(o[r]);t!==n&&(uve(e,t),--e._statistics.numberOfTilesTotal)}n.children=[]}function lG(e,t){e.tileUnload.raiseEvent(t),e._statistics.decrementLoadCounts(t.content),--e._statistics.numberOfTilesWithContentReady,t.unloadContent()}function uve(e,t){e._cache.unloadTile(e,t,lG),t.destroy()}hi.prototype.trimLoadedTiles=function(){this._cache.trim()};function dve(e,t){const n=e._statistics,i=e._statisticsLast,o=n.numberOfPendingRequests,r=n.numberOfTilesProcessing,s=i.numberOfPendingRequests,a=i.numberOfTilesProcessing;eu.clone(n,i);const l=o!==s||r!==a;l&&t.afterRender.push(function(){return e.loadProgress.raiseEvent(o,r),!0}),e._tilesLoaded=n.numberOfPendingRequests===0&&n.numberOfTilesProcessing===0&&n.numberOfAttemptedRequests===0,l&&e._tilesLoaded&&(t.afterRender.push(function(){return e.allTilesLoaded.raiseEvent(),!0}),e._initialTilesLoaded||(e._initialTilesLoaded=!0,t.afterRender.push(function(){return e.initialTilesLoaded.raiseEvent(),!0})))}function hve(e){e._heatmap.resetMinimumMaximum(),e._minimumPriority.depth=Number.MAX_VALUE,e._maximumPriority.depth=-Number.MAX_VALUE,e._minimumPriority.foveatedFactor=Number.MAX_VALUE,e._maximumPriority.foveatedFactor=-Number.MAX_VALUE,e._minimumPriority.distance=Number.MAX_VALUE,e._maximumPriority.distance=-Number.MAX_VALUE,e._minimumPriority.reverseScreenSpaceError=Number.MAX_VALUE,e._maximumPriority.reverseScreenSpaceError=-Number.MAX_VALUE}function fve(e,t){t.frameNumber===e._updatedModelMatrixFrame&&c(e._previousModelMatrix)||(e._updatedModelMatrixFrame=t.frameNumber,e._modelMatrixChanged=!L.equals(e.modelMatrix,e._previousModelMatrix),e._modelMatrixChanged&&(e._previousModelMatrix=L.clone(e.modelMatrix,e._previousModelMatrix)))}function pve(e,t,n,i){if(t.mode===oe.MORPHING||!c(e._root))return!1;const o=e._statistics;o.clear(),++e._updatedVisibilityFrame,hve(e),fve(e,t),e._cullRequestsWhileMoving=e.cullRequestsWhileMoving&&!e._modelMatrixChanged;const r=e.getTraversal(i).selectTiles(e,t);if(i.requestTiles&&KSe(e),cv
in vec4 v_outlineColor;
in float v_innerPercent;
in float v_pixelDistance;
in vec4 v_pickColor;
void main()
{
// The distance in UV space from this fragment to the center of the point, at most 0.5.
float distanceToCenter = length(gl_PointCoord - vec2(0.5));
// The max distance stops one pixel shy of the edge to leave space for anti-aliasing.
float maxDistance = max(0.0, 0.5 - v_pixelDistance);
float wholeAlpha = 1.0 - smoothstep(maxDistance, 0.5, distanceToCenter);
float innerAlpha = 1.0 - smoothstep(maxDistance * v_innerPercent, 0.5 * v_innerPercent, distanceToCenter);
vec4 color = mix(v_outlineColor, v_color, innerAlpha);
color.a *= wholeAlpha;
// 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
out_FragColor = czm_gammaCorrect(color);
czm_writeLogDepth();
}
`,EIe=`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;
}
`,wIe=Dn.SHOW_INDEX,bD=Dn.POSITION_INDEX,UG=Dn.COLOR_INDEX,SIe=Dn.OUTLINE_COLOR_INDEX,vIe=Dn.OUTLINE_WIDTH_INDEX,IIe=Dn.PIXEL_SIZE_INDEX,kG=Dn.SCALE_BY_DISTANCE_INDEX,VG=Dn.TRANSLUCENCY_BY_DISTANCE_INDEX,HG=Dn.DISTANCE_DISPLAY_CONDITION_INDEX,DIe=Dn.DISABLE_DEPTH_DISTANCE_INDEX,ZO=Dn.NUMBER_OF_PROPERTIES,cs={positionHighAndSize:0,positionLowAndOutline:1,compressedAttribute0:2,compressedAttribute1:3,scaleByDistance:4,distanceDisplayConditionAndDisableDepth:5};function ja(e){e=y(e,y.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=!1,this._createVertexArray=!1,this._shaderScaleByDistance=!1,this._compiledShaderScaleByDistance=!1,this._shaderTranslucencyByDistance=!1,this._compiledShaderTranslucencyByDistance=!1,this._shaderDistanceDisplayCondition=!1,this._compiledShaderDistanceDisplayCondition=!1,this._shaderDisableDepthDistance=!1,this._compiledShaderDisableDepthDistance=!1,this._propertiesChanged=new Uint32Array(ZO),this._maxPixelSize=1,this._baseVolume=new se,this._baseVolumeWC=new se,this._baseVolume2D=new se,this._boundingVolume=new se,this._boundingVolumeDirty=!1,this._colorCommands=[],this.show=y(e.show,!0),this.modelMatrix=L.clone(y(e.modelMatrix,L.IDENTITY)),this._modelMatrix=L.clone(L.IDENTITY),this.debugShowBoundingVolume=y(e.debugShowBoundingVolume,!1),this.blendOption=y(e.blendOption,io.OPAQUE_AND_TRANSLUCENT),this._blendOption=void 0,this._mode=oe.SCENE3D,this._maxTotalPointSize=1,this._buffersUsage=[ke.STATIC_DRAW,ke.STATIC_DRAW,ke.STATIC_DRAW,ke.STATIC_DRAW,ke.STATIC_DRAW,ke.STATIC_DRAW,ke.STATIC_DRAW,ke.STATIC_DRAW,ke.STATIC_DRAW];const t=this;this._uniforms={u_maxTotalPointSize:function(){return t._maxTotalPointSize}}}Object.defineProperties(ja.prototype,{length:{get:function(){return JO(this),this._pointPrimitives.length}}});function GG(e){const t=e.length;for(let n=0;n<t;++n)e[n]&&e[n]._destroy()}ja.prototype.add=function(e){const t=new Dn(e,this);return t._index=this._pointPrimitives.length,this._pointPrimitives.push(t),this._createVertexArray=!0,t};ja.prototype.remove=function(e){return this.contains(e)?(this._pointPrimitives[e._index]=null,this._pointPrimitivesRemoved=!0,this._createVertexArray=!0,e._destroy(),!0):!1};ja.prototype.removeAll=function(){GG(this._pointPrimitives),this._pointPrimitives=[],this._pointPrimitivesToUpdate=[],this._pointPrimitivesToUpdateIndex=0,this._pointPrimitivesRemoved=!1,this._createVertexArray=!0};function JO(e){if(e._pointPrimitivesRemoved){e._pointPrimitivesRemoved=!1;const t=[],n=e._pointPrimitives,i=n.length;for(let o=0,r=0;o<i;++o){const s=n[o];s&&(s._index=r++,t.push(s))}e._pointPrimitives=t}}ja.prototype._updatePointPrimitive=function(e,t){e._dirty||(this._pointPrimitivesToUpdate[this._pointPrimitivesToUpdateIndex++]=e),++this._propertiesChanged[t]};ja.prototype.contains=function(e){return c(e)&&e._pointPrimitiveCollection===this};ja.prototype.get=function(e){if(!c(e))throw new E("index is required.");return JO(this),this._pointPrimitives[e]};ja.prototype.computeNewBuffersUsage=function(){const e=this._buffersUsage;let t=!1;const n=this._propertiesChanged;for(let i=0;i<ZO;++i){const o=n[i]===0?ke.STATIC_DRAW:ke.STREAM_DRAW;t=t||e[i]!==o,e[i]=o}return t};function PIe(e,t,n){return new qo(e,[{index:cs.positionHighAndSize,componentsPerAttribute:4,componentDatatype:Z.FLOAT,usage:n[bD]},{index:cs.positionLowAndShow,componentsPerAttribute:4,componentDatatype:Z.FLOAT,usage:n[bD]},{index:cs.compressedAttribute0,componentsPerAttribute:4,componentDatatype:Z.FLOAT,usage:n[UG]},{index:cs.compressedAttribute1,componentsPerAttribute:4,componentDatatype:Z.FLOAT,usage:n[VG]},{index:cs.scaleByDistance,componentsPerAttribute:4,componentDatatype:Z.FLOAT,usage:n[kG]},{index:cs.distanceDisplayConditionAndDisableDepth,componentsPerAttribute:3,componentDatatype:Z.FLOAT,usage:n[HG]}],t)}const $S=new rn;function jG(e,t,n,i){const o=i._index,r=i._getActualPosition();e._mode===oe.SCENE3D&&(se
layout (location = 0) out vec4 out_FragData_0;
layout (location = 1) out vec4 out_FragData_1;
#else
layout (location = 0) out vec4 out_FragColor;
#endif
uniform vec4 u_bgColor;
uniform sampler2D u_depthTexture;
in vec2 v_textureCoordinates;
void main()
{
if (texture(u_depthTexture, v_textureCoordinates).r < 1.0)
{
#ifdef MRT
out_FragData_0 = u_bgColor;
out_FragData_1 = vec4(u_bgColor.a);
#else
out_FragColor = u_bgColor;
#endif
return;
}
discard;
}
`,tC=`uniform vec3 u_radiiAndDynamicAtmosphereColor;
uniform float u_atmosphereLightIntensity;
uniform float u_atmosphereRayleighScaleHeight;
uniform float u_atmosphereMieScaleHeight;
uniform float u_atmosphereMieAnisotropy;
uniform vec3 u_atmosphereRayleighCoefficient;
uniform vec3 u_atmosphereMieCoefficient;
const float ATMOSPHERE_THICKNESS = 111e3; // The thickness of the atmosphere in meters.
const int PRIMARY_STEPS_MAX = 16; // Maximum number of times the ray from the camera to the world position (primary ray) is sampled.
const 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.
/**
* This function computes the colors contributed by Rayliegh and Mie scattering on a given ray, as well as
* the transmittance value for the ray.
*
* @param {czm_ray} primaryRay The ray from the camera to the position.
* @param {float} primaryRayLength The length of the primary ray.
* @param {vec3} lightDirection The direction of the light to calculate the scattering from.
* @param {vec3} rayleighColor The variable the Rayleigh scattering will be written to.
* @param {vec3} mieColor The variable the Mie scattering will be written to.
* @param {float} opacity The variable the transmittance will be written to.
* @glslFunction
*/
void computeScattering(
czm_ray primaryRay,
float primaryRayLength,
vec3 lightDirection,
float atmosphereInnerRadius,
out vec3 rayleighColor,
out vec3 mieColor,
out float opacity
) {
// Initialize the default scattering amounts to 0.
rayleighColor = vec3(0.0);
mieColor = vec3(0.0);
opacity = 0.0;
float atmosphereOuterRadius = atmosphereInnerRadius + ATMOSPHERE_THICKNESS;
vec3 origin = vec3(0.0);
// Calculate intersection from the camera to the outer ring of the atmosphere.
czm_raySegment primaryRayAtmosphereIntersect = czm_raySphereIntersectionInterval(primaryRay, origin, atmosphereOuterRadius);
// Return empty colors if no intersection with the atmosphere geometry.
if (primaryRayAtmosphereIntersect == czm_emptyRaySegment) {
return;
}
// To deal with smaller values of PRIMARY_STEPS (e.g. 4)
// we implement a split strategy: sky or horizon.
// For performance reasons, instead of a if/else branch
// a soft choice is implemented through a weight 0.0 <= w_stop_gt_lprl <= 1.0
float x = 1e-7 * primaryRayAtmosphereIntersect.stop / length(primaryRayLength);
// Value close to 0.0: close to the horizon
// Value close to 1.0: above in the sky
float w_stop_gt_lprl = 0.5 * (1.0 + czm_approximateTanh(x));
// The ray should start from the first intersection with the outer atmopshere, or from the camera position, if it is inside the atmosphere.
float start_0 = primaryRayAtmosphereIntersect.start;
primaryRayAtmosphereIntersect.start = max(primaryRayAtmosphereIntersect.start, 0.0);
// The ray should end at the exit from the atmosphere or at the distance to the vertex, whichever is smaller.
primaryRayAtmosphereIntersect.stop = min(primaryRayAtmosphereIntersect.stop, length(primaryRayLength));
// For the number of ray steps, distinguish inside or outside atmosphere (outer space)
// (1) from outer space we have to use more ray steps to get a realistic rendering
// (2) within atmosphere we need fewer steps for faster rendering
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
float w_inside_atmosphere = 1.0 - 0.5 * (1.0 + czm_approximateTanh(x_o_a));
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.
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.
// Setup for sampling positions along the ray - starting from the intersection with the outer ring of the atmosphere.
float rayPositionLength = primaryRayAtmosphereIntersect.start;
// (1) Outside the atmosphere: constant rayStepLength
// (2) Inside atmosphere: variable rayStepLength to compensate the rough rendering of the smaller number of ray steps
float totalRayLength = primaryRayAtmosphereIntersect.stop - rayPositionLength;
float rayStepLengthIncrease = w_inside_atmosphere * ((1.0 - w_stop_gt_lprl) * totalRayLength / (float(PRIMARY_STEPS * (PRIMARY_STEPS + 1)) / 2.0));
float rayStepLength = max(1.0 - w_inside_atmosphere, w_stop_gt_lprl) * totalRayLength / max(7.0 * w_inside_atmosphere, float(PRIMARY_STEPS));
vec3 rayleighAccumulation = vec3(0.0);
vec3 mieAccumulation = vec3(0.0);
vec2 opticalDepth = vec2(0.0);
vec2 heightScale = vec2(u_atmosphereRayleighScaleHeight, u_atmosphereMieScaleHeight);
// Sample positions on the primary ray.
for (int i = 0; i < PRIMARY_STEPS_MAX; ++i) {
// The loop should be: for (int i = 0; i < PRIMARY_STEPS; ++i) {...} but WebGL1 cannot
// loop with non-constant condition, so it has to break early instead
if (i >= PRIMARY_STEPS) {
break;
}
// Calculate sample position along viewpoint ray.
vec3 samplePosition = primaryRay.origin + primaryRay.direction * (rayPositionLength + rayStepLength);
// Calculate height of sample position above ellipsoid.
float sampleHeight = length(samplePosition) - atmosphereInnerRadius;
// Calculate and accumulate density of particles at the sample position.
vec2 sampleDensity = exp(-sampleHeight / heightScale) * rayStepLength;
opticalDepth += sampleDensity;
// Generate ray from the sample position segment to the light source, up to the outer ring of the atmosphere.
czm_ray lightRay = czm_ray(samplePosition, lightDirection);
czm_raySegment lightRayAtmosphereIntersect = czm_raySphereIntersectionInterval(lightRay, origin, atmosphereOuterRadius);
float lightStepLength = lightRayAtmosphereIntersect.stop / float(LIGHT_STEPS);
float lightPositionLength = 0.0;
vec2 lightOpticalDepth = vec2(0.0);
// Sample positions along the light ray, to accumulate incidence of light on the latest sample segment.
for (int j = 0; j < LIGHT_STEPS_MAX; ++j) {
// The loop should be: for (int j = 0; i < LIGHT_STEPS; ++j) {...} but WebGL1 cannot
// loop with non-constant condition, so it has to break early instead
if (j >= LIGHT_STEPS) {
break;
}
// Calculate sample position along light ray.
vec3 lightPosition = samplePosition + lightDirection * (lightPositionLength + lightStepLength * 0.5);
// Calculate height of the light sample position above ellipsoid.
float lightHeight = length(lightPosition) - atmosphereInnerRadius;
// Calculate density of photons at the light sample position.
lightOpticalDepth += exp(-lightHeight / heightScale) * lightStepLength;
// Increment distance on light ray.
lightPositionLength += lightStepLength;
}
// Compute attenuation via the primary ray and the light ray.
vec3 attenuation = exp(-((u_atmosphereMieCoefficient * (opticalDepth.y + lightOpticalDepth.y)) + (u_atmosphereRayleighCoefficient * (opticalDepth.x + lightOpticalDepth.x))));
// Accumulate the scattering.
rayleighAccumulation += sampleDensity.x * attenuation;
mieAccumulation += sampleDensity.y * attenuation;
// Increment distance on primary ray.
rayPositionLength += (rayStepLength += rayStepLengthIncrease);
}
// Compute the scattering amount.
rayleighColor = u_atmosphereRayleighCoefficient * rayleighAccumulation;
mieColor = u_atmosphereMieCoefficient * mieAccumulation;
// Compute the transmittance i.e. how much light is passing through the atmosphere.
opacity = length(exp(-((u_atmosphereMieCoefficient * opticalDepth.y) + (u_atmosphereRayleighCoefficient * opticalDepth.x))));
}
vec4 computeAtmosphereColor(
vec3 positionWC,
vec3 lightDirection,
vec3 rayleighColor,
vec3 mieColor,
float opacity
) {
// Setup the primary ray: from the camera position to the vertex position.
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);
float cosAngle = dot(cameraToPositionWCDirection, lightDirection);
float cosAngleSq = cosAngle * cosAngle;
float G = u_atmosphereMieAnisotropy;
float GSq = G * G;
// The Rayleigh phase function.
float rayleighPhase = 3.0 / (50.2654824574) * (1.0 + cosAngleSq);
// The Mie phase function.
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));
// The final color is generated by combining the effects of the Rayleigh and Mie scattering.
vec3 rayleigh = rayleighPhase * rayleighColor;
vec3 mie = miePhase * mieColor;
vec3 color = (rayleigh + mie) * u_atmosphereLightIntensity;
return vec4(color, opacity);
}
`,v1e=`in vec2 v_textureCoordinates;
const float M_PI = 3.141592653589793;
float vdcRadicalInverse(int i)
{
float r;
float base = 2.0;
float value = 0.0;
float invBase = 1.0 / base;
float invBi = invBase;
for (int x = 0; x < 100; x++)
{
if (i <= 0)
{
break;
}
r = mod(float(i), base);
value += r * invBi;
invBi *= invBase;
i = int(float(i) * invBase);
}
return value;
}
vec2 hammersley2D(int i, int N)
{
return vec2(float(i) / float(N), vdcRadicalInverse(i));
}
vec3 importanceSampleGGX(vec2 xi, float roughness, vec3 N)
{
float a = roughness * roughness;
float phi = 2.0 * M_PI * xi.x;
float cosTheta = sqrt((1.0 - xi.y) / (1.0 + (a * a - 1.0) * xi.y));
float sinTheta = sqrt(1.0 - cosTheta * cosTheta);
vec3 H = vec3(sinTheta * cos(phi), sinTheta * sin(phi), cosTheta);
vec3 upVector = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
vec3 tangentX = normalize(cross(upVector, N));
vec3 tangentY = cross(N, tangentX);
return tangentX * H.x + tangentY * H.y + N * H.z;
}
float G1_Smith(float NdotV, float k)
{
return NdotV / (NdotV * (1.0 - k) + k);
}
float G_Smith(float roughness, float NdotV, float NdotL)
{
float k = roughness * roughness / 2.0;
return G1_Smith(NdotV, k) * G1_Smith(NdotL, k);
}
vec2 integrateBrdf(float roughness, float NdotV)
{
vec3 V = vec3(sqrt(1.0 - NdotV * NdotV), 0.0, NdotV);
float A = 0.0;
float B = 0.0;
const int NumSamples = 1024;
for (int i = 0; i < NumSamples; i++)
{
vec2 xi = hammersley2D(i, NumSamples);
vec3 H = importanceSampleGGX(xi, roughness, vec3(0.0, 0.0, 1.0));
vec3 L = 2.0 * dot(V, H) * H - V;
float NdotL = clamp(L.z, 0.0, 1.0);
float NdotH = clamp(H.z, 0.0, 1.0);
float VdotH = clamp(dot(V, H), 0.0, 1.0);
if (NdotL > 0.0)
{
float G = G_Smith(roughness, NdotV, NdotL);
float G_Vis = G * VdotH / (NdotH * NdotV);
float Fc = pow(1.0 - VdotH, 5.0);
A += (1.0 - Fc) * G_Vis;
B += Fc * G_Vis;
}
}
return vec2(A, B) / float(NumSamples);
}
void main()
{
out_FragColor = vec4(integrateBrdf(v_textureCoordinates.y, v_textureCoordinates.x), 0.0, 1.0);
}
`,I1e=`uniform sampler2D u_opaqueDepthTexture;
uniform sampler2D u_translucentDepthTexture;
in vec2 v_textureCoordinates;
void main()
{
float opaqueDepth = texture(u_opaqueDepthTexture, v_textureCoordinates).r;
float translucentDepth = texture(u_translucentDepthTexture, v_textureCoordinates).r;
translucentDepth = czm_branchFreeTernary(translucentDepth > opaqueDepth, 1.0, translucentDepth);
out_FragColor = czm_packDepth(translucentDepth);
}
`,D1e=`/**
* Compositing for Weighted Blended Order-Independent Transparency. See:
* - http://jcgt.org/published/0002/02/09/
* - http://casual-effects.blogspot.com/2014/03/weighted-blended-order-independent.html
*/
uniform sampler2D u_opaque;
uniform sampler2D u_accumulation;
uniform sampler2D u_revealage;
in vec2 v_textureCoordinates;
void main()
{
vec4 opaque = texture(u_opaque, v_textureCoordinates);
vec4 accum = texture(u_accumulation, v_textureCoordinates);
float r = texture(u_revealage, v_textureCoordinates).r;
#ifdef MRT
vec4 transparent = vec4(accum.rgb / clamp(r, 1e-4, 5e4), accum.a);
#else
vec4 transparent = vec4(accum.rgb / clamp(accum.a, 1e-4, 5e4), r);
#endif
out_FragColor = (1.0 - transparent.a) * transparent + transparent.a * opaque;
if (opaque != czm_backgroundColor)
{
out_FragColor.a = 1.0;
}
}
`,P1e=`in vec4 positionEC;
void main()
{
vec3 position;
vec3 direction;
if (czm_orthographicIn3D == 1.0)
{
vec2 uv = (gl_FragCoord.xy - czm_viewport.xy) / czm_viewport.zw;
vec2 minPlane = vec2(czm_frustumPlanes.z, czm_frustumPlanes.y); // left, bottom
vec2 maxPlane = vec2(czm_frustumPlanes.w, czm_frustumPlanes.x); // right, top
position = vec3(mix(minPlane, maxPlane, uv), 0.0);
direction = vec3(0.0, 0.0, -1.0);
}
else
{
position = vec3(0.0);
direction = normalize(positionEC.xyz);
}
czm_ray ray = czm_ray(position, direction);
vec3 ellipsoid_center = czm_view[3].xyz;
czm_raySegment intersection = czm_rayEllipsoidIntersectionInterval(ray, ellipsoid_center, czm_ellipsoidInverseRadii);
if (!czm_isEmpty(intersection))
{
out_FragColor = vec4(1.0, 1.0, 0.0, 1.0);
}
else
{
discard;
}
czm_writeLogDepth();
}
`,O1e=`in vec4 position;
out vec4 positionEC;
void main()
{
positionEC = czm_modelView * position;
gl_Position = czm_projection * positionEC;
czm_vertexLogDepth();
}
`,vB=`uniform vec3 u_radii;
uniform vec3 u_oneOverEllipsoidRadiiSquared;
in vec3 v_positionEC;
vec4 computeEllipsoidColor(czm_ray ray, float intersection, float side)
{
vec3 positionEC = czm_pointAlongRay(ray, intersection);
vec3 positionMC = (czm_inverseModelView * vec4(positionEC, 1.0)).xyz;
vec3 geodeticNormal = normalize(czm_geodeticSurfaceNormal(positionMC, vec3(0.0), u_oneOverEllipsoidRadiiSquared));
vec3 sphericalNormal = normalize(positionMC / u_radii);
vec3 normalMC = geodeticNormal * side; // normalized surface normal (always facing the viewer) in model coordinates
vec3 normalEC = normalize(czm_normal * normalMC); // normalized surface normal in eye coordinates
vec2 st = czm_ellipsoidWgs84TextureCoordinates(sphericalNormal);
vec3 positionToEyeEC = -positionEC;
czm_materialInput materialInput;
materialInput.s = st.s;
materialInput.st = st;
materialInput.str = (positionMC + u_radii) / u_radii;
materialInput.normalEC = normalEC;
materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(positionMC, normalEC);
materialInput.positionToEyeEC = positionToEyeEC;
czm_material material = czm_getMaterial(materialInput);
#ifdef ONLY_SUN_LIGHTING
return czm_private_phong(normalize(positionToEyeEC), material, czm_sunDirectionEC);
#else
return czm_phong(normalize(positionToEyeEC), material, czm_lightDirectionEC);
#endif
}
void main()
{
// PERFORMANCE_TODO: When dynamic branching is available, compute ratio of maximum and minimum radii
// in the vertex shader. Only when it is larger than some constant, march along the ray.
// Otherwise perform one intersection test which will be the common case.
// Test if the ray intersects a sphere with the ellipsoid's maximum radius.
// For very oblate ellipsoids, using the ellipsoid's radii for an intersection test
// may cause false negatives. This will discard fragments before marching the ray forward.
float maxRadius = max(u_radii.x, max(u_radii.y, u_radii.z)) * 1.5;
vec3 direction = normalize(v_positionEC);
vec3 ellipsoidCenter = czm_modelView[3].xyz;
float t1 = -1.0;
float t2 = -1.0;
float b = -2.0 * dot(direction, ellipsoidCenter);
float c = dot(ellipsoidCenter, ellipsoidCenter) - maxRadius * maxRadius;
float discriminant = b * b - 4.0 * c;
if (discriminant >= 0.0) {
t1 = (-b - sqrt(discriminant)) * 0.5;
t2 = (-b + sqrt(discriminant)) * 0.5;
}
if (t1 < 0.0 && t2 < 0.0) {
discard;
}
float t = min(t1, t2);
if (t < 0.0) {
t = 0.0;
}
// March ray forward to intersection with larger sphere and find
czm_ray ray = czm_ray(t * direction, direction);
vec3 ellipsoid_inverseRadii = vec3(1.0 / u_radii.x, 1.0 / u_radii.y, 1.0 / u_radii.z);
czm_raySegment intersection = czm_rayEllipsoidIntersectionInterval(ray, ellipsoidCenter, ellipsoid_inverseRadii);
if (czm_isEmpty(intersection))
{
discard;
}
// If the viewer is outside, compute outsideFaceColor, with normals facing outward.
vec4 outsideFaceColor = (intersection.start != 0.0) ? computeEllipsoidColor(ray, intersection.start, 1.0) : vec4(0.0);
// If the viewer either is inside or can see inside, compute insideFaceColor, with normals facing inward.
vec4 insideFaceColor = (outsideFaceColor.a < 1.0) ? computeEllipsoidColor(ray, intersection.stop, -1.0) : vec4(0.0);
out_FragColor = mix(insideFaceColor, outsideFaceColor, outsideFaceColor.a);
out_FragColor.a = 1.0 - (1.0 - insideFaceColor.a) * (1.0 - outsideFaceColor.a);
#if (defined(WRITE_DEPTH) && (__VERSION__ == 300 || defined(GL_EXT_frag_depth)))
t = (intersection.start != 0.0) ? intersection.start : intersection.stop;
vec3 positionEC = czm_pointAlongRay(ray, t);
vec4 positionCC = czm_projection * vec4(positionEC, 1.0);
#ifdef LOG_DEPTH
czm_writeLogDepth(1.0 + positionCC.w);
#else
float z = positionCC.z / positionCC.w;
float n = czm_depthRange.near;
float f = czm_depthRange.far;
gl_FragDepth = (z * (f - n) + f + n) * 0.5;
#endif
#endif
}
`,IB=`in vec3 position;
uniform vec3 u_radii;
out vec3 v_positionEC;
void main()
{
// In the vertex data, the cube goes from (-1.0, -1.0, -1.0) to (1.0, 1.0, 1.0) in model coordinates.
// Scale to consider the radii. We could also do this once on the CPU when using the BoxGeometry,
// but doing it here allows us to change the radii without rewriting the vertex data, and
// allows all ellipsoids to reuse the same vertex data.
vec4 p = vec4(u_radii * position, 1.0);
v_positionEC = (czm_modelView * p).xyz; // position in eye coordinates
gl_Position = czm_modelViewProjection * p; // position in clip coordinates
// With multi-frustum, when the ellipsoid primitive is positioned on the intersection of two frustums
// and close to terrain, the terrain (writes depth) in the closest frustum can overwrite part of the
// ellipsoid (does not write depth) that was rendered in the farther frustum.
//
// Here, we clamp the depth in the vertex shader to avoid being overwritten; however, this creates
// artifacts since some fragments can be alpha blended twice. This is solved by only rendering
// the ellipsoid in the closest frustum to the viewer.
gl_Position.z = clamp(gl_Position.z, czm_depthRange.near, czm_depthRange.far);
czm_vertexLogDepth();
}
`;/**
* @license
* Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/const L1e=`/**
* @license
* Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS \`\`AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// NVIDIA GameWorks Graphics Samples GitHub link: https://github.com/NVIDIAGameWorks/GraphicsSamples
// Original FXAA 3.11 shader link: https://github.com/NVIDIAGameWorks/GraphicsSamples/blob/master/samples/es3-kepler/FXAA/FXAA3_11.h
// Steps used to integrate into Cesium:
// * The following defines are set:
// #define FXAA_PC 1
// #define FXAA_WEBGL_1 1
// #define FXAA_GREEN_AS_LUMA 1
// #define FXAA_EARLY_EXIT 1
// #define FXAA_GLSL_120 1
// * All other preprocessor directives besides the FXAA_QUALITY__P* directives were removed.
// * Double underscores are invalid for preprocessor directives so replace them with a single underscore. Replace
// /FXAA_QUALITY__P(.*)/g with /FXAA_QUALITY__P$1/.
// * There are no implicit conversions from ivec* to vec* so replace:
// #define FxaaInt2 ivec2
// with
// #define FxaaInt2 vec2
// * The texture2DLod function is only available in vertex shaders so replace:
// #define FxaaTexTop(t, p) texture2DLod(t, p, 0.0)
// #define FxaaTexOff(t, p, o, r) texture2DLod(t, p + (o * r), 0.0)
// with
// #define FxaaTexTop(t, p) texture(t, p)
// #define FxaaTexOff(t, p, o, r) texture(t, p + (o * r))
// * FXAA_QUALITY_PRESET is prepended in the javascript code. We may want to expose that setting in the future.
// * The following parameters to FxaaPixelShader are unused and can be removed:
// fxaaConsolePosPos
// fxaaConsoleRcpFrameOpt
// fxaaConsoleRcpFrameOpt2
// fxaaConsole360RcpFrameOpt2
// fxaaConsoleEdgeSharpness
// fxaaConsoleEdgeThreshold
// fxaaConsoleEdgeThresholdMi
// fxaaConsole360ConstDir
//
// Choose the quality preset.
// This needs to be compiled into the shader as it effects code.
// Best option to include multiple presets is to
// in each shader define the preset, then include this file.
//
// OPTIONS
// -----------------------------------------------------------------------
// 10 to 15 - default medium dither (10=fastest, 15=highest quality)
// 20 to 29 - less dither, more expensive (20=fastest, 29=highest quality)
// 39 - no dither, very expensive
//
// NOTES
// -----------------------------------------------------------------------
// 12 = slightly faster then FXAA 3.9 and higher edge quality (default)
// 13 = about same speed as FXAA 3.9 and better than 12
// 23 = closest to FXAA 3.9 visually and performance wise
// _ = the lowest digit is directly related to performance
// _ = the highest digit is directly related to style
//
//#define FXAA_QUALITY_PRESET 12
#if (FXAA_QUALITY_PRESET == 10)
#define FXAA_QUALITY_PS 3
#define FXAA_QUALITY_P0 1.5
#define FXAA_QUALITY_P1 3.0
#define FXAA_QUALITY_P2 12.0
#endif
#if (FXAA_QUALITY_PRESET == 11)
#define FXAA_QUALITY_PS 4
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 3.0
#define FXAA_QUALITY_P3 12.0
#endif
#if (FXAA_QUALITY_PRESET == 12)
#define FXAA_QUALITY_PS 5
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 4.0
#define FXAA_QUALITY_P4 12.0
#endif
#if (FXAA_QUALITY_PRESET == 13)
#define FXAA_QUALITY_PS 6
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 4.0
#define FXAA_QUALITY_P5 12.0
#endif
#if (FXAA_QUALITY_PRESET == 14)
#define FXAA_QUALITY_PS 7
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 4.0
#define FXAA_QUALITY_P6 12.0
#endif
#if (FXAA_QUALITY_PRESET == 15)
#define FXAA_QUALITY_PS 8
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 2.0
#define FXAA_QUALITY_P6 4.0
#define FXAA_QUALITY_P7 12.0
#endif
#if (FXAA_QUALITY_PRESET == 20)
#define FXAA_QUALITY_PS 3
#define FXAA_QUALITY_P0 1.5
#define FXAA_QUALITY_P1 2.0
#define FXAA_QUALITY_P2 8.0
#endif
#if (FXAA_QUALITY_PRESET == 21)
#define FXAA_QUALITY_PS 4
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 8.0
#endif
#if (FXAA_QUALITY_PRESET == 22)
#define FXAA_QUALITY_PS 5
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 8.0
#endif
#if (FXAA_QUALITY_PRESET == 23)
#define FXAA_QUALITY_PS 6
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 8.0
#endif
#if (FXAA_QUALITY_PRESET == 24)
#define FXAA_QUALITY_PS 7
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 3.0
#define FXAA_QUALITY_P6 8.0
#endif
#if (FXAA_QUALITY_PRESET == 25)
#define FXAA_QUALITY_PS 8
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 2.0
#define FXAA_QUALITY_P6 4.0
#define FXAA_QUALITY_P7 8.0
#endif
#if (FXAA_QUALITY_PRESET == 26)
#define FXAA_QUALITY_PS 9
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 2.0
#define FXAA_QUALITY_P6 2.0
#define FXAA_QUALITY_P7 4.0
#define FXAA_QUALITY_P8 8.0
#endif
#if (FXAA_QUALITY_PRESET == 27)
#define FXAA_QUALITY_PS 10
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 2.0
#define FXAA_QUALITY_P6 2.0
#define FXAA_QUALITY_P7 2.0
#define FXAA_QUALITY_P8 4.0
#define FXAA_QUALITY_P9 8.0
#endif
#if (FXAA_QUALITY_PRESET == 28)
#define FXAA_QUALITY_PS 11
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 2.0
#define FXAA_QUALITY_P6 2.0
#define FXAA_QUALITY_P7 2.0
#define FXAA_QUALITY_P8 2.0
#define FXAA_QUALITY_P9 4.0
#define FXAA_QUALITY_P10 8.0
#endif
#if (FXAA_QUALITY_PRESET == 29)
#define FXAA_QUALITY_PS 12
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.5
#define FXAA_QUALITY_P2 2.0
#define FXAA_QUALITY_P3 2.0
#define FXAA_QUALITY_P4 2.0
#define FXAA_QUALITY_P5 2.0
#define FXAA_QUALITY_P6 2.0
#define FXAA_QUALITY_P7 2.0
#define FXAA_QUALITY_P8 2.0
#define FXAA_QUALITY_P9 2.0
#define FXAA_QUALITY_P10 4.0
#define FXAA_QUALITY_P11 8.0
#endif
#if (FXAA_QUALITY_PRESET == 39)
#define FXAA_QUALITY_PS 12
#define FXAA_QUALITY_P0 1.0
#define FXAA_QUALITY_P1 1.0
#define FXAA_QUALITY_P2 1.0
#define FXAA_QUALITY_P3 1.0
#define FXAA_QUALITY_P4 1.0
#define FXAA_QUALITY_P5 1.5
#define FXAA_QUALITY_P6 2.0
#define FXAA_QUALITY_P7 2.0
#define FXAA_QUALITY_P8 2.0
#define FXAA_QUALITY_P9 2.0
#define FXAA_QUALITY_P10 4.0
#define FXAA_QUALITY_P11 8.0
#endif
#define FxaaBool bool
#define FxaaFloat float
#define FxaaFloat2 vec2
#define FxaaFloat3 vec3
#define FxaaFloat4 vec4
#define FxaaHalf float
#define FxaaHalf2 vec2
#define FxaaHalf3 vec3
#define FxaaHalf4 vec4
#define FxaaInt2 vec2
#define FxaaTex sampler2D
#define FxaaSat(x) clamp(x, 0.0, 1.0)
#define FxaaTexTop(t, p) texture(t, p)
#define FxaaTexOff(t, p, o, r) texture(t, p + (o * r))
FxaaFloat FxaaLuma(FxaaFloat4 rgba) { return rgba.y; }
FxaaFloat4 FxaaPixelShader(
//
// Use noperspective interpolation here (turn off perspective interpolation).
// {xy} = center of pixel
FxaaFloat2 pos,
//
// Input color texture.
// {rgb_} = color in linear or perceptual color space
// if (FXAA_GREEN_AS_LUMA == 0)
// {___a} = luma in perceptual color space (not linear)
FxaaTex tex,
//
// Only used on FXAA Quality.
// This must be from a constant/uniform.
// {x_} = 1.0/screenWidthInPixels
// {_y} = 1.0/screenHeightInPixels
FxaaFloat2 fxaaQualityRcpFrame,
//
// Only used on FXAA Quality.
// This used to be the FXAA_QUALITY_SUBPIX define.
// It is here now to allow easier tuning.
// Choose the amount of sub-pixel aliasing removal.
// This can effect sharpness.
// 1.00 - upper limit (softer)
// 0.75 - default amount of filtering
// 0.50 - lower limit (sharper, less sub-pixel aliasing removal)
// 0.25 - almost off
// 0.00 - completely off
FxaaFloat fxaaQualitySubpix,
//
// Only used on FXAA Quality.
// This used to be the FXAA_QUALITY_EDGE_THRESHOLD define.
// It is here now to allow easier tuning.
// The minimum amount of local contrast required to apply algorithm.
// 0.333 - too little (faster)
// 0.250 - low quality
// 0.166 - default
// 0.125 - high quality
// 0.063 - overkill (slower)
FxaaFloat fxaaQualityEdgeThreshold,
//
// Only used on FXAA Quality.
// This used to be the FXAA_QUALITY_EDGE_THRESHOLD_MIN define.
// It is here now to allow easier tuning.
// Trims the algorithm from processing darks.
// 0.0833 - upper limit (default, the start of visible unfiltered edges)
// 0.0625 - high quality (faster)
// 0.0312 - visible limit (slower)
// Special notes when using FXAA_GREEN_AS_LUMA,
// Likely want to set this to zero.
// As colors that are mostly not-green
// will appear very dark in the green channel!
// Tune by looking at mostly non-green content,
// then start at zero and increase until aliasing is a problem.
FxaaFloat fxaaQualityEdgeThresholdMin
) {
/*--------------------------------------------------------------------------*/
FxaaFloat2 posM;
posM.x = pos.x;
posM.y = pos.y;
FxaaFloat4 rgbyM = FxaaTexTop(tex, posM);
#define lumaM rgbyM.y
FxaaFloat lumaS = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0, 1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 0), fxaaQualityRcpFrame.xy));
FxaaFloat lumaN = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 0,-1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 0), fxaaQualityRcpFrame.xy));
/*--------------------------------------------------------------------------*/
FxaaFloat maxSM = max(lumaS, lumaM);
FxaaFloat minSM = min(lumaS, lumaM);
FxaaFloat maxESM = max(lumaE, maxSM);
FxaaFloat minESM = min(lumaE, minSM);
FxaaFloat maxWN = max(lumaN, lumaW);
FxaaFloat minWN = min(lumaN, lumaW);
FxaaFloat rangeMax = max(maxWN, maxESM);
FxaaFloat rangeMin = min(minWN, minESM);
FxaaFloat rangeMaxScaled = rangeMax * fxaaQualityEdgeThreshold;
FxaaFloat range = rangeMax - rangeMin;
FxaaFloat rangeMaxClamped = max(fxaaQualityEdgeThresholdMin, rangeMaxScaled);
FxaaBool earlyExit = range < rangeMaxClamped;
/*--------------------------------------------------------------------------*/
if(earlyExit)
return rgbyM;
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1,-1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaSE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1, 1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaNE = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2( 1,-1), fxaaQualityRcpFrame.xy));
FxaaFloat lumaSW = FxaaLuma(FxaaTexOff(tex, posM, FxaaInt2(-1, 1), fxaaQualityRcpFrame.xy));
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNS = lumaN + lumaS;
FxaaFloat lumaWE = lumaW + lumaE;
FxaaFloat subpixRcpRange = 1.0/range;
FxaaFloat subpixNSWE = lumaNS + lumaWE;
FxaaFloat edgeHorz1 = (-2.0 * lumaM) + lumaNS;
FxaaFloat edgeVert1 = (-2.0 * lumaM) + lumaWE;
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNESE = lumaNE + lumaSE;
FxaaFloat lumaNWNE = lumaNW + lumaNE;
FxaaFloat edgeHorz2 = (-2.0 * lumaE) + lumaNESE;
FxaaFloat edgeVert2 = (-2.0 * lumaN) + lumaNWNE;
/*--------------------------------------------------------------------------*/
FxaaFloat lumaNWSW = lumaNW + lumaSW;
FxaaFloat lumaSWSE = lumaSW + lumaSE;
FxaaFloat edgeHorz4 = (abs(edgeHorz1) * 2.0) + abs(edgeHorz2);
FxaaFloat edgeVert4 = (abs(edgeVert1) * 2.0) + abs(edgeVert2);
FxaaFloat edgeHorz3 = (-2.0 * lumaW) + lumaNWSW;
FxaaFloat edgeVert3 = (-2.0 * lumaS) + lumaSWSE;
FxaaFloat edgeHorz = abs(edgeHorz3) + edgeHorz4;
FxaaFloat edgeVert = abs(edgeVert3) + edgeVert4;
/*--------------------------------------------------------------------------*/
FxaaFloat subpixNWSWNESE = lumaNWSW + lumaNESE;
FxaaFloat lengthSign = fxaaQualityRcpFrame.x;
FxaaBool horzSpan = edgeHorz >= edgeVert;
FxaaFloat subpixA = subpixNSWE * 2.0 + subpixNWSWNESE;
/*--------------------------------------------------------------------------*/
if(!horzSpan) lumaN = lumaW;
if(!horzSpan) lumaS = lumaE;
if(horzSpan) lengthSign = fxaaQualityRcpFrame.y;
FxaaFloat subpixB = (subpixA * (1.0/12.0)) - lumaM;
/*--------------------------------------------------------------------------*/
FxaaFloat gradientN = lumaN - lumaM;
FxaaFloat gradientS = lumaS - lumaM;
FxaaFloat lumaNN = lumaN + lumaM;
FxaaFloat lumaSS = lumaS + lumaM;
FxaaBool pairN = abs(gradientN) >= abs(gradientS);
FxaaFloat gradient = max(abs(gradientN), abs(gradientS));
if(pairN) lengthSign = -lengthSign;
FxaaFloat subpixC = FxaaSat(abs(subpixB) * subpixRcpRange);
/*--------------------------------------------------------------------------*/
FxaaFloat2 posB;
posB.x = posM.x;
posB.y = posM.y;
FxaaFloat2 offNP;
offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;
offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;
if(!horzSpan) posB.x += lengthSign * 0.5;
if( horzSpan) posB.y += lengthSign * 0.5;
/*--------------------------------------------------------------------------*/
FxaaFloat2 posN;
posN.x = posB.x - offNP.x * FXAA_QUALITY_P0;
posN.y = posB.y - offNP.y * FXAA_QUALITY_P0;
FxaaFloat2 posP;
posP.x = posB.x + offNP.x * FXAA_QUALITY_P0;
posP.y = posB.y + offNP.y * FXAA_QUALITY_P0;
FxaaFloat subpixD = ((-2.0)*subpixC) + 3.0;
FxaaFloat lumaEndN = FxaaLuma(FxaaTexTop(tex, posN));
FxaaFloat subpixE = subpixC * subpixC;
FxaaFloat lumaEndP = FxaaLuma(FxaaTexTop(tex, posP));
/*--------------------------------------------------------------------------*/
if(!pairN) lumaNN = lumaSS;
FxaaFloat gradientScaled = gradient * 1.0/4.0;
FxaaFloat lumaMM = lumaM - lumaNN * 0.5;
FxaaFloat subpixF = subpixD * subpixE;
FxaaBool lumaMLTZero = lumaMM < 0.0;
/*--------------------------------------------------------------------------*/
lumaEndN -= lumaNN * 0.5;
lumaEndP -= lumaNN * 0.5;
FxaaBool doneN = abs(lumaEndN) >= gradientScaled;
FxaaBool doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P1;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P1;
FxaaBool doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P1;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P1;
/*--------------------------------------------------------------------------*/
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P2;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P2;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P2;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P2;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 3)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P3;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P3;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P3;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P3;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 4)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P4;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P4;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P4;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P4;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 5)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P5;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P5;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P5;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P5;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 6)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P6;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P6;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P6;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P6;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 7)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P7;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P7;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P7;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P7;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 8)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P8;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P8;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P8;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P8;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 9)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P9;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P9;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P9;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P9;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 10)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P10;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P10;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P10;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P10;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 11)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P11;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P11;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P11;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P11;
/*--------------------------------------------------------------------------*/
#if (FXAA_QUALITY_PS > 12)
if(doneNP) {
if(!doneN) lumaEndN = FxaaLuma(FxaaTexTop(tex, posN.xy));
if(!doneP) lumaEndP = FxaaLuma(FxaaTexTop(tex, posP.xy));
if(!doneN) lumaEndN = lumaEndN - lumaNN * 0.5;
if(!doneP) lumaEndP = lumaEndP - lumaNN * 0.5;
doneN = abs(lumaEndN) >= gradientScaled;
doneP = abs(lumaEndP) >= gradientScaled;
if(!doneN) posN.x -= offNP.x * FXAA_QUALITY_P12;
if(!doneN) posN.y -= offNP.y * FXAA_QUALITY_P12;
doneNP = (!doneN) || (!doneP);
if(!doneP) posP.x += offNP.x * FXAA_QUALITY_P12;
if(!doneP) posP.y += offNP.y * FXAA_QUALITY_P12;
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
#endif
/*--------------------------------------------------------------------------*/
}
/*--------------------------------------------------------------------------*/
FxaaFloat dstN = posM.x - posN.x;
FxaaFloat dstP = posP.x - posM.x;
if(!horzSpan) dstN = posM.y - posN.y;
if(!horzSpan) dstP = posP.y - posM.y;
/*--------------------------------------------------------------------------*/
FxaaBool goodSpanN = (lumaEndN < 0.0) != lumaMLTZero;
FxaaFloat spanLength = (dstP + dstN);
FxaaBool goodSpanP = (lumaEndP < 0.0) != lumaMLTZero;
FxaaFloat spanLengthRcp = 1.0/spanLength;
/*--------------------------------------------------------------------------*/
FxaaBool directionN = dstN < dstP;
FxaaFloat dst = min(dstN, dstP);
FxaaBool goodSpan = directionN ? goodSpanN : goodSpanP;
FxaaFloat subpixG = subpixF * subpixF;
FxaaFloat pixelOffset = (dst * (-spanLengthRcp)) + 0.5;
FxaaFloat subpixH = subpixG * fxaaQualitySubpix;
/*--------------------------------------------------------------------------*/
FxaaFloat pixelOffsetGood = goodSpan ? pixelOffset : 0.0;
FxaaFloat pixelOffsetSubpix = max(pixelOffsetGood, subpixH);
if(!horzSpan) posM.x += pixelOffsetSubpix * lengthSign;
if( horzSpan) posM.y += pixelOffsetSubpix * lengthSign;
return FxaaFloat4(FxaaTexTop(tex, posM).xyz, lumaM);
}
`,R1e=`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
#ifdef ENABLE_CLIPPING_POLYGONS
uniform highp sampler2D u_clippingDistance;
in vec2 v_clippingPosition;
flat in int v_regionIndex;
#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));
}
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 coordinates
#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 ENABLE_CLIPPING_POLYGONS
vec2 clippingPosition = v_clippingPosition;
int regionIndex = v_regionIndex;
clipPolygons(u_clippingDistance, CLIPPING_POLYGON_REGIONS_LENGTH, clippingPosition, regionIndex);
#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
#ifdef COLOR_CORRECT
const bool ignoreBlackPixels = true;
rayleighColor = czm_applyHSBShift(rayleighColor, u_hsbShift, ignoreBlackPixels);
mieColor = czm_applyHSBShift(mieColor, u_hsbShift, ignoreBlackPixels);
#endif
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
// Apply ground atmosphere. This happens when the camera is far away from the earth.
// 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
`,N1e=`#ifdef QUANTIZATION_BITS12
in vec4 compressed0;
in float compressed1;
#else
in vec4 position3DAndHeight;
in vec4 textureCoordAndEncodedNormals;
#endif
#ifdef GEODETIC_SURFACE_NORMALS
in vec3 geodeticSurfaceNormal;
#endif
#ifdef EXAGGERATION
uniform vec2 u_verticalExaggerationAndRelativeHeight;
#endif
uniform vec3 u_center3D;
uniform mat4 u_modifiedModelView;
uniform mat4 u_modifiedModelViewProjection;
uniform vec4 u_tileRectangle;
// Uniforms for 2D Mercator projection
uniform vec2 u_southAndNorthLatitude;
uniform vec2 u_southMercatorYAndOneOverHeight;
out vec3 v_positionMC;
out vec3 v_positionEC;
out vec3 v_textureCoordinates;
out vec3 v_normalMC;
out vec3 v_normalEC;
#ifdef APPLY_MATERIAL
out float v_slope;
out float v_aspect;
out float v_height;
#endif
#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)
out float v_distance;
#endif
#if defined(FOG) || defined(GROUND_ATMOSPHERE)
out vec3 v_atmosphereRayleighColor;
out vec3 v_atmosphereMieColor;
out float v_atmosphereOpacity;
#endif
#ifdef ENABLE_CLIPPING_POLYGONS
uniform highp sampler2D u_clippingExtents;
out vec2 v_clippingPosition;
flat out int v_regionIndex;
#endif
// These functions are generated at runtime.
vec4 getPosition(vec3 position, float height, vec2 textureCoordinates);
float get2DYPositionFraction(vec2 textureCoordinates);
vec4 getPosition3DMode(vec3 position, float height, vec2 textureCoordinates)
{
return u_modifiedModelViewProjection * vec4(position, 1.0);
}
float get2DMercatorYPositionFraction(vec2 textureCoordinates)
{
// The width of a tile at level 11, in radians and assuming a single root tile, is
// 2.0 * czm_pi / pow(2.0, 11.0)
// We want to just linearly interpolate the 2D position from the texture coordinates
// when we're at this level or higher. The constant below is the expression
// above evaluated and then rounded up at the 4th significant digit.
const float maxTileWidth = 0.003068;
float positionFraction = textureCoordinates.y;
float southLatitude = u_southAndNorthLatitude.x;
float northLatitude = u_southAndNorthLatitude.y;
if (northLatitude - southLatitude > maxTileWidth)
{
float southMercatorY = u_southMercatorYAndOneOverHeight.x;
float oneOverMercatorHeight = u_southMercatorYAndOneOverHeight.y;
float currentLatitude = mix(southLatitude, northLatitude, textureCoordinates.y);
currentLatitude = clamp(currentLatitude, -czm_webMercatorMaxLatitude, czm_webMercatorMaxLatitude);
positionFraction = czm_latitudeToWebMercatorFraction(currentLatitude, southMercatorY, oneOverMercatorHeight);
}
return positionFraction;
}
float get2DGeographicYPositionFraction(vec2 textureCoordinates)
{
return textureCoordinates.y;
}
vec4 getPositionPlanarEarth(vec3 position, float height, vec2 textureCoordinates)
{
float yPositionFraction = get2DYPositionFraction(textureCoordinates);
vec4 rtcPosition2D = vec4(height, mix(u_tileRectangle.st, u_tileRectangle.pq, vec2(textureCoordinates.x, yPositionFraction)), 1.0);
return u_modifiedModelViewProjection * rtcPosition2D;
}
vec4 getPosition2DMode(vec3 position, float height, vec2 textureCoordinates)
{
return getPositionPlanarEarth(position, 0.0, textureCoordinates);
}
vec4 getPositionColumbusViewMode(vec3 position, float height, vec2 textureCoordinates)
{
return getPositionPlanarEarth(position, height, textureCoordinates);
}
vec4 getPositionMorphingMode(vec3 position, float height, vec2 textureCoordinates)
{
// We do not do RTC while morphing, so there is potential for jitter.
// This is unlikely to be noticeable, though.
vec3 position3DWC = position + u_center3D;
float yPositionFraction = get2DYPositionFraction(textureCoordinates);
vec4 position2DWC = vec4(height, mix(u_tileRectangle.st, u_tileRectangle.pq, vec2(textureCoordinates.x, yPositionFraction)), 1.0);
vec4 morphPosition = czm_columbusViewMorph(position2DWC, vec4(position3DWC, 1.0), czm_morphTime);
return czm_modelViewProjection * morphPosition;
}
#ifdef QUANTIZATION_BITS12
uniform vec2 u_minMaxHeight;
uniform mat4 u_scaleAndBias;
#endif
void main()
{
#ifdef QUANTIZATION_BITS12
vec2 xy = czm_decompressTextureCoordinates(compressed0.x);
vec2 zh = czm_decompressTextureCoordinates(compressed0.y);
vec3 position = vec3(xy, zh.x);
float height = zh.y;
vec2 textureCoordinates = czm_decompressTextureCoordinates(compressed0.z);
height = height * (u_minMaxHeight.y - u_minMaxHeight.x) + u_minMaxHeight.x;
position = (u_scaleAndBias * vec4(position, 1.0)).xyz;
#if (defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL)) && defined(INCLUDE_WEB_MERCATOR_Y) || defined(APPLY_MATERIAL)
float webMercatorT = czm_decompressTextureCoordinates(compressed0.w).x;
float encodedNormal = compressed1;
#elif defined(INCLUDE_WEB_MERCATOR_Y)
float webMercatorT = czm_decompressTextureCoordinates(compressed0.w).x;
float encodedNormal = 0.0;
#elif defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL)
float webMercatorT = textureCoordinates.y;
float encodedNormal = compressed0.w;
#else
float webMercatorT = textureCoordinates.y;
float encodedNormal = 0.0;
#endif
#else
// A single float per element
vec3 position = position3DAndHeight.xyz;
float height = position3DAndHeight.w;
vec2 textureCoordinates = textureCoordAndEncodedNormals.xy;
#if (defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL) || defined(APPLY_MATERIAL)) && defined(INCLUDE_WEB_MERCATOR_Y)
float webMercatorT = textureCoordAndEncodedNormals.z;
float encodedNormal = textureCoordAndEncodedNormals.w;
#elif defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL) || defined(APPLY_MATERIAL)
float webMercatorT = textureCoordinates.y;
float encodedNormal = textureCoordAndEncodedNormals.z;
#elif defined(INCLUDE_WEB_MERCATOR_Y)
float webMercatorT = textureCoordAndEncodedNormals.z;
float encodedNormal = 0.0;
#else
float webMercatorT = textureCoordinates.y;
float encodedNormal = 0.0;
#endif
#endif
vec3 position3DWC = position + u_center3D;
#ifdef GEODETIC_SURFACE_NORMALS
vec3 ellipsoidNormal = geodeticSurfaceNormal;
#else
vec3 ellipsoidNormal = normalize(position3DWC);
#endif
#if defined(EXAGGERATION) && defined(GEODETIC_SURFACE_NORMALS)
float exaggeration = u_verticalExaggerationAndRelativeHeight.x;
float relativeHeight = u_verticalExaggerationAndRelativeHeight.y;
float newHeight = (height - relativeHeight) * exaggeration + relativeHeight;
// stop from going through center of earth
float minRadius = min(min(czm_ellipsoidRadii.x, czm_ellipsoidRadii.y), czm_ellipsoidRadii.z);
newHeight = max(newHeight, -minRadius);
vec3 offset = ellipsoidNormal * (newHeight - height);
position += offset;
position3DWC += offset;
height = newHeight;
#endif
gl_Position = getPosition(position, height, textureCoordinates);
v_positionEC = (u_modifiedModelView * vec4(position, 1.0)).xyz;
v_positionMC = position3DWC; // position in model coordinates
v_textureCoordinates = vec3(textureCoordinates, webMercatorT);
#if defined(ENABLE_VERTEX_LIGHTING) || defined(GENERATE_POSITION_AND_NORMAL) || defined(APPLY_MATERIAL)
vec3 normalMC = czm_octDecode(encodedNormal);
#if defined(EXAGGERATION) && defined(GEODETIC_SURFACE_NORMALS)
vec3 projection = dot(normalMC, ellipsoidNormal) * ellipsoidNormal;
vec3 rejection = normalMC - projection;
normalMC = normalize(projection + rejection * exaggeration);
#endif
v_normalMC = normalMC;
v_normalEC = czm_normal3D * v_normalMC;
#endif
#ifdef ENABLE_CLIPPING_POLYGONS
vec2 sphericalLatLong = czm_approximateSphericalCoordinates(position3DWC);
sphericalLatLong.y = czm_branchFreeTernary(sphericalLatLong.y < czm_pi, sphericalLatLong.y, sphericalLatLong.y - czm_twoPi);
vec2 minDistance = vec2(czm_infinity);
v_clippingPosition = vec2(czm_infinity);
v_regionIndex = -1;
for (int regionIndex = 0; regionIndex < CLIPPING_POLYGON_REGIONS_LENGTH; regionIndex++) {
vec4 extents = unpackClippingExtents(u_clippingExtents, regionIndex);
vec2 rectUv = (sphericalLatLong.yx - extents.yx) * extents.wz;
vec2 clamped = clamp(rectUv, vec2(0.0), vec2(1.0));
vec2 distance = abs(rectUv - clamped) * extents.wz;
float threshold = 0.01;
if (minDistance.x > distance.x || minDistance.y > distance.y) {
minDistance = distance;
v_clippingPosition = rectUv;
if (rectUv.x > threshold && rectUv.y > threshold && rectUv.x < 1.0 - threshold && rectUv.y < 1.0 - threshold) {
v_regionIndex = regionIndex;
}
}
}
#endif
#if defined(FOG) || (defined(GROUND_ATMOSPHERE) && !defined(PER_FRAGMENT_GROUND_ATMOSPHERE))
bool dynamicLighting = false;
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_DAYNIGHT_SHADING) || defined(ENABLE_VERTEX_LIGHTING))
dynamicLighting = true;
#endif
#if defined(DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN)
vec3 atmosphereLightDirection = czm_sunDirectionWC;
#else
vec3 atmosphereLightDirection = czm_lightDirectionWC;
#endif
vec3 lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(position3DWC));
computeAtmosphereScattering(
position3DWC,
lightDirection,
v_atmosphereRayleighColor,
v_atmosphereMieColor,
v_atmosphereOpacity
);
#endif
#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT)
v_distance = length((czm_modelView3D * vec4(position3DWC, 1.0)).xyz);
#endif
#ifdef APPLY_MATERIAL
float northPoleZ = czm_ellipsoidRadii.z;
vec3 northPolePositionMC = vec3(0.0, 0.0, northPoleZ);
vec3 vectorEastMC = normalize(cross(northPolePositionMC - v_positionMC, ellipsoidNormal));
float dotProd = abs(dot(ellipsoidNormal, v_normalMC));
v_slope = acos(dotProd);
vec3 normalRejected = ellipsoidNormal * dotProd;
vec3 normalProjected = v_normalMC - normalRejected;
vec3 aspectVector = normalize(normalProjected);
v_aspect = acos(dot(aspectVector, vectorEastMC));
float determ = dot(cross(vectorEastMC, aspectVector), ellipsoidNormal);
v_aspect = czm_branchFreeTernary(determ < 0.0, 2.0 * czm_pi - v_aspect, v_aspect);
v_height = height;
#endif
}
`,DB=`void computeAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity) {
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);
czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);
float atmosphereInnerRadius = length(positionWC);
computeScattering(
primaryRay,
length(cameraToPositionWC),
lightDirection,
atmosphereInnerRadius,
rayleighColor,
mieColor,
opacity
);
}
`,M1e=`uniform sampler2D u_texture;
in vec2 v_textureCoordinates;
void main()
{
out_FragColor = texture(u_texture, v_textureCoordinates);
}
`,F1e=`in vec4 position;
in float webMercatorT;
uniform vec2 u_textureDimensions;
out vec2 v_textureCoordinates;
void main()
{
v_textureCoordinates = vec2(position.x, webMercatorT);
gl_Position = czm_viewportOrthographic * (position * vec4(u_textureDimensions, 1.0, 1.0));
}
`,PB=`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);
}
void computeAtmosphereScattering(vec3 positionWC, vec3 lightDirection, out vec3 rayleighColor, out vec3 mieColor, out float opacity, out float underTranslucentGlobe)
{
float ellipsoidRadiiDifference = czm_ellipsoidRadii.x - czm_ellipsoidRadii.z;
// Adjustment to the atmosphere radius applied based on the camera height.
float distanceAdjustMin = czm_ellipsoidRadii.x / 4.0;
float distanceAdjustMax = czm_ellipsoidRadii.x;
float distanceAdjustModifier = ellipsoidRadiiDifference / 2.0;
float distanceAdjust = distanceAdjustModifier * clamp((czm_eyeHeight - distanceAdjustMin) / (distanceAdjustMax - distanceAdjustMin), 0.0, 1.0);
// Since atmosphere scattering assumes the atmosphere is a spherical shell, we compute an inner radius of the atmosphere best fit
// for the position on the ellipsoid.
float radiusAdjust = (ellipsoidRadiiDifference / 4.0) + distanceAdjust;
float atmosphereInnerRadius = (length(czm_viewerPositionWC) - czm_eyeHeight) - radiusAdjust;
// Setup the primary ray: from the camera position to the vertex position.
vec3 cameraToPositionWC = positionWC - czm_viewerPositionWC;
vec3 cameraToPositionWCDirection = normalize(cameraToPositionWC);
czm_ray primaryRay = czm_ray(czm_viewerPositionWC, cameraToPositionWCDirection);
underTranslucentGlobe = 0.0;
// Brighten the sky atmosphere under the Earth's atmosphere when translucency is enabled.
#if defined(GLOBE_TRANSLUCENT)
// Check for intersection with the inner radius of the atmopshere.
czm_raySegment primaryRayEarthIntersect = czm_raySphereIntersectionInterval(primaryRay, vec3(0.0), atmosphereInnerRadius + radiusAdjust);
if (primaryRayEarthIntersect.start > 0.0 && primaryRayEarthIntersect.stop > 0.0) {
// Compute position on globe.
vec3 direction = normalize(positionWC);
czm_ray ellipsoidRay = czm_ray(positionWC, -direction);
czm_raySegment ellipsoidIntersection = czm_rayEllipsoidIntersectionInterval(ellipsoidRay, vec3(0.0), czm_ellipsoidInverseRadii);
vec3 onEarth = positionWC - (direction * ellipsoidIntersection.start);
// Control the color using the camera angle.
float angle = dot(normalize(czm_viewerPositionWC), normalize(onEarth));
// Control the opacity using the distance from Earth.
opacity = interpolateByDistance(vec4(0.0, 1.0, czm_ellipsoidRadii.x, 0.0), length(czm_viewerPositionWC - onEarth));
vec3 horizonColor = vec3(0.1, 0.2, 0.3);
vec3 nearColor = vec3(0.0);
rayleighColor = mix(nearColor, horizonColor, exp(-angle) * opacity);
// Set the traslucent flag to avoid alpha adjustment in computeFinalColor funciton.
underTranslucentGlobe = 1.0;
return;
}
#endif
computeScattering(
primaryRay,
length(cameraToPositionWC),
lightDirection,
atmosphereInnerRadius,
rayleighColor,
mieColor,
opacity
);
// Alter the opacity based on how close the viewer is to the ground.
// (0.0 = At edge of atmosphere, 1.0 = On ground)
float cameraHeight = czm_eyeHeight + atmosphereInnerRadius;
float atmosphereOuterRadius = atmosphereInnerRadius + ATMOSPHERE_THICKNESS;
opacity = clamp((atmosphereOuterRadius - cameraHeight) / (atmosphereOuterRadius - atmosphereInnerRadius), 0.0, 1.0);
// Alter alpha based on time of day (0.0 = night , 1.0 = day)
float nightAlpha = (u_radiiAndDynamicAtmosphereColor.z != 0.0) ? clamp(dot(normalize(positionWC), lightDirection), 0.0, 1.0) : 1.0;
opacity *= pow(nightAlpha, 0.5);
}
`,B1e=`in vec3 v_outerPositionWC;
uniform vec3 u_hsbShift;
#ifndef PER_FRAGMENT_ATMOSPHERE
in vec3 v_mieColor;
in vec3 v_rayleighColor;
in float v_opacity;
in float v_translucent;
#endif
void main (void)
{
float lightEnum = u_radiiAndDynamicAtmosphereColor.z;
vec3 lightDirection = czm_getDynamicAtmosphereLightDirection(v_outerPositionWC, lightEnum);
vec3 mieColor;
vec3 rayleighColor;
float opacity;
float translucent;
#ifdef PER_FRAGMENT_ATMOSPHERE
computeAtmosphereScattering(
v_outerPositionWC,
lightDirection,
rayleighColor,
mieColor,
opacity,
translucent
);
#else
mieColor = v_mieColor;
rayleighColor = v_rayleighColor;
opacity = v_opacity;
translucent = v_translucent;
#endif
vec4 color = computeAtmosphereColor(v_outerPositionWC, lightDirection, rayleighColor, mieColor, opacity);
#ifndef HDR
color.rgb = czm_acesTonemapping(color.rgb);
color.rgb = czm_inverseGamma(color.rgb);
#endif
#ifdef COLOR_CORRECT
const bool ignoreBlackPixels = true;
color.rgb = czm_applyHSBShift(color.rgb, u_hsbShift, ignoreBlackPixels);
#endif
// For the parts of the sky atmosphere that are not behind a translucent globe,
// we mix in the default opacity so that the sky atmosphere still appears at distance.
// This is needed because the opacity in the sky atmosphere is initially adjusted based
// on the camera height.
if (translucent == 0.0) {
color.a = mix(color.b, 1.0, color.a) * smoothstep(0.0, 1.0, czm_morphTime);
}
out_FragColor = color;
}
`,z1e=`in vec4 position;
out vec3 v_outerPositionWC;
#ifndef PER_FRAGMENT_ATMOSPHERE
out vec3 v_mieColor;
out vec3 v_rayleighColor;
out float v_opacity;
out float v_translucent;
#endif
void main(void)
{
vec4 positionWC = czm_model * position;
float lightEnum = u_radiiAndDynamicAtmosphereColor.z;
vec3 lightDirection = czm_getDynamicAtmosphereLightDirection(positionWC.xyz, lightEnum);
#ifndef PER_FRAGMENT_ATMOSPHERE
computeAtmosphereScattering(
positionWC.xyz,
lightDirection,
v_rayleighColor,
v_mieColor,
v_opacity,
v_translucent
);
#endif
v_outerPositionWC = positionWC.xyz;
gl_Position = czm_modelViewProjection * position;
}
`,U1e=`uniform samplerCube u_cubeMap;
in vec3 v_texCoord;
void main()
{
vec4 color = czm_textureCube(u_cubeMap, normalize(v_texCoord));
out_FragColor = vec4(czm_gammaCorrect(color).rgb, czm_morphTime);
}
`,k1e=`in vec3 position;
out vec3 v_texCoord;
void main()
{
vec3 p = czm_viewRotation * (czm_temeToPseudoFixed * (czm_entireFrustum.y * position));
gl_Position = czm_projection * vec4(p, 1.0);
v_texCoord = position.xyz;
}
`,V1e=`uniform sampler2D u_texture;
in vec2 v_textureCoordinates;
void main()
{
vec4 color = texture(u_texture, v_textureCoordinates);
out_FragColor = czm_gammaCorrect(color);
}
`,H1e=`uniform float u_radiusTS;
in vec2 v_textureCoordinates;
vec2 rotate(vec2 p, vec2 direction)
{
return vec2(p.x * direction.x - p.y * direction.y, p.x * direction.y + p.y * direction.x);
}
vec4 addBurst(vec2 position, vec2 direction, float lengthScalar)
{
vec2 rotatedPosition = rotate(position, direction) * vec2(25.0, 0.75);
float radius = length(rotatedPosition) * lengthScalar;
float burst = 1.0 - smoothstep(0.0, 0.55, radius);
return vec4(burst);
}
void main()
{
float lengthScalar = 2.0 / sqrt(2.0);
vec2 position = v_textureCoordinates - vec2(0.5);
float radius = length(position) * lengthScalar;
float surface = step(radius, u_radiusTS);
vec4 color = vec4(vec2(1.0), surface + 0.2, surface);
float glow = 1.0 - smoothstep(0.0, 0.55, radius);
color.ba += mix(vec2(0.0), vec2(1.0), glow) * 0.75;
vec4 burst = vec4(0.0);
// The following loop has been manually unrolled for speed, to
// avoid sin() and cos().
//
//for (float i = 0.4; i < 3.2; i += 1.047) {
// vec2 direction = vec2(sin(i), cos(i));
// burst += 0.4 * addBurst(position, direction, lengthScalar);
//
// direction = vec2(sin(i - 0.08), cos(i - 0.08));
// burst += 0.3 * addBurst(position, direction, lengthScalar);
//}
burst += 0.4 * addBurst(position, vec2(0.38942, 0.92106), lengthScalar); // angle == 0.4
burst += 0.4 * addBurst(position, vec2(0.99235, 0.12348), lengthScalar); // angle == 0.4 + 1.047
burst += 0.4 * addBurst(position, vec2(0.60327, -0.79754), lengthScalar); // angle == 0.4 + 1.047 * 2.0
burst += 0.3 * addBurst(position, vec2(0.31457, 0.94924), lengthScalar); // angle == 0.4 - 0.08
burst += 0.3 * addBurst(position, vec2(0.97931, 0.20239), lengthScalar); // angle == 0.4 + 1.047 - 0.08
burst += 0.3 * addBurst(position, vec2(0.66507, -0.74678), lengthScalar); // angle == 0.4 + 1.047 * 2.0 - 0.08
// End of manual loop unrolling.
color += clamp(burst, vec4(0.0), vec4(1.0)) * 0.15;
out_FragColor = clamp(color, vec4(0.0), vec4(1.0));
}
`,G1e=`in vec2 direction;
uniform float u_size;
out vec2 v_textureCoordinates;
void main()
{
vec4 position;
if (czm_morphTime == 1.0)
{
position = vec4(czm_sunPositionWC, 1.0);
}
else
{
position = vec4(czm_sunPositionColumbusView.zxy, 1.0);
}
vec4 positionEC = czm_view * position;
vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);
vec2 halfSize = vec2(u_size * 0.5);
halfSize *= ((direction * 2.0) - 1.0);
gl_Position = czm_viewportOrthographic * vec4(positionWC.xy + halfSize, -positionWC.z, 1.0);
v_textureCoordinates = direction;
}
`;function DD(e){let t;const n=e.name,i=e.message;c(n)&&c(i)?t=`${n}: ${i}`:t=e.toString();const o=e.stack;return c(o)&&(t+=`
${o}`),t}const j1e={NONE:0,LERC:1},PD=Object.freeze(j1e),W1e={NONE:0,BITS12:1},Pa=Object.freeze(W1e),Vf=new d,q1e=new d,ac=new H,qT=new L,Y1e=new L,$1e=Math.pow(2,12);function Oo(e,t,n,i,o,r,s,a,l,u){let h=Pa.NONE,f,_;if(c(t)&&c(n)&&c(i)&&c(o)){const g=t.minimum,m=t.maximum,b=d.subtract(m,g,q1e),T=i-n;Math.max(d.maximumComponent(b),T)<$1e-1?h=Pa.BITS12:h=Pa.NONE,f=L.inverseTransformation(o,new L);const C=d.negate(g,Vf);L.multiply(L.fromTranslation(C,qT),f,f);const w=Vf;w.x=1/b.x,w.y=1/b.y,w.z=1/b.z,L.multiply(L.fromScale(w,qT),f,f),_=L.clone(o),L.setTranslation(_,d.ZERO,_),o=L.clone(o,new L);const v=L.fromTranslation(g,qT),P=L.fromScale(b,Y1e),N=L.multiply(v,P,qT);L.multiply(o,N,o),L.multiply(_,N,_)}this.quantization=h,this.minimumHeight=n,this.maximumHeight=i,this.center=d.clone(e),this.toScaledENU=f,this.fromScaledENU=o,this.matrix=_,this.hasVertexNormals=r,this.hasWebMercatorT=y(s,!1),this.hasGeodeticSurfaceNormals=y(a,!1),this.exaggeration=y(l,1),this.exaggerationRelativeHeight=y(u,0),this.stride=0,this._offsetGeodeticSurfaceNormal=0,this._offsetVertexNormal=0,this._calculateStrideAndOffsets()}Oo.prototype.encode=function(e,t,n,i,o,r,s,a){const l=i.x,u=i.y;if(this.quantization===Pa.BITS12){n=L.multiplyByPoint(this.toScaledENU,n,Vf),n.x=R.clamp(n.x,0,1),n.y=R.clamp(n.y,0,1),n.z=R.clamp(n.z,0,1);const h=this.maximumHeight-this.minimumHeight,f=R.clamp((o-this.minimumHeight)/h,0,1);H.fromElements(n.x,n.y,ac);const _=En.compressTextureCoordinates(ac);H.fromElements(n.z,f,ac);const g=En.compressTextureCoordinates(ac);H.fromElements(l,u,ac);const m=En.compressTextureCoordinates(ac);if(e[t++]=_,e[t++]=g,e[t++]=m,this.hasWebMercatorT){H.fromElements(s,0,ac);const b=En.compressTextureCoordinates(ac);e[t++]=b}}else d.subtract(n,this.center,Vf),e[t++]=Vf.x,e[t++]=Vf.y,e[t++]=Vf.z,e[t++]=o,e[t++]=l,e[t++]=u,this.hasWebMercatorT&&(e[t++]=s);return this.hasVertexNormals&&(e[t++]=En.octPackFloat(r)),this.hasGeodeticSurfaceNormals&&(e[t++]=a.x,e[t++]=a.y,e[t++]=a.z),t};const X1e=new d,_9=new d;Oo.prototype.addGeodeticSurfaceNormals=function(e,t,n){if(this.hasGeodeticSurfaceNormals)return;const i=this.stride,o=e.length/i;this.hasGeodeticSurfaceNormals=!0,this._calculateStrideAndOffsets();const r=this.stride;for(let s=0;s<o;s++){for(let h=0;h<i;h++){const f=s*i+h,_=s*r+h;t[_]=e[f]}const a=this.decodePosition(t,s,X1e),l=n.geodeticSurfaceNormal(a,_9),u=s*r+this._offsetGeodeticSurfaceNormal;t[u]=l.x,t[u+1]=l.y,t[u+2]=l.z}};Oo.prototype.removeGeodeticSurfaceNormals=function(e,t){if(!this.hasGeodeticSurfaceNormals)return;const n=this.stride,i=e.length/n;this.hasGeodeticSurfaceNormals=!1,this._calculateStrideAndOffsets();const o=this.stride;for(let r=0;r<i;r++)for(let s=0;s<o;s++){const a=r*n+s,l=r*o+s;t[l]=e[a]}};Oo.prototype.decodePosition=function(e,t,n){if(c(n)||(n=new d),t*=this.stride,this.quantization===Pa.BITS12){const i=En.decompressTextureCoordinates(e[t],ac);n.x=i.x,n.y=i.y;const o=En.decompressTextureCoordinates(e[t+1],ac);return n.z=o.x,L.multiplyByPoint(this.fromScaledENU,n,n)}return n.x=e[t],n.y=e[t+1],n.z=e[t+2],d.add(n,this.center,n)};Oo.prototype.getExaggeratedPosition=function(e,t,n){n=this.decodePosition(e,t,n);const i=this.exaggeration,o=this.exaggerationRelativeHeight;if(i!==1&&this.hasGeodeticSurfaceNormals){const s=this.decodeGeodeticSurfaceNormal(e,t,_9),a=this.decodeHeight(e,t),l=oa.getHeight(a,i,o)-a;n.x+=s.x*l,n.y+=s.y*l,n.z+=s.z*l}return n};Oo.prototype.decodeTextureCoordinates=function(e,t,n){return c(n)||(n=new H),t*=this.stride,this.quantization===Pa.BITS12?En.decompressTextureCoordinates(e[t+2],n):H.fromElements(e[t+4],e[t+5],n)};Oo.prototype.decodeHeight=function(e,t){return t*=this.stride,this.quantization===Pa.BITS12?En.decompressTextureCoordinates(e[t+1],ac).y*(this.maximumHeight-this.minimumHeight)+this.minimumHeight:e[t+3]};Oo.prototype.decodeWebMercatorT=function(e,t){return t*=this.stride,this.quantization===Pa.BITS12?En.decompressTextureCoordinates(e[t+3],ac).x:e[t+6]};Oo.prototype.getOctEncodedNormal=function(e,t,n){t=t*this.stride+this._offsetVertexNormal;const i=e[t]/256,o=Math.floor(i),r=(i-o)*2
`,l+=n?oLe(i):rLe(i),l}function oLe(e){return`float clip(vec4 fragCoord, sampler2D clippingPlanes, mat4 clippingPlanesMatrix)
{
vec4 position = czm_windowToEyeCoordinates(fragCoord);
vec3 clipNormal = vec3(0.0);
vec3 clipPosition = vec3(0.0);
float clipAmount;
float pixelWidth = czm_metersPerPixel(position);
bool breakAndDiscard = false;
for (int i = 0; i < ${e}; ++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;
}
`}function rLe(e){return`float clip(vec4 fragCoord, sampler2D clippingPlanes, mat4 clippingPlanesMatrix)
{
bool clipped = true;
vec4 position = czm_windowToEyeCoordinates(fragCoord);
vec3 clipNormal = vec3(0.0);
vec3 clipPosition = vec3(0.0);
float clipAmount = 0.0;
float pixelWidth = czm_metersPerPixel(position);
for (int i = 0; i < ${e}; ++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;
}
`}function sLe(e,t){const n=1/e,i=1/t;let o=`${n}`;o.indexOf(".")===-1&&(o+=".0");let r=`${i}`;return r.indexOf(".")===-1&&(r+=".0"),`vec4 getClippingPlane(highp sampler2D packedClippingPlanes, int clippingPlaneNumber, mat4 transform)
{
int pixY = clippingPlaneNumber / ${e};
int pixX = clippingPlaneNumber - (pixY * ${e});
float u = (float(pixX) + 0.5) * ${o};
float v = (float(pixY) + 0.5) * ${r};
vec4 plane = texture(packedClippingPlanes, vec2(u, v));
return czm_transformPlane(plane, transform);
}
`}function aLe(e,t){const n=1/e,i=1/t;let o=`${n}`;o.indexOf(".")===-1&&(o+=".0");let r=`${i}`;return r.indexOf(".")===-1&&(r+=".0"),`vec4 getClippingPlane(highp sampler2D packedClippingPlanes, int clippingPlaneNumber, mat4 transform)
{
int clippingPlaneStartIndex = clippingPlaneNumber * 2;
int pixY = clippingPlaneStartIndex / ${e};
int pixX = clippingPlaneStartIndex - (pixY * ${e});
float u = (float(pixX) + 0.5) * ${o};
float v = (float(pixY) + 0.5) * ${r};
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 + ${o}, v)));
return czm_transformPlane(plane, transform);
}
`}function cLe(e,t,n,i,o,r){this.numberOfDayTextures=e,this.flags=t,this.material=n,this.shaderProgram=i,this.clippingShaderState=o,this.clippingPolygonShaderState=r}function m1(){this.baseVertexShaderSource=void 0,this.baseFragmentShaderSource=void 0,this._shadersByTexturesFlags=[],this.material=void 0}function lLe(e){const t="vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPosition3DMode(position, height, textureCoordinates); }",n="vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPositionColumbusViewMode(position, height, textureCoordinates); }",i="vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPositionMorphingMode(position, height, textureCoordinates); }";let o;switch(e){case oe.SCENE3D:o=t;break;case oe.SCENE2D:case oe.COLUMBUS_VIEW:o=n;break;case oe.MORPHING:o=i;break}return o}function uLe(e){return e.webgl2?`void clipPolygons(highp sampler2D clippingDistance, int regionsLength, vec2 clippingPosition, int regionIndex) {
czm_clipPolygons(clippingDistance, regionsLength, clippingPosition, regionIndex);
}`:`void clipPolygons(highp sampler2D clippingDistance, int regionsLength, vec2 clippingPosition, int regionIndex) {
}`}function dLe(e){return e.webgl2?`vec4 unpackClippingExtents(highp sampler2D extentsTexture, int index) {
return czm_unpackClippingExtents(extentsTexture, index);
}`:`vec4 unpackClippingExtents(highp sampler2D extentsTexture, int index) {
return vec4();
}`}function hLe(e){return e?"float get2DYPositionFraction(vec2 textureCoordinates) { return get2DMercatorYPositionFraction(textureCoordinates); }":"float get2DYPositionFraction(vec2 textureCoordinates) { return get2DGeographicYPositionFraction(textureCoordinates); }"}m1.prototype.getShaderProgram=function(e){const t=e.frameState,n=e.surfaceTile,i=e.numberOfDayTextures,o=e.applyBrightness,r=e.applyContrast,s=e.applyHue,a=e.applySaturation,l=e.applyGamma,u=e.applyAlpha,h=e.applyDayNightAlpha,f=e.applySplit,_=e.showReflectiveOcean,g=e.showOceanWaves,m=e.enableLighting,b=e.dynamicAtmosphereLighting,T=e.dynamicAtmosphereLightingFromSun,x=e.showGroundAtmosphere,C=e.perFragmentGroundAtmosphere,w=e.hasVertexNormals,v=e.useWebMercatorProjection,P=e.enableFog,N=e.enableClippingPlanes,k=e.clippingPlanes,M=e.enableClippingPolygons,U=e.clippingPolygons,B=e.clippedByBoundaries,S=e.hasImageryLayerCutout,D=e.colorCorrect,p=e.highlightFillTile,I=e.colorToAlpha,O=e.hasGeodeticSurfaceNormals,F=e.hasExaggeration,V=e.showUndergroundColor,G=e.translucent;let j=0,W="";const q=n.renderedMesh.encoding;q.quantization===Pa.BITS12&&(j=1,W="QUANTIZATION_BITS12");let Y=0,ne="";B&&(Y=1,ne="TILE_LIMIT_RECTANGLE");let Q=0,le="";S&&(Q=1,le="APPLY_IMAGERY_CUTOUT");const pe=t.mode,re=pe|o<<2|r<<3|s<<4|a<<5|l<<6|u<<7|_<<8|g<<9|m<<10|b<<11|T<<12|x<<13|C<<14|w<<15|v<<16|P<<17|j<<18|f<<19|N<<20|M<<21|Y<<22|Q<<23|D<<24|p<<25|I<<26|O<<27|F<<28|V<<29|G<<30|h<<31;let de=0;c(k)&&k.length>0&&(de=N?k.clippingPlanesState:0);let fe=0;c(U)&&U.length>0&&(fe=M?U.clippingPolygonsState:0);let ye=n.surfaceShader;if(c(ye)&&ye.numberOfDayTextures===i&&ye.flags===re&&ye.material===this.material&&ye.clippingShaderState===de&&ye.clippingPolygonShaderState===fe)return ye.shaderProgram;let Ce=this._shadersByTexturesFlags[i];if(c(Ce)||(Ce=this._shadersByTexturesFlags[i]=[]),ye=Ce[re],!c(ye)||ye.material!==this.material||ye.clippingShaderState!==de||ye.clippingPolygonShaderState!==fe){const we=this.baseVertexShaderSource.clone(),Pe=this.baseFragmentShaderSource.clone();de!==0&&Pe.sources.unshift(p1(k,t.context)),fe!==0&&(Pe.sources.unshift(uLe(t.context)),we.sources.unshift(dLe(t.context))),we.defines.push(W),Pe.defines.push(`TEXTURE_UNITS ${i}`,ne,le),o&&Pe.defines.push("APPLY_BRIGHTNESS"),r&&Pe.defines.push("APPLY_CONTRAST"),s&&Pe.defines.push("APPLY_HUE"),a&&Pe.defines.push("APPLY_SATURATION"),l&&Pe.defines.push("APPLY_GAMMA"),u&&Pe.defines.push("APPLY_ALPHA"),h&&Pe.defines.push("APPLY_DAY_NIGHT_ALPHA"),_&&(Pe.defines.push("SHOW_REFLECTIVE_OCEAN"),we.defines.push("SHOW_REFLECTIVE_OCEAN")),g&&Pe.defines.push("SHOW_OCEAN_WAVES"),I&&Pe.defines.push("APPLY_COLOR_TO_ALPHA"),V&&(we.defines.push("UNDERGROUND_COLOR"),Pe.defines.push("UNDERGROUND_COLOR")),G&&(we.defines.push("TRANSLUCENT"),Pe.defines.push("TRANSLUCENT")),m&&(w?(we.defines.push("ENABLE_VERTEX_LIGHTING"),Pe.defines.push("ENABLE_VERTEX_LIGHTING")):(we.defines.push("ENABLE_DAYNIGHT_SHADING"),Pe.defines.push("ENABLE_DAYNIGHT_SHADING"))),b&&(we.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING"),Pe.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING"),T&&(we.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN"),Pe.defines.push("DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN"))),x&&(we.defines.push("GROUND_ATMOSPHERE"),Pe.defines.push("GROUND_ATMOSPHERE"),C&&(we.defines.push("PER_FRAGMENT_GROUND_ATMOSPHERE"),Pe.defines.push("PER_FRAGMENT_GROUND_ATMOSPHERE"))),we.defines.push("INCLUDE_WEB_MERCATOR_Y"),Pe.defines.push("INCLUDE_WEB_MERCATOR_Y"),P&&(we.defines.push("FOG"),Pe.defines.push("FOG")),f&&Pe.defines.push("APPLY_SPLIT"),N&&Pe.defines.push("ENABLE_CLIPPING_PLANES"),M&&(Pe.defines.push("ENABLE_CLIPPING_POLYGONS"),we.defines.push("ENABLE_CLIPPING_POLYGONS"),U.inverse&&Pe.defines.push("CLIPPING_INVERSE"),Pe.defines.push(`CLIPPING_POLYGON_REGIONS_LENGTH ${U.extentsCount}`),we.defines.push(`CLIPPING_POLYGON_REGIONS_LENGTH ${U.extentsCount}`)),D&&Pe.defines.push("COLOR_CORRECT"),p&&Pe.defines.push("HIGHLIGHT_FILL_TILE"),O&&we.defines.push("GEODETIC_SURFACE_NORMALS"),F&&we.defines.push("EXAGGERATION");let lt=` vec4 computeDayColor(vec4 initialColor, vec
{
vec4 color = initialColor;
`;S&&(lt+=` vec4 cutoutAndColorResult;
bool texelUnclipped;
`);for(let We=0;We<i;++We)S?lt+=` cutoutAndColorResult = u_dayTextureCutoutRectangles[${We}];
texelUnclipped = v_textureCoordinates.x < cutoutAndColorResult.x || cutoutAndColorResult.z < v_textureCoordinates.x || v_textureCoordinates.y < cutoutAndColorResult.y || cutoutAndColorResult.w < v_textureCoordinates.y;
cutoutAndColorResult = sampleAndBlend(
`:lt+=` color = sampleAndBlend(
`,lt+=` color,
u_dayTextures[${We}],
u_dayTextureUseWebMercatorT[${We}] ? textureCoordinates.xz : textureCoordinates.xy,
u_dayTextureTexCoordsRectangle[${We}],
u_dayTextureTranslationAndScale[${We}],
${u?`u_dayTextureAlpha[${We}]`:"1.0"},
${h?`u_dayTextureNightAlpha[${We}]`:"1.0"},
${h?`u_dayTextureDayAlpha[${We}]`:"1.0"},
${o?`u_dayTextureBrightness[${We}]`:"0.0"},
${r?`u_dayTextureContrast[${We}]`:"0.0"},
${s?`u_dayTextureHue[${We}]`:"0.0"},
${a?`u_dayTextureSaturation[${We}]`:"0.0"},
${l?`u_dayTextureOneOverGamma[${We}]`:"0.0"},
${f?`u_dayTextureSplit[${We}]`:"0.0"},
${I?`u_colorsToAlpha[${We}]`:"vec4(0.0)"},
nightBlend );
`,S&&(lt+=` color = czm_branchFreeTernary(texelUnclipped, cutoutAndColorResult, color);
`);lt+=` return color;
}`,Pe.sources.push(lt),we.sources.push(lLe(pe)),we.sources.push(hLe(v));const ft=Jt.fromCache({context:t.context,vertexShaderSource:we,fragmentShaderSource:Pe,attributeLocations:q.getAttributeLocations()});ye=Ce[re]=new cLe(i,re,this.material,ft,de,fe)}return n.surfaceShader=ye,ye.shaderProgram};m1.prototype.destroy=function(){let e,t;const n=this._shadersByTexturesFlags;for(const i in n)if(n.hasOwnProperty(i)){const o=n[i];if(!c(o))continue;for(e in o)o.hasOwnProperty(e)&&(t=o[e],c(t)&&t.shaderProgram.destroy())}return ve(this)};const fLe={NONE:-1,PARTIAL:0,FULL:1},ir=Object.freeze(fLe);function Er(e,t,n,i,o,r,s){this.provider=e,this.message=t,this.x=n,this.y=i,this.level=o,this.timesRetried=y(r,0),this.retry=!1,this.error=s}Er.reportError=function(e,t,n,i,o,r,s,a){let l=e;return c(e)?(l.provider=t,l.message=i,l.x=o,l.y=r,l.level=s,l.retry=!1,l.error=a,++l.timesRetried):l=new Er(t,i,o,r,s,0,a),c(n)&&n.numberOfListeners>0?n.raiseEvent(l):c(t)&&console.log(`An error occurred in "${t.constructor.name}": ${DD(i)}`),l};Er.reportSuccess=function(e){c(e)&&(e.timesRetried=-1)};const pLe={UNLOADED:0,TRANSITIONING:1,RECEIVED:2,TEXTURE_LOADED:3,READY:4,FAILED:5,INVALID:6,PLACEHOLDER:7},Rn=Object.freeze(pLe),mLe={START:0,LOADING:1,DONE:2,FAILED:3},Mc=Object.freeze(mLe),_Le={FAILED:0,UNLOADED:1,RECEIVING:2,RECEIVED:3,TRANSFORMING:4,TRANSFORMED:5,READY:6},yi=Object.freeze(_Le);function Yn(){this.imagery=[],this.waterMaskTexture=void 0,this.waterMaskTranslationAndScale=new te(0,0,1,1),this.terrainData=void 0,this.vertexArray=void 0,this.tileBoundingRegion=void 0,this.occludeePointInScaledSpace=new d,this.boundingVolumeSourceTile=void 0,this.boundingVolumeIsFromMesh=!1,this.terrainState=yi.UNLOADED,this.mesh=void 0,this.fill=void 0,this.pickBoundingSphere=new se,this.surfaceShader=void 0,this.isClipped=!0,this.clippedByBoundaries=!1}Object.defineProperties(Yn.prototype,{eligibleForUnloading:{get:function(){const e=this.terrainState;let n=!(e===yi.RECEIVING||e===yi.TRANSFORMING);const i=this.imagery;for(let o=0,r=i.length;n&&o<r;++o){const s=i[o];n=!c(s.loadingImagery)||s.loadingImagery.state!==Rn.TRANSITIONING}return n}},renderedMesh:{get:function(){if(c(this.vertexArray))return this.mesh;if(c(this.fill))return this.fill.mesh}}});const gLe=new he;function hv(e,t,n,i,o,r){let s=e.getExaggeratedPosition(i,o,r);if(c(t)&&t!==oe.SCENE3D){const l=n.ellipsoid.cartesianToCartographic(s,gLe);s=n.project(l,r),s=d.fromElements(s.z,s.x,s.y,r)}return s}const yLe=new d,bLe=new d,TLe=new d;Yn.prototype.pick=function(e,t,n,i,o){const r=this.renderedMesh;if(!c(r))return;const s=r.vertices,a=r.indices,l=r.encoding,u=a.length;let h=Number.MAX_VALUE;for(let f=0;f<u;f+=3){const _=a[f],g=a[f+1],m=a[f+2],b=hv(l,t,n,s,_,yLe),T=hv(l,t,n,s,g,bLe),x=hv(l,t,n,s,m,TLe),C=Ei.rayTriangleParametric(e,b,T,x,i);c(C)&&C<h&&C>=0&&(h=C)}return h!==Number.MAX_VALUE?nn.getPoint(e,h,o):void 0};Yn.prototype.freeResources=function(){c(this.waterMaskTexture)&&(--this.waterMaskTexture.referenceCount,this.waterMaskTexture.referenceCount===0&&this.waterMaskTexture.destroy(),this.waterMaskTexture=void 0),this.terrainData=void 0,this.terrainState=yi.UNLOADED,this.mesh=void 0,this.fill=this.fill&&this.fill.destroy();const e=this.imagery;for(let t=0,n=e.length;t<n;++t)e[t].freeResources();this.imagery.length=0,this.freeVertexArray()};Yn.prototype.freeVertexArray=function(){Yn._freeVertexArray(this.vertexArray),this.vertexArray=void 0,Yn._freeVertexArray(this.wireframeVertexArray),this.wireframeVertexArray=void 0};Yn.initialize=function(e,t,n){let i=e.data;c(i)||(i=e.data=new Yn),e.state===Mc.START&&(ALe(e,t,n),e.state=Mc.LOADING)};Yn.processStateMachine=function(e,t,n,i,o,r,s){Yn.initialize(e,n,i);const a=e.data;if(e.state===Mc.LOADING&&xLe(e,t,n,i,o,r),s)return;const l=e.renderable;e.renderable=c(a.vertexArray);const u=a.terrainState===yi.READY;e.upsampledFromParent=c(a.terrainData)&&a.terrainData.wasCreatedByUpsampling();const h=a.processImagery(e,n,t);if(u&&h){const f=e._loadedCallbacks,_={};for(const g in f)f.hasOwnProperty(g)&&(f[g](e)||(_[g]=f[g]));e._loadedCallbacks=_,e.st
`,n}function I2e(e){let t="";t+=ts(".cesium-credit-lightbox-overlay",{display:"none","z-index":"1",position:"absolute",top:"0",left:"0",width:"100%",height:"100%","background-color":"rgba(80, 80, 80, 0.8)"}),t+=ts(".cesium-credit-lightbox",{"background-color":"#303336",color:iy,position:"relative","min-height":`${E2e}px`,margin:"auto"}),t+=ts(".cesium-credit-lightbox > ul > li a, .cesium-credit-lightbox > ul > li a:visited",{color:iy}),t+=ts(".cesium-credit-lightbox > ul > li a:hover",{color:Sv}),t+=ts(".cesium-credit-lightbox.cesium-credit-lightbox-expanded",{border:"1px solid #444","border-radius":"5px","max-width":"370px"}),t+=ts(".cesium-credit-lightbox.cesium-credit-lightbox-mobile",{height:"100%",width:"100%"}),t+=ts(".cesium-credit-lightbox-title",{padding:"20px 20px 0 20px"}),t+=ts(".cesium-credit-lightbox-close",{"font-size":"18pt",cursor:"pointer",position:"absolute",top:"0",right:"6px",color:iy}),t+=ts(".cesium-credit-lightbox-close:hover",{color:Sv}),t+=ts(".cesium-credit-lightbox > ul",{margin:"0",padding:"12px 20px 12px 40px","font-size":"13px"}),t+=ts(".cesium-credit-lightbox > ul > li",{"padding-bottom":"6px"}),t+=ts(".cesium-credit-lightbox > ul > li *",{padding:"0",margin:"0"}),t+=ts(".cesium-credit-expand-link",{"padding-left":"5px",cursor:"pointer","text-decoration":"underline",color:iy}),t+=ts(".cesium-credit-expand-link:hover",{color:Sv}),t+=ts(".cesium-credit-text",{color:iy}),t+=ts(".cesium-credit-textContainer *, .cesium-credit-logoContainer *",{display:"inline"});function n(r){if(r.shadowRoot)return r.shadowRoot;if(r.getRootNode){const s=r.getRootNode();if(s instanceof ShadowRoot)return s}}const i=y(n(e),document.head),o=document.createElement("style");o.innerHTML=t,i.appendChild(o)}function ki(e,t,n){A.defined("container",e);const i=this;n=y(n,document.body);const o=document.createElement("div");o.className="cesium-credit-lightbox-overlay",n.appendChild(o);const r=document.createElement("div");r.className="cesium-credit-lightbox",o.appendChild(r);function s(m){r.contains(m.target)||i.hideLightbox()}o.addEventListener("click",s,!1);const a=document.createElement("div");a.className="cesium-credit-lightbox-title",a.textContent="Data provided by:",r.appendChild(a);const l=document.createElement("a");l.onclick=this.hideLightbox.bind(this),l.innerHTML="&times;",l.className="cesium-credit-lightbox-close",r.appendChild(l);const u=document.createElement("ul");r.appendChild(u);const h=document.createElement("div");h.className="cesium-credit-logoContainer",h.style.display="inline",e.appendChild(h);const f=document.createElement("div");f.className="cesium-credit-textContainer",f.style.display="inline",e.appendChild(f);const _=document.createElement("a");_.className="cesium-credit-expand-link",_.onclick=this.showLightbox.bind(this),_.textContent="Data attribution",e.appendChild(_),I2e(e);const g=Wt.clone(ki.cesiumCredit);this._delimiter=y(t," \u2022 "),this._screenContainer=f,this._cesiumCreditContainer=h,this._lastViewportHeight=void 0,this._lastViewportWidth=void 0,this._lightboxCredits=r,this._creditList=u,this._lightbox=o,this._hideLightbox=s,this._expandLink=_,this._expanded=!1,this._staticCredits=[],this._cesiumCredit=g,this._previousCesiumCredit=void 0,this._currentCesiumCredit=g,this._creditDisplayElementPool=[],this._creditDisplayElementIndex=0,this._currentFrameCredits={screenCredits:new mt,lightboxCredits:new mt},this._defaultCredit=void 0,this.viewport=n,this.container=e}function vW(e,t,n,i){i=y(i,1);let o=t.get(n.id);if(c(o))o.count<Number.MAX_VALUE&&(o.count+=i);else{const r=e._creditDisplayElementPool,s=e._creditDisplayElementPoolIndex;s<r.length?(o=r[s],o.credit=n,o.count=i):(o=new wW(n,i),r.push(o)),++e._creditDisplayElementPoolIndex,t.set(n.id,o)}}ki.prototype.addCreditToNextFrame=function(e){if(A.defined("credit",e),e.isIon()){c(this._defaultCredit)||(this._defaultCredit=Wt.clone(IW())),this._currentCesiumCredit=this._defaultCredit;return}let t;e.showOnScreen?t=this._currentFrameCredits.screenCredits:t=this._currentFrameCredits.lightboxCredits,vW(this,t,e)};ki.prototype.addStaticCredit=f
{
out_FragColor = vec4(1.0);
}
`,o=new Oe({sources:[f]})):!s&&u&&(f=`void main()
{
out_FragColor = vec4(1.0);
czm_writeLogDepth();
}
`,o=new Oe({defines:["LOG_DEPTH"],sources:[f]})),n=e.shaderCache.createDerivedShaderProgram(t,"depthOnly",{vertexShaderSource:t.vertexShaderSource,fragmentShaderSource:o,attributeLocations:i})}return n}function oBe(e,t){const n=e._depthOnlyRenderStateCache;let i=n[t.id];if(!c(i)){const o=Ue.getState(t);o.depthMask=!0,o.colorMask={red:!1,green:!1,blue:!1,alpha:!1},i=Ue.fromCache(o),n[t.id]=i}return i}sd.createDepthOnlyDerivedCommand=function(e,t,n,i){c(i)||(i={});let o,r;return c(i.depthOnlyCommand)&&(o=i.depthOnlyCommand.shaderProgram,r=i.depthOnlyCommand.renderState),i.depthOnlyCommand=Ze.shallowClone(t,i.depthOnlyCommand),!c(o)||i.shaderProgramId!==t.shaderProgram.id?(i.depthOnlyCommand.shaderProgram=iBe(n,t.shaderProgram),i.depthOnlyCommand.renderState=oBe(e,t.renderState),i.shaderProgramId=t.shaderProgram.id):(i.depthOnlyCommand.shaderProgram=o,i.depthOnlyCommand.renderState=r),i};const rBe=/\s+czm_writeLogDepth\(/,sBe=/\s+czm_vertexLogDepth\(/;function aBe(e,t){if(t.fragmentShaderSource.defines.indexOf("LOG_DEPTH_READ_ONLY")>=0)return t;let i=e.shaderCache.getDerivedShaderProgram(t,"logDepth");if(!c(i)){const o=t._attributeLocations,r=t.vertexShaderSource.clone(),s=t.fragmentShaderSource.clone();r.defines=c(r.defines)?r.defines.slice(0):[],r.defines.push("LOG_DEPTH"),s.defines=c(s.defines)?s.defines.slice(0):[],s.defines.push("LOG_DEPTH");let a,l,u=!1,h=r.sources,f=h.length;for(a=0;a<f;++a)if(sBe.test(h[a])){u=!0;break}if(!u){for(a=0;a<f;++a)h[a]=Oe.replaceMain(h[a],"czm_log_depth_main");l=`
void main()
{
czm_log_depth_main();
czm_vertexLogDepth();
}
`,h.push(l)}for(h=s.sources,f=h.length,u=!1,a=0;a<f;++a)rBe.test(h[a])&&(u=!0);s.defines.indexOf("LOG_DEPTH_WRITE")!==-1&&(u=!0);let _="";if(!u){for(a=0;a<f;a++)h[a]=Oe.replaceMain(h[a],"czm_log_depth_main");_+=`
void main()
{
czm_log_depth_main();
czm_writeLogDepth();
}
`}h.push(_),i=e.shaderCache.createDerivedShaderProgram(t,"logDepth",{vertexShaderSource:r,fragmentShaderSource:s,attributeLocations:o})}return i}sd.createLogDepthCommand=function(e,t,n){c(n)||(n={});let i;return c(n.command)&&(i=n.command.shaderProgram),n.command=Ze.shallowClone(e,n.command),!c(i)||n.shaderProgramId!==e.shaderProgram.id?(n.command.shaderProgram=aBe(t,e.shaderProgram),n.shaderProgramId=e.shaderProgram.id):n.command.shaderProgram=i,n};function cBe(e,t,n){let i=e.shaderCache.getDerivedShaderProgram(t,"pick");if(!c(i)){const o=t._attributeLocations;let r=t.fragmentShaderSource;const s=r.sources,a=s.length,u=s.some(_=>_.includes("out_FragData"))?"out_FragData_0":"out_FragColor",h=`void main ()
{
czm_non_pick_main();
if (${u}.a == 0.0) {
discard;
}
${u} = ${n};
} `,f=new Array(a+1);for(let _=0;_<a;++_)f[_]=Oe.replaceMain(s[_],"czm_non_pick_main");f[a]=h,r=new Oe({sources:f,defines:r.defines}),i=e.shaderCache.createDerivedShaderProgram(t,"pick",{vertexShaderSource:t.vertexShaderSource,fragmentShaderSource:r,attributeLocations:o})}return i}function lBe(e,t){const n=e.picking.pickRenderStateCache;let i=n[t.id];if(!c(i)){const o=Ue.getState(t);o.blending.enabled=!1,o.depthMask=!0,i=Ue.fromCache(o),n[t.id]=i}return i}sd.createPickDerivedCommand=function(e,t,n,i){c(i)||(i={});let o,r;return c(i.pickCommand)&&(o=i.pickCommand.shaderProgram,r=i.pickCommand.renderState),i.pickCommand=Ze.shallowClone(t,i.pickCommand),!c(o)||i.shaderProgramId!==t.shaderProgram.id?(i.pickCommand.shaderProgram=cBe(n,t.shaderProgram,t.pickId),i.pickCommand.renderState=lBe(e,t.renderState),i.shaderProgramId=t.shaderProgram.id):(i.pickCommand.shaderProgram=o,i.pickCommand.renderState=r),i};function uBe(e,t){let n=e.shaderCache.getDerivedShaderProgram(t,"HDR");if(!c(n)){const i=t._attributeLocations,o=t.vertexShaderSource.clone(),r=t.fragmentShaderSource.clone();o.defines=c(o.defines)?o.defines.slice(0):[],o.defines.push("HDR"),r.defines=c(r.defines)?r.defines.slice(0):[],r.defines.push("HDR"),n=e.shaderCache.createDerivedShaderProgram(t,"HDR",{vertexShaderSource:o,fragmentShaderSource:r,attributeLocations:i})}return n}sd.createHdrCommand=function(e,t,n){c(n)||(n={});let i;return c(n.command)&&(i=n.command.shaderProgram),n.command=Ze.shallowClone(e,n.command),!c(i)||n.shaderProgramId!==e.shaderProgram.id?(n.command.shaderProgram=uBe(t,e.shaderProgram),n.shaderProgramId=e.shaderProgram.id):n.command.shaderProgram=i,n};function oE(e){if(!c(e))throw new E("scene is required.");this._scene=e,this._lastAlpha=void 0,this._lastBeta=void 0,this._lastGamma=void 0,this._alpha=void 0,this._beta=void 0,this._gamma=void 0;const t=this;function n(i){const o=i.alpha;if(!c(o)){t._alpha=void 0,t._beta=void 0,t._gamma=void 0;return}t._alpha=R.toRadians(o),t._beta=R.toRadians(i.beta),t._gamma=R.toRadians(i.gamma)}window.addEventListener("deviceorientation",n,!1),this._removeListener=function(){window.removeEventListener("deviceorientation",n,!1)}}const dBe=new _e,v3=new _e,hBe=new $;function fBe(e,t,n,i){const o=e.direction,r=e.right,s=e.up,a=_e.fromAxisAngle(o,n,v3),l=_e.fromAxisAngle(r,i,dBe),u=_e.multiply(l,a,l),h=_e.fromAxisAngle(s,t,v3);_e.multiply(h,u,u);const f=$.fromQuaternion(u,hBe);$.multiplyByVector(f,r,r),$.multiplyByVector(f,s,s),$.multiplyByVector(f,o,o)}oE.prototype.update=function(){if(!c(this._alpha))return;c(this._lastAlpha)||(this._lastAlpha=this._alpha,this._lastBeta=this._beta,this._lastGamma=this._gamma);const e=this._lastAlpha-this._alpha,t=this._lastBeta-this._beta,n=this._lastGamma-this._gamma;fBe(this._scene.camera,-e,t,n),this._lastAlpha=this._alpha,this._lastBeta=this._beta,this._lastGamma=this._gamma};oE.prototype.isDestroyed=function(){return!1};oE.prototype.destroy=function(){return this._removeListener(),ve(this)};function RW(){this.enabled=!0,this.renderable=!0,this.density=2e-4,this.screenSpaceErrorFactor=2,this.minimumBrightness=.03}const ax=[359.393,800.749,1275.6501,2151.1192,3141.7763,4777.5198,6281.2493,12364.307,15900.765,49889.0549,78026.8259,99260.7344,120036.3873,151011.0158,156091.1953,203849.3112,274866.9803,319916.3149,493552.0528,628733.5874],nu=[2e-5,2e-4,1e-4,7e-5,5e-5,4e-5,3e-5,19e-6,1e-5,85e-7,62e-7,58e-7,53e-7,52e-7,51e-7,42e-7,4e-6,34e-7,26e-7,22e-7];for(let e=0;e<nu.length;++e)nu[e]*=1e6;const NW=nu[1],WD=nu[nu.length-1];for(let e=0;e<nu.length;++e)nu[e]=(nu[e]-WD)/(NW-WD);let _r=0;function pBe(e){const t=ax,n=t.length;if(e<t[0])return _r=0,_r;if(e>t[n-1])return _r=n-2,_r;if(e>=t[_r]){if(_r+1<n&&e<t[_r+1])return _r;if(_r+2<n&&e<t[_r+2])return++_r,_r}else if(_r-1>=0&&e>=t[_r-1])return--_r,_r;let i;for(i=0;i<n-2&&!(e>=t[i]&&e<t[i+1]);++i);return _r=i,_r}const mBe=new d;RW.prototype.update=function(e){if(!(e.fog.enabled=this.enabled))return;e.fog.renderable=this.renderable;const n=e.camera,i=n.positionCartographic;if(!c(i)||i.height>8e5||e.mode!==oe.SCENE3D){e.fog.enabled=!1,e.f
{
out_FragColor = vec4(1.0);
}
`;t.sources=[n]}function I1(e,t){const n=t.sources,i=n.length;for(let r=0;r<i;++r)n[r]=Oe.replaceMain(n[r],"czm_globe_translucency_main");const o=`
uniform sampler2D u_classificationTexture;
void main()
{
vec2 st = gl_FragCoord.xy / czm_viewport.zw;
#ifdef MANUAL_DEPTH_TEST
float logDepthOrDepth = czm_unpackDepth(texture(czm_globeDepthTexture, st));
if (logDepthOrDepth != 0.0)
{
vec4 eyeCoordinate = czm_windowToEyeCoordinates(gl_FragCoord.xy, logDepthOrDepth);
float depthEC = eyeCoordinate.z / eyeCoordinate.w;
if (v_positionEC.z < depthEC)
{
discard;
}
}
#endif
czm_globe_translucency_main();
vec4 classificationColor = texture(u_classificationTexture, st);
if (classificationColor.a > 0.0)
{
// Reverse premultiplication process to get the correct composited result of the classification primitives
classificationColor.rgb /= classificationColor.a;
}
out_FragColor = classificationColor * vec4(classificationColor.aaa, 1.0) + out_FragColor * (1.0 - classificationColor.a);
}
`;n.push(o)}function FW(e,t){I1(e,t),hc(e.defines,"GROUND_ATMOSPHERE"),hc(t.defines,"GROUND_ATMOSPHERE"),hc(e.defines,"FOG"),hc(t.defines,"FOG")}function wBe(e,t){I1(e,t),e.defines.push("GENERATE_POSITION"),t.defines.push("MANUAL_DEPTH_TEST")}function SBe(e,t){FW(e,t),e.defines.push("GENERATE_POSITION"),t.defines.push("MANUAL_DEPTH_TEST")}function O3(e,t){const n=`uniform sampler2D u_classificationTexture;
void main()
{
vec2 st = gl_FragCoord.xy / czm_viewport.zw;
vec4 pickColor = texture(u_classificationTexture, st);
if (pickColor == vec4(0.0))
{
discard;
}
out_FragColor = pickColor;
}
`;t.sources=[n]}function vBe(e,t,n,i,o,r){if(!c(o))return t;if(!i&&c(n))return n;let s=e.shaderCache.getDerivedShaderProgram(t,r);if(!c(s)){const a=t._attributeLocations,l=t.vertexShaderSource.clone(),u=t.fragmentShaderSource.clone();l.defines=c(l.defines)?l.defines.slice(0):[],u.defines=c(u.defines)?u.defines.slice(0):[],o(l,u),s=e.shaderCache.createDerivedShaderProgram(t,r,{vertexShaderSource:l,fragmentShaderSource:u,attributeLocations:a})}return s}function IBe(e){e.cull.face=Qi.BACK,e.cull.enabled=!0}function DBe(e){e.cull.face=Qi.FRONT,e.cull.enabled=!0}function PBe(e){e.cull.face=Qi.BACK,e.cull.enabled=!0,e.colorMask={red:!1,green:!1,blue:!1,alpha:!1}}function OBe(e){e.cull.face=Qi.FRONT,e.cull.enabled=!0,e.colorMask={red:!1,green:!1,blue:!1,alpha:!1}}function LBe(e){e.cull.enabled=!1,e.colorMask={red:!1,green:!1,blue:!1,alpha:!1}}function L3(e){e.cull.face=Qi.BACK,e.cull.enabled=!0,e.depthMask=!1,e.blending=Zn.ALPHA_BLEND}function R3(e){e.cull.face=Qi.FRONT,e.cull.enabled=!0,e.depthMask=!1,e.blending=Zn.ALPHA_BLEND}function RBe(e){e.cull.face=Qi.BACK,e.cull.enabled=!0,e.blending.enabled=!1}function NBe(e){e.cull.face=Qi.FRONT,e.cull.enabled=!0,e.blending.enabled=!1}function MBe(e,t,n,i,o){if(!c(i))return e;if(!n&&c(t))return t;let r=o[e.id];if(!c(r)){const s=Ue.getState(e);i(s),r=Ue.fromCache(s),o[e.id]=r}return r}function Dm(e){return{u_classificationTexture:function(){return e._globeTranslucencyFramebuffer.classificationTexture}}}function FBe(e,t,n,i,o){return c(o)?!i&&c(n)?n:jt(t,o(e),!1):t}function Kc(e){this.pass=e.pass,this.pickOnly=e.pickOnly,this.getShaderProgramFunction=e.getShaderProgramFunction,this.getRenderStateFunction=e.getRenderStateFunction,this.getUniformMapFunction=e.getUniformMapFunction,this.renderStateCache={}}function BBe(){return[new Kc({pass:xe.GLOBE,pickOnly:!1,getShaderProgramFunction:CBe,getRenderStateFunction:IBe,getUniformMapFunction:void 0}),new Kc({pass:xe.GLOBE,pickOnly:!1,getShaderProgramFunction:EBe,getRenderStateFunction:DBe,getUniformMapFunction:void 0}),new Kc({pass:xe.GLOBE,pickOnly:!1,getShaderProgramFunction:Pv,getRenderStateFunction:PBe,getUniformMapFunction:void 0}),new Kc({pass:xe.GLOBE,pickOnly:!1,getShaderProgramFunction:Pv,getRenderStateFunction:OBe,getUniformMapFunction:void 0}),new Kc({pass:xe.GLOBE,pickOnly:!1,getShaderProgramFunction:Pv,getRenderStateFunction:LBe,getUniformMapFunction:void 0}),new Kc({pass:xe.TRANSLUCENT,pickOnly:!1,getShaderProgramFunction:I1,getRenderStateFunction:L3,getUniformMapFunction:Dm}),new Kc({pass:xe.TRANSLUCENT,pickOnly:!1,getShaderProgramFunction:FW,getRenderStateFunction:R3,getUniformMapFunction:Dm}),new Kc({pass:xe.TRANSLUCENT,pickOnly:!1,getShaderProgramFunction:wBe,getRenderStateFunction:L3,getUniformMapFunction:Dm}),new Kc({pass:xe.TRANSLUCENT,pickOnly:!1,getShaderProgramFunction:SBe,getRenderStateFunction:R3,getUniformMapFunction:Dm}),new Kc({pass:xe.TRANSLUCENT,pickOnly:!0,getShaderProgramFunction:O3,getRenderStateFunction:RBe,getUniformMapFunction:Dm}),new Kc({pass:xe.TRANSLUCENT,pickOnly:!0,getShaderProgramFunction:O3,getRenderStateFunction:NBe,getUniformMapFunction:Dm})]}const N3=new Array(Yf),M3=new Array(Yf);Wp.prototype.updateDerivedCommands=function(e,t){const n=this._derivedCommandTypesToUpdate,i=this._derivedCommandsToUpdateLength;if(i!==0){for(let o=0;o<i;++o)M3[o]=this._derivedCommandPacks[n[o]],N3[o]=MW[n[o]];zBe(this,e,i,n,N3,M3,t)}};function zBe(e,t,n,i,o,r,s){let a=t.derivedCommands.globeTranslucency;const l=e._derivedCommandsDirty;if(t.dirty||!c(a)||l){t.dirty=!1,c(a)||(a={},t.derivedCommands.globeTranslucency=a);const u=s.frameNumber,h=y(a.uniformMapDirtyFrame,0),f=y(a.shaderProgramDirtyFrame,0),_=y(a.renderStateDirtyFrame,0),g=a.uniformMap!==t.uniformMap,m=a.shaderProgramId!==t.shaderProgram.id,b=a.renderStateId!==t.renderState.id;g&&(a.uniformMapDirtyFrame=u),m&&(a.shaderProgramDirtyFrame=u),b&&(a.renderStateDirtyFrame=u),a.uniformMap=t.uniformMap,a.shaderProgramId=t.shaderProgram.id,a.renderStateId=t.renderState.id;for(let T=0;T<n;++T){const x=r[T],C=i[T],w=o[T];let v=a[w],P,N,k;c(v)?(P=v.uniformMap,N=v.shad
in vec2 v_textureCoordinates;
void main()
{
out_FragColor = texture(colorTexture, v_textureCoordinates);
}
`;function kl(){this._numSamples=1,this.previousFramebuffer=void 0,this._previousFramebuffer=void 0,this._depthStencilTexture=void 0,this._depthStencilRenderbuffer=void 0,this._fbo=new on({depthStencil:!0,createDepthAttachments:!1}),this._fboClassified=new on({depthStencil:!0,createDepthAttachments:!1}),this._rsUnclassified=void 0,this._rsClassified=void 0,this._unclassifiedCommand=void 0,this._classifiedCommand=void 0,this._translucentCommand=void 0,this._clearColorCommand=new bi({color:new z(0,0,0,0),owner:this}),this._clearCommand=new bi({color:new z(0,0,0,0),depth:1,stencil:0});const e=this;this._uniformMap={colorTexture:function(){return e._fbo.getColorTexture()},depthTexture:function(){return e._depthStencilTexture},classifiedTexture:function(){return e._fboClassified.getColorTexture()}}}Object.defineProperties(kl.prototype,{unclassifiedCommand:{get:function(){return this._unclassifiedCommand}}});kl.isTranslucencySupported=function(e){return e.depthTexture&&e.fragmentDepth};const VBe={depthMask:!1,stencilTest:{enabled:!0,frontFunction:Pn.EQUAL,frontOperation:{fail:nt.KEEP,zFail:nt.KEEP,zPass:nt.KEEP},backFunction:Pn.NEVER,reference:0,mask:At.CLASSIFICATION_MASK},blending:Zn.ALPHA_BLEND},HBe={depthMask:!1,stencilTest:{enabled:!0,frontFunction:Pn.NOT_EQUAL,frontOperation:{fail:nt.KEEP,zFail:nt.KEEP,zPass:nt.KEEP},backFunction:Pn.NEVER,reference:0,mask:At.CLASSIFICATION_MASK},blending:Zn.ALPHA_BLEND},GBe={depthMask:!0,depthTest:{enabled:!0},stencilTest:At.setCesium3DTileBit(),stencilMask:At.CESIUM_3D_TILE_MASK,blending:Zn.ALPHA_BLEND},jBe=`uniform sampler2D colorTexture;
uniform sampler2D depthTexture;
uniform sampler2D classifiedTexture;
in vec2 v_textureCoordinates;
void main()
{
vec4 color = texture(colorTexture, v_textureCoordinates);
if (color.a == 0.0)
{
discard;
}
bool isClassified = all(equal(texture(classifiedTexture, v_textureCoordinates), vec4(0.0)));
#ifdef UNCLASSIFIED
vec4 highlightColor = czm_invertClassificationColor;
if (isClassified)
{
discard;
}
#else
vec4 highlightColor = vec4(1.0);
if (!isClassified)
{
discard;
}
#endif
out_FragColor = color * highlightColor;
gl_FragDepth = texture(depthTexture, v_textureCoordinates).r;
}
`,WBe=`uniform sampler2D colorTexture;
in vec2 v_textureCoordinates;
void main()
{
vec4 color = texture(colorTexture, v_textureCoordinates);
if (color.a == 0.0)
{
discard;
}
#ifdef UNCLASSIFIED
out_FragColor = color * czm_invertClassificationColor;
#else
out_FragColor = color;
#endif
}
`;kl.prototype.update=function(e,t,n){const i=this._fbo.getColorTexture(),o=this.previousFramebuffer!==this._previousFramebuffer;this._previousFramebuffer=this.previousFramebuffer;const r=this._numSamples!==t,s=e.drawingBufferWidth,a=e.drawingBufferHeight,l=!c(i)||i.width!==s||i.height!==a;if((l||o||r)&&(this._numSamples=t,this._depthStencilTexture=this._depthStencilTexture&&this._depthStencilTexture.destroy(),this._depthStencilRenderbuffer=this._depthStencilRenderbuffer&&this._depthStencilRenderbuffer.destroy(),c(this._previousFramebuffer)||(this._depthStencilTexture=new xt({context:e,width:s,height:a,pixelFormat:Ve.DEPTH_STENCIL,pixelDatatype:Me.UNSIGNED_INT_24_8}),t>1&&(this._depthStencilRenderbuffer=new cl({context:e,width:s,height:a,format:qu.DEPTH24_STENCIL8,numSamples:t})))),!c(this._fbo.framebuffer)||l||o||r){this._fbo.destroy(),this._fboClassified.destroy();let u,h;c(this._previousFramebuffer)?(u=n.getDepthStencilTexture(),h=n.getDepthStencilRenderbuffer()):(u=this._depthStencilTexture,h=this._depthStencilRenderbuffer),this._fbo.setDepthStencilTexture(u),c(h)&&this._fbo.setDepthStencilRenderbuffer(h),this._fbo.update(e,s,a,t),c(this._previousFramebuffer)||(this._fboClassified.setDepthStencilTexture(u),this._fboClassified.update(e,s,a))}if(c(this._rsUnclassified)||(this._rsUnclassified=Ue.fromCache(VBe),this._rsClassified=Ue.fromCache(HBe),this._rsDefault=Ue.fromCache(GBe)),!c(this._unclassifiedCommand)||o||r){c(this._unclassifiedCommand)&&(this._unclassifiedCommand.shaderProgram=this._unclassifiedCommand.shaderProgram&&this._unclassifiedCommand.shaderProgram.destroy(),this._classifiedCommand.shaderProgram=this._classifiedCommand.shaderProgram&&this._classifiedCommand.shaderProgram.destroy());const u=c(this._previousFramebuffer)?WBe:jBe,h=new Oe({defines:["UNCLASSIFIED"],sources:[u]}),f=new Oe({sources:[u]});this._unclassifiedCommand=e.createViewportQuadCommand(h,{renderState:c(this._previousFramebuffer)?this._rsUnclassified:this._rsDefault,uniformMap:this._uniformMap,owner:this}),this._classifiedCommand=e.createViewportQuadCommand(f,{renderState:c(this._previousFramebuffer)?this._rsClassified:this._rsDefault,uniformMap:this._uniformMap,owner:this}),c(this._translucentCommand)&&(this._translucentCommand.shaderProgram=this._translucentCommand.shaderProgram&&this._translucentCommand.shaderProgram.destroy()),c(this._previousFramebuffer)||(this._translucentCommand=e.createViewportQuadCommand(Ep,{renderState:this._rsUnclassified,uniformMap:this._uniformMap,owner:this}))}};kl.prototype.prepareTextures=function(e,t){this._fbo._numSamples>1&&this._fbo.prepareTextures(e,t)};kl.prototype.clear=function(e,t){c(this._previousFramebuffer)?this._fbo.clear(e,this._clearColorCommand,t):(this._fbo.clear(e,this._clearCommand,t),this._fboClassified.clear(e,this._clearCommand,t))};kl.prototype.executeClassified=function(e,t){if(!c(this._previousFramebuffer)){const n=t.framebuffer;this.prepareTextures(e,!0),t.framebuffer=this._fboClassified.framebuffer,this._translucentCommand.execute(e,t),t.framebuffer=n}this._classifiedCommand.execute(e,t)};kl.prototype.executeUnclassified=function(e,t){this._unclassifiedCommand.execute(e,t)};kl.prototype.isDestroyed=function(){return!1};kl.prototype.destroy=function(){return this._fbo.destroy(),this._fboClassified.destroy(),this._depthStencilTexture=this._depthStencilTexture&&this._depthStencilTexture.destroy(),this._depthStencilRenderbuffer=this._depthStencilRenderbuffer&&this._depthStencilRenderbuffer.destroy(),c(this._unclassifiedCommand)&&(this._unclassifiedCommand.shaderProgram=this._unclassifiedCommand.shaderProgram&&this._unclassifiedCommand.shaderProgram.destroy(),this._classifiedCommand.shaderProgram=this._classifiedCommand.shaderProgram&&this._classifiedCommand.shaderProgram.destroy()),ve(this)};function cx(e){this._total=e,this.usedThisFrame=0,this.stolenFromMeThisFrame=0,this.starvedThisFrame=!1,this.starvedLastFrame=!1}Object.defineProperties(cx.prototype,{total:{get:function(){return this._total}}});function Sh(e){if(c(e)&&e.length!==nl.NUMBER_OF_JOB_TYPES)throw new E("A budget must
in vec2 v_textureCoordinates;
void main()
{
out_FragColor = czm_packDepth(texture(u_texture, v_textureCoordinates).r);
}
`;e._copyDepthCommand=t.createViewportQuadCommand(i,{renderState:Ue.fromCache(),uniformMap:{u_texture:function(){return e._textureToCopy}},owner:e})}e._textureToCopy=n,e._copyDepthCommand.framebuffer=e.framebuffer}qp.prototype.update=function(e,t){qBe(this,e,t),YBe(this,e,t)};const $Be=new te,XBe=new te(1,1/255,1/65025,1/16581375);qp.prototype.getDepth=function(e,t,n){if(!c(this.framebuffer))return;const i=e.readPixels({x:t,y:n,width:1,height:1,framebuffer:this.framebuffer}),o=te.unpack(i,0,$Be);return te.divideByScalar(o,255,o),te.dot(o,XBe)};qp.prototype.executeCopyDepth=function(e,t){this._copyDepthCommand.execute(e,t)};qp.prototype.isDestroyed=function(){return!1};qp.prototype.destroy=function(){return this._framebuffer.destroy(),c(this._copyDepthCommand)&&(this._copyDepthCommand.shaderProgram=c(this._copyDepthCommand.shaderProgram)&&this._copyDepthCommand.shaderProgram.destroy()),ve(this)};function QBe(e,t){this.near=y(e,0),this.far=y(t,0);const n=xe.NUMBER_OF_PASSES,i=new Array(n),o=new Array(n);for(let r=0;r<n;++r)i[r]=[],o[r]=0;this.commands=i,this.indices=o}const qD=`uniform highp sampler2D u_depthTexture;
in vec2 v_textureCoordinates;
void main()
{
out_FragColor = czm_packDepth(texture(u_depthTexture, v_textureCoordinates).r);
}
`;function Cu(){this._picking=!1,this._numSamples=1,this._tempCopyDepthTexture=void 0,this._pickColorFramebuffer=new on({depthStencil:!0,supportsDepthTexture:!0}),this._outputFramebuffer=new on({depthStencil:!0,supportsDepthTexture:!0}),this._copyDepthFramebuffer=new on,this._tempCopyDepthFramebuffer=new on,this._updateDepthFramebuffer=new on({createColorAttachments:!1,createDepthAttachments:!1,depthStencil:!0}),this._clearGlobeColorCommand=void 0,this._copyColorCommand=void 0,this._copyDepthCommand=void 0,this._tempCopyDepthCommand=void 0,this._updateDepthCommand=void 0,this._viewport=new Re,this._rs=void 0,this._rsBlend=void 0,this._rsUpdate=void 0,this._useScissorTest=!1,this._scissorRectangle=void 0,this._useHdr=void 0,this._clearGlobeDepth=void 0}Object.defineProperties(Cu.prototype,{colorFramebufferManager:{get:function(){return this._picking?this._pickColorFramebuffer:this._outputFramebuffer}},framebuffer:{get:function(){return this.colorFramebufferManager.framebuffer}},depthStencilTexture:{get:function(){return this.colorFramebufferManager.getDepthStencilTexture()}},picking:{get:function(){return this._picking},set:function(e){this._picking=e}}});function KBe(e){e._pickColorFramebuffer.destroy(),e._outputFramebuffer.destroy(),e._copyDepthFramebuffer.destroy(),e._tempCopyDepthFramebuffer.destroy(),e._updateDepthFramebuffer.destroy()}function zW(e,t,n,i,o){e._viewport.width=n,e._viewport.height=i;const r=!Re.equals(e._viewport,o.viewport);let s=r!==e._useScissorTest;e._useScissorTest=r,Re.equals(e._scissorRectangle,o.viewport)||(e._scissorRectangle=Re.clone(o.viewport,e._scissorRectangle),s=!0),(!c(e._rs)||!Re.equals(e._viewport,e._rs.viewport)||s)&&(e._rs=Ue.fromCache({viewport:e._viewport,scissorTest:{enabled:e._useScissorTest,rectangle:e._scissorRectangle}}),e._rsBlend=Ue.fromCache({viewport:e._viewport,scissorTest:{enabled:e._useScissorTest,rectangle:e._scissorRectangle},blending:Zn.ALPHA_BLEND}),e._rsUpdate=Ue.fromCache({viewport:e._viewport,scissorTest:{enabled:e._useScissorTest,rectangle:e._scissorRectangle},stencilTest:{enabled:!0,frontFunction:Pn.EQUAL,frontOperation:{fail:nt.KEEP,zFail:nt.KEEP,zPass:nt.KEEP},backFunction:Pn.NEVER,reference:At.CESIUM_3D_TILE_MASK,mask:At.CESIUM_3D_TILE_MASK}})),c(e._copyDepthCommand)||(e._copyDepthCommand=t.createViewportQuadCommand(qD,{uniformMap:{u_depthTexture:function(){return e.colorFramebufferManager.getDepthStencilTexture()}},owner:e})),e._copyDepthCommand.framebuffer=e._copyDepthFramebuffer.framebuffer,e._copyDepthCommand.renderState=e._rs,c(e._copyColorCommand)||(e._copyColorCommand=t.createViewportQuadCommand(Ep,{uniformMap:{colorTexture:function(){return e.colorFramebufferManager.getColorTexture()}},owner:e})),e._copyColorCommand.renderState=e._rs,c(e._tempCopyDepthCommand)||(e._tempCopyDepthCommand=t.createViewportQuadCommand(qD,{uniformMap:{u_depthTexture:function(){return e._tempCopyDepthTexture}},owner:e})),e._tempCopyDepthCommand.framebuffer=e._tempCopyDepthFramebuffer.framebuffer,e._tempCopyDepthCommand.renderState=e._rs,c(e._updateDepthCommand)||(e._updateDepthCommand=t.createViewportQuadCommand(Ep,{uniformMap:{colorTexture:function(){return e._tempCopyDepthFramebuffer.getColorTexture()}},owner:e})),e._updateDepthCommand.framebuffer=e._updateDepthFramebuffer.framebuffer,e._updateDepthCommand.renderState=e._rsUpdate,c(e._clearGlobeColorCommand)||(e._clearGlobeColorCommand=new bi({color:new z(0,0,0,0),stencil:0,owner:e})),e._clearGlobeColorCommand.framebuffer=e.framebuffer}Cu.prototype.update=function(e,t,n,i,o,r){const s=n.width,a=n.height,l=o?e.halfFloatingPointTexture?Me.HALF_FLOAT:Me.FLOAT:Me.UNSIGNED_BYTE;this._numSamples=i,this.picking?this._pickColorFramebuffer.update(e,s,a):this._outputFramebuffer.update(e,s,a,i,l),this._copyDepthFramebuffer.update(e,s,a),zW(this,e,s,a,t),e.uniformState.globeDepthTexture=void 0,this._useHdr=o,this._clearGlobeDepth=r};Cu.prototype.prepareColorTextures=function(e,t){!this.picking&&this._numSamples>1&&this._outputFramebuffer.prepareTextures(e,t)};Cu.prototype.executeCopyDepth=function(e,t){c(this._copyDepthCommand)&&(
float ai = czm_out_FragColor.a;
float wzi = czm_alphaWeight(ai);
out_FragData_0 = vec4(Ci * wzi, ai);
out_FragData_1 = vec4(ai * wzi);
`,u3e=` vec3 Ci = czm_out_FragColor.rgb * czm_out_FragColor.a;
float ai = czm_out_FragColor.a;
float wzi = czm_alphaWeight(ai);
out_FragColor = vec4(Ci, ai) * wzi;
`,d3e=` float ai = czm_out_FragColor.a;
out_FragColor = vec4(ai);
`;function P1(e,t,n,i){const{shaderCache:o}=e,r=o.getDerivedShaderProgram(t,n);if(c(r))return r;const s=t._attributeLocations,a=t.fragmentShaderSource.clone();a.sources=a.sources.map(function(h){return Oe.replaceMain(h,"czm_translucent_main").replace(/out_FragColor/g,"czm_out_FragColor").replace(/layout\s*\(location\s*=\s*0\)\s*out\s+vec4\s+out_FragColor;/g,"").replace(/\bdiscard\b/g,"czm_discard = true").replace(/czm_phong/g,"czm_translucentPhong")}),a.sources.splice(0,0,`vec4 czm_out_FragColor;
bool czm_discard = false;
`);const l=[...i.matchAll(/out_FragData_(\d+)/g)];let u="";for(let h=0;h<l.length;h++){const f=l[h];u=`layout (location = ${f[1]}) out vec4 ${f[0]};
${u}`}return a.sources.push(u),a.sources.push(`void main()
{
czm_translucent_main();
if (czm_discard)
{
discard;
}
${i}}
`),o.createDerivedShaderProgram(t,n,{vertexShaderSource:t.vertexShaderSource,fragmentShaderSource:a,attributeLocations:s})}function h3e(e,t){return P1(e,t,"translucentMRT",l3e)}function f3e(e,t){return P1(e,t,"translucentMultipass",u3e)}function p3e(e,t){return P1(e,t,"alphaMultipass",d3e)}Pd.prototype.createDerivedCommands=function(e,t,n){if(c(n)||(n={}),this._translucentMRTSupport){let a,l;return c(n.translucentCommand)&&(a=n.translucentCommand.shaderProgram,l=n.translucentCommand.renderState),n.translucentCommand=Ze.shallowClone(e,n.translucentCommand),!c(a)||n.shaderProgramId!==e.shaderProgram.id?(n.translucentCommand.shaderProgram=h3e(t,e.shaderProgram),n.translucentCommand.renderState=s3e(this,t,e.renderState),n.shaderProgramId=e.shaderProgram.id):(n.translucentCommand.shaderProgram=a,n.translucentCommand.renderState=l),n}let i,o,r,s;return c(n.translucentCommand)&&(i=n.translucentCommand.shaderProgram,o=n.translucentCommand.renderState,r=n.alphaCommand.shaderProgram,s=n.alphaCommand.renderState),n.translucentCommand=Ze.shallowClone(e,n.translucentCommand),n.alphaCommand=Ze.shallowClone(e,n.alphaCommand),!c(i)||n.shaderProgramId!==e.shaderProgram.id?(n.translucentCommand.shaderProgram=f3e(t,e.shaderProgram),n.translucentCommand.renderState=a3e(this,t,e.renderState),n.alphaCommand.shaderProgram=p3e(t,e.shaderProgram),n.alphaCommand.renderState=c3e(this,t,e.renderState),n.shaderProgramId=e.shaderProgram.id):(n.translucentCommand.shaderProgram=i,n.translucentCommand.renderState=o,n.alphaCommand.shaderProgram=r,n.alphaCommand.renderState=s),n};function m3e(e,t,n,i,o,r){let s,a,l;const{context:u,frameState:h}=t,{useLogDepth:f,shadowState:_}=h,g=t._hdr,m=i.framebuffer,b=_.lightShadowsEnabled;i.framebuffer=e._adjustTranslucentFBO.framebuffer,e._adjustTranslucentCommand.execute(u,i),i.framebuffer=e._adjustAlphaFBO.framebuffer,e._adjustAlphaCommand.execute(u,i);const T=e._opaqueFBO.framebuffer;for(i.framebuffer=e._translucentFBO.framebuffer,l=0;l<o.length;++l)s=o[l],s=f?s.derivedCommands.logDepth.command:s,s=g?s.derivedCommands.hdr.command:s,a=b&&s.receiveShadows?s.derivedCommands.oit.shadows.translucentCommand:s.derivedCommands.oit.translucentCommand,n(a,t,u,i,T);for(c(r)&&(s=r.unclassifiedCommand,a=b&&s.receiveShadows?s.derivedCommands.oit.shadows.translucentCommand:s.derivedCommands.oit.translucentCommand,n(a,t,u,i,T)),i.framebuffer=e._alphaFBO.framebuffer,l=0;l<o.length;++l)s=o[l],s=f?s.derivedCommands.logDepth.command:s,s=g?s.derivedCommands.hdr.command:s,a=b&&s.receiveShadows?s.derivedCommands.oit.shadows.alphaCommand:s.derivedCommands.oit.alphaCommand,n(a,t,u,i,T);c(r)&&(s=r.unclassifiedCommand,a=b&&s.receiveShadows?s.derivedCommands.oit.shadows.alphaCommand:s.derivedCommands.oit.alphaCommand,n(a,t,u,i,T)),i.framebuffer=m}function _3e(e,t,n,i,o,r){const{context:s,frameState:a}=t,{useLogDepth:l,shadowState:u}=a,h=t._hdr,f=i.framebuffer,_=u.lightShadowsEnabled;i.framebuffer=e._adjustTranslucentFBO.framebuffer,e._adjustTranslucentCommand.execute(s,i);const g=e._opaqueFBO.framebuffer;i.framebuffer=e._translucentFBO.framebuffer;let m,b;for(let T=0;T<o.length;++T)m=o[T],m=l?m.derivedCommands.logDepth.command:m,m=h?m.derivedCommands.hdr.command:m,b=_&&m.receiveShadows?m.derivedCommands.oit.shadows.translucentCommand:m.derivedCommands.oit.translucentCommand,n(b,t,s,i,g);c(r)&&(m=r.unclassifiedCommand,b=_&&m.receiveShadows?m.derivedCommands.oit.shadows.translucentCommand:m.derivedCommands.oit.translucentCommand,n(b,t,s,i,g)),i.framebuffer=f}Pd.prototype.executeCommands=function(e,t,n,i,o){if(this._translucentMRTSupport){_3e(this,e,t,n,i,o);return}m3e(this,e,t,n,i,o)};Pd.prototype.execute=function(e,t){this._compositeCommand.execute(e,t)};Pd.prototype.clear=function(e,t,n){const i=t.framebuffer;t.framebuffer=this._opaqueFBO.framebuffer,z.clone(n,this._opaqueClearCommand.color),this._opaqueClearCommand.execute(e,t),t.framebuffer=this._translucentFBO.framebuffer,(this._translucentMRTSupport?this._translucentMRTClearCommand:this._translucentMultipassClearCommand).execute(e,t),this._translucentMultipassSupport&&(t.framebuffer=thi
void main()
{
czm_shadow_cast_main();
v_positionEC = (czm_inverseProjection * gl_Position).xyz;
}`;o.push(l)}return new Oe({defines:i,sources:o})};bc.createShadowCastFragmentShader=function(e,t,n,i){const o=e.defines.slice(0),r=e.sources.slice(0);o.push("SHADOW_MAP");let s=Oe.findPositionVarying(e);const a=c(s);a||(s="v_positionEC");const l=r.length;for(let h=0;h<l;++h)r[h]=Oe.replaceMain(r[h],"czm_shadow_cast_main");let u="";return t&&(a||(u+=`in vec3 v_positionEC;
`),u+=`uniform vec4 shadowMap_lightPositionEC;
`),i?u+=`void main()
{
`:u+=`void main()
{
czm_shadow_cast_main();
if (out_FragColor.a == 0.0)
{
discard;
}
`,t?u+=` float distance = length(${s});
if (distance >= shadowMap_lightPositionEC.w)
{
discard;
}
distance /= shadowMap_lightPositionEC.w; // radius
out_FragColor = czm_packDepth(distance);
`:n?u+=` out_FragColor = vec4(1.0);
`:u+=` out_FragColor = czm_packDepth(gl_FragCoord.z);
`,u+=`}
`,r.push(u),new Oe({defines:o,sources:r})};bc.getShadowReceiveShaderKeyword=function(e,t,n,i){const o=e._usesDepthTexture,r=e._polygonOffsetSupported,s=e._isPointLight,a=e._isSpotLight,l=e._numberOfCascades>1,u=e.debugCascadeColors,h=e.softShadows;return`receiveShadow ${o}${r}${s}${a}${l}${u}${h}${t}${n}${i}`};bc.createShadowReceiveVertexShader=function(e,t,n){const i=e.defines.slice(0),o=e.sources.slice(0);return i.push("SHADOW_MAP"),t&&(n?i.push("GENERATE_POSITION_AND_NORMAL"):i.push("GENERATE_POSITION")),new Oe({defines:i,sources:o})};bc.createShadowReceiveFragmentShader=function(e,t,n,i,o){const r=Oe.findNormalVarying(e),s=!i&&c(r)||i&&o,a=Oe.findPositionVarying(e),l=c(a),u=t._usesDepthTexture,h=t._polygonOffsetSupported,f=t._isPointLight,_=t._isSpotLight,g=t._numberOfCascades>1,m=t.debugCascadeColors,b=t.softShadows,T=f?t._pointBias:i?t._terrainBias:t._primitiveBias,x=e.defines.slice(0),C=e.sources.slice(0),w=C.length;for(let N=0;N<w;++N)C[N]=Oe.replaceMain(C[N],"czm_shadow_receive_main");f?x.push("USE_CUBE_MAP_SHADOW"):u&&x.push("USE_SHADOW_DEPTH_TEXTURE"),b&&!f&&x.push("USE_SOFT_SHADOWS"),g&&n&&i&&(s?x.push("ENABLE_VERTEX_LIGHTING"):x.push("ENABLE_DAYNIGHT_SHADING")),n&&T.normalShading&&s&&(x.push("USE_NORMAL_SHADING"),T.normalShadingSmooth>0&&x.push("USE_NORMAL_SHADING_SMOOTH"));let v="";f?v+=`uniform samplerCube shadowMap_textureCube;
`:v+=`uniform sampler2D shadowMap_texture;
`;let P;return l?P=` return vec4(${a}, 1.0);
`:P=`#ifndef LOG_DEPTH
return czm_windowToEyeCoordinates(gl_FragCoord);
#else
return vec4(v_logPositionEC, 1.0);
#endif
`,v+=`uniform mat4 shadowMap_matrix;
uniform vec3 shadowMap_lightDirectionEC;
uniform vec4 shadowMap_lightPositionEC;
uniform vec4 shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness;
uniform vec4 shadowMap_texelSizeDepthBiasAndNormalShadingSmooth;
#ifdef LOG_DEPTH
in vec3 v_logPositionEC;
#endif
vec4 getPositionEC()
{
${P}}
vec3 getNormalEC()
{
${s?` return normalize(${r});
`:` return vec3(1.0);
`}}
void applyNormalOffset(inout vec4 positionEC, vec3 normalEC, float nDotL)
{
${T.normalOffset&&s?` float normalOffset = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.x;
float normalOffsetScale = 1.0 - nDotL;
vec3 offset = normalOffset * normalOffsetScale * normalEC;
positionEC.xyz += offset;
`:""}}
`,v+=`void main()
{
czm_shadow_receive_main();
vec4 positionEC = getPositionEC();
vec3 normalEC = getNormalEC();
float depth = -positionEC.z;
`,v+=` czm_shadowParameters shadowParameters;
shadowParameters.texelStepSize = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.xy;
shadowParameters.depthBias = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.z;
shadowParameters.normalShadingSmooth = shadowMap_texelSizeDepthBiasAndNormalShadingSmooth.w;
shadowParameters.darkness = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.w;
`,i?v+=` shadowParameters.depthBias *= max(depth * 0.01, 1.0);
`:h||(v+=` shadowParameters.depthBias *= mix(1.0, 100.0, depth * 0.0015);
`),f?v+=` vec3 directionEC = positionEC.xyz - shadowMap_lightPositionEC.xyz;
float distance = length(directionEC);
directionEC = normalize(directionEC);
float radius = shadowMap_lightPositionEC.w;
// Stop early if the fragment is beyond the point light radius
if (distance > radius)
{
return;
}
vec3 directionWC = czm_inverseViewRotation * directionEC;
shadowParameters.depth = distance / radius;
shadowParameters.nDotL = clamp(dot(normalEC, -directionEC), 0.0, 1.0);
shadowParameters.texCoords = directionWC;
float visibility = czm_shadowVisibility(shadowMap_textureCube, shadowParameters);
`:_?v+=` vec3 directionEC = normalize(positionEC.xyz - shadowMap_lightPositionEC.xyz);
float nDotL = clamp(dot(normalEC, -directionEC), 0.0, 1.0);
applyNormalOffset(positionEC, normalEC, nDotL);
vec4 shadowPosition = shadowMap_matrix * positionEC;
// Spot light uses a perspective projection, so perform the perspective divide
shadowPosition /= shadowPosition.w;
// Stop early if the fragment is not in the shadow bounds
if (any(lessThan(shadowPosition.xyz, vec3(0.0))) || any(greaterThan(shadowPosition.xyz, vec3(1.0))))
{
return;
}
shadowParameters.texCoords = shadowPosition.xy;
shadowParameters.depth = shadowPosition.z;
shadowParameters.nDotL = nDotL;
float visibility = czm_shadowVisibility(shadowMap_texture, shadowParameters);
`:g?v+=` float maxDepth = shadowMap_cascadeSplits[1].w;
// Stop early if the eye depth exceeds the last cascade
if (depth > maxDepth)
{
return;
}
// Get the cascade based on the eye-space depth
vec4 weights = czm_cascadeWeights(depth);
// Apply normal offset
float nDotL = clamp(dot(normalEC, shadowMap_lightDirectionEC), 0.0, 1.0);
applyNormalOffset(positionEC, normalEC, nDotL);
// Transform position into the cascade
vec4 shadowPosition = czm_cascadeMatrix(weights) * positionEC;
// Get visibility
shadowParameters.texCoords = shadowPosition.xy;
shadowParameters.depth = shadowPosition.z;
shadowParameters.nDotL = nDotL;
float visibility = czm_shadowVisibility(shadowMap_texture, shadowParameters);
// Fade out shadows that are far away
float shadowMapMaximumDistance = shadowMap_normalOffsetScaleDistanceMaxDistanceAndDarkness.z;
float fade = max((depth - shadowMapMaximumDistance * 0.8) / (shadowMapMaximumDistance * 0.2), 0.0);
visibility = mix(visibility, 1.0, fade);
${m?` // Draw cascade colors for debugging
out_FragColor *= czm_cascadeColor(weights);
`:""}`:v+=` float nDotL = clamp(dot(normalEC, shadowMap_lightDirectionEC), 0.0, 1.0);
applyNormalOffset(positionEC, normalEC, nDotL);
vec4 shadowPosition = shadowMap_matrix * positionEC;
// Stop early if the fragment is not in the shadow bounds
if (any(lessThan(shadowPosition.xyz, vec3(0.0))) || any(greaterThan(shadowPosition.xyz, vec3(1.0))))
{
return;
}
shadowParameters.texCoords = shadowPosition.xy;
shadowParameters.depth = shadowPosition.z;
shadowParameters.nDotL = nDotL;
float visibility = czm_shadowVisibility(shadowMap_texture, shadowParameters);
`,v+=` out_FragColor.rgb *= visibility;
}
`,C.push(v),new Oe({defines:x,sources:C})};function Wa(e){e=y(e,y.EMPTY_OBJECT);const t=e.context;if(!c(t))throw new E("context is required.");if(!c(e.lightCamera))throw new E("lightCamera is required.");if(c(e.numberOfCascades)&&e.numberOfCascades!==1&&e.numberOfCascades!==4)throw new E("Only one or four cascades are supported.");this._enabled=y(e.enabled,!0),this._softShadows=y(e.softShadows,!1),this._normalOffset=y(e.normalOffset,!0),this.dirty=!0,this.fromLightSource=y(e.fromLightSource,!0),this.darkness=y(e.darkness,.3),this._darkness=this.darkness,this.fadingEnabled=y(e.fadingEnabled,!0),this.maximumDistance=y(e.maximumDistance,5e3),this._outOfView=!1,this._outOfViewPrevious=!1,this._needsUpdate=!0;let n=!0;(Yt.isInternetExplorer()||Yt.isEdge()||(Yt.isChrome()||Yt.isFirefox())&&Yt.isWindows()&&!t.depthTexture)&&(n=!1),this._polygonOffsetSupported=n,this._terrainBias={polygonOffset:n,polygonOffsetFactor:1.1,polygonOffsetUnits:4,normalOffset:this._normalOffset,normalOffsetScale:.5,normalShading:!0,normalShadingSmooth:.3,depthBias:1e-4},this._primitiveBias={polygonOffset:n,polygonOffsetFactor:1.1,polygonOffsetUnits:4,normalOffset:this._normalOffset,normalOffsetScale:.1,normalShading:!0,normalShadingSmooth:.05,depthBias:2e-5},this._pointBias={polygonOffset:!1,polygonOffsetFactor:1.1,polygonOffsetUnits:4,normalOffset:this._normalOffset,normalOffsetScale:0,normalShading:!0,normalShadingSmooth:.1,depthBias:5e-4},this._depthAttachment=void 0,this._colorAttachment=void 0,this._shadowMapMatrix=new L,this._shadowMapTexture=void 0,this._lightDirectionEC=new d,this._lightPositionEC=new te,this._distance=0,this._lightCamera=e.lightCamera,this._shadowMapCamera=new sE,this._shadowMapCullingVolume=void 0,this._sceneCamera=void 0,this._boundingSphere=new se,this._isPointLight=y(e.isPointLight,!1),this._pointLightRadius=y(e.pointLightRadius,100),this._cascadesEnabled=this._isPointLight?!1:y(e.cascadesEnabled,!0),this._numberOfCascades=this._cascadesEnabled?y(e.numberOfCascades,4):0,this._fitNearFar=!0,this._maximumCascadeDistances=[25,150,700,Number.MAX_VALUE],this._textureSize=new H,this._isSpotLight=!1,this._cascadesEnabled?this._shadowMapCamera.frustum=new Ki:c(this._lightCamera.frustum.fov)&&(this._isSpotLight=!0),this._cascadeSplits=[new te,new te],this._cascadeMatrices=[new L,new L,new L,new L],this._cascadeDistances=new te;let i;this._isPointLight?i=6:this._cascadesEnabled?i=this._numberOfCascades:i=1,this._passes=new Array(i);for(let o=0;o<i;++o)this._passes[o]=new T3e(t);this.debugShow=!1,this.debugFreezeFrame=!1,this._debugFreezeFrame=!1,this._debugCascadeColors=!1,this._debugLightFrustum=void 0,this._debugCameraFrustum=void 0,this._debugCascadeFrustums=new Array(this._numberOfCascades),this._debugShadowViewCommand=void 0,this._usesDepthTexture=t.depthTexture,this._isPointLight&&(this._usesDepthTexture=!1),this._primitiveRenderState=void 0,this._terrainRenderState=void 0,this._pointRenderState=void 0,O1(this),this._clearCommand=new bi({depth:1,color:new z}),this._clearPassState=new Lp(t),this._size=y(e.size,2048),this.size=this._size}Wa.MAXIMUM_DISTANCE=2e4;function T3e(e){this.camera=new sE,this.passState=new Lp(e),this.framebuffer=void 0,this.textureOffsets=void 0,this.commandList=[],this.cullingVolume=void 0}function Ov(e,t){return Ue.fromCache({cull:{enabled:!0,face:Qi.BACK},depthTest:{enabled:!0},colorMask:{red:e,green:e,blue:e,alpha:e},depthMask:!0,polygonOffset:{enabled:t.polygonOffset,factor:t.polygonOffsetFactor,units:t.polygonOffsetUnits}})}function O1(e){const t=!e._usesDepthTexture;e._primitiveRenderState=Ov(t,e._primitiveBias),e._terrainRenderState=Ov(t,e._terrainBias),e._pointRenderState=Ov(t,e._pointBias)}Wa.prototype.debugCreateRenderStates=function(){O1(this)};Object.defineProperties(Wa.prototype,{enabled:{get:function(){return this._enabled},set:function(e){this.dirty=this._enabled!==e,this._enabled=e}},normalOffset:{get:function(){return this._normalOffset},set:function(e){this.dirty=this._normalOffset!==e,this._normalOffset=e,this._terrainBias.normalOffset=e,this._primitiveBias.normalOffset=e,this._poin
in vec2 v_textureCoordinates;
void main()
{
vec2 uv = v_textureCoordinates;
vec3 dir;
if (uv.y < 0.5)
{
if (uv.x < 0.333)
{
dir.x = -1.0;
dir.y = uv.x * 6.0 - 1.0;
dir.z = uv.y * 4.0 - 1.0;
}
else if (uv.x < 0.666)
{
dir.y = -1.0;
dir.x = uv.x * 6.0 - 3.0;
dir.z = uv.y * 4.0 - 1.0;
}
else
{
dir.z = -1.0;
dir.x = uv.x * 6.0 - 5.0;
dir.y = uv.y * 4.0 - 1.0;
}
}
else
{
if (uv.x < 0.333)
{
dir.x = 1.0;
dir.y = uv.x * 6.0 - 1.0;
dir.z = uv.y * 4.0 - 3.0;
}
else if (uv.x < 0.666)
{
dir.y = 1.0;
dir.x = uv.x * 6.0 - 3.0;
dir.z = uv.y * 4.0 - 3.0;
}
else
{
dir.z = 1.0;
dir.x = uv.x * 6.0 - 5.0;
dir.y = uv.y * 4.0 - 3.0;
}
}
float shadow = czm_unpackDepth(czm_textureCube(shadowMap_textureCube, dir));
out_FragColor = vec4(vec3(shadow), 1.0);
}
`:n=`uniform sampler2D shadowMap_texture;
in vec2 v_textureCoordinates;
void main()
{
${e._usesDepthTexture?` float shadow = texture(shadowMap_texture, v_textureCoordinates).r;
`:` float shadow = czm_unpackDepth(texture(shadowMap_texture, v_textureCoordinates));
`} out_FragColor = vec4(vec3(shadow), 1.0);
}
`;const i=t.createViewportQuadCommand(n,{uniformMap:{shadowMap_texture:function(){return e._shadowMapTexture},shadowMap_textureCube:function(){return e._shadowMapTexture}}});return i.pass=xe.OVERLAY,i}function D3e(e,t){const n=t.context,i=t.context.drawingBufferWidth,o=t.context.drawingBufferHeight,r=Math.min(i,o)*.3,s=v3e;s.x=i-r,s.y=0,s.width=r,s.height=r;let a=e._debugShadowViewCommand;c(a)||(a=I3e(e,n),e._debugShadowViewCommand=a),(!c(a.renderState)||!Re.equals(a.renderState.viewport,s))&&(a.renderState=Ue.fromCache({viewport:Re.clone(s)})),t.commandList.push(e._debugShadowViewCommand)}const wu=new Array(8);wu[0]=new te(-1,-1,-1,1);wu[1]=new te(1,-1,-1,1);wu[2]=new te(1,1,-1,1);wu[3]=new te(-1,1,-1,1);wu[4]=new te(-1,-1,1,1);wu[5]=new te(1,-1,1,1);wu[6]=new te(1,1,1,1);wu[7]=new te(-1,1,1,1);const mh=new L,R1=new Array(8);for(let e=0;e<8;++e)R1[e]=new te;function P3e(e,t){const n=new Gt({geometry:new Na({minimum:new d(-.5,-.5,-.5),maximum:new d(.5,.5,.5)}),attributes:{color:$t.fromColor(t)}}),i=new Gt({geometry:new Fh({radius:.5}),attributes:{color:$t.fromColor(t)}});return new Mt({geometryInstances:[n,i],appearance:new tn({translucent:!1,flat:!0}),asynchronous:!1,modelMatrix:e})}const O3e=[z.RED,z.GREEN,z.BLUE,z.MAGENTA],L3e=new d;function R3e(e,t){D3e(e,t);const n=e.debugFreezeFrame&&!e._debugFreezeFrame;if(e._debugFreezeFrame=e.debugFreezeFrame,e.debugFreezeFrame&&(n&&(e._debugCameraFrustum=e._debugCameraFrustum&&e._debugCameraFrustum.destroy(),e._debugCameraFrustum=new ph({camera:e._sceneCamera,color:z.CYAN,updateOnChange:!1})),e._debugCameraFrustum.update(t)),e._cascadesEnabled){if(e.debugFreezeFrame){n&&(e._debugLightFrustum=e._debugLightFrustum&&e._debugLightFrustum.destroy(),e._debugLightFrustum=new ph({camera:e._shadowMapCamera,color:z.YELLOW,updateOnChange:!1})),e._debugLightFrustum.update(t);for(let i=0;i<e._numberOfCascades;++i)n&&(e._debugCascadeFrustums[i]=e._debugCascadeFrustums[i]&&e._debugCascadeFrustums[i].destroy(),e._debugCascadeFrustums[i]=new ph({camera:e._passes[i].camera,color:O3e[i],updateOnChange:!1})),e._debugCascadeFrustums[i].update(t)}}else if(e._isPointLight){if(!c(e._debugLightFrustum)||e._needsUpdate){const i=e._shadowMapCamera.positionWC,o=_e.IDENTITY,r=e._pointLightRadius*2,s=d.fromElements(r,r,r,L3e),a=L.fromTranslationQuaternionRotationScale(i,o,s,mh);e._debugLightFrustum=e._debugLightFrustum&&e._debugLightFrustum.destroy(),e._debugLightFrustum=P3e(a,z.YELLOW)}e._debugLightFrustum.update(t)}else(!c(e._debugLightFrustum)||e._needsUpdate)&&(e._debugLightFrustum=new ph({camera:e._shadowMapCamera,color:z.YELLOW,updateOnChange:!1})),e._debugLightFrustum.update(t)}function sE(){this.viewMatrix=new L,this.inverseViewMatrix=new L,this.frustum=void 0,this.positionCartographic=new he,this.positionWC=new d,this.directionWC=d.clone(d.UNIT_Z),this.upWC=d.clone(d.UNIT_Y),this.rightWC=d.clone(d.UNIT_X),this.viewProjectionMatrix=new L}sE.prototype.clone=function(e){L.clone(e.viewMatrix,this.viewMatrix),L.clone(e.inverseViewMatrix,this.inverseViewMatrix),this.frustum=e.frustum.clone(this.frustum),he.clone(e.positionCartographic,this.positionCartographic),d.clone(e.positionWC,this.positionWC),d.clone(e.directionWC,this.directionWC),d.clone(e.upWC,this.upWC),d.clone(e.rightWC,this.rightWC)};const N3e=new L(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);sE.prototype.getViewProjection=function(){const e=this.viewMatrix,t=this.frustum.projectionMatrix;return L.multiply(t,e,this.viewProjectionMatrix),L.multiply(N3e,this.viewProjectionMatrix,this.viewProjectionMatrix),this.viewProjectionMatrix};const M3e=new Array(5),F3e=new _n,B3e=new Array(4),GW=new d,jW=new d;function z3e(e,t){const n=e._shadowMapCamera,i=e._sceneCamera,o=i.frustum.near,r=i.frustum.far,s=e._numberOfCascades;let a;const l=r-o,u=r/o;let h=.9,f=!1;t.shadowState.closestObjectSize<200&&(f=!0,h=.9);const _=B3e,g=M3e;for(g[0]=o,g[s]=r,a=0;a<s;++a){const B=(a+1)/s,S=o*Math.pow(u,B),D=o+l*B,p=R.lerp(D,S,h);g[a+1]=p,_[a]=p-g[a]}if(f){for(a=0;a<s;++a)_[a]=Math.min(_[a],e._maximumCascadeDistances[a]);let B=g[0];for(a=0;a<s-1;++a)B+=_[a],g[a+1]=B}te.unpa
#ifdef DEBUG_SHOW_DEPTH
uniform sampler2D u_packedTranslucentDepth;
#endif
in vec2 v_textureCoordinates;
void main()
{
#ifdef DEBUG_SHOW_DEPTH
if (v_textureCoordinates.x < 0.5)
{
out_FragColor.rgb = vec3(czm_unpackDepth(texture(u_packedTranslucentDepth, v_textureCoordinates)));
out_FragColor.a = 1.0;
}
#else
vec4 color = texture(colorTexture, v_textureCoordinates);
#ifdef PICK
if (color == vec4(0.0))
{
discard;
}
#else
// Reverse premultiplication process to get the correct composited result of the classification primitives
color.rgb /= color.a;
#endif
out_FragColor = color;
#endif
}
`;function rf(e){this._drawClassificationFBO=new on({createDepthAttachments:!1}),this._accumulationFBO=new on({createDepthAttachments:!1}),this._packFBO=new on,this._opaqueDepthStencilTexture=void 0,this._textureToComposite=void 0,this._translucentDepthStencilTexture=void 0,this._packDepthCommand=void 0,this._accumulateCommand=void 0,this._compositeCommand=void 0,this._copyCommand=void 0,this._clearColorCommand=new bi({color:new z(0,0,0,0),owner:this}),this._clearDepthStencilCommand=new bi({depth:1,stencil:0,owner:this}),this._supported=e.depthTexture,this._viewport=new Re,this._rsDepth=void 0,this._rsAccumulate=void 0,this._rsComp=void 0,this._useScissorTest=void 0,this._scissorRectangle=void 0,this._hasTranslucentDepth=!1,this._frustumsDrawn=0}Object.defineProperties(rf.prototype,{hasTranslucentDepth:{get:function(){return this._hasTranslucentDepth}}});function YW(e){e._textureToComposite=void 0,e._translucentDepthStencilTexture=e._translucentDepthStencilTexture&&!e._translucentDepthStencilTexture.isDestroyed()&&e._translucentDepthStencilTexture.destroy()}function $W(e){e._drawClassificationFBO.destroy(),e._accumulationFBO.destroy(),e._packFBO.destroy()}function J3e(e,t,n,i){YW(e),e._translucentDepthStencilTexture=new xt({context:t,width:n,height:i,pixelFormat:Ve.DEPTH_STENCIL,pixelDatatype:Me.UNSIGNED_INT_24_8,sampler:un.NEAREST})}function eze(e,t,n,i){$W(e),e._drawClassificationFBO.setDepthStencilTexture(e._translucentDepthStencilTexture),e._drawClassificationFBO.update(t,n,i),e._accumulationFBO.setDepthStencilTexture(e._translucentDepthStencilTexture),e._accumulationFBO.update(t,n,i),e._packFBO.update(t,n,i)}function tze(e,t,n,i){if(!e.isSupported())return;e._opaqueDepthStencilTexture=i;const o=e._opaqueDepthStencilTexture.width,r=e._opaqueDepthStencilTexture.height;e._drawClassificationFBO.isDirty(o,r)&&(J3e(e,t,o,r),eze(e,t,o,r));let s,a;if(c(e._packDepthCommand)||(s=new Oe({sources:[I1e]}),a={u_opaqueDepthTexture:function(){return e._opaqueDepthStencilTexture},u_translucentDepthTexture:function(){return e._translucentDepthStencilTexture}},e._packDepthCommand=t.createViewportQuadCommand(s,{uniformMap:a,owner:e})),!c(e._compositeCommand)){s=new Oe({sources:[Lv]}),a={colorTexture:function(){return e._textureToComposite}},e._compositeCommand=t.createViewportQuadCommand(s,{uniformMap:a,owner:e});const h=e._compositeCommand,f=h.shaderProgram,_=t.shaderCache.createDerivedShaderProgram(f,"pick",{vertexShaderSource:f.vertexShaderSource,fragmentShaderSource:new Oe({sources:s.sources,defines:["PICK"]}),attributeLocations:f._attributeLocations}),g=Ze.shallowClone(h);g.shaderProgram=_,h.derivedCommands.pick=g}c(e._copyCommand)||(s=new Oe({sources:[Lv]}),a={colorTexture:function(){return e._drawClassificationFBO.getColorTexture()}},e._copyCommand=t.createViewportQuadCommand(s,{uniformMap:a,owner:e})),c(e._accumulateCommand)||(s=new Oe({sources:[Lv]}),a={colorTexture:function(){return e._drawClassificationFBO.getColorTexture()}},e._accumulateCommand=t.createViewportQuadCommand(s,{uniformMap:a,owner:e})),e._viewport.width=o,e._viewport.height=r;const l=!Re.equals(e._viewport,n.viewport);let u=l!==e._useScissorTest;e._useScissorTest=l,Re.equals(e._scissorRectangle,n.viewport)||(e._scissorRectangle=Re.clone(n.viewport,e._scissorRectangle),u=!0),(!c(e._rsDepth)||!Re.equals(e._viewport,e._rsDepth.viewport)||u)&&(e._rsDepth=Ue.fromCache({viewport:e._viewport,scissorTest:{enabled:e._useScissorTest,rectangle:e._scissorRectangle}})),c(e._packDepthCommand)&&(e._packDepthCommand.renderState=e._rsDepth),(!c(e._rsAccumulate)||!Re.equals(e._viewport,e._rsAccumulate.viewport)||u)&&(e._rsAccumulate=Ue.fromCache({viewport:e._viewport,scissorTest:{enabled:e._useScissorTest,rectangle:e._scissorRectangle},stencilTest:{enabled:!0,frontFunction:Pn.EQUAL,reference:At.CESIUM_3D_TILE_MASK}})),c(e._accumulateCommand)&&(e._accumulateCommand.renderState=e._rsAccumulate),(!c(e._rsComp)||!Re.equals(e._viewport,e._rsComp.viewport)||u)&&(e._rsComp=Ue.fromCache({viewport:e._viewport,scissorTest:{enabled:e._useScissorTest,rectangle:e._scissorRectangle},blendin
in vec2 v_textureCoordinates;
#ifdef AUTO_EXPOSURE
uniform sampler2D autoExposure;
#endif
void main()
{
vec4 fragmentColor = texture(colorTexture, v_textureCoordinates);
vec3 color = fragmentColor.rgb;
#ifdef AUTO_EXPOSURE
color /= texture(autoExposure, vec2(0.5)).r;
#endif
color = czm_acesTonemapping(color);
color = czm_inverseGamma(color);
out_FragColor = vec4(color, fragmentColor.a);
}
`,Fze=`uniform sampler2D randomTexture;
uniform sampler2D depthTexture;
uniform float intensity;
uniform float bias;
uniform float lengthCap;
uniform float stepSize;
uniform float frustumLength;
in vec2 v_textureCoordinates;
vec4 clipToEye(vec2 uv, float depth)
{
vec2 xy = vec2((uv.x * 2.0 - 1.0), ((1.0 - uv.y) * 2.0 - 1.0));
vec4 posEC = czm_inverseProjection * vec4(xy, depth, 1.0);
posEC = posEC / posEC.w;
return posEC;
}
//Reconstruct Normal Without Edge Removation
vec3 getNormalXEdge(vec3 posInCamera, float depthU, float depthD, float depthL, float depthR, vec2 pixelSize)
{
vec4 posInCameraUp = clipToEye(v_textureCoordinates - vec2(0.0, pixelSize.y), depthU);
vec4 posInCameraDown = clipToEye(v_textureCoordinates + vec2(0.0, pixelSize.y), depthD);
vec4 posInCameraLeft = clipToEye(v_textureCoordinates - vec2(pixelSize.x, 0.0), depthL);
vec4 posInCameraRight = clipToEye(v_textureCoordinates + vec2(pixelSize.x, 0.0), depthR);
vec3 up = posInCamera.xyz - posInCameraUp.xyz;
vec3 down = posInCameraDown.xyz - posInCamera.xyz;
vec3 left = posInCamera.xyz - posInCameraLeft.xyz;
vec3 right = posInCameraRight.xyz - posInCamera.xyz;
vec3 DX = length(left) < length(right) ? left : right;
vec3 DY = length(up) < length(down) ? up : down;
return normalize(cross(DY, DX));
}
void main(void)
{
float depth = czm_readDepth(depthTexture, v_textureCoordinates);
vec4 posInCamera = clipToEye(v_textureCoordinates, depth);
if (posInCamera.z > frustumLength)
{
out_FragColor = vec4(1.0);
return;
}
vec2 pixelSize = czm_pixelRatio / czm_viewport.zw;
float depthU = czm_readDepth(depthTexture, v_textureCoordinates - vec2(0.0, pixelSize.y));
float depthD = czm_readDepth(depthTexture, v_textureCoordinates + vec2(0.0, pixelSize.y));
float depthL = czm_readDepth(depthTexture, v_textureCoordinates - vec2(pixelSize.x, 0.0));
float depthR = czm_readDepth(depthTexture, v_textureCoordinates + vec2(pixelSize.x, 0.0));
vec3 normalInCamera = getNormalXEdge(posInCamera.xyz, depthU, depthD, depthL, depthR, pixelSize);
float ao = 0.0;
vec2 sampleDirection = vec2(1.0, 0.0);
float gapAngle = 90.0 * czm_radiansPerDegree;
// RandomNoise
float randomVal = texture(randomTexture, v_textureCoordinates / pixelSize / 255.0).x;
//Loop for each direction
for (int i = 0; i < 4; i++)
{
float newGapAngle = gapAngle * (float(i) + randomVal);
float cosVal = cos(newGapAngle);
float sinVal = sin(newGapAngle);
//Rotate Sampling Direction
vec2 rotatedSampleDirection = vec2(cosVal * sampleDirection.x - sinVal * sampleDirection.y, sinVal * sampleDirection.x + cosVal * sampleDirection.y);
float localAO = 0.0;
float localStepSize = stepSize;
//Loop for each step
for (int j = 0; j < 6; j++)
{
vec2 newCoords = v_textureCoordinates + rotatedSampleDirection * localStepSize * pixelSize;
//Exception Handling
if(newCoords.x > 1.0 || newCoords.y > 1.0 || newCoords.x < 0.0 || newCoords.y < 0.0)
{
break;
}
float stepDepthInfo = czm_readDepth(depthTexture, newCoords);
vec4 stepPosInCamera = clipToEye(newCoords, stepDepthInfo);
vec3 diffVec = stepPosInCamera.xyz - posInCamera.xyz;
float len = length(diffVec);
if (len > lengthCap)
{
break;
}
float dotVal = clamp(dot(normalInCamera, normalize(diffVec)), 0.0, 1.0 );
float weight = len / lengthCap;
weight = 1.0 - weight * weight;
if (dotVal < bias)
{
dotVal = 0.0;
}
localAO = max(localAO, dotVal * weight);
localStepSize += stepSize;
}
ao += localAO;
}
ao /= 4.0;
ao = 1.0 - clamp(ao, 0.0, 1.0);
ao = pow(ao, intensity);
out_FragColor = vec4(vec3(ao), 1.0);
}
`,Bze=`uniform sampler2D colorTexture;
uniform sampler2D ambientOcclusionTexture;
uniform bool ambientOcclusionOnly;
in vec2 v_textureCoordinates;
void main(void)
{
vec4 color = texture(colorTexture, v_textureCoordinates);
vec4 ao = texture(ambientOcclusionTexture, v_textureCoordinates);
out_FragColor = ambientOcclusionOnly ? ao : ao * color;
}
`,zze=`uniform sampler2D colorTexture;
uniform float gradations;
in vec2 v_textureCoordinates;
void main(void)
{
vec3 rgb = texture(colorTexture, v_textureCoordinates).rgb;
#ifdef CZM_SELECTED_FEATURE
if (czm_selected()) {
out_FragColor = vec4(rgb, 1.0);
return;
}
#endif
float luminance = czm_luminance(rgb);
float darkness = luminance * gradations;
darkness = (darkness - fract(darkness)) / gradations;
out_FragColor = vec4(vec3(darkness), 1.0);
}
`,Uze=`uniform sampler2D colorTexture;
uniform sampler2D bloomTexture;
uniform bool glowOnly;
in vec2 v_textureCoordinates;
void main(void)
{
vec4 color = texture(colorTexture, v_textureCoordinates);
#ifdef CZM_SELECTED_FEATURE
if (czm_selected()) {
out_FragColor = color;
return;
}
#endif
vec4 bloom = texture(bloomTexture, v_textureCoordinates);
out_FragColor = glowOnly ? bloom : bloom + color;
}
`,kze=`uniform sampler2D colorTexture;
uniform float brightness;
in vec2 v_textureCoordinates;
void main(void)
{
vec3 rgb = texture(colorTexture, v_textureCoordinates).rgb;
vec3 target = vec3(0.0);
out_FragColor = vec4(mix(target, rgb, brightness), 1.0);
}
`,Vze=`uniform sampler2D colorTexture;
uniform float contrast;
uniform float brightness;
in vec2 v_textureCoordinates;
void main(void)
{
vec3 sceneColor = texture(colorTexture, v_textureCoordinates).xyz;
sceneColor = czm_RGBToHSB(sceneColor);
sceneColor.z += brightness;
sceneColor = czm_HSBToRGB(sceneColor);
float factor = (259.0 * (contrast + 255.0)) / (255.0 * (259.0 - contrast));
sceneColor = factor * (sceneColor - vec3(0.5)) + vec3(0.5);
out_FragColor = vec4(sceneColor, 1.0);
}
`,Hze=`uniform sampler2D colorTexture;
uniform sampler2D blurTexture;
uniform sampler2D depthTexture;
uniform float focalDistance;
in vec2 v_textureCoordinates;
vec4 toEye(vec2 uv, float depth)
{
vec2 xy = vec2((uv.x * 2.0 - 1.0), ((1.0 - uv.y) * 2.0 - 1.0));
vec4 posInCamera = czm_inverseProjection * vec4(xy, depth, 1.0);
posInCamera = posInCamera / posInCamera.w;
return posInCamera;
}
float computeDepthBlur(float depth)
{
float f;
if (depth < focalDistance)
{
f = (focalDistance - depth) / (focalDistance - czm_currentFrustum.x);
}
else
{
f = (depth - focalDistance) / (czm_currentFrustum.y - focalDistance);
f = pow(f, 0.1);
}
f *= f;
f = clamp(f, 0.0, 1.0);
return pow(f, 0.5);
}
void main(void)
{
float depth = czm_readDepth(depthTexture, v_textureCoordinates);
vec4 posInCamera = toEye(v_textureCoordinates, depth);
float d = computeDepthBlur(-posInCamera.z);
out_FragColor = mix(texture(colorTexture, v_textureCoordinates), texture(blurTexture, v_textureCoordinates), d);
}
`,Gze=`uniform sampler2D depthTexture;
in vec2 v_textureCoordinates;
void main(void)
{
float depth = czm_readDepth(depthTexture, v_textureCoordinates);
out_FragColor = vec4(vec3(depth), 1.0);
}
`,jze=`uniform sampler2D depthTexture;
uniform float length;
uniform vec4 color;
in vec2 v_textureCoordinates;
void main(void)
{
float directions[3];
directions[0] = -1.0;
directions[1] = 0.0;
directions[2] = 1.0;
float scalars[3];
scalars[0] = 3.0;
scalars[1] = 10.0;
scalars[2] = 3.0;
float padx = czm_pixelRatio / czm_viewport.z;
float pady = czm_pixelRatio / czm_viewport.w;
#ifdef CZM_SELECTED_FEATURE
bool selected = false;
for (int i = 0; i < 3; ++i)
{
float dir = directions[i];
selected = selected || czm_selected(vec2(-padx, dir * pady));
selected = selected || czm_selected(vec2(padx, dir * pady));
selected = selected || czm_selected(vec2(dir * padx, -pady));
selected = selected || czm_selected(vec2(dir * padx, pady));
if (selected)
{
break;
}
}
if (!selected)
{
out_FragColor = vec4(color.rgb, 0.0);
return;
}
#endif
float horizEdge = 0.0;
float vertEdge = 0.0;
for (int i = 0; i < 3; ++i)
{
float dir = directions[i];
float scale = scalars[i];
horizEdge -= texture(depthTexture, v_textureCoordinates + vec2(-padx, dir * pady)).x * scale;
horizEdge += texture(depthTexture, v_textureCoordinates + vec2(padx, dir * pady)).x * scale;
vertEdge -= texture(depthTexture, v_textureCoordinates + vec2(dir * padx, -pady)).x * scale;
vertEdge += texture(depthTexture, v_textureCoordinates + vec2(dir * padx, pady)).x * scale;
}
float len = sqrt(horizEdge * horizEdge + vertEdge * vertEdge);
out_FragColor = vec4(color.rgb, len > length ? color.a : 0.0);
}
`,Wze=`uniform sampler2D colorTexture;
in vec2 v_textureCoordinates;
#ifdef AUTO_EXPOSURE
uniform sampler2D autoExposure;
#endif
// See slides 142 and 143:
// http://www.gdcvault.com/play/1012459/Uncharted_2__HDR_Lighting
void main()
{
vec4 fragmentColor = texture(colorTexture, v_textureCoordinates);
vec3 color = fragmentColor.rgb;
#ifdef AUTO_EXPOSURE
float exposure = texture(autoExposure, vec2(0.5)).r;
color /= exposure;
#endif
const float A = 0.22; // shoulder strength
const float B = 0.30; // linear strength
const float C = 0.10; // linear angle
const float D = 0.20; // toe strength
const float E = 0.01; // toe numerator
const float F = 0.30; // toe denominator
const float white = 11.2; // linear white point value
vec3 c = ((color * (A * color + C * B) + D * E) / (color * ( A * color + B) + D * F)) - E / F;
float w = ((white * (A * white + C * B) + D * E) / (white * ( A * white + B) + D * F)) - E / F;
c = czm_inverseGamma(c / w);
out_FragColor = vec4(c, fragmentColor.a);
}
`,qze=`in vec2 v_textureCoordinates;
uniform sampler2D colorTexture;
const float fxaaQualitySubpix = 0.5;
const float fxaaQualityEdgeThreshold = 0.125;
const float fxaaQualityEdgeThresholdMin = 0.0833;
void main()
{
vec2 fxaaQualityRcpFrame = vec2(1.0) / czm_viewport.zw;
vec4 color = FxaaPixelShader(
v_textureCoordinates,
colorTexture,
fxaaQualityRcpFrame,
fxaaQualitySubpix,
fxaaQualityEdgeThreshold,
fxaaQualityEdgeThresholdMin);
float alpha = texture(colorTexture, v_textureCoordinates).a;
out_FragColor = vec4(color.rgb, alpha);
}
`,$D=`#define SAMPLES 8
uniform float delta;
uniform float sigma;
uniform float direction; // 0.0 for x direction, 1.0 for y direction
uniform sampler2D colorTexture;
#ifdef USE_STEP_SIZE
uniform float stepSize;
#else
uniform vec2 step;
#endif
in vec2 v_textureCoordinates;
// Incremental Computation of the Gaussian:
// https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch40.html
void main()
{
vec2 st = v_textureCoordinates;
vec2 dir = vec2(1.0 - direction, direction);
#ifdef USE_STEP_SIZE
vec2 step = vec2(stepSize * (czm_pixelRatio / czm_viewport.zw));
#else
vec2 step = step;
#endif
vec3 g;
g.x = 1.0 / (sqrt(czm_twoPi) * sigma);
g.y = exp((-0.5 * delta * delta) / (sigma * sigma));
g.z = g.y * g.y;
vec4 result = texture(colorTexture, st) * g.x;
for (int i = 1; i < SAMPLES; ++i)
{
g.xy *= g.yz;
vec2 offset = float(i) * dir * step;
result += texture(colorTexture, st - offset) * g.x;
result += texture(colorTexture, st + offset) * g.x;
}
out_FragColor = result;
}
`,Yze=`uniform sampler2D colorTexture;
uniform sampler2D dirtTexture;
uniform sampler2D starTexture;
uniform vec2 dirtTextureDimensions;
uniform float distortion;
uniform float ghostDispersal;
uniform float haloWidth;
uniform float dirtAmount;
uniform float earthRadius;
uniform float intensity;
in vec2 v_textureCoordinates;
// whether it is in space or not
// 6500000.0 is empirical value
#define DISTANCE_TO_SPACE 6500000.0
// return ndc from world coordinate biased earthRadius
vec4 getNDCFromWC(vec3 WC, float earthRadius)
{
vec4 positionEC = czm_view * vec4(WC, 1.0);
positionEC = vec4(positionEC.x + earthRadius, positionEC.y, positionEC.z, 1.0);
vec4 positionWC = czm_eyeToWindowCoordinates(positionEC);
return czm_viewportOrthographic * vec4(positionWC.xy, -positionWC.z, 1.0);
}
// Check if current pixel is included Earth
// if then mask it gradually
float isInEarth(vec2 texcoord, vec2 sceneSize)
{
vec2 NDC = texcoord * 2.0 - 1.0;
vec4 earthPosSC = getNDCFromWC(vec3(0.0), 0.0);
vec4 earthPosSCEdge = getNDCFromWC(vec3(0.0), earthRadius * 1.5);
NDC.xy -= earthPosSC.xy;
float X = abs(NDC.x) * sceneSize.x;
float Y = abs(NDC.y) * sceneSize.y;
return clamp(0.0, 1.0, max(sqrt(X * X + Y * Y) / max(abs(earthPosSCEdge.x * sceneSize.x), 1.0) - 0.8 , 0.0));
}
// For Chromatic effect
vec4 textureDistorted(sampler2D tex, vec2 texcoord, vec2 direction, vec3 distortion, bool isSpace)
{
vec2 sceneSize = czm_viewport.zw;
vec3 color;
if(isSpace)
{
color.r = isInEarth(texcoord + direction * distortion.r, sceneSize) * texture(tex, texcoord + direction * distortion.r).r;
color.g = isInEarth(texcoord + direction * distortion.g, sceneSize) * texture(tex, texcoord + direction * distortion.g).g;
color.b = isInEarth(texcoord + direction * distortion.b, sceneSize) * texture(tex, texcoord + direction * distortion.b).b;
}
else
{
color.r = texture(tex, texcoord + direction * distortion.r).r;
color.g = texture(tex, texcoord + direction * distortion.g).g;
color.b = texture(tex, texcoord + direction * distortion.b).b;
}
return vec4(clamp(color, 0.0, 1.0), 0.0);
}
void main(void)
{
vec4 originalColor = texture(colorTexture, v_textureCoordinates);
vec3 rgb = originalColor.rgb;
bool isSpace = length(czm_viewerPositionWC.xyz) > DISTANCE_TO_SPACE;
// Sun position
vec4 sunPos = czm_morphTime == 1.0 ? vec4(czm_sunPositionWC, 1.0) : vec4(czm_sunPositionColumbusView.zxy, 1.0);
vec4 sunPositionEC = czm_view * sunPos;
vec4 sunPositionWC = czm_eyeToWindowCoordinates(sunPositionEC);
sunPos = czm_viewportOrthographic * vec4(sunPositionWC.xy, -sunPositionWC.z, 1.0);
// If sun is not in the screen space, use original color.
if(!isSpace || !((sunPos.x >= -1.1 && sunPos.x <= 1.1) && (sunPos.y >= -1.1 && sunPos.y <= 1.1)))
{
// Lens flare is disabled when not in space until #5932 is fixed.
// https://github.com/CesiumGS/cesium/issues/5932
out_FragColor = originalColor;
return;
}
vec2 texcoord = vec2(1.0) - v_textureCoordinates;
vec2 pixelSize = czm_pixelRatio / czm_viewport.zw;
vec2 invPixelSize = 1.0 / pixelSize;
vec3 distortionVec = pixelSize.x * vec3(-distortion, 0.0, distortion);
// ghost vector to image centre:
vec2 ghostVec = (vec2(0.5) - texcoord) * ghostDispersal;
vec3 direction = normalize(vec3(ghostVec, 0.0));
// sample ghosts:
vec4 result = vec4(0.0);
vec4 ghost = vec4(0.0);
for (int i = 0; i < 4; ++i)
{
vec2 offset = fract(texcoord + ghostVec * float(i));
// Only bright spots from the centre of the source image
ghost += textureDistorted(colorTexture, offset, direction.xy, distortionVec, isSpace);
}
result += ghost;
// sample halo
vec2 haloVec = normalize(ghostVec) * haloWidth;
float weightForHalo = length(vec2(0.5) - fract(texcoord + haloVec)) / length(vec2(0.5));
weightForHalo = pow(1.0 - weightForHalo, 5.0);
result += textureDistorted(colorTexture, texcoord + haloVec, direction.xy, distortionVec, isSpace) * weightForHalo * 1.5;
// dirt on lens
vec2 dirtTexCoords = (v_textureCoordinates * invPixelSize) / dirtTextureDimensions;
if (dirtTexCoords.x > 1.0)
{
dirtTexCoords.x = mod(floor(dirtTexCoords.x), 2.0) == 1.0 ? 1.0 - fract(dirtTexCoords.x) : fract(dirtTexCoords.x);
}
if (dirtTexCoords.y > 1.0)
{
dirtTexCoords.y = mod(floor(dirtTexCoords.y), 2.0) == 1.0 ? 1.0 - fract(dirtTexCoords.y) : fract(dirtTexCoords.y);
}
result += dirtAmount * texture(dirtTexture, dirtTexCoords);
// Rotating starburst texture's coordinate
// dot(czm_view[0].xyz, vec3(0.0, 0.0, 1.0)) + dot(czm_view[1].xyz, vec3(0.0, 1.0, 0.0))
float camrot = czm_view[0].z + czm_view[1].y;
float cosValue = cos(camrot);
float sinValue = sin(camrot);
mat3 rotation = mat3(
cosValue, -sinValue, 0.0,
sinValue, cosValue, 0.0,
0.0, 0.0, 1.0
);
vec3 st1 = vec3(v_textureCoordinates * 2.0 - vec2(1.0), 1.0);
vec3 st2 = vec3((rotation * st1).xy, 1.0);
vec3 st3 = st2 * 0.5 + vec3(0.5);
vec2 lensStarTexcoord = st3.xy;
float weightForLensFlare = length(vec3(sunPos.xy, 0.0));
float oneMinusWeightForLensFlare = max(1.0 - weightForLensFlare, 0.0);
if (!isSpace)
{
result *= oneMinusWeightForLensFlare * intensity * 0.2;
}
else
{
result *= oneMinusWeightForLensFlare * intensity;
result *= texture(starTexture, lensStarTexcoord) * pow(weightForLensFlare, 1.0) * max((1.0 - length(vec3(st1.xy, 0.0))), 0.0) * 2.0;
}
result += texture(colorTexture, v_textureCoordinates);
out_FragColor = result;
}
`,$ze=`uniform sampler2D colorTexture;
uniform vec3 white;
in vec2 v_textureCoordinates;
#ifdef AUTO_EXPOSURE
uniform sampler2D autoExposure;
#endif
// See equation 4:
// http://www.cs.utah.edu/~reinhard/cdrom/tonemap.pdf
void main()
{
vec4 fragmentColor = texture(colorTexture, v_textureCoordinates);
vec3 color = fragmentColor.rgb;
#ifdef AUTO_EXPOSURE
float exposure = texture(autoExposure, vec2(0.5)).r;
color /= exposure;
#endif
color = (color * (1.0 + color / white)) / (1.0 + color);
color = czm_inverseGamma(color);
out_FragColor = vec4(color, fragmentColor.a);
}
`,Xze=`uniform sampler2D colorTexture;
in vec2 v_textureCoordinates;
float rand(vec2 co)
{
return fract(sin(dot(co.xy ,vec2(12.9898, 78.233))) * 43758.5453);
}
void main(void)
{
float noiseValue = rand(v_textureCoordinates + sin(czm_frameNumber)) * 0.1;
vec3 rgb = texture(colorTexture, v_textureCoordinates).rgb;
vec3 green = vec3(0.0, 1.0, 0.0);
out_FragColor = vec4((noiseValue + rgb) * green, 1.0);
}
`,Qze=`uniform sampler2D colorTexture;
in vec2 v_textureCoordinates;
#ifdef AUTO_EXPOSURE
uniform sampler2D autoExposure;
#endif
// See equation 3:
// http://www.cs.utah.edu/~reinhard/cdrom/tonemap.pdf
void main()
{
vec4 fragmentColor = texture(colorTexture, v_textureCoordinates);
vec3 color = fragmentColor.rgb;
#ifdef AUTO_EXPOSURE
float exposure = texture(autoExposure, vec2(0.5)).r;
color /= exposure;
#endif
color = color / (1.0 + color);
color = czm_inverseGamma(color);
out_FragColor = vec4(color, fragmentColor.a);
}
`,Kze=`uniform sampler2D colorTexture;
uniform sampler2D silhouetteTexture;
in vec2 v_textureCoordinates;
void main(void)
{
vec4 silhouetteColor = texture(silhouetteTexture, v_textureCoordinates);
vec4 color = texture(colorTexture, v_textureCoordinates);
out_FragColor = mix(color, silhouetteColor, silhouetteColor.a);
}
`;function $p(){this._uniformMap=void 0,this._command=void 0,this._colorTexture=void 0,this._depthTexture=void 0,this._ready=!1,this._name="czm_autoexposure",this._logDepthChanged=void 0,this._useLogDepth=void 0,this._framebuffers=void 0,this._previousLuminance=new on,this._commands=void 0,this._clearCommand=void 0,this._minMaxLuminance=new H,this.enabled=!0,this._enabled=!0,this.minimumLuminance=.1,this.maximumLuminance=10}Object.defineProperties($p.prototype,{ready:{get:function(){return this._ready}},name:{get:function(){return this._name}},outputTexture:{get:function(){const e=this._framebuffers;if(!!c(e))return e[e.length-1].getColorTexture(0)}}});function o6(e){const t=e._framebuffers;if(!c(t))return;const n=t.length;for(let i=0;i<n;++i)t[i].destroy();e._framebuffers=void 0,e._previousLuminance.destroy(),e._previousLuminance=void 0}function Zze(e,t){o6(e);let n=e._width,i=e._height;const o=t.halfFloatingPointTexture?Me.HALF_FLOAT:Me.FLOAT,r=Math.ceil(Math.log(Math.max(n,i))/Math.log(3)),s=new Array(r);for(let l=0;l<r;++l)n=Math.max(Math.ceil(n/3),1),i=Math.max(Math.ceil(i/3),1),s[l]=new on,s[l].update(t,n,i,1,o);const a=s[r-1].getColorTexture(0);e._previousLuminance.update(t,a.width,a.height,1,o),e._framebuffers=s}function r6(e){const t=e._commands;if(!c(t))return;const n=t.length;for(let i=0;i<n;++i)t[i].shaderProgram.destroy();e._commands=void 0}function Jze(e,t){let n;if(t===0)n={colorTexture:function(){return e._colorTexture},colorTextureDimensions:function(){return e._colorTexture.dimensions}};else{const i=e._framebuffers[t-1].getColorTexture(0);n={colorTexture:function(){return i},colorTextureDimensions:function(){return i.dimensions}}}return n.minMaxLuminance=function(){return e._minMaxLuminance},n.previousLuminance=function(){return e._previousLuminance.getColorTexture(0)},n}function eUe(e,t){let n=`uniform sampler2D colorTexture;
in vec2 v_textureCoordinates;
float sampleTexture(vec2 offset) {
`;return e===0?n+=` vec4 color = texture(colorTexture, v_textureCoordinates + offset);
return czm_luminance(color.rgb);
`:n+=` return texture(colorTexture, v_textureCoordinates + offset).r;
`,n+=`}
`,n+=`uniform vec2 colorTextureDimensions;
uniform vec2 minMaxLuminance;
uniform sampler2D previousLuminance;
void main() {
float color = 0.0;
float xStep = 1.0 / colorTextureDimensions.x;
float yStep = 1.0 / colorTextureDimensions.y;
int count = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
vec2 offset;
offset.x = -xStep + float(i) * xStep;
offset.y = -yStep + float(j) * yStep;
if (offset.x < 0.0 || offset.x > 1.0 || offset.y < 0.0 || offset.y > 1.0) {
continue;
}
color += sampleTexture(offset);
++count;
}
}
if (count > 0) {
color /= float(count);
}
`,e===t-1&&(n+=` float previous = texture(previousLuminance, vec2(0.5)).r;
color = clamp(color, minMaxLuminance.x, minMaxLuminance.y);
color = previous + (color - previous) / (60.0 * 1.5);
color = clamp(color, minMaxLuminance.x, minMaxLuminance.y);
`),n+=` out_FragColor = vec4(color);
}
`,n}function tUe(e,t){r6(e);const n=e._framebuffers,i=n.length,o=new Array(i);for(let r=0;r<i;++r)o[r]=t.createViewportQuadCommand(eUe(r,i),{framebuffer:n[r].framebuffer,uniformMap:Jze(e,r)});e._commands=o}$p.prototype.clear=function(e){const t=this._framebuffers;if(!c(t))return;let n=this._clearCommand;c(n)||(n=this._clearCommand=new bi({color:new z(0,0,0,0),framebuffer:void 0}));const i=t.length;for(let o=0;o<i;++o)t[o].clear(e,n)};$p.prototype.update=function(e){const t=e.drawingBufferWidth,n=e.drawingBufferHeight;(t!==this._width||n!==this._height)&&(this._width=t,this._height=n,Zze(this,e),tUe(this,e),this._ready||(this._ready=!0)),this._minMaxLuminance.x=this.minimumLuminance,this._minMaxLuminance.y=this.maximumLuminance;const i=this._framebuffers,o=i[i.length-1];i[i.length-1]=this._previousLuminance,this._commands[this._commands.length-1].framebuffer=this._previousLuminance.framebuffer,this._previousLuminance=o};$p.prototype.execute=function(e,t){this._colorTexture=t;const n=this._commands;if(!c(n))return;const i=n.length;for(let o=0;o<i;++o)n[o].execute(e)};$p.prototype.isDestroyed=function(){return!1};$p.prototype.destroy=function(){return o6(this),r6(this),ve(this)};const nUe={NEAREST:0,LINEAR:1},wp=nUe;function Wn(e){e=y(e,y.EMPTY_OBJECT);const t=e.fragmentShader,n=y(e.textureScale,1),i=y(e.pixelFormat,Ve.RGBA);if(A.typeOf.string("options.fragmentShader",t),A.typeOf.number.greaterThan("options.textureScale",n,0),A.typeOf.number.lessThanOrEquals("options.textureScale",n,1),!Ve.isColorFormat(i))throw new E("options.pixelFormat must be a color format.");this._fragmentShader=t,this._uniforms=e.uniforms,this._textureScale=n,this._forcePowerOfTwo=y(e.forcePowerOfTwo,!1),this._sampleMode=y(e.sampleMode,wp.NEAREST),this._pixelFormat=i,this._pixelDatatype=y(e.pixelDatatype,Me.UNSIGNED_BYTE),this._clearColor=y(e.clearColor,z.BLACK),this._uniformMap=void 0,this._command=void 0,this._colorTexture=void 0,this._depthTexture=void 0,this._idTexture=void 0,this._actualUniforms={},this._dirtyUniforms=[],this._texturesToRelease=[],this._texturesToCreate=[],this._texturePromise=void 0;const o=new Lp;o.scissorTest={enabled:!0,rectangle:c(e.scissorRectangle)?Re.clone(e.scissorRectangle):new Re},this._passState=o,this._ready=!1;let r=e.name;c(r)||(r=Wr()),this._name=r,this._logDepthChanged=void 0,this._useLogDepth=void 0,this._selectedIdTexture=void 0,this._selected=void 0,this._selectedShadow=void 0,this._parentSelected=void 0,this._parentSelectedShadow=void 0,this._combinedSelected=void 0,this._combinedSelectedShadow=void 0,this._selectedLength=0,this._parentSelectedLength=0,this._selectedDirty=!0,this._textureCache=void 0,this._index=void 0,this.enabled=!0,this._enabled=!0}Object.defineProperties(Wn.prototype,{ready:{get:function(){return this._ready}},name:{get:function(){return this._name}},fragmentShader:{get:function(){return this._fragmentShader}},uniforms:{get:function(){return this._uniforms}},textureScale:{get:function(){return this._textureScale}},forcePowerOfTwo:{get:function(){return this._forcePowerOfTwo}},sampleMode:{get:function(){return this._sampleMode}},pixelFormat:{get:function(){return this._pixelFormat}},pixelDatatype:{get:function(){return this._pixelDatatype}},clearColor:{get:function(){return this._clearColor}},scissorRectangle:{get:function(){return this._passState.scissorTest.rectangle}},outputTexture:{get:function(){if(c(this._textureCache)){const e=this._textureCache.getFramebuffer(this._name);if(c(e))return e.getColorTexture(0)}}},selected:{get:function(){return this._selected},set:function(e){this._selected=e}},parentSelected:{get:function(){return this._parentSelected},set:function(e){this._parentSelected=e}}});const iUe=/uniform\s+sampler2D\s+depthTexture/g;Wn.prototype._isSupported=function(e){return!iUe.test(this._fragmentShader)||e.depthTexture};function oUe(e,t,n){const i=t[n];return(typeof i=="string"||i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement||i instanceof ImageData)&&e._dirtyUniforms.push(n),{get:function(){return t[n]},set:function(o){const
uniform sampler2D czm_idTexture;
uniform sampler2D czm_selectedIdTexture;
uniform float czm_selectedIdTextureStep;
in vec2 v_textureCoordinates;
bool czm_selected(vec2 offset)
{
bool selected = false;
vec4 id = texture(czm_idTexture, v_textureCoordinates + offset);
for (int i = 0; i < ${o}; ++i)
{
vec4 selectedId = texture(czm_selectedIdTexture, vec2((float(i) + 0.5) * czm_selectedIdTextureStep, 0.5));
if (all(equal(id, selectedId)))
{
return true;
}
}
return false;
}
bool czm_selected()
{
return czm_selected(vec2(0.0));
}
${n}`}const i=new Oe({defines:[e._useLogDepth?"LOG_DEPTH":""],sources:[n]});e._command=t.createViewportQuadCommand(i,{uniformMap:e._uniformMap,owner:e})}function lUe(e){const t=e._sampleMode;let n,i;t===wp.LINEAR?(n=en.LINEAR,i=Yo.LINEAR):(n=en.NEAREST,i=Yo.NEAREST);const o=e._sampler;(!c(o)||o.minificationFilter!==n||o.magnificationFilter!==i)&&(e._sampler=new un({wrapS:Fn.CLAMP_TO_EDGE,wrapT:Fn.CLAMP_TO_EDGE,minificationFilter:n,magnificationFilter:i}))}function uUe(e,t){return function(n){e._texturesToCreate.push({name:t,source:n})}}function dUe(e,t){return function(){return e._textureCache.getOutputTexture(t)}}function hUe(e,t){let n,i,o;const r=e._texturesToRelease;let s=r.length;for(n=0;n<s;++n)i=r[n],i=i&&i.destroy();r.length=0;const a=e._texturesToCreate;for(s=a.length,n=0;n<s;++n){const f=a[n];o=f.name;const _=f.source;e._actualUniforms[o]=new xt({context:t,source:_})}a.length=0;const l=e._dirtyUniforms;if(l.length===0&&!c(e._texturePromise)){e._ready=!0;return}if(l.length===0||c(e._texturePromise))return;s=l.length;const u=e._uniforms,h=[];for(n=0;n<s;++n){o=l[n];const f=u[o],_=e._textureCache.getStageByName(f);if(c(_))e._actualUniforms[o]=dUe(e,f);else if(typeof f=="string"){const g=new Ae({url:f});h.push(g.fetchImage().then(uUe(e,o)))}else e._texturesToCreate.push({name:o,source:f})}l.length=0,h.length>0?(e._ready=!1,e._texturePromise=Promise.all(h).then(function(){e._ready=!0,e._texturePromise=void 0})):e._ready=!0}function s6(e){c(e._command)&&(e._command.shaderProgram=e._command.shaderProgram&&e._command.shaderProgram.destroy(),e._command=void 0),e._selectedIdTexture=e._selectedIdTexture&&e._selectedIdTexture.destroy();const t=e._textureCache;if(!c(t))return;const n=e._uniforms,i=e._actualUniforms;for(const o in i)i.hasOwnProperty(o)&&i[o]instanceof xt&&(c(t.getStageByName(n[o]))||i[o].destroy(),e._dirtyUniforms.push(o))}function fUe(e){let t=c(e._selected)?e._selected.length:0;const n=c(e._parentSelected)?e._parentSelected:0;let i=e._selected!==e._selectedShadow||t!==e._selectedLength;if(i=i||e._parentSelected!==e._parentSelectedShadow||n!==e._parentSelectedLength,c(e._selected)&&c(e._parentSelected)?e._combinedSelected=e._selected.concat(e._parentSelected):c(e._parentSelected)?e._combinedSelected=e._parentSelected:e._combinedSelected=e._selected,!i&&c(e._combinedSelected)){if(!c(e._combinedSelectedShadow))return!0;t=e._combinedSelected.length;for(let o=0;o<t;++o)if(e._combinedSelected[o]!==e._combinedSelectedShadow[o])return!0}return i}function pUe(e,t){if(!e._selectedDirty)return;e._selectedIdTexture=e._selectedIdTexture&&e._selectedIdTexture.destroy(),e._selectedIdTexture=void 0;const n=e._combinedSelected;if(!c(n))return;let i,o,r=0;const s=n.length;for(i=0;i<s;++i)o=n[i],c(o.pickIds)?r+=o.pickIds.length:c(o.pickId)&&++r;if(s===0||r===0){const h=new Uint8Array(4);h[0]=255,h[1]=255,h[2]=255,h[3]=255,e._selectedIdTexture=new xt({context:t,pixelFormat:Ve.RGBA,pixelDatatype:Me.UNSIGNED_BYTE,source:{arrayBufferView:h,width:1,height:1},sampler:un.NEAREST});return}let a,l=0;const u=new Uint8Array(r*4);for(i=0;i<s;++i)if(o=n[i],c(o.pickIds)){const h=o.pickIds,f=h.length;for(let _=0;_<f;++_)a=h[_].color,u[l]=z.floatToByte(a.red),u[l+1]=z.floatToByte(a.green),u[l+2]=z.floatToByte(a.blue),u[l+3]=z.floatToByte(a.alpha),l+=4}else c(o.pickId)&&(a=o.pickId.color,u[l]=z.floatToByte(a.red),u[l+1]=z.floatToByte(a.green),u[l+2]=z.floatToByte(a.blue),u[l+3]=z.floatToByte(a.alpha),l+=4);e._selectedIdTexture=new xt({context:t,pixelFormat:Ve.RGBA,pixelDatatype:Me.UNSIGNED_BYTE,source:{arrayBufferView:u,width:r,height:1},sampler:un.NEAREST})}Wn.prototype.update=function(e,t){if(this.enabled!==this._enabled&&!this.enabled&&s6(this),this._enabled=this.enabled,!this._enabled||(this._logDepthChanged=t!==this._useLogDepth,this._useLogDepth=t,this._selectedDirty=fUe(this),this._selectedShadow=this._selected,this._parentSelectedShadow=this._parentSelected,this._combinedSelectedShadow=this._combinedSelected,this._selectedLength=c(this._selected)?this._selected.length:0,this._parentSelectedLength=c(this._parentSelected)?this._parent
${$D}`,r=new Wn({name:`${e}_x_direction`,fragmentShader:o,uniforms:{delta:1,sigma:2,stepSize:1,direction:0},sampleMode:wp.LINEAR}),s=new Wn({name:`${e}_y_direction`,fragmentShader:o,uniforms:{delta:1,sigma:2,stepSize:1,direction:1},sampleMode:wp.LINEAR}),a={};return Object.defineProperties(a,{delta:{get:function(){return r.uniforms.delta},set:function(l){const u=r.uniforms,h=s.uniforms;u.delta=h.delta=l}},sigma:{get:function(){return r.uniforms.sigma},set:function(l){const u=r.uniforms,h=s.uniforms;u.sigma=h.sigma=l}},stepSize:{get:function(){return r.uniforms.stepSize},set:function(l){const u=r.uniforms,h=s.uniforms;u.stepSize=h.stepSize=l}}}),new Cs({name:e,stages:[r,s],uniforms:a})}uo.createBlurStage=function(){return dE("czm_blur")};uo.createDepthOfFieldStage=function(){const e=dE("czm_depth_of_field_blur"),t=new Wn({name:"czm_depth_of_field_composite",fragmentShader:Hze,uniforms:{focalDistance:5,blurTexture:e.name}}),n={};return Object.defineProperties(n,{focalDistance:{get:function(){return t.uniforms.focalDistance},set:function(i){t.uniforms.focalDistance=i}},delta:{get:function(){return e.uniforms.delta},set:function(i){e.uniforms.delta=i}},sigma:{get:function(){return e.uniforms.sigma},set:function(i){e.uniforms.sigma=i}},stepSize:{get:function(){return e.uniforms.stepSize},set:function(i){e.uniforms.stepSize=i}}}),new Cs({name:"czm_depth_of_field",stages:[e,t],inputPreviousStageTexture:!1,uniforms:n})};uo.isDepthOfFieldSupported=function(e){return e.context.depthTexture};uo.createEdgeDetectionStage=function(){const e=Wr();return new Wn({name:`czm_edge_detection_${e}`,fragmentShader:jze,uniforms:{length:.25,color:z.clone(z.BLACK)}})};uo.isEdgeDetectionSupported=function(e){return e.context.depthTexture};function _Ue(e){if(!c(e))return uo.createEdgeDetectionStage();const t=new Cs({name:"czm_edge_detection_multiple",stages:e,inputPreviousStageTexture:!1}),n={};let i="",o="";for(let a=0;a<e.length;++a)i+=`uniform sampler2D edgeTexture${a};
`,o+=` vec4 edge${a} = texture(edgeTexture${a}, v_textureCoordinates);
if (edge${a}.a > 0.0)
{
color = edge${a};
break;
}
`,n[`edgeTexture${a}`]=e[a].name;const r=`${i}in vec2 v_textureCoordinates;
void main() {
vec4 color = vec4(0.0);
for (int i = 0; i < ${e.length}; i++)
{
${o} }
out_FragColor = color;
}
`,s=new Wn({name:"czm_edge_detection_combine",fragmentShader:r,uniforms:n});return new Cs({name:"czm_edge_detection_composite",stages:[t,s]})}uo.createSilhouetteStage=function(e){const t=_Ue(e),n=new Wn({name:"czm_silhouette_color_edges",fragmentShader:Kze,uniforms:{silhouetteTexture:t.name}});return new Cs({name:"czm_silhouette",stages:[t,n],inputPreviousStageTexture:!1,uniforms:t.uniforms})};uo.isSilhouetteSupported=function(e){return e.context.depthTexture};uo.createBloomStage=function(){const e=new Wn({name:"czm_bloom_contrast_bias",fragmentShader:Vze,uniforms:{contrast:128,brightness:-.3}}),t=dE("czm_bloom_blur"),n=new Cs({name:"czm_bloom_contrast_bias_blur",stages:[e,t]}),i=new Wn({name:"czm_bloom_generate_composite",fragmentShader:Uze,uniforms:{glowOnly:!1,bloomTexture:n.name}}),o={};return Object.defineProperties(o,{glowOnly:{get:function(){return i.uniforms.glowOnly},set:function(r){i.uniforms.glowOnly=r}},contrast:{get:function(){return e.uniforms.contrast},set:function(r){e.uniforms.contrast=r}},brightness:{get:function(){return e.uniforms.brightness},set:function(r){e.uniforms.brightness=r}},delta:{get:function(){return t.uniforms.delta},set:function(r){t.uniforms.delta=r}},sigma:{get:function(){return t.uniforms.sigma},set:function(r){t.uniforms.sigma=r}},stepSize:{get:function(){return t.uniforms.stepSize},set:function(r){t.uniforms.stepSize=r}}}),new Cs({name:"czm_bloom",stages:[n,i],inputPreviousStageTexture:!1,uniforms:o})};uo.createAmbientOcclusionStage=function(){const e=new Wn({name:"czm_ambient_occlusion_generate",fragmentShader:Fze,uniforms:{intensity:3,bias:.1,lengthCap:.26,stepSize:1.95,frustumLength:1e3,randomTexture:void 0}}),t=dE("czm_ambient_occlusion_blur");t.uniforms.stepSize=.86;const n=new Cs({name:"czm_ambient_occlusion_generate_blur",stages:[e,t]}),i=new Wn({name:"czm_ambient_occlusion_composite",fragmentShader:Bze,uniforms:{ambientOcclusionOnly:!1,ambientOcclusionTexture:n.name}}),o={};return Object.defineProperties(o,{intensity:{get:function(){return e.uniforms.intensity},set:function(r){e.uniforms.intensity=r}},bias:{get:function(){return e.uniforms.bias},set:function(r){e.uniforms.bias=r}},lengthCap:{get:function(){return e.uniforms.lengthCap},set:function(r){e.uniforms.lengthCap=r}},stepSize:{get:function(){return e.uniforms.stepSize},set:function(r){e.uniforms.stepSize=r}},frustumLength:{get:function(){return e.uniforms.frustumLength},set:function(r){e.uniforms.frustumLength=r}},randomTexture:{get:function(){return e.uniforms.randomTexture},set:function(r){e.uniforms.randomTexture=r}},delta:{get:function(){return t.uniforms.delta},set:function(r){t.uniforms.delta=r}},sigma:{get:function(){return t.uniforms.sigma},set:function(r){t.uniforms.sigma=r}},blurStepSize:{get:function(){return t.uniforms.stepSize},set:function(r){t.uniforms.stepSize=r}},ambientOcclusionOnly:{get:function(){return i.uniforms.ambientOcclusionOnly},set:function(r){i.uniforms.ambientOcclusionOnly=r}}}),new Cs({name:"czm_ambient_occlusion",stages:[n,i],inputPreviousStageTexture:!1,uniforms:o})};uo.isAmbientOcclusionSupported=function(e){return e.context.depthTexture};const gUe=`#define FXAA_QUALITY_PRESET 39
${L1e}
${qze}`;uo.createFXAAStage=function(){return new Wn({name:"czm_FXAA",fragmentShader:gUe,sampleMode:wp.LINEAR})};uo.createAcesTonemappingStage=function(e){let t=e?`#define AUTO_EXPOSURE
`:"";return t+=Mze,new Wn({name:"czm_aces",fragmentShader:t,uniforms:{autoExposure:void 0}})};uo.createFilmicTonemappingStage=function(e){let t=e?`#define AUTO_EXPOSURE
`:"";return t+=Wze,new Wn({name:"czm_filmic",fragmentShader:t,uniforms:{autoExposure:void 0}})};uo.createReinhardTonemappingStage=function(e){let t=e?`#define AUTO_EXPOSURE
`:"";return t+=Qze,new Wn({name:"czm_reinhard",fragmentShader:t,uniforms:{autoExposure:void 0}})};uo.createModifiedReinhardTonemappingStage=function(e){let t=e?`#define AUTO_EXPOSURE
`:"";return t+=$ze,new Wn({name:"czm_modified_reinhard",fragmentShader:t,uniforms:{white:z.WHITE,autoExposure:void 0}})};uo.createAutoExposureStage=function(){return new $p};uo.createBlackAndWhiteStage=function(){return new Wn({name:"czm_black_and_white",fragmentShader:zze,uniforms:{gradations:5}})};uo.createBrightnessStage=function(){return new Wn({name:"czm_brightness",fragmentShader:kze,uniforms:{brightness:.5}})};uo.createNightVisionStage=function(){return new Wn({name:"czm_night_vision",fragmentShader:Xze})};uo.createDepthViewStage=function(){return new Wn({name:"czm_depth_view",fragmentShader:Gze})};uo.createLensFlareStage=function(){return new Wn({name:"czm_lens_flare",fragmentShader:Yze,uniforms:{dirtTexture:Zt("Assets/Textures/LensFlare/DirtMask.jpg"),starTexture:Zt("Assets/Textures/LensFlare/StarBurst.jpg"),intensity:2,distortion:10,ghostDispersal:.4,haloWidth:.4,dirtAmount:.4,earthRadius:ae.WGS84.maximumRadius}})};const _h=uo;function Su(e){this._collection=e,this._framebuffers=[],this._stageNameToFramebuffer={},this._width=void 0,this._height=void 0,this._updateDependencies=!1}function Wy(e){for(;c(e.length);)e=e.get(e.length-1);return e.name}function XD(e,t,n,i,o){if(!i.enabled||!i._isSupported(t))return o;const r=n[i.name]={};if(c(o)){const a=e.getStageByName(o);r[Wy(a)]=!0}const s=i.uniforms;if(c(s)){const a=Object.getOwnPropertyNames(s),l=a.length;for(let u=0;u<l;++u){const h=s[a[u]];if(typeof h=="string"){const f=e.getStageByName(h);c(f)&&(r[Wy(f)]=!0)}}}return i.name}function Ty(e,t,n,i,o){if(c(i.enabled)&&!i.enabled||c(i._isSupported)&&!i._isSupported(t))return o;const r=o,s=!c(i.inputPreviousStageTexture)||i.inputPreviousStageTexture;let a=o;const l=i.length;for(let f=0;f<l;++f){const _=i.get(f);c(_.length)?a=Ty(e,t,n,_,o):a=XD(e,t,n,_,o),s&&(o=a)}let u,h;if(s)for(u=1;u<l;++u)h=Wy(i.get(u)),c(n[h])||(n[h]={}),n[h][r]=!0;else for(u=1;u<l;++u){h=Wy(i.get(u));const f=n[h];for(let _=0;_<u;++_)f[Wy(i.get(_))]=!0}return a}function yUe(e,t){const n={};if(c(e.ambientOcclusion)){const i=e.ambientOcclusion,o=e.bloom,r=e._tonemapping,s=e.fxaa;let a=Ty(e,t,n,i,void 0);a=Ty(e,t,n,o,a),a=XD(e,t,n,r,a),a=Ty(e,t,n,e,a),XD(e,t,n,s,a)}else Ty(e,t,n,e,void 0);return n}function bUe(e,t,n){const o=e._collection.getStageByName(t),r=o._textureScale,s=o._forcePowerOfTwo,a=o._pixelFormat,l=o._pixelDatatype,u=o._clearColor;let h,f;const _=e._framebuffers,g=_.length;for(h=0;h<g;++h){if(f=_[h],r!==f.textureScale||s!==f.forcePowerOfTwo||a!==f.pixelFormat||l!==f.pixelDatatype||!z.equals(u,f.clearColor))continue;const m=f.stages,b=m.length;let T=!1;for(let x=0;x<b;++x)if(n[m[x]]){T=!0;break}if(!T)break}return c(f)&&h<g?(f.stages.push(t),f):(f={textureScale:r,forcePowerOfTwo:s,pixelFormat:a,pixelDatatype:l,clearColor:u,stages:[t],buffer:new on({pixelFormat:a,pixelDatatype:l}),clear:void 0},_.push(f),f)}function TUe(e,t){const n=yUe(e._collection,t);for(const i in n)n.hasOwnProperty(i)&&(e._stageNameToFramebuffer[i]=bUe(e,i,n[i]))}function QD(e){const t=e._framebuffers,n=t.length;for(let i=0;i<n;++i)t[i].buffer.destroy()}function AUe(e,t){const n=e._width,i=e._height,o=e._framebuffers,r=o.length;for(let s=0;s<r;++s){const a=o[s],l=a.textureScale;let u=Math.ceil(n*l),h=Math.ceil(i*l),f=Math.min(u,h);a.forcePowerOfTwo&&(R.isPowerOfTwo(f)||(f=R.nextPowerOfTwo(f)),u=f,h=f),a.buffer.update(t,u,h),a.clear=new bi({color:a.clearColor,framebuffer:a.buffer.framebuffer})}}Su.prototype.updateDependencies=function(){this._updateDependencies=!0};Su.prototype.update=function(e){const t=this._collection,n=this._updateDependencies,i=c(t.ambientOcclusion)&&t.ambientOcclusion.enabled&&t.ambientOcclusion._isSupported(e),o=c(t.bloom)&&t.bloom.enabled&&t.bloom._isSupported(e),r=c(t._tonemapping)&&t._tonemapping.enabled&&t._tonemapping._isSupported(e),s=c(t.fxaa)&&t.fxaa.enabled&&t.fxaa._isSupported(e),a=!c(t._activeStages)||t._activeStages.length>0||i||o||r||s;if((n||!a&&this._framebuffers.length>0)&&(QD(this),this._framebuffers.length=0,this._stageNameToFramebuffer={},this._width=void 0,this._height=void 0),!n&&!a)return;this._framebuffers.length===0&&T
uniform sampler2D colorTexture2;
uniform vec2 center;
uniform float radius;
in vec2 v_textureCoordinates;
void main()
{
vec4 color0 = texture(colorTexture, v_textureCoordinates);
vec4 color1 = texture(colorTexture2, v_textureCoordinates);
float x = length(gl_FragCoord.xy - center) / radius;
float t = smoothstep(0.5, 0.8, x);
out_FragColor = mix(color0 + color1, color1, t);
}
`,n4e=`uniform sampler2D colorTexture;
uniform float avgLuminance;
uniform float threshold;
uniform float offset;
in vec2 v_textureCoordinates;
float key(float avg)
{
float guess = 1.5 - (1.5 / (avg * 0.1 + 1.0));
return max(0.0, guess) + 0.1;
}
// See section 9. "The bright-pass filter" of Realtime HDR Rendering
// http://www.cg.tuwien.ac.at/research/publications/2007/Luksch_2007_RHR/Luksch_2007_RHR-RealtimeHDR%20.pdf
void main()
{
vec4 color = texture(colorTexture, v_textureCoordinates);
vec3 xyz = czm_RGBToXYZ(color.rgb);
float luminance = xyz.r;
float scaledLum = key(avgLuminance) * luminance / avgLuminance;
float brightLum = max(scaledLum - threshold, 0.0);
float brightness = brightLum / (offset + brightLum);
xyz.r = brightness;
out_FragColor = vec4(czm_XYZToRGB(xyz), 1.0);
}
`;function Od(){this._sceneFramebuffer=new Eu;const e=.125,t=new Array(6);t[0]=new Wn({fragmentShader:Ep,textureScale:e,forcePowerOfTwo:!0,sampleMode:wp.LINEAR});const n=t[1]=new Wn({fragmentShader:n4e,uniforms:{avgLuminance:.5,threshold:.25,offset:.1},textureScale:e,forcePowerOfTwo:!0}),i=this;this._delta=1,this._sigma=2,this._blurStep=new H,t[2]=new Wn({fragmentShader:$D,uniforms:{step:function(){return i._blurStep.x=i._blurStep.y=1/n.outputTexture.width,i._blurStep},delta:function(){return i._delta},sigma:function(){return i._sigma},direction:0},textureScale:e,forcePowerOfTwo:!0}),t[3]=new Wn({fragmentShader:$D,uniforms:{step:function(){return i._blurStep.x=i._blurStep.y=1/n.outputTexture.width,i._blurStep},delta:function(){return i._delta},sigma:function(){return i._sigma},direction:1},textureScale:e,forcePowerOfTwo:!0}),t[4]=new Wn({fragmentShader:Ep,sampleMode:wp.LINEAR}),this._uCenter=new H,this._uRadius=void 0,t[5]=new Wn({fragmentShader:t4e,uniforms:{center:function(){return i._uCenter},radius:function(){return i._uRadius},colorTexture2:function(){return i._sceneFramebuffer.framebuffer.getColorTexture(0)}}}),this._stages=new Cs({stages:t});const o=new Su(this),r=t.length;for(let s=0;s<r;++s)t[s]._textureCache=o;this._textureCache=o,this.length=t.length}Od.prototype.get=function(e){return this._stages.get(e)};Od.prototype.getStageByName=function(e){const t=this._stages.length;for(let n=0;n<t;++n){const i=this._stages.get(n);if(i.name===e)return i}};const i4e=new te,_z=new H,o4e=new H,gz=new L;function r4e(e,t,n){const i=t.uniformState,o=i.sunPositionWC,r=i.view,s=i.viewProjection,a=i.projection;let l=L.computeViewportTransformation(n,0,1,gz);const u=L.multiplyByPoint(r,o,i4e);let h=zt.pointToGLWindowCoordinates(s,l,o,_z);u.x+=R.SOLAR_RADIUS;const f=zt.pointToGLWindowCoordinates(a,l,u,u),_=H.magnitude(H.subtract(f,h,f))*30*2,g=o4e;g.x=_,g.y=_,e._uCenter=H.clone(h,e._uCenter),e._uRadius=Math.max(g.x,g.y)*.15;const m=t.drawingBufferWidth,b=t.drawingBufferHeight,T=e._stages,x=T.get(0),C=x.outputTexture.width,w=x.outputTexture.height,v=new Re;v.width=C,v.height=w,l=L.computeViewportTransformation(v,0,1,gz),h=zt.pointToGLWindowCoordinates(s,l,o,_z),g.x*=C/m,g.y*=w/b;const P=x.scissorRectangle;P.x=Math.max(h.x-g.x*.5,0),P.y=Math.max(h.y-g.y*.5,0),P.width=Math.min(g.x,m),P.height=Math.min(g.y,b);for(let N=1;N<4;++N)Re.clone(P,T.get(N).scissorRectangle)}Od.prototype.clear=function(e,t,n){this._sceneFramebuffer.clear(e,t,n),this._textureCache.clear(e)};Od.prototype.update=function(e){const t=e.context,n=e.viewport,i=this._sceneFramebuffer;i.update(t,n);const o=i.framebuffer;return this._textureCache.update(t),this._stages.update(t,!1),r4e(this,t,n),o};Od.prototype.execute=function(e){const t=this._sceneFramebuffer.framebuffer.getColorTexture(0),n=this._stages,i=n.length;n.get(0).execute(e,t);for(let o=1;o<i;++o)n.get(o).execute(e,n.get(o-1).outputTexture)};Od.prototype.copy=function(e,t){if(!c(this._copyColorCommand)){const n=this;this._copyColorCommand=e.createViewportQuadCommand(Ep,{uniformMap:{colorTexture:function(){return n._stages.get(n._stages.length-1).outputTexture}},owner:this})}this._copyColorCommand.framebuffer=t,this._copyColorCommand.execute(e)};Od.prototype.isDestroyed=function(){return!1};Od.prototype.destroy=function(){return this._textureCache.destroy(),this._stages.destroy(),ve(this)};function V6(){this._cachedShowFrustumsShaders={}}function s4e(e){const t={},n=e.vertexAttributes;for(const i in n)n.hasOwnProperty(i)&&(t[i]=n[i].index);return t}function a4e(e,t){const n=e.context,i=t,o=i.fragmentShaderSource.clone(),r=[];o.sources=o.sources.map(function(h){h=Oe.replaceMain(h,"czm_Debug_main");const f=/out_FragData_(\d+)/g;let _;for(;(_=f.exec(h))!==null;)r.indexOf(_[1])===-1&&r.push(_[1]);return h});const s=r.length;let a="";a+=`uniform vec3 debugShowCommandsColor;
`,a+=`uniform vec3 debugShowFrustumsColor;
`,a+=`void main()
{
czm_Debug_main();
`;let l;if(s>0)for(l=0;l<s;++l)a+=` out_FragData_${r[l]}.rgb *= debugShowCommandsColor;
`,a+=` out_FragData_${r[l]}.rgb *= debugShowFrustumsColor;
`;else a+=` out_FragColor.rgb *= debugShowCommandsColor;
`,a+=` out_FragColor.rgb *= debugShowFrustumsColor;
`;a+="}",o.sources.push(a);const u=s4e(i);return Jt.fromCache({context:n,vertexShaderSource:i.vertexShaderSource,fragmentShaderSource:o,attributeLocations:u})}const ay=new z;function c4e(e,t){let n;return c(t.uniformMap)?n=t.uniformMap:n={},c(n.debugShowCommandsColor)||c(n.debugShowFrustumsColor)||(n.debugShowCommandsColor=function(){return e.debugShowCommands?(c(t._debugColor)||(t._debugColor=z.fromRandom()),t._debugColor):z.WHITE},n.debugShowFrustumsColor=function(){return e.debugShowFrustums?(ay.red=t.debugOverlappingFrustums&1<<0?1:0,ay.green=t.debugOverlappingFrustums&1<<1?1:0,ay.blue=t.debugOverlappingFrustums&1<<2?1:0,ay.alpha=1,ay):z.WHITE}),n}const l4e=new Ze;V6.prototype.executeDebugShowFrustumsCommand=function(e,t,n){const i=t.shaderProgram.id;let o=this._cachedShowFrustumsShaders[i];c(o)||(o=a4e(e,t.shaderProgram),this._cachedShowFrustumsShaders[i]=o);const r=Ze.shallowClone(t,l4e);r.shaderProgram=o,r.uniformMap=c4e(e,t),r.execute(e.context,n)};function Sp(e,t,n){this._primitive=e,this._tileIndex=t,this._sampleIndex=n,this._metadata={},this._orientedBoundingBox=new Ct}Sp.fromKeyframeNode=function(e,t,n,i){A.typeOf.object("primitive",e),A.typeOf.number("tileIndex",t),A.typeOf.number("sampleIndex",n),A.typeOf.object("keyframeNode",i);const o=new Sp(e,t,n),{spatialNode:r,metadata:s}=i;return o._metadata=u4e(e,s,n),o._orientedBoundingBox=h4e(e,r,n,o._orientedBoundingBox),o};function u4e(e,t,n){if(!c(t))return;const{names:i,types:o}=e.provider,r={};for(let s=0;s<i.length;s++){const a=i[s],l=bt.getComponentCount(o[s]),u=t[s].slice(n*l,(n+1)*l);r[a]=u}return r}const yz=new d,d4e=new d;function h4e(e,t,n,i){const o=t.dimensions,r=o.x*o.y,s=Math.floor(n/r),a=n-s*r,l=Math.floor(a/o.x),u=a-l*o.x,h=d.fromElements(u,l,s,yz),f=d.divideComponents(d.subtract(h,e._paddingBefore,yz),e.dimensions,d4e);return e._shape.computeOrientedBoundingBoxForSample(t,e.dimensions,f,i)}Object.defineProperties(Sp.prototype,{metadata:{get:function(){return this._metadata}},primitive:{get:function(){return this._primitive}},sampleIndex:{get:function(){return this._sampleIndex}},tileIndex:{get:function(){return this._tileIndex}},orientedBoundingBox:{get:function(){return this._orientedBoundingBox.clone()}}});Sp.prototype.hasProperty=function(e){return c(this._metadata[e])};Sp.prototype.getNames=function(){return Object.keys(this._metadata)};Sp.prototype.getProperty=function(e){return this._metadata[e]};const f4e=`struct Ray {
vec3 pos;
vec3 dir;
vec3 rawDir;
};
#if defined(JITTER)
/**
* Generate a pseudo-random value for a given 2D screen coordinate.
* Similar to https://www.shadertoy.com/view/4djSRW with a modified hashscale.
*/
float hash(vec2 p)
{
vec3 p3 = fract(vec3(p.xyx) * 50.0);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
#endif
float minComponent(in vec3 v) {
return min(min(v.x, v.y), v.z);
}
float maxComponent(in vec3 v) {
return max(max(v.x, v.y), v.z);
}
struct PointJacobianT {
vec3 point;
mat3 jacobianT;
};
`,p4e=`// See Intersection.glsl for the definition of intersectScene
// See IntersectionUtils.glsl for the definition of nextIntersection
// See convertUvToBox.glsl, convertUvToCylinder.glsl, or convertUvToEllipsoid.glsl
// for the definition of convertUvToShapeUvSpace. The appropriate function is
// selected based on the VoxelPrimitive shape type, and added to the shader in
// Scene/VoxelRenderResources.js.
// See Octree.glsl for the definitions of TraversalData, SampleData,
// traverseOctreeFromBeginning, and traverseOctreeFromExisting
// See Megatexture.glsl for the definition of accumulatePropertiesFromMegatexture
#define STEP_COUNT_MAX 1000 // Harcoded value because GLSL doesn't like variable length loops
#if defined(PICKING_VOXEL)
#define ALPHA_ACCUM_MAX 0.1
#else
#define ALPHA_ACCUM_MAX 0.98 // Must be > 0.0 and <= 1.0
#endif
uniform mat3 u_transformDirectionViewToLocal;
uniform vec3 u_cameraPositionUv;
uniform float u_stepSize;
#if defined(PICKING)
uniform vec4 u_pickColor;
#endif
vec3 getSampleSize(in int level) {
vec3 sampleCount = exp2(float(level)) * vec3(u_dimensions);
vec3 sampleSizeUv = 1.0 / sampleCount;
return scaleShapeUvToShapeSpace(sampleSizeUv);
}
#define MINIMUM_STEP_SCALAR (0.02)
#define SHIFT_FRACTION (0.001)
/**
* Given a coordinate within a tile, and sample spacings along a ray through
* the coordinate, find the distance to the points where the ray entered and
* exited the voxel cell, along with the surface normals at those points.
* The surface normals are returned in shape space coordinates.
*/
RayShapeIntersection getVoxelIntersection(in vec3 tileUv, in vec3 sampleSizeAlongRay) {
vec3 voxelCoord = tileUv * vec3(u_dimensions);
vec3 directions = sign(sampleSizeAlongRay);
vec3 positiveDirections = max(directions, 0.0);
vec3 entryCoord = mix(ceil(voxelCoord), floor(voxelCoord), positiveDirections);
vec3 exitCoord = entryCoord + directions;
vec3 distanceFromEntry = -abs((entryCoord - voxelCoord) * sampleSizeAlongRay);
float lastEntry = maxComponent(distanceFromEntry);
bvec3 isLastEntry = equal(distanceFromEntry, vec3(lastEntry));
vec3 entryNormal = -1.0 * vec3(isLastEntry) * directions;
vec4 entry = vec4(entryNormal, lastEntry);
vec3 distanceToExit = abs((exitCoord - voxelCoord) * sampleSizeAlongRay);
float firstExit = minComponent(distanceToExit);
bvec3 isFirstExit = equal(distanceToExit, vec3(firstExit));
vec3 exitNormal = vec3(isFirstExit) * directions;
vec4 exit = vec4(exitNormal, firstExit);
return RayShapeIntersection(entry, exit);
}
vec4 getStepSize(in SampleData sampleData, in Ray viewRay, in RayShapeIntersection shapeIntersection, in mat3 jacobianT, in float currentT) {
// The Jacobian is computed in a space where the shape spans [-1, 1].
// But the ray is marched in a space where the shape fills [0, 1].
// So we need to scale the Jacobian by 2.
vec3 gradient = 2.0 * viewRay.rawDir * jacobianT;
vec3 sampleSizeAlongRay = getSampleSize(sampleData.tileCoords.w) / gradient;
RayShapeIntersection voxelIntersection = getVoxelIntersection(sampleData.tileUv, sampleSizeAlongRay);
// Transform normal from shape space to Cartesian space
vec3 voxelNormal = normalize(jacobianT * voxelIntersection.entry.xyz);
// Compare with the shape intersection, to choose the appropriate normal
vec4 voxelEntry = vec4(voxelNormal, currentT + voxelIntersection.entry.w);
vec4 entry = intersectionMax(shapeIntersection.entry, voxelEntry);
float fixedStep = minComponent(abs(sampleSizeAlongRay)) * u_stepSize;
float shift = fixedStep * SHIFT_FRACTION;
float dt = voxelIntersection.exit.w + shift;
if ((currentT + dt) > shapeIntersection.exit.w) {
// Stop at end of shape
dt = shapeIntersection.exit.w - currentT + shift;
}
float stepSize = clamp(dt, fixedStep * MINIMUM_STEP_SCALAR, fixedStep + shift);
return vec4(entry.xyz, stepSize);
}
vec2 packIntToVec2(int value) {
float shifted = float(value) / 255.0;
float lowBits = fract(shifted);
float highBits = floor(shifted) / 255.0;
return vec2(highBits, lowBits);
}
vec2 packFloatToVec2(float value) {
float lowBits = fract(value);
float highBits = floor(value) / 255.0;
return vec2(highBits, lowBits);
}
int getSampleIndex(in vec3 tileUv) {
ivec3 voxelDimensions = u_dimensions;
vec3 sampleCoordinate = tileUv * vec3(voxelDimensions);
// tileUv = 1.0 is a valid coordinate but sampleIndex = voxelDimensions is not.
// (tileUv = 1.0 corresponds to the last sample, at index = voxelDimensions - 1).
// Clamp to [0, voxelDimensions - 0.5) to avoid numerical error before flooring
vec3 maxCoordinate = vec3(voxelDimensions) - vec3(0.5);
sampleCoordinate = clamp(sampleCoordinate, vec3(0.0), maxCoordinate);
ivec3 sampleIndex = ivec3(floor(sampleCoordinate));
#if defined(PADDING)
voxelDimensions += u_paddingBefore + u_paddingAfter;
sampleIndex += u_paddingBefore;
#endif
// Convert to a 1D index for lookup in a 1D data array
return sampleIndex.x + voxelDimensions.x * (sampleIndex.y + voxelDimensions.y * sampleIndex.z);
}
void main()
{
vec4 fragCoord = gl_FragCoord;
vec2 screenCoord = (fragCoord.xy - czm_viewport.xy) / czm_viewport.zw; // [0,1]
vec3 eyeDirection = normalize(czm_windowToEyeCoordinates(fragCoord).xyz);
vec3 viewDirWorld = normalize(czm_inverseViewRotation * eyeDirection); // normalize again just in case
vec3 viewDirUv = normalize(u_transformDirectionViewToLocal * eyeDirection); // normalize again just in case
vec3 viewPosUv = u_cameraPositionUv;
#if defined(SHAPE_ELLIPSOID)
// viewDirUv has been scaled to a space where the ellipsoid is a sphere.
// Undo this scaling to get the raw direction.
vec3 rawDir = viewDirUv * u_ellipsoidRadiiUv;
Ray viewRayUv = Ray(viewPosUv, viewDirUv, rawDir);
#else
Ray viewRayUv = Ray(viewPosUv, viewDirUv, viewDirUv);
#endif
Intersections ix;
RayShapeIntersection shapeIntersection = intersectScene(screenCoord, viewRayUv, ix);
// Exit early if the scene was completely missed.
if (shapeIntersection.entry.w == NO_HIT) {
discard;
}
float currentT = shapeIntersection.entry.w;
float endT = shapeIntersection.exit.w;
vec3 positionUv = viewPosUv + currentT * viewDirUv;
PointJacobianT pointJacobian = convertUvToShapeUvSpaceDerivative(positionUv);
// Traverse the tree from the start position
TraversalData traversalData;
SampleData sampleDatas[SAMPLE_COUNT];
traverseOctreeFromBeginning(pointJacobian.point, traversalData, sampleDatas);
vec4 step = getStepSize(sampleDatas[0], viewRayUv, shapeIntersection, pointJacobian.jacobianT, currentT);
#if defined(JITTER)
float noise = hash(screenCoord); // [0,1]
currentT += noise * step.w;
positionUv += noise * step.w * viewDirUv;
#endif
FragmentInput fragmentInput;
#if defined(STATISTICS)
setStatistics(fragmentInput.metadata.statistics);
#endif
vec4 colorAccum = vec4(0.0);
for (int stepCount = 0; stepCount < STEP_COUNT_MAX; ++stepCount) {
// Read properties from the megatexture based on the traversal state
Properties properties = accumulatePropertiesFromMegatexture(sampleDatas);
// Prepare the custom shader inputs
copyPropertiesToMetadata(properties, fragmentInput.metadata);
fragmentInput.voxel.positionUv = positionUv;
fragmentInput.voxel.positionShapeUv = pointJacobian.point;
fragmentInput.voxel.positionUvLocal = sampleDatas[0].tileUv;
fragmentInput.voxel.viewDirUv = viewDirUv;
fragmentInput.voxel.viewDirWorld = viewDirWorld;
fragmentInput.voxel.surfaceNormal = step.xyz;
fragmentInput.voxel.travelDistance = step.w;
fragmentInput.voxel.stepCount = stepCount;
fragmentInput.voxel.tileIndex = sampleDatas[0].megatextureIndex;
fragmentInput.voxel.sampleIndex = getSampleIndex(sampleDatas[0].tileUv);
// Run the custom shader
czm_modelMaterial materialOutput;
fragmentMain(fragmentInput, materialOutput);
// Sanitize the custom shader output
vec4 color = vec4(materialOutput.diffuse, materialOutput.alpha);
color.rgb = max(color.rgb, vec3(0.0));
color.a = clamp(color.a, 0.0, 1.0);
// Pre-multiplied alpha blend
colorAccum += (1.0 - colorAccum.a) * vec4(color.rgb * color.a, color.a);
// Stop traversing if the alpha has been fully saturated
if (colorAccum.a > ALPHA_ACCUM_MAX) {
colorAccum.a = ALPHA_ACCUM_MAX;
break;
}
if (step.w == 0.0) {
// Shape is infinitely thin. The ray may have hit the edge of a
// foreground voxel. Step ahead slightly to check for more voxels
step.w == 0.00001;
}
// Keep raymarching
currentT += step.w;
positionUv = viewPosUv + currentT * viewDirUv;
// Check if there's more intersections.
if (currentT > endT) {
#if (INTERSECTION_COUNT == 1)
break;
#else
shapeIntersection = nextIntersection(ix);
if (shapeIntersection.entry.w == NO_HIT) {
break;
} else {
// Found another intersection. Resume raymarching there
currentT = shapeIntersection.entry.w;
endT = shapeIntersection.exit.w;
positionUv = viewPosUv + currentT * viewDirUv;
}
#endif
}
// Traverse the tree from the current ray position.
// This is similar to traverseOctreeFromBeginning but is faster when the ray is in the same tile as the previous step.
pointJacobian = convertUvToShapeUvSpaceDerivative(positionUv);
traverseOctreeFromExisting(pointJacobian.point, traversalData, sampleDatas);
step = getStepSize(sampleDatas[0], viewRayUv, shapeIntersection, pointJacobian.jacobianT, currentT);
}
// Convert the alpha from [0,ALPHA_ACCUM_MAX] to [0,1]
colorAccum.a /= ALPHA_ACCUM_MAX;
#if defined(PICKING)
// If alpha is 0.0 there is nothing to pick
if (colorAccum.a == 0.0) {
discard;
}
out_FragColor = u_pickColor;
#elif defined(PICKING_VOXEL)
// If alpha is 0.0 there is nothing to pick
if (colorAccum.a == 0.0) {
discard;
}
vec2 megatextureId = packIntToVec2(sampleDatas[0].megatextureIndex);
vec2 sampleIndex = packIntToVec2(getSampleIndex(sampleDatas[0].tileUv));
out_FragColor = vec4(megatextureId, sampleIndex);
#else
out_FragColor = colorAccum;
#endif
}
`,m4e=`in vec2 position;
uniform vec4 u_ndcSpaceAxisAlignedBoundingBox;
void main() {
vec2 aabbMin = u_ndcSpaceAxisAlignedBoundingBox.xy;
vec2 aabbMax = u_ndcSpaceAxisAlignedBoundingBox.zw;
vec2 translation = 0.5 * (aabbMax + aabbMin);
vec2 scale = 0.5 * (aabbMax - aabbMin);
gl_Position = vec4(position * scale + translation, 0.0, 1.0);
}
`,_4e=`/* Intersection defines
#define INTERSECTION_COUNT ###
*/
#define NO_HIT (-czm_infinity)
#define INF_HIT (czm_infinity * 0.5)
struct RayShapeIntersection {
vec4 entry;
vec4 exit;
};
vec4 intersectionMin(in vec4 intersect0, in vec4 intersect1)
{
if (intersect0.w == NO_HIT) {
return intersect1;
} else if (intersect1.w == NO_HIT) {
return intersect0;
}
return (intersect0.w <= intersect1.w) ? intersect0 : intersect1;
}
vec4 intersectionMax(in vec4 intersect0, in vec4 intersect1)
{
return (intersect0.w >= intersect1.w) ? intersect0 : intersect1;
}
RayShapeIntersection intersectIntersections(in Ray ray, in RayShapeIntersection intersect0, in RayShapeIntersection intersect1)
{
bool missed = (intersect0.entry.w == NO_HIT) ||
(intersect1.entry.w == NO_HIT) ||
(intersect0.exit.w < intersect1.entry.w) ||
(intersect0.entry.w > intersect1.exit.w);
if (missed) {
vec4 miss = vec4(normalize(ray.dir), NO_HIT);
return RayShapeIntersection(miss, miss);
}
vec4 entry = intersectionMax(intersect0.entry, intersect1.entry);
vec4 exit = intersectionMin(intersect0.exit, intersect1.exit);
return RayShapeIntersection(entry, exit);
}
struct Intersections {
// Don't access these member variables directly - call the functions instead.
// Store an array of ray-surface intersections. Each intersection is composed of:
// .xyz for the surface normal at the intersection point
// .w for the T value
// The scale of the normal encodes the shape intersection type:
// length(intersection.xyz) = 1: positive shape entry
// length(intersection.xyz) = 2: positive shape exit
// length(intersection.xyz) = 3: negative shape entry
// length(intersection.xyz) = 4: negative shape exit
// INTERSECTION_COUNT is the number of ray-*shape* (volume) intersections,
// so we need twice as many to track ray-*surface* intersections
vec4 intersections[INTERSECTION_COUNT * 2];
#if (INTERSECTION_COUNT > 1)
// Maintain state for future nextIntersection calls
int index;
int surroundCount;
bool surroundIsPositive;
#endif
};
RayShapeIntersection getFirstIntersection(in Intersections ix)
{
return RayShapeIntersection(ix.intersections[0], ix.intersections[1]);
}
vec4 encodeIntersectionType(vec4 intersection, int index, bool entry)
{
float scale = float(index > 0) * 2.0 + float(!entry) + 1.0;
return vec4(intersection.xyz * scale, intersection.w);
}
// Use defines instead of real functions because WebGL1 cannot access array with non-constant index.
#define setIntersection(/*inout Intersections*/ ix, /*int*/ index, /*float*/ t, /*bool*/ positive, /*bool*/ enter) (ix).intersections[(index)] = vec4(0.0, float(!positive) * 2.0 + float(!enter) + 1.0, 0.0, (t))
#define setIntersectionPair(/*inout Intersections*/ ix, /*int*/ index, /*vec2*/ entryExit) (ix).intersections[(index) * 2 + 0] = vec4(0.0, float((index) > 0) * 2.0 + 1.0, 0.0, (entryExit).x); (ix).intersections[(index) * 2 + 1] = vec4(0.0, float((index) > 0) * 2.0 + 2.0, 0.0, (entryExit).y)
#define setSurfaceIntersection(/*inout Intersections*/ ix, /*int*/ index, /*vec4*/ intersection, /*bool*/ positive, /*bool*/ enter) (ix).intersections[(index)] = encodeIntersectionType((intersection), int(!positive), (enter))
#define setShapeIntersection(/*inout Intersections*/ ix, /*int*/ index, /*RayShapeIntersection*/ intersection) (ix).intersections[(index) * 2 + 0] = encodeIntersectionType((intersection).entry, (index), true); (ix).intersections[(index) * 2 + 1] = encodeIntersectionType((intersection).exit, (index), false)
#if (INTERSECTION_COUNT > 1)
void initializeIntersections(inout Intersections ix) {
// Sort the intersections from min T to max T with bubble sort.
// Note: If this sorting function changes, some of the intersection test may
// need to be updated. Search for "bubble sort" to find those areas.
const int sortPasses = INTERSECTION_COUNT * 2 - 1;
for (int n = sortPasses; n > 0; --n) {
for (int i = 0; i < sortPasses; ++i) {
// The loop should be: for (i = 0; i < n; ++i) {...} but WebGL1 cannot
// loop with non-constant condition, so it has to break early instead
if (i >= n) { break; }
vec4 intersect0 = ix.intersections[i + 0];
vec4 intersect1 = ix.intersections[i + 1];
bool inOrder = intersect0.w <= intersect1.w;
ix.intersections[i + 0] = inOrder ? intersect0 : intersect1;
ix.intersections[i + 1] = inOrder ? intersect1 : intersect0;
}
}
// Prepare initial state for nextIntersection
ix.index = 0;
ix.surroundCount = 0;
ix.surroundIsPositive = false;
}
#endif
#if (INTERSECTION_COUNT > 1)
RayShapeIntersection nextIntersection(inout Intersections ix) {
vec4 surfaceIntersection = vec4(0.0, 0.0, 0.0, NO_HIT);
RayShapeIntersection shapeIntersection = RayShapeIntersection(surfaceIntersection, surfaceIntersection);
const int passCount = INTERSECTION_COUNT * 2;
if (ix.index == passCount) {
return shapeIntersection;
}
for (int i = 0; i < passCount; ++i) {
// The loop should be: for (i = ix.index; i < passCount; ++i) {...} but WebGL1 cannot
// loop with non-constant condition, so it has to continue instead.
if (i < ix.index) {
continue;
}
ix.index = i + 1;
surfaceIntersection = ix.intersections[i];
int intersectionType = int(length(surfaceIntersection.xyz) - 0.5);
bool currShapeIsPositive = intersectionType < 2;
bool enter = intMod(intersectionType, 2) == 0;
ix.surroundCount += enter ? +1 : -1;
ix.surroundIsPositive = currShapeIsPositive ? enter : ix.surroundIsPositive;
// entering positive or exiting negative
if (ix.surroundCount == 1 && ix.surroundIsPositive && enter == currShapeIsPositive) {
shapeIntersection.entry = surfaceIntersection;
}
// exiting positive or entering negative after being inside positive
bool exitPositive = !enter && currShapeIsPositive && ix.surroundCount == 0;
bool enterNegativeFromPositive = enter && !currShapeIsPositive && ix.surroundCount == 2 && ix.surroundIsPositive;
if (exitPositive || enterNegativeFromPositive) {
shapeIntersection.exit = surfaceIntersection;
// entry and exit have been found, so the loop can stop
if (exitPositive) {
// After exiting positive shape there is nothing left to intersect, so jump to the end index.
ix.index = passCount;
}
break;
}
}
return shapeIntersection;
}
#endif
// NOTE: initializeIntersections, nextIntersection aren't even declared unless INTERSECTION_COUNT > 1
`,g4e=`// See IntersectionUtils.glsl for the definitions of Ray, Intersections,
// setIntersectionPair, INF_HIT, NO_HIT
/* intersectDepth defines (set in Scene/VoxelRenderResources.js)
#define DEPTH_INTERSECTION_INDEX ###
*/
uniform mat4 u_transformPositionViewToUv;
void intersectDepth(in vec2 screenCoord, in Ray ray, inout Intersections ix) {
float logDepthOrDepth = czm_unpackDepth(texture(czm_globeDepthTexture, screenCoord));
if (logDepthOrDepth != 0.0) {
// Calculate how far the ray must travel before it hits the depth buffer.
vec4 eyeCoordinateDepth = czm_screenToEyeCoordinates(screenCoord, logDepthOrDepth);
eyeCoordinateDepth /= eyeCoordinateDepth.w;
vec3 depthPositionUv = vec3(u_transformPositionViewToUv * eyeCoordinateDepth);
float t = dot(depthPositionUv - ray.pos, ray.dir);
setIntersectionPair(ix, DEPTH_INTERSECTION_INDEX, vec2(t, +INF_HIT));
} else {
// There's no depth at this location.
setIntersectionPair(ix, DEPTH_INTERSECTION_INDEX, vec2(NO_HIT));
}
}
`,y4e=`// See IntersectionUtils.glsl for the definitions of Ray, Intersections, INF_HIT,
// NO_HIT, setShapeIntersection
/* Clipping plane defines (set in Scene/VoxelRenderResources.js)
#define CLIPPING_PLANES_UNION
#define CLIPPING_PLANES_COUNT
#define CLIPPING_PLANES_INTERSECTION_INDEX
*/
uniform sampler2D u_clippingPlanesTexture;
uniform mat4 u_clippingPlanesMatrix;
// Plane is in Hessian Normal Form
vec4 intersectPlane(in Ray ray, in vec4 plane) {
vec3 n = plane.xyz; // normal
float w = plane.w; // -dot(pointOnPlane, normal)
float a = dot(ray.pos, n);
float b = dot(ray.dir, n);
float t = -(w + a) / b;
return vec4(n, t);
}
void intersectClippingPlanes(in Ray ray, inout Intersections ix) {
vec4 backSide = vec4(-ray.dir, -INF_HIT);
vec4 farSide = vec4(ray.dir, +INF_HIT);
RayShapeIntersection clippingVolume;
#if (CLIPPING_PLANES_COUNT == 1)
// Union and intersection are the same when there's one clipping plane, and the code
// is more simplified.
vec4 planeUv = getClippingPlane(u_clippingPlanesTexture, 0, u_clippingPlanesMatrix);
vec4 intersection = intersectPlane(ray, planeUv);
bool reflects = dot(ray.dir, intersection.xyz) < 0.0;
clippingVolume.entry = reflects ? backSide : intersection;
clippingVolume.exit = reflects ? intersection : farSide;
setShapeIntersection(ix, CLIPPING_PLANES_INTERSECTION_INDEX, clippingVolume);
#elif defined(CLIPPING_PLANES_UNION)
vec4 firstTransmission = vec4(ray.dir, +INF_HIT);
vec4 lastReflection = vec4(-ray.dir, -INF_HIT);
for (int i = 0; i < CLIPPING_PLANES_COUNT; i++) {
vec4 planeUv = getClippingPlane(u_clippingPlanesTexture, i, u_clippingPlanesMatrix);
vec4 intersection = intersectPlane(ray, planeUv);
if (dot(ray.dir, planeUv.xyz) > 0.0) {
firstTransmission = intersection.w <= firstTransmission.w ? intersection : firstTransmission;
} else {
lastReflection = intersection.w >= lastReflection.w ? intersection : lastReflection;
}
}
clippingVolume.entry = backSide;
clippingVolume.exit = lastReflection;
setShapeIntersection(ix, CLIPPING_PLANES_INTERSECTION_INDEX + 0, clippingVolume);
clippingVolume.entry = firstTransmission;
clippingVolume.exit = farSide;
setShapeIntersection(ix, CLIPPING_PLANES_INTERSECTION_INDEX + 1, clippingVolume);
#else // intersection
vec4 lastTransmission = vec4(ray.dir, -INF_HIT);
vec4 firstReflection = vec4(-ray.dir, +INF_HIT);
for (int i = 0; i < CLIPPING_PLANES_COUNT; i++) {
vec4 planeUv = getClippingPlane(u_clippingPlanesTexture, i, u_clippingPlanesMatrix);
vec4 intersection = intersectPlane(ray, planeUv);
if (dot(ray.dir, planeUv.xyz) > 0.0) {
lastTransmission = intersection.w > lastTransmission.w ? intersection : lastTransmission;
} else {
firstReflection = intersection.w < firstReflection.w ? intersection: firstReflection;
}
}
if (lastTransmission.w < firstReflection.w) {
clippingVolume.entry = lastTransmission;
clippingVolume.exit = firstReflection;
} else {
clippingVolume.entry = vec4(-ray.dir, NO_HIT);
clippingVolume.exit = vec4(ray.dir, NO_HIT);
}
setShapeIntersection(ix, CLIPPING_PLANES_INTERSECTION_INDEX, clippingVolume);
#endif
}
`,bz=`// See IntersectionUtils.glsl for the definitions of Ray, NO_HIT, INF_HIT,
// RayShapeIntersection
vec4 intersectLongitude(in Ray ray, in float angle, in bool positiveNormal) {
float normalSign = positiveNormal ? 1.0 : -1.0;
vec2 planeNormal = vec2(-sin(angle), cos(angle)) * normalSign;
vec2 position = ray.pos.xy;
vec2 direction = ray.dir.xy;
float approachRate = dot(direction, planeNormal);
float distance = -dot(position, planeNormal);
float t = (approachRate == 0.0)
? NO_HIT
: distance / approachRate;
return vec4(planeNormal, 0.0, t);
}
RayShapeIntersection intersectHalfSpace(in Ray ray, in float angle, in bool positiveNormal)
{
vec4 intersection = intersectLongitude(ray, angle, positiveNormal);
vec4 farSide = vec4(normalize(ray.dir), INF_HIT);
bool hitFront = (intersection.w > 0.0) == (dot(ray.pos.xy, intersection.xy) > 0.0);
if (!hitFront) {
return RayShapeIntersection(intersection, farSide);
} else {
return RayShapeIntersection(-1.0 * farSide, intersection);
}
}
void intersectFlippedWedge(in Ray ray, in vec2 minMaxAngle, out RayShapeIntersection intersections[2])
{
intersections[0] = intersectHalfSpace(ray, minMaxAngle.x, false);
intersections[1] = intersectHalfSpace(ray, minMaxAngle.y, true);
}
bool hitPositiveHalfPlane(in Ray ray, in vec4 intersection, in bool positiveNormal) {
float normalSign = positiveNormal ? 1.0 : -1.0;
vec2 planeDirection = vec2(intersection.y, -intersection.x) * normalSign;
vec2 hit = ray.pos.xy + intersection.w * ray.dir.xy;
return dot(hit, planeDirection) > 0.0;
}
void intersectHalfPlane(in Ray ray, in float angle, out RayShapeIntersection intersections[2]) {
vec4 intersection = intersectLongitude(ray, angle, true);
vec4 farSide = vec4(normalize(ray.dir), INF_HIT);
if (hitPositiveHalfPlane(ray, intersection, true)) {
intersections[0].entry = -1.0 * farSide;
intersections[0].exit = vec4(-1.0 * intersection.xy, 0.0, intersection.w);
intersections[1].entry = intersection;
intersections[1].exit = farSide;
} else {
vec4 miss = vec4(normalize(ray.dir), NO_HIT);
intersections[0].entry = -1.0 * farSide;
intersections[0].exit = farSide;
intersections[1].entry = miss;
intersections[1].exit = miss;
}
}
RayShapeIntersection intersectRegularWedge(in Ray ray, in vec2 minMaxAngle)
{
// Note: works for maxAngle > minAngle + pi, where the "regular wedge"
// is actually a negative volume.
// Compute intersections with the two planes.
// Normals will point toward the "outside" (negative space)
vec4 intersect1 = intersectLongitude(ray, minMaxAngle.x, false);
vec4 intersect2 = intersectLongitude(ray, minMaxAngle.y, true);
// Choose intersection with smallest T as the "first", the other as "last"
// Note: first or last could be in the "shadow" wedge, beyond the tip
bool inOrder = intersect1.w <= intersect2.w;
vec4 first = inOrder ? intersect1 : intersect2;
vec4 last = inOrder ? intersect2 : intersect1;
bool firstIsAhead = first.w >= 0.0;
bool startedInsideFirst = dot(ray.pos.xy, first.xy) < 0.0;
bool exitFromInside = firstIsAhead == startedInsideFirst;
bool lastIsAhead = last.w > 0.0;
bool startedOutsideLast = dot(ray.pos.xy, last.xy) >= 0.0;
bool enterFromOutside = lastIsAhead == startedOutsideLast;
vec4 farSide = vec4(normalize(ray.dir), INF_HIT);
vec4 miss = vec4(normalize(ray.dir), NO_HIT);
if (exitFromInside && enterFromOutside) {
// Ray crosses both faces of negative wedge, exiting then entering the positive shape
return RayShapeIntersection(first, last);
} else if (!exitFromInside && enterFromOutside) {
// Ray starts inside wedge. last is in shadow wedge, and first is actually the entry
return RayShapeIntersection(-1.0 * farSide, first);
} else if (exitFromInside && !enterFromOutside) {
// First intersection was in the shadow wedge, so last is actually the exit
return RayShapeIntersection(last, farSide);
} else { // !exitFromInside && !enterFromOutside
// Both intersections were in the shadow wedge
return RayShapeIntersection(miss, miss);
}
}
`,b4e=`// See IntersectionUtils.glsl for the definitions of Ray, RayShapeIntersection,
// NO_HIT, Intersections
/* Box defines (set in Scene/VoxelBoxShape.js)
#define BOX_INTERSECTION_INDEX ### // always 0
*/
uniform vec3 u_renderMinBounds;
uniform vec3 u_renderMaxBounds;
RayShapeIntersection intersectBox(in Ray ray, in vec3 minBound, in vec3 maxBound)
{
// Consider the box as the intersection of the space between 3 pairs of parallel planes
// Compute the distance along the ray to each plane
vec3 t0 = (minBound - ray.pos) / ray.dir;
vec3 t1 = (maxBound - ray.pos) / ray.dir;
// Identify candidate entries/exits based on distance from ray.pos
vec3 entries = min(t0, t1);
vec3 exits = max(t0, t1);
vec3 directions = sign(ray.dir);
// The actual intersection points are the furthest entry and the closest exit
float lastEntry = maxComponent(entries);
bvec3 isLastEntry = equal(entries, vec3(lastEntry));
vec3 entryNormal = -1.0 * vec3(isLastEntry) * directions;
vec4 entry = vec4(entryNormal, lastEntry);
float firstExit = minComponent(exits);
bvec3 isFirstExit = equal(exits, vec3(firstExit));
vec3 exitNormal = vec3(isLastEntry) * directions;
vec4 exit = vec4(exitNormal, firstExit);
if (entry.w > exit.w) {
entry.w = NO_HIT;
exit.w = NO_HIT;
}
return RayShapeIntersection(entry, exit);
}
void intersectShape(in Ray ray, inout Intersections ix)
{
RayShapeIntersection intersection = intersectBox(ray, u_renderMinBounds, u_renderMaxBounds);
setShapeIntersection(ix, BOX_INTERSECTION_INDEX, intersection);
}
`,T4e=`// See IntersectionUtils.glsl for the definitions of Ray, NO_HIT, Intersections,
// RayShapeIntersection, setSurfaceIntersection, setShapeIntersection,
// intersectIntersections
// See IntersectLongitude.glsl for the definitions of intersectHalfPlane,
// intersectFlippedWedge, intersectRegularWedge
/* Cylinder defines (set in Scene/VoxelCylinderShape.js)
#define CYLINDER_HAS_RENDER_BOUNDS_RADIUS_MIN
#define CYLINDER_HAS_RENDER_BOUNDS_RADIUS_FLAT
#define CYLINDER_HAS_RENDER_BOUNDS_ANGLE
#define CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_UNDER_HALF
#define CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_OVER_HALF
#define CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_EQUAL_ZERO
#define CYLINDER_INTERSECTION_INDEX_RADIUS_MAX
#define CYLINDER_INTERSECTION_INDEX_RADIUS_MIN
#define CYLINDER_INTERSECTION_INDEX_ANGLE
*/
// Cylinder uniforms
uniform vec2 u_cylinderRenderRadiusMinMax;
uniform vec2 u_cylinderRenderHeightMinMax;
#if defined(CYLINDER_HAS_RENDER_BOUNDS_ANGLE)
uniform vec2 u_cylinderRenderAngleMinMax;
#endif
/**
* Find the intersection of a ray with the volume defined by two planes of constant z
*/
RayShapeIntersection intersectHeightBounds(in Ray ray, in vec2 minMaxHeight, in bool convex)
{
float zPosition = ray.pos.z;
float zDirection = ray.dir.z;
float tmin = (minMaxHeight.x - zPosition) / zDirection;
float tmax = (minMaxHeight.y - zPosition) / zDirection;
// Normals point outside the volume
float signFlip = convex ? 1.0 : -1.0;
vec4 intersectMin = vec4(0.0, 0.0, -1.0 * signFlip, tmin);
vec4 intersectMax = vec4(0.0, 0.0, 1.0 * signFlip, tmax);
bool topEntry = zDirection < 0.0;
vec4 entry = topEntry ? intersectMax : intersectMin;
vec4 exit = topEntry ? intersectMin : intersectMax;
return RayShapeIntersection(entry, exit);
}
/**
* Find the intersection of a ray with a right cylindrical surface of a given radius
* about the z-axis.
*/
RayShapeIntersection intersectCylinder(in Ray ray, in float radius, in bool convex)
{
vec2 position = ray.pos.xy;
vec2 direction = ray.dir.xy;
float a = dot(direction, direction);
float b = dot(position, direction);
float c = dot(position, position) - radius * radius;
float determinant = b * b - a * c;
if (determinant < 0.0) {
vec4 miss = vec4(normalize(ray.dir), NO_HIT);
return RayShapeIntersection(miss, miss);
}
determinant = sqrt(determinant);
float t1 = (-b - determinant) / a;
float t2 = (-b + determinant) / a;
float signFlip = convex ? 1.0 : -1.0;
vec4 intersect1 = vec4(normalize(position + t1 * direction) * signFlip, 0.0, t1);
vec4 intersect2 = vec4(normalize(position + t2 * direction) * signFlip, 0.0, t2);
return RayShapeIntersection(intersect1, intersect2);
}
/**
* Find the intersection of a ray with a right cylindrical solid of given
* radius and height bounds. NOTE: The shape is assumed to be convex.
*/
RayShapeIntersection intersectBoundedCylinder(in Ray ray, in float radius, in vec2 minMaxHeight)
{
RayShapeIntersection cylinderIntersection = intersectCylinder(ray, radius, true);
RayShapeIntersection heightBoundsIntersection = intersectHeightBounds(ray, minMaxHeight, true);
return intersectIntersections(ray, cylinderIntersection, heightBoundsIntersection);
}
void intersectShape(Ray ray, inout Intersections ix)
{
// Position is converted from [0,1] to [-1,+1] because shape intersections assume unit space is [-1,+1].
// Direction is scaled as well to be in sync with position.
ray.pos = ray.pos * 2.0 - 1.0;
ray.dir *= 2.0;
RayShapeIntersection outerIntersect = intersectBoundedCylinder(ray, u_cylinderRenderRadiusMinMax.y, u_cylinderRenderHeightMinMax);
setShapeIntersection(ix, CYLINDER_INTERSECTION_INDEX_RADIUS_MAX, outerIntersect);
if (outerIntersect.entry.w == NO_HIT) {
return;
}
#if defined(CYLINDER_HAS_RENDER_BOUNDS_RADIUS_FLAT)
// When the cylinder is perfectly thin it's necessary to sandwich the
// inner cylinder intersection inside the outer cylinder intersection.
// Without this special case,
// [outerMin, outerMax, innerMin, innerMax] will bubble sort to
// [outerMin, innerMin, outerMax, innerMax] which will cause the back
// side of the cylinder to be invisible because it will think the ray
// is still inside the inner (negative) cylinder after exiting the
// outer (positive) cylinder.
// With this special case,
// [outerMin, innerMin, innerMax, outerMax] will bubble sort to
// [outerMin, innerMin, innerMax, outerMax] which will work correctly.
// Note: If initializeIntersections() changes its sorting function
// from bubble sort to something else, this code may need to change.
RayShapeIntersection innerIntersect = intersectCylinder(ray, 1.0, false);
setSurfaceIntersection(ix, 0, outerIntersect.entry, true, true); // positive, enter
setSurfaceIntersection(ix, 1, innerIntersect.entry, false, true); // negative, enter
setSurfaceIntersection(ix, 2, innerIntersect.exit, false, false); // negative, exit
setSurfaceIntersection(ix, 3, outerIntersect.exit, true, false); // positive, exit
#elif defined(CYLINDER_HAS_RENDER_BOUNDS_RADIUS_MIN)
RayShapeIntersection innerIntersect = intersectCylinder(ray, u_cylinderRenderRadiusMinMax.x, false);
setShapeIntersection(ix, CYLINDER_INTERSECTION_INDEX_RADIUS_MIN, innerIntersect);
#endif
#if defined(CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_UNDER_HALF)
RayShapeIntersection wedgeIntersect = intersectRegularWedge(ray, u_cylinderRenderAngleMinMax);
setShapeIntersection(ix, CYLINDER_INTERSECTION_INDEX_ANGLE, wedgeIntersect);
#elif defined(CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_OVER_HALF)
RayShapeIntersection wedgeIntersects[2];
intersectFlippedWedge(ray, u_cylinderRenderAngleMinMax, wedgeIntersects);
setShapeIntersection(ix, CYLINDER_INTERSECTION_INDEX_ANGLE + 0, wedgeIntersects[0]);
setShapeIntersection(ix, CYLINDER_INTERSECTION_INDEX_ANGLE + 1, wedgeIntersects[1]);
#elif defined(CYLINDER_HAS_RENDER_BOUNDS_ANGLE_RANGE_EQUAL_ZERO)
RayShapeIntersection wedgeIntersects[2];
intersectHalfPlane(ray, u_cylinderRenderAngleMinMax.x, wedgeIntersects);
setShapeIntersection(ix, CYLINDER_INTERSECTION_INDEX_ANGLE + 0, wedgeIntersects[0]);
setShapeIntersection(ix, CYLINDER_INTERSECTION_INDEX_ANGLE + 1, wedgeIntersects[1]);
#endif
}
`,A4e=`// See IntersectionUtils.glsl for the definitions of Ray, NO_HIT, INF_HIT, Intersections,
// RayShapeIntersection, setSurfaceIntersection, setShapeIntersection
// See IntersectLongitude.glsl for the definitions of intersectHalfPlane,
// intersectFlippedWedge, intersectRegularWedge
/* Ellipsoid defines (set in Scene/VoxelEllipsoidShape.js)
#define ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE
#define ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_EQUAL_ZERO
#define ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_UNDER_HALF
#define ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_OVER_HALF
#define ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_UNDER_HALF
#define ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_EQUAL_HALF
#define ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_OVER_HALF
#define ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_UNDER_HALF
#define ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_EQUAL_HALF
#define ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_OVER_HALF
#define ELLIPSOID_INTERSECTION_INDEX_LONGITUDE
#define ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MAX
#define ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MIN
#define ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MAX
#define ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MIN
*/
#if defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE)
uniform vec2 u_ellipsoidRenderLongitudeMinMax;
#endif
uniform float u_eccentricitySquared;
uniform vec2 u_ellipsoidRenderLatitudeSinMinMax;
uniform vec2 u_clipMinMaxHeight;
RayShapeIntersection intersectZPlane(in Ray ray, in float z) {
float t = -ray.pos.z / ray.dir.z;
bool startsOutside = sign(ray.pos.z) == sign(z);
bool entry = (t >= 0.0) != startsOutside;
vec4 intersect = vec4(0.0, 0.0, z, t);
vec4 farSide = vec4(normalize(ray.dir), INF_HIT);
if (entry) {
return RayShapeIntersection(intersect, farSide);
} else {
return RayShapeIntersection(-1.0 * farSide, intersect);
}
}
RayShapeIntersection intersectHeight(in Ray ray, in float relativeHeight, in bool convex)
{
// Scale the ray by the ellipsoid axes to make it a unit sphere
// Note: approximating ellipsoid + height as an ellipsoid
vec3 radiiCorrection = u_ellipsoidRadiiUv / (u_ellipsoidRadiiUv + relativeHeight);
vec3 position = ray.pos * radiiCorrection;
vec3 direction = ray.dir * radiiCorrection;
float a = dot(direction, direction); // ~ 1.0 (or maybe 4.0 if ray is scaled)
float b = dot(direction, position); // roughly inside [-1.0, 1.0] when zoomed in
float c = dot(position, position) - 1.0; // ~ 0.0 when zoomed in.
float determinant = b * b - a * c; // ~ b * b when zoomed in
if (determinant < 0.0) {
vec4 miss = vec4(normalize(direction), NO_HIT);
return RayShapeIntersection(miss, miss);
}
determinant = sqrt(determinant);
// Compute larger root using standard formula
float signB = b < 0.0 ? -1.0 : 1.0;
// The other root may suffer from subtractive cancellation in the standard formula.
// Compute it from the first root instead.
float t1 = (-b - signB * determinant) / a;
float t2 = c / (a * t1);
float tmin = min(t1, t2);
float tmax = max(t1, t2);
float directionScale = convex ? 1.0 : -1.0;
vec3 d1 = directionScale * normalize(position + tmin * direction);
vec3 d2 = directionScale * normalize(position + tmax * direction);
return RayShapeIntersection(vec4(d1, tmin), vec4(d2, tmax));
}
/**
* Given a circular cone around the z-axis, with apex at the origin,
* find the parametric distance(s) along a ray where that ray intersects
* the cone.
* The cone opening angle is described by the squared cosine of
* its half-angle (the angle between the Z-axis and the surface)
*/
vec2 intersectDoubleEndedCone(in Ray ray, in float cosSqrHalfAngle)
{
vec3 o = ray.pos;
vec3 d = ray.dir;
float sinSqrHalfAngle = 1.0 - cosSqrHalfAngle;
float aSin = d.z * d.z * sinSqrHalfAngle;
float aCos = -dot(d.xy, d.xy) * cosSqrHalfAngle;
float a = aSin + aCos;
float bSin = d.z * o.z * sinSqrHalfAngle;
float bCos = -dot(o.xy, d.xy) * cosSqrHalfAngle;
float b = bSin + bCos;
float cSin = o.z * o.z * sinSqrHalfAngle;
float cCos = -dot(o.xy, o.xy) * cosSqrHalfAngle;
float c = cSin + cCos;
// determinant = b * b - a * c. But bSin * bSin = aSin * cSin.
// Avoid subtractive cancellation by expanding to eliminate these terms
float determinant = 2.0 * bSin * bCos + bCos * bCos - aSin * cCos - aCos * cSin - aCos * cCos;
if (determinant < 0.0) {
return vec2(NO_HIT);
} else if (a == 0.0) {
// Ray is parallel to cone surface
return (b == 0.0)
? vec2(NO_HIT) // Ray is on cone surface
: vec2(-0.5 * c / b, NO_HIT);
}
determinant = sqrt(determinant);
// Compute larger root using standard formula
float signB = b < 0.0 ? -1.0 : 1.0;
float t1 = (-b - signB * determinant) / a;
// The other root may suffer from subtractive cancellation in the standard formula.
// Compute it from the first root instead.
float t2 = c / (a * t1);
float tmin = min(t1, t2);
float tmax = max(t1, t2);
return vec2(tmin, tmax);
}
/**
* Given a point on a conical surface, find the surface normal at that point.
*/
vec3 getConeNormal(in vec3 p, in bool convex) {
// Start with radial component pointing toward z-axis
vec2 radial = -abs(p.z) * normalize(p.xy);
// Z component points toward opening of cone
float zSign = (p.z < 0.0) ? -1.0 : 1.0;
float z = length(p.xy) * zSign;
// Flip normal if shape is convex
float flip = (convex) ? -1.0 : 1.0;
return normalize(vec3(radial, z) * flip);
}
/**
* Compute the shift between the ellipsoid origin and the apex of a cone of latitude
*/
float getLatitudeConeShift(in float sinLatitude) {
// Find prime vertical radius of curvature:
// the distance along the ellipsoid normal to the intersection with the z-axis
float x2 = u_eccentricitySquared * sinLatitude * sinLatitude;
float primeVerticalRadius = inversesqrt(1.0 - x2);
// Compute a shift from the origin to the intersection of the cone with the z-axis
return primeVerticalRadius * u_eccentricitySquared * sinLatitude;
}
void intersectFlippedCone(in Ray ray, in float cosHalfAngle, out RayShapeIntersection intersections[2]) {
// Undo the scaling from ellipsoid to sphere
ray.pos = ray.pos * u_ellipsoidRadiiUv;
ray.dir = ray.dir * u_ellipsoidRadiiUv;
// Shift the ray to account for the latitude cone not being centered at the Earth center
ray.pos.z += getLatitudeConeShift(cosHalfAngle);
float cosSqrHalfAngle = cosHalfAngle * cosHalfAngle;
vec2 intersect = intersectDoubleEndedCone(ray, cosSqrHalfAngle);
vec4 miss = vec4(normalize(ray.dir), NO_HIT);
vec4 farSide = vec4(normalize(ray.dir), INF_HIT);
// Initialize output with no intersections
intersections[0].entry = -1.0 * farSide;
intersections[0].exit = farSide;
intersections[1].entry = miss;
intersections[1].exit = miss;
if (intersect.x == NO_HIT) {
return;
}
// Find the points of intersection
float tmin = intersect.x;
float tmax = intersect.y;
vec3 p0 = ray.pos + tmin * ray.dir;
vec3 p1 = ray.pos + tmax * ray.dir;
vec4 intersect0 = vec4(getConeNormal(p0, true), tmin);
vec4 intersect1 = vec4(getConeNormal(p1, true), tmax);
bool p0InShadowCone = sign(p0.z) != sign(cosHalfAngle);
bool p1InShadowCone = sign(p1.z) != sign(cosHalfAngle);
if (p0InShadowCone && p1InShadowCone) {
// no valid intersections
} else if (p0InShadowCone) {
intersections[0].exit = intersect1;
} else if (p1InShadowCone) {
intersections[0].entry = intersect0;
} else {
intersections[0].exit = intersect0;
intersections[1].entry = intersect1;
intersections[1].exit = farSide;
}
}
RayShapeIntersection intersectRegularCone(in Ray ray, in float cosHalfAngle, in bool convex) {
// Undo the scaling from ellipsoid to sphere
ray.pos = ray.pos * u_ellipsoidRadiiUv;
ray.dir = ray.dir * u_ellipsoidRadiiUv;
// Shift the ray to account for the latitude cone not being centered at the Earth center
ray.pos.z += getLatitudeConeShift(cosHalfAngle);
float cosSqrHalfAngle = cosHalfAngle * cosHalfAngle;
vec2 intersect = intersectDoubleEndedCone(ray, cosSqrHalfAngle);
vec4 miss = vec4(normalize(ray.dir), NO_HIT);
vec4 farSide = vec4(normalize(ray.dir), INF_HIT);
if (intersect.x == NO_HIT) {
return RayShapeIntersection(miss, miss);
}
// Find the points of intersection
float tmin = intersect.x;
float tmax = intersect.y;
vec3 p0 = ray.pos + tmin * ray.dir;
vec3 p1 = ray.pos + tmax * ray.dir;
vec4 intersect0 = vec4(getConeNormal(p0, convex), tmin);
vec4 intersect1 = vec4(getConeNormal(p1, convex), tmax);
bool p0InShadowCone = sign(p0.z) != sign(cosHalfAngle);
bool p1InShadowCone = sign(p1.z) != sign(cosHalfAngle);
if (p0InShadowCone && p1InShadowCone) {
return RayShapeIntersection(miss, miss);
} else if (p0InShadowCone) {
return RayShapeIntersection(intersect1, farSide);
} else if (p1InShadowCone) {
return RayShapeIntersection(-1.0 * farSide, intersect0);
} else {
return RayShapeIntersection(intersect0, intersect1);
}
}
void intersectShape(in Ray ray, inout Intersections ix) {
// Position is converted from [0,1] to [-1,+1] because shape intersections assume unit space is [-1,+1].
// Direction is scaled as well to be in sync with position.
ray.pos = ray.pos * 2.0 - 1.0;
ray.dir *= 2.0;
// Outer ellipsoid
RayShapeIntersection outerIntersect = intersectHeight(ray, u_clipMinMaxHeight.y, true);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MAX, outerIntersect);
// Exit early if the outer ellipsoid was missed.
if (outerIntersect.entry.w == NO_HIT) {
return;
}
// Inner ellipsoid
RayShapeIntersection innerIntersect = intersectHeight(ray, u_clipMinMaxHeight.x, false);
if (innerIntersect.entry.w == NO_HIT) {
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_HEIGHT_MIN, innerIntersect);
} else {
// When the ellipsoid is large and thin it's possible for floating point math
// to cause the ray to intersect the inner ellipsoid before the outer ellipsoid.
// To prevent this from happening, clamp innerIntersect to outerIntersect and
// sandwich the inner ellipsoid intersection inside the outer ellipsoid intersection.
// Without this special case,
// [outerMin, outerMax, innerMin, innerMax] will bubble sort to
// [outerMin, innerMin, outerMax, innerMax] which will cause the back
// side of the ellipsoid to be invisible because it will think the ray
// is still inside the inner (negative) ellipsoid after exiting the
// outer (positive) ellipsoid.
// With this special case,
// [outerMin, innerMin, innerMax, outerMax] will bubble sort to
// [outerMin, innerMin, innerMax, outerMax] which will work correctly.
// Note: If initializeIntersections() changes its sorting function
// from bubble sort to something else, this code may need to change.
innerIntersect.entry.w = max(innerIntersect.entry.w, outerIntersect.entry.w);
innerIntersect.exit.w = min(innerIntersect.exit.w, outerIntersect.exit.w);
setSurfaceIntersection(ix, 0, outerIntersect.entry, true, true); // positive, enter
setSurfaceIntersection(ix, 1, innerIntersect.entry, false, true); // negative, enter
setSurfaceIntersection(ix, 2, innerIntersect.exit, false, false); // negative, exit
setSurfaceIntersection(ix, 3, outerIntersect.exit, true, false); // positive, exit
}
// Bottom cone
#if defined(ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_UNDER_HALF)
RayShapeIntersection bottomConeIntersection = intersectRegularCone(ray, u_ellipsoidRenderLatitudeSinMinMax.x, false);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MIN, bottomConeIntersection);
#elif defined(ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_EQUAL_HALF)
RayShapeIntersection bottomConeIntersection = intersectZPlane(ray, -1.0);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MIN, bottomConeIntersection);
#elif defined(ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MIN_OVER_HALF)
RayShapeIntersection bottomConeIntersections[2];
intersectFlippedCone(ray, u_ellipsoidRenderLatitudeSinMinMax.x, bottomConeIntersections);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MIN + 0, bottomConeIntersections[0]);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MIN + 1, bottomConeIntersections[1]);
#endif
// Top cone
#if defined(ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_UNDER_HALF)
RayShapeIntersection topConeIntersections[2];
intersectFlippedCone(ray, u_ellipsoidRenderLatitudeSinMinMax.y, topConeIntersections);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MAX + 0, topConeIntersections[0]);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MAX + 1, topConeIntersections[1]);
#elif defined(ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_EQUAL_HALF)
RayShapeIntersection topConeIntersection = intersectZPlane(ray, 1.0);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MAX, topConeIntersection);
#elif defined(ELLIPSOID_HAS_RENDER_BOUNDS_LATITUDE_MAX_OVER_HALF)
RayShapeIntersection topConeIntersection = intersectRegularCone(ray, u_ellipsoidRenderLatitudeSinMinMax.y, false);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LATITUDE_MAX, topConeIntersection);
#endif
// Wedge
#if defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_EQUAL_ZERO)
RayShapeIntersection wedgeIntersects[2];
intersectHalfPlane(ray, u_ellipsoidRenderLongitudeMinMax.x, wedgeIntersects);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LONGITUDE + 0, wedgeIntersects[0]);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LONGITUDE + 1, wedgeIntersects[1]);
#elif defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_UNDER_HALF)
RayShapeIntersection wedgeIntersect = intersectRegularWedge(ray, u_ellipsoidRenderLongitudeMinMax);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LONGITUDE, wedgeIntersect);
#elif defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_RANGE_OVER_HALF)
RayShapeIntersection wedgeIntersects[2];
intersectFlippedWedge(ray, u_ellipsoidRenderLongitudeMinMax, wedgeIntersects);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LONGITUDE + 0, wedgeIntersects[0]);
setShapeIntersection(ix, ELLIPSOID_INTERSECTION_INDEX_LONGITUDE + 1, wedgeIntersects[1]);
#endif
}
`,Gv=`// Main intersection function for Voxel scenes.
// See IntersectBox.glsl, IntersectCylinder.glsl, or IntersectEllipsoid.glsl
// for the definition of intersectShape. The appropriate function is selected
// based on the VoxelPrimitive shape type, and added to the shader in
// Scene/VoxelRenderResources.js.
// See also IntersectClippingPlane.glsl and IntersectDepth.glsl.
// See IntersectionUtils.glsl for the definitions of Ray, NO_HIT,
// getFirstIntersection, initializeIntersections, nextIntersection.
/* Intersection defines (set in Scene/VoxelRenderResources.js)
#define INTERSECTION_COUNT ###
*/
RayShapeIntersection intersectScene(in vec2 screenCoord, in Ray ray, out Intersections ix) {
// Do a ray-shape intersection to find the exact starting and ending points.
intersectShape(ray, ix);
// Exit early if the positive shape was completely missed or behind the ray.
RayShapeIntersection intersection = getFirstIntersection(ix);
if (intersection.entry.w == NO_HIT) {
// Positive shape was completely missed - so exit early.
return intersection;
}
// Clipping planes
#if defined(CLIPPING_PLANES)
intersectClippingPlanes(ray, ix);
#endif
// Depth
#if defined(DEPTH_TEST)
intersectDepth(screenCoord, ray, ix);
#endif
// Find the first intersection that's in front of the ray
#if (INTERSECTION_COUNT > 1)
initializeIntersections(ix);
for (int i = 0; i < INTERSECTION_COUNT; ++i) {
intersection = nextIntersection(ix);
if (intersection.exit.w > 0.0) {
// Set start to 0.0 when ray is inside the shape.
intersection.entry.w = max(intersection.entry.w, 0.0);
break;
}
}
#else
// Set start to 0.0 when ray is inside the shape.
intersection.entry.w = max(intersection.entry.w, 0.0);
#endif
return intersection;
}
`,x4e=`/* Box defines (set in Scene/VoxelBoxShape.js)
#define BOX_HAS_SHAPE_BOUNDS
*/
#if defined(BOX_HAS_SHAPE_BOUNDS)
uniform vec3 u_boxUvToShapeUvScale;
uniform vec3 u_boxUvToShapeUvTranslate;
#endif
PointJacobianT convertUvToShapeSpaceDerivative(in vec3 positionUv) {
// For BOX, UV space = shape space, so we can use positionUv as-is,
// and the Jacobian is the identity matrix, except that a step of 1
// only spans half the shape space [-1, 1], so the identity is scaled.
return PointJacobianT(positionUv, mat3(0.5));
}
vec3 convertShapeToShapeUvSpace(in vec3 positionShape) {
#if defined(BOX_HAS_SHAPE_BOUNDS)
return positionShape * u_boxUvToShapeUvScale + u_boxUvToShapeUvTranslate;
#else
return positionShape;
#endif
}
PointJacobianT convertUvToShapeUvSpaceDerivative(in vec3 positionUv) {
PointJacobianT pointJacobian = convertUvToShapeSpaceDerivative(positionUv);
pointJacobian.point = convertShapeToShapeUvSpace(pointJacobian.point);
return pointJacobian;
}
vec3 convertShapeUvToUvSpace(in vec3 shapeUv) {
#if defined(BOX_HAS_SHAPE_BOUNDS)
return (shapeUv - u_boxUvToShapeUvTranslate) / u_boxUvToShapeUvScale;
#else
return shapeUv;
#endif
}
vec3 scaleShapeUvToShapeSpace(in vec3 shapeUv) {
#if defined(BOX_HAS_SHAPE_BOUNDS)
return shapeUv / u_boxUvToShapeUvScale;
#else
return shapeUv;
#endif
}`,C4e=`/* Cylinder defines (set in Scene/VoxelCylinderShape.js)
#define CYLINDER_HAS_SHAPE_BOUNDS_RADIUS
#define CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT
#define CYLINDER_HAS_SHAPE_BOUNDS_ANGLE
#define CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_DISCONTINUITY
#define CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MAX_DISCONTINUITY
#define CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_MAX_REVERSED
*/
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_RADIUS)
uniform vec2 u_cylinderUvToShapeUvRadius; // x = scale, y = offset
#endif
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT)
uniform vec2 u_cylinderUvToShapeUvHeight; // x = scale, y = offset
#endif
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE)
uniform vec2 u_cylinderUvToShapeUvAngle; // x = scale, y = offset
#endif
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_DISCONTINUITY) || defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MAX_DISCONTINUITY)
uniform vec2 u_cylinderShapeUvAngleMinMax;
#endif
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_DISCONTINUITY) || defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MAX_DISCONTINUITY) || defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_MAX_REVERSED)
uniform float u_cylinderShapeUvAngleRangeZeroMid;
#endif
PointJacobianT convertUvToShapeSpaceDerivative(in vec3 positionUv) {
// Convert from Cartesian UV space [0, 1] to Cartesian local space [-1, 1]
vec3 position = positionUv * 2.0 - 1.0;
float radius = length(position.xy); // [0, 1]
vec3 radial = normalize(vec3(position.xy, 0.0));
// Shape space height is defined within [0, 1]
float height = positionUv.z; // [0, 1]
vec3 z = vec3(0.0, 0.0, 1.0);
float angle = atan(position.y, position.x);
vec3 east = normalize(vec3(-position.y, position.x, 0.0));
vec3 point = vec3(radius, height, angle);
mat3 jacobianT = mat3(radial, z, east / length(position.xy));
return PointJacobianT(point, jacobianT);
}
vec3 convertShapeToShapeUvSpace(in vec3 positionShape) {
float radius = positionShape.x;
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_RADIUS)
radius = radius * u_cylinderUvToShapeUvRadius.x + u_cylinderUvToShapeUvRadius.y;
#endif
float height = positionShape.y;
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT)
height = height * u_cylinderUvToShapeUvHeight.x + u_cylinderUvToShapeUvHeight.y;
#endif
float angle = (positionShape.z + czm_pi) / czm_twoPi;
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE)
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_MAX_REVERSED)
// Comparing against u_cylinderShapeUvAngleMinMax has precision problems. u_cylinderShapeUvAngleRangeZeroMid is more conservative.
angle += float(angle < u_cylinderShapeUvAngleRangeZeroMid);
#endif
// Avoid flickering from reading voxels from both sides of the -pi/+pi discontinuity.
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MIN_DISCONTINUITY)
angle = angle > u_cylinderShapeUvAngleRangeZeroMid ? u_cylinderShapeUvAngleMinMax.x : angle;
#elif defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE_MAX_DISCONTINUITY)
angle = angle < u_cylinderShapeUvAngleRangeZeroMid ? u_cylinderShapeUvAngleMinMax.y : angle;
#endif
angle = angle * u_cylinderUvToShapeUvAngle.x + u_cylinderUvToShapeUvAngle.y;
#endif
return vec3(radius, height, angle);
}
PointJacobianT convertUvToShapeUvSpaceDerivative(in vec3 positionUv) {
PointJacobianT pointJacobian = convertUvToShapeSpaceDerivative(positionUv);
pointJacobian.point = convertShapeToShapeUvSpace(pointJacobian.point);
return pointJacobian;
}
vec3 scaleShapeUvToShapeSpace(in vec3 shapeUv) {
float radius = shapeUv.x;
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_RADIUS)
radius /= u_cylinderUvToShapeUvRadius.x;
#endif
float height = shapeUv.y;
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_HEIGHT)
height /= u_cylinderUvToShapeUvHeight.x;
#endif
float angle = shapeUv.z * czm_twoPi;
#if defined(CYLINDER_HAS_SHAPE_BOUNDS_ANGLE)
angle /= u_cylinderUvToShapeUvAngle.x;
#endif
return vec3(radius, height, angle);
}
`,E4e=`/* Ellipsoid defines (set in Scene/VoxelEllipsoidShape.js)
#define ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MIN_DISCONTINUITY
#define ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MAX_DISCONTINUITY
#define ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE
#define ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE_MIN_MAX_REVERSED
#define ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE
*/
uniform vec3 u_ellipsoidRadiiUv; // [0,1]
uniform vec2 u_evoluteScale; // (radiiUv.x ^ 2 - radiiUv.z ^ 2) * vec2(1.0, -1.0) / radiiUv;
uniform vec3 u_ellipsoidInverseRadiiSquaredUv;
#if defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MIN_DISCONTINUITY) || defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MAX_DISCONTINUITY) || defined(ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE_MIN_MAX_REVERSED)
uniform vec3 u_ellipsoidShapeUvLongitudeMinMaxMid;
#endif
#if defined(ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE)
uniform vec2 u_ellipsoidUvToShapeUvLongitude; // x = scale, y = offset
#endif
#if defined(ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE)
uniform vec2 u_ellipsoidUvToShapeUvLatitude; // x = scale, y = offset
#endif
uniform float u_ellipsoidInverseHeightDifferenceUv;
// robust iterative solution without trig functions
// https://github.com/0xfaded/ellipse_demo/issues/1
// https://stackoverflow.com/questions/22959698/distance-from-given-point-to-given-ellipse
// Extended to return radius of curvature along with the point
vec3 nearestPointAndRadiusOnEllipse(vec2 pos, vec2 radii) {
vec2 p = abs(pos);
vec2 inverseRadii = 1.0 / radii;
// We describe the ellipse parametrically: v = radii * vec2(cos(t), sin(t))
// but store the cos and sin of t in a vec2 for efficiency.
// Initial guess: t = pi/4
vec2 tTrigs = vec2(0.7071067811865476);
// Initial guess of point on ellipsoid
vec2 v = radii * tTrigs;
// Center of curvature of the ellipse at v
vec2 evolute = u_evoluteScale * tTrigs * tTrigs * tTrigs;
const int iterations = 3;
for (int i = 0; i < iterations; ++i) {
// Find the (approximate) intersection of p - evolute with the ellipsoid.
vec2 q = normalize(p - evolute) * length(v - evolute);
// Update the estimate of t.
tTrigs = (q + evolute) * inverseRadii;
tTrigs = normalize(clamp(tTrigs, 0.0, 1.0));
v = radii * tTrigs;
evolute = u_evoluteScale * tTrigs * tTrigs * tTrigs;
}
return vec3(v * sign(pos), length(v - evolute));
}
PointJacobianT convertUvToShapeSpaceDerivative(in vec3 positionUv) {
// Convert from UV space [0, 1] to local space [-1, 1]
vec3 position = positionUv * 2.0 - 1.0;
// Undo the scaling from ellipsoid to sphere
position = position * u_ellipsoidRadiiUv;
float longitude = atan(position.y, position.x);
vec3 east = normalize(vec3(-position.y, position.x, 0.0));
// Convert the 3D position to a 2D position relative to the ellipse (radii.x, radii.z)
// (assume radii.y == radii.x) and find the nearest point on the ellipse and its normal
float distanceFromZAxis = length(position.xy);
vec2 posEllipse = vec2(distanceFromZAxis, position.z);
vec3 surfacePointAndRadius = nearestPointAndRadiusOnEllipse(posEllipse, u_ellipsoidRadiiUv.xz);
vec2 surfacePoint = surfacePointAndRadius.xy;
vec2 normal2d = normalize(surfacePoint * u_ellipsoidInverseRadiiSquaredUv.xz);
float latitude = atan(normal2d.y, normal2d.x);
vec3 north = vec3(-normal2d.y * normalize(position.xy), abs(normal2d.x));
float heightSign = length(posEllipse) < length(surfacePoint) ? -1.0 : 1.0;
float height = heightSign * length(posEllipse - surfacePoint);
vec3 up = normalize(cross(east, north));
vec3 point = vec3(longitude, latitude, height);
mat3 jacobianT = mat3(east / distanceFromZAxis, north / (surfacePointAndRadius.z + height), up);
return PointJacobianT(point, jacobianT);
}
vec3 convertShapeToShapeUvSpace(in vec3 positionShape) {
// Longitude: shift & scale to [0, 1]
float longitude = (positionShape.x + czm_pi) / czm_twoPi;
// Correct the angle when max < min
// Technically this should compare against min longitude - but it has precision problems so compare against the middle of empty space.
#if defined(ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE_MIN_MAX_REVERSED)
longitude += float(longitude < u_ellipsoidShapeUvLongitudeMinMaxMid.z);
#endif
// Avoid flickering from reading voxels from both sides of the -pi/+pi discontinuity.
#if defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MIN_DISCONTINUITY)
longitude = longitude > u_ellipsoidShapeUvLongitudeMinMaxMid.z ? u_ellipsoidShapeUvLongitudeMinMaxMid.x : longitude;
#endif
#if defined(ELLIPSOID_HAS_RENDER_BOUNDS_LONGITUDE_MAX_DISCONTINUITY)
longitude = longitude < u_ellipsoidShapeUvLongitudeMinMaxMid.z ? u_ellipsoidShapeUvLongitudeMinMaxMid.y : longitude;
#endif
#if defined(ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE)
longitude = longitude * u_ellipsoidUvToShapeUvLongitude.x + u_ellipsoidUvToShapeUvLongitude.y;
#endif
// Latitude: shift and scale to [0, 1]
float latitude = (positionShape.y + czm_piOverTwo) / czm_pi;
#if defined(ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE)
latitude = latitude * u_ellipsoidUvToShapeUvLatitude.x + u_ellipsoidUvToShapeUvLatitude.y;
#endif
// Height: scale to the range [0, 1]
float height = 1.0 + positionShape.z * u_ellipsoidInverseHeightDifferenceUv;
return vec3(longitude, latitude, height);
}
PointJacobianT convertUvToShapeUvSpaceDerivative(in vec3 positionUv) {
PointJacobianT pointJacobian = convertUvToShapeSpaceDerivative(positionUv);
pointJacobian.point = convertShapeToShapeUvSpace(pointJacobian.point);
return pointJacobian;
}
vec3 scaleShapeUvToShapeSpace(in vec3 shapeUv) {
// Convert from [0, 1] to radians [-pi, pi]
float longitude = shapeUv.x * czm_twoPi;
#if defined (ELLIPSOID_HAS_SHAPE_BOUNDS_LONGITUDE)
longitude /= u_ellipsoidUvToShapeUvLongitude.x;
#endif
// Convert from [0, 1] to radians [-pi/2, pi/2]
float latitude = shapeUv.y * czm_pi;
#if defined(ELLIPSOID_HAS_SHAPE_BOUNDS_LATITUDE)
latitude /= u_ellipsoidUvToShapeUvLatitude.x;
#endif
float height = shapeUv.z / u_ellipsoidInverseHeightDifferenceUv;
return vec3(longitude, latitude, height);
}
`,w4e=`// These octree flags must be in sync with GpuOctreeFlag in VoxelTraversal.js
#define OCTREE_FLAG_INTERNAL 0
#define OCTREE_FLAG_LEAF 1
#define OCTREE_FLAG_PACKED_LEAF_FROM_PARENT 2
#define OCTREE_MAX_LEVELS 32 // Harcoded value because GLSL doesn't like variable length loops
uniform sampler2D u_octreeInternalNodeTexture;
uniform vec2 u_octreeInternalNodeTexelSizeUv;
uniform int u_octreeInternalNodeTilesPerRow;
#if (SAMPLE_COUNT > 1)
uniform sampler2D u_octreeLeafNodeTexture;
uniform vec2 u_octreeLeafNodeTexelSizeUv;
uniform int u_octreeLeafNodeTilesPerRow;
#endif
struct OctreeNodeData {
int data;
int flag;
};
struct TraversalData {
ivec4 octreeCoords;
int parentOctreeIndex;
};
struct SampleData {
int megatextureIndex;
ivec4 tileCoords;
vec3 tileUv;
#if (SAMPLE_COUNT > 1)
float weight;
#endif
};
// Integer mod: For WebGL1 only
int intMod(in int a, in int b) {
return a - (b * (a / b));
}
int normU8_toInt(in float value) {
return int(value * 255.0);
}
int normU8x2_toInt(in vec2 value) {
return int(value.x * 255.0) + 256 * int(value.y * 255.0);
}
float normU8x2_toFloat(in vec2 value) {
return float(normU8x2_toInt(value)) / 65535.0;
}
OctreeNodeData getOctreeNodeData(in vec2 octreeUv) {
vec4 texData = texture(u_octreeInternalNodeTexture, octreeUv);
OctreeNodeData data;
data.data = normU8x2_toInt(texData.xy);
data.flag = normU8x2_toInt(texData.zw);
return data;
}
OctreeNodeData getOctreeChildData(in int parentOctreeIndex, in ivec3 childCoord) {
int childIndex = childCoord.z * 4 + childCoord.y * 2 + childCoord.x;
int octreeCoordX = intMod(parentOctreeIndex, u_octreeInternalNodeTilesPerRow) * 9 + 1 + childIndex;
int octreeCoordY = parentOctreeIndex / u_octreeInternalNodeTilesPerRow;
vec2 octreeUv = u_octreeInternalNodeTexelSizeUv * vec2(float(octreeCoordX) + 0.5, float(octreeCoordY) + 0.5);
return getOctreeNodeData(octreeUv);
}
int getOctreeParentIndex(in int octreeIndex) {
int octreeCoordX = intMod(octreeIndex, u_octreeInternalNodeTilesPerRow) * 9;
int octreeCoordY = octreeIndex / u_octreeInternalNodeTilesPerRow;
vec2 octreeUv = u_octreeInternalNodeTexelSizeUv * vec2(float(octreeCoordX) + 0.5, float(octreeCoordY) + 0.5);
vec4 parentData = texture(u_octreeInternalNodeTexture, octreeUv);
int parentOctreeIndex = normU8x2_toInt(parentData.xy);
return parentOctreeIndex;
}
/**
* Convert a position in the uv-space of the tileset bounding shape
* into the uv-space of a tile within the tileset
*/
vec3 getTileUv(in vec3 shapePosition, in ivec4 octreeCoords) {
// PERFORMANCE_IDEA: use bit-shifting (only in WebGL2)
float dimAtLevel = exp2(float(octreeCoords.w));
return shapePosition * dimAtLevel - vec3(octreeCoords.xyz);
}
vec3 getClampedTileUv(in vec3 shapePosition, in ivec4 octreeCoords) {
vec3 tileUv = getTileUv(shapePosition, octreeCoords);
return clamp(tileUv, vec3(0.0), vec3(1.0));
}
void getOctreeLeafSampleData(in OctreeNodeData data, in ivec4 octreeCoords, out SampleData sampleData) {
sampleData.megatextureIndex = data.data;
sampleData.tileCoords = (data.flag == OCTREE_FLAG_PACKED_LEAF_FROM_PARENT)
? ivec4(octreeCoords.xyz / 2, octreeCoords.w - 1)
: octreeCoords;
}
#if (SAMPLE_COUNT > 1)
void getOctreeLeafSampleDatas(in OctreeNodeData data, in ivec4 octreeCoords, out SampleData sampleDatas[SAMPLE_COUNT]) {
int leafIndex = data.data;
int leafNodeTexelCount = 2;
// Adding 0.5 moves to the center of the texel
float leafCoordXStart = float(intMod(leafIndex, u_octreeLeafNodeTilesPerRow) * leafNodeTexelCount) + 0.5;
float leafCoordY = float(leafIndex / u_octreeLeafNodeTilesPerRow) + 0.5;
// Get an interpolation weight and a flag to determine whether to read the parent texture
vec2 leafUv0 = u_octreeLeafNodeTexelSizeUv * vec2(leafCoordXStart + 0.0, leafCoordY);
vec4 leafData0 = texture(u_octreeLeafNodeTexture, leafUv0);
float lerp = normU8x2_toFloat(leafData0.xy);
sampleDatas[0].weight = 1.0 - lerp;
sampleDatas[1].weight = lerp;
// TODO: this looks wrong? Should be comparing to OCTREE_FLAG_PACKED_LEAF_FROM_PARENT
sampleDatas[0].tileCoords = (normU8_toInt(leafData0.z) == 1)
? ivec4(octreeCoords.xyz / 2, octreeCoords.w - 1)
: octreeCoords;
sampleDatas[1].tileCoords = (normU8_toInt(leafData0.w) == 1)
? ivec4(octreeCoords.xyz / 2, octreeCoords.w - 1)
: octreeCoords;
// Get megatexture indices for both samples
vec2 leafUv1 = u_octreeLeafNodeTexelSizeUv * vec2(leafCoordXStart + 1.0, leafCoordY);
vec4 leafData1 = texture(u_octreeLeafNodeTexture, leafUv1);
sampleDatas[0].megatextureIndex = normU8x2_toInt(leafData1.xy);
sampleDatas[1].megatextureIndex = normU8x2_toInt(leafData1.zw);
}
#endif
OctreeNodeData traverseOctreeDownwards(in vec3 shapePosition, inout TraversalData traversalData) {
float sizeAtLevel = exp2(-1.0 * float(traversalData.octreeCoords.w));
vec3 start = vec3(traversalData.octreeCoords.xyz) * sizeAtLevel;
vec3 end = start + vec3(sizeAtLevel);
OctreeNodeData childData;
for (int i = 0; i < OCTREE_MAX_LEVELS; ++i) {
// Find out which octree child contains the position
// 0 if before center, 1 if after
vec3 center = 0.5 * (start + end);
vec3 childCoord = step(center, shapePosition);
// Get octree coords for the next level down
ivec4 octreeCoords = traversalData.octreeCoords;
traversalData.octreeCoords = ivec4(octreeCoords.xyz * 2 + ivec3(childCoord), octreeCoords.w + 1);
childData = getOctreeChildData(traversalData.parentOctreeIndex, ivec3(childCoord));
if (childData.flag != OCTREE_FLAG_INTERNAL) {
// leaf tile - stop traversing
break;
}
// interior tile - keep going deeper
start = mix(start, center, childCoord);
end = mix(center, end, childCoord);
traversalData.parentOctreeIndex = childData.data;
}
return childData;
}
/**
* Transform a given position to an octree tile coordinate and a position within that tile,
* and find the corresponding megatexture index and texture coordinates
*/
void traverseOctreeFromBeginning(in vec3 shapePosition, out TraversalData traversalData, out SampleData sampleDatas[SAMPLE_COUNT]) {
traversalData.octreeCoords = ivec4(0);
traversalData.parentOctreeIndex = 0;
OctreeNodeData nodeData = getOctreeNodeData(vec2(0.0));
if (nodeData.flag != OCTREE_FLAG_LEAF) {
nodeData = traverseOctreeDownwards(shapePosition, traversalData);
}
#if (SAMPLE_COUNT == 1)
getOctreeLeafSampleData(nodeData, traversalData.octreeCoords, sampleDatas[0]);
sampleDatas[0].tileUv = getClampedTileUv(shapePosition, sampleDatas[0].tileCoords);
#else
getOctreeLeafSampleDatas(nodeData, traversalData.octreeCoords, sampleDatas);
sampleDatas[0].tileUv = getClampedTileUv(shapePosition, sampleDatas[0].tileCoords);
sampleDatas[1].tileUv = getClampedTileUv(shapePosition, sampleDatas[1].tileCoords);
#endif
}
bool inRange(in vec3 v, in vec3 minVal, in vec3 maxVal) {
return clamp(v, minVal, maxVal) == v;
}
bool insideTile(in vec3 shapePosition, in ivec4 octreeCoords) {
vec3 tileUv = getTileUv(shapePosition, octreeCoords);
bool inside = inRange(tileUv, vec3(0.0), vec3(1.0));
// Assume (!) the position is always inside the root tile.
return inside || octreeCoords.w == 0;
}
void traverseOctreeFromExisting(in vec3 shapePosition, inout TraversalData traversalData, inout SampleData sampleDatas[SAMPLE_COUNT]) {
if (insideTile(shapePosition, traversalData.octreeCoords)) {
for (int i = 0; i < SAMPLE_COUNT; i++) {
sampleDatas[0].tileUv = getClampedTileUv(shapePosition, sampleDatas[0].tileCoords);
}
return;
}
// Go up tree until we find a parent tile containing shapePosition
for (int i = 0; i < OCTREE_MAX_LEVELS; ++i) {
traversalData.octreeCoords.xyz /= 2;
traversalData.octreeCoords.w -= 1;
if (insideTile(shapePosition, traversalData.octreeCoords)) {
break;
}
traversalData.parentOctreeIndex = getOctreeParentIndex(traversalData.parentOctreeIndex);
}
// Go down tree
OctreeNodeData nodeData = traverseOctreeDownwards(shapePosition, traversalData);
#if (SAMPLE_COUNT == 1)
getOctreeLeafSampleData(nodeData, traversalData.octreeCoords, sampleDatas[0]);
sampleDatas[0].tileUv = getClampedTileUv(shapePosition, sampleDatas[0].tileCoords);
#else
getOctreeLeafSampleDatas(nodeData, traversalData.octreeCoords, sampleDatas);
sampleDatas[0].tileUv = getClampedTileUv(shapePosition, sampleDatas[0].tileCoords);
sampleDatas[1].tileUv = getClampedTileUv(shapePosition, sampleDatas[1].tileCoords);
#endif
}
`,S4e=`// See Octree.glsl for the definitions of SampleData and intMod
/* Megatexture defines (set in Scene/VoxelRenderResources.js)
#define SAMPLE_COUNT ###
#define NEAREST_SAMPLING
#define PADDING
*/
uniform ivec2 u_megatextureSliceDimensions; // number of slices per tile, in two dimensions
uniform ivec2 u_megatextureTileDimensions; // number of tiles per megatexture, in two dimensions
uniform vec2 u_megatextureVoxelSizeUv;
uniform vec2 u_megatextureSliceSizeUv;
uniform vec2 u_megatextureTileSizeUv;
uniform ivec3 u_dimensions; // does not include padding
#if defined(PADDING)
uniform ivec3 u_paddingBefore;
uniform ivec3 u_paddingAfter;
#endif
// Integer min, max, clamp: For WebGL1 only
int intMin(int a, int b) {
return a <= b ? a : b;
}
int intMax(int a, int b) {
return a >= b ? a : b;
}
int intClamp(int v, int minVal, int maxVal) {
return intMin(intMax(v, minVal), maxVal);
}
vec2 index1DTo2DTexcoord(int index, ivec2 dimensions, vec2 uvScale)
{
int indexX = intMod(index, dimensions.x);
int indexY = index / dimensions.x;
return vec2(indexX, indexY) * uvScale;
}
/*
How is 3D data stored in a 2D megatexture?
In this example there is only one loaded tile and it has 2x2x2 voxels (8 voxels total).
The data is sliced by Z. The data at Z = 0 is placed in texels (0,0), (0,1), (1,0), (1,1) and
the data at Z = 1 is placed in texels (2,0), (2,1), (3,0), (3,1).
Note that there could be empty space in the megatexture because it's a power of two.
0 1 2 3
+---+---+---+---+
| | | | | 3
+---+---+---+---+
| | | | | 2
+-------+-------+
|010|110|011|111| 1
|--- ---|--- ---|
|000|100|001|101| 0
+-------+-------+
When doing linear interpolation the megatexture needs to be sampled twice: once for
the Z slice above the voxel coordinate and once for the slice below. The two slices
are interpolated with fract(coord.z - 0.5). For example, a Z coordinate of 1.0 is
halfway between two Z slices so the interpolation factor is 0.5. Below is a side view
of the 3D voxel grid with voxel coordinates on the left side.
2 +---+
|001|
1 +-z-+
|000|
0 +---+
When doing nearest neighbor the megatexture only needs to be sampled once at the closest Z slice.
*/
Properties getPropertiesFromMegatexture(in SampleData sampleData) {
int tileIndex = sampleData.megatextureIndex;
vec3 voxelCoord = sampleData.tileUv * vec3(u_dimensions);
ivec3 voxelDimensions = u_dimensions;
#if defined(PADDING)
voxelDimensions += u_paddingBefore + u_paddingAfter;
voxelCoord += vec3(u_paddingBefore);
#endif
#if defined(NEAREST_SAMPLING)
// Round to the center of the nearest voxel
voxelCoord = floor(voxelCoord) + vec3(0.5);
#endif
// Tile location
vec2 tileUvOffset = index1DTo2DTexcoord(tileIndex, u_megatextureTileDimensions, u_megatextureTileSizeUv);
// Slice location
float slice = voxelCoord.z - 0.5;
int sliceIndex = int(floor(slice));
int sliceIndex0 = intClamp(sliceIndex, 0, voxelDimensions.z - 1);
vec2 sliceUvOffset0 = index1DTo2DTexcoord(sliceIndex0, u_megatextureSliceDimensions, u_megatextureSliceSizeUv);
// Voxel location
vec2 voxelUvOffset = clamp(voxelCoord.xy, vec2(0.5), vec2(voxelDimensions.xy) - vec2(0.5)) * u_megatextureVoxelSizeUv;
// Final location in the megatexture
vec2 uv0 = tileUvOffset + sliceUvOffset0 + voxelUvOffset;
#if defined(NEAREST_SAMPLING)
return getPropertiesFromMegatextureAtUv(uv0);
#else
float sliceLerp = fract(slice);
int sliceIndex1 = intMin(sliceIndex + 1, voxelDimensions.z - 1);
vec2 sliceUvOffset1 = index1DTo2DTexcoord(sliceIndex1, u_megatextureSliceDimensions, u_megatextureSliceSizeUv);
vec2 uv1 = tileUvOffset + sliceUvOffset1 + voxelUvOffset;
Properties properties0 = getPropertiesFromMegatextureAtUv(uv0);
Properties properties1 = getPropertiesFromMegatextureAtUv(uv1);
return mixProperties(properties0, properties1, sliceLerp);
#endif
}
// Convert an array of sample datas to a final weighted properties.
Properties accumulatePropertiesFromMegatexture(in SampleData sampleDatas[SAMPLE_COUNT]) {
#if (SAMPLE_COUNT == 1)
return getPropertiesFromMegatexture(sampleDatas[0]);
#else
// When more than one sample is taken the accumulator needs to start at 0
Properties properties = clearProperties();
for (int i = 0; i < SAMPLE_COUNT; ++i) {
float weight = sampleDatas[i].weight;
// Avoid reading the megatexture when the weight is 0 as it can be costly.
if (weight > 0.0) {
Properties tempProperties = getPropertiesFromMegatexture(sampleDatas[i]);
tempProperties = scaleProperties(tempProperties, weight);
properties = sumProperties(properties, tempProperties);
}
}
return properties;
#endif
}
`;function v4e(e){const t=new Es;this.shaderBuilder=t;const n=e._customShader,i=jt(e._uniformMap,n.uniformMap);e._uniformMap=i;const o=n.uniforms;for(const _ in o)if(o.hasOwnProperty(_)){const g=o[_];t.addUniform(g.type,_,ge.FRAGMENT)}t.addUniform("sampler2D","u_megatextureTextures[METADATA_COUNT]",ge.FRAGMENT),this.uniformMap=i;const r=e._clippingPlanes,s=c(r)&&r.enabled?r.length:0;this.clippingPlanes=r,this.clippingPlanesLength=s,t.addVertexLines([m4e]),t.addFragmentLines([n.fragmentShaderText,"#line 0",w4e,f4e,_4e,S4e]),s>0&&(t.addDefine("CLIPPING_PLANES",void 0,ge.FRAGMENT),t.addDefine("CLIPPING_PLANES_COUNT",s,ge.FRAGMENT),r.unionClippingRegions&&t.addDefine("CLIPPING_PLANES_UNION",void 0,ge.FRAGMENT),t.addFragmentLines([y4e])),e._depthTest&&(t.addDefine("DEPTH_TEST",void 0,ge.FRAGMENT),t.addFragmentLines([g4e]));const a=e._provider.shape;a==="BOX"?t.addFragmentLines([x4e,b4e,Gv]):a==="CYLINDER"?t.addFragmentLines([C4e,bz,T4e,Gv]):a==="ELLIPSOID"&&(t.addDefine("SHAPE_ELLIPSOID",void 0,ge.FRAGMENT),t.addFragmentLines([E4e,bz,A4e,Gv])),t.addFragmentLines([p4e]);const l=e._shape,u=l.shaderDefines;for(const _ in u)if(u.hasOwnProperty(_)){let g=u[_];c(g)&&(g=g===!0?void 0:g,t.addDefine(_,g,ge.FRAGMENT))}let h=l.shaderMaximumIntersectionsLength;s>0&&(t.addDefine("CLIPPING_PLANES_INTERSECTION_INDEX",h,ge.FRAGMENT),s===1?h+=1:r.unionClippingRegions?h+=2:h+=1),e._depthTest&&(t.addDefine("DEPTH_INTERSECTION_INDEX",h,ge.FRAGMENT),h+=1),t.addDefine("INTERSECTION_COUNT",h,ge.FRAGMENT),(!d.equals(e.paddingBefore,d.ZERO)||!d.equals(e.paddingAfter,d.ZERO))&&t.addDefine("PADDING",void 0,ge.FRAGMENT),e._useLogDepth&&t.addDefine("LOG_DEPTH_READ_ONLY",void 0,ge.FRAGMENT),e._jitter&&t.addDefine("JITTER",void 0,ge.FRAGMENT),e._nearestSampling&&t.addDefine("NEAREST_SAMPLING",void 0,ge.FRAGMENT);const f=e._traversal;t.addDefine("SAMPLE_COUNT",`${f._sampleCount}`,ge.FRAGMENT)}function I4e(e,t){const{shaderBuilder:n}=e,{names:i,types:o,componentTypes:r,minimumValues:s,maximumValues:a}=t._provider,l=o.length,u=c(s)&&c(a);n.addDefine("METADATA_COUNT",l,ge.FRAGMENT),u&&n.addDefine("STATISTICS",void 0,ge.FRAGMENT);for(let M=0;M<l;M++){const U=i[M],B=o[M],S=`PropertyStatistics_${U}`,D=`PropertyStatistics_${U}`;n.addStruct(S,D,ge.FRAGMENT);const p=bA(B);n.addStructField(S,p,"min"),n.addStructField(S,p,"max")}const h="Statistics",f="Statistics",_="statistics";n.addStruct(h,f,ge.FRAGMENT);for(let M=0;M<l;M++){const U=i[M],B=`PropertyStatistics_${U}`,S=U;n.addStructField(h,B,S)}const g="Metadata",m="Metadata",b="metadata";n.addStruct(g,m,ge.FRAGMENT),n.addStructField(g,f,_);for(let M=0;M<l;M++){const U=i[M],B=o[M],S=bA(B);n.addStructField(g,S,U)}for(let M=0;M<l;M++){const U=i[M],B=o[M],S=P4e(B),D=`VoxelProperty_${U}`,p=`VoxelProperty_${U}`;n.addStruct(D,p,ge.FRAGMENT),n.addStructField(D,S,"partialDerivativeLocal"),n.addStructField(D,S,"partialDerivativeWorld"),n.addStructField(D,S,"partialDerivativeView"),n.addStructField(D,S,"partialDerivativeValid")}const T="Voxel",x="Voxel",C="voxel";n.addStruct(T,x,ge.FRAGMENT);for(let M=0;M<l;M++){const U=i[M],B=`VoxelProperty_${U}`;n.addStructField(T,B,U)}n.addStructField(T,"vec3","positionEC"),n.addStructField(T,"vec3","positionUv"),n.addStructField(T,"vec3","positionShapeUv"),n.addStructField(T,"vec3","positionUvLocal"),n.addStructField(T,"vec3","viewDirUv"),n.addStructField(T,"vec3","viewDirWorld"),n.addStructField(T,"vec3","surfaceNormal"),n.addStructField(T,"float","travelDistance"),n.addStructField(T,"int","stepCount"),n.addStructField(T,"int","tileIndex"),n.addStructField(T,"int","sampleIndex");const w="FragmentInput",v="FragmentInput";n.addStruct(w,v,ge.FRAGMENT),n.addStructField(w,m,b),n.addStructField(w,x,C);const P="Properties",N="Properties",k="properties";n.addStruct(P,N,ge.FRAGMENT);for(let M=0;M<l;M++){const U=i[M],B=o[M],S=bA(B);n.addStructField(P,S,U)}{const M="clearProperties";n.addFunction(M,`${N} clearProperties()`,ge.FRAGMENT),n.addFunctionLines(M,[`${N} ${k};`]);for(let U=0;U<l;U++){const B=i[U],S=o[U];r[U];const D=bA(S);n.addFunctionLines(M,[`${k}.${B} = ${D}(0.0);`])}n.addFunctionLines(
{
material.diffuse = vec3(1.0);
material.alpha = 1.0;
}`});function J6(){this.ready=!0,this.shape=ah.BOX,this.dimensions=new d(1,1,1),this.names=["data"],this.types=[bt.SCALAR],this.componentTypes=[Ot.FLOAT32],this.maximumTileCount=1}J6.prototype.requestData=function(e){if(!((c(e)?y(e.tileLevel,0):0)>=1))return Promise.resolve([new Float32Array(1)])};Bc.DefaultProvider=new J6;const uC=function(e){return function(){e.frameState.afterRender.push(function(){e.requestRender()})}};function gn(e){e=y(e,y.EMPTY_OBJECT);const t=e.canvas;let n=e.creditContainer,i=e.creditViewport;const o=Je(e.contextOptions);if(!c(t))throw new E("options and options.canvas are required.");const r=c(n),s=new Va(t,o);r||(n=document.createElement("div"),n.style.position="absolute",n.style.bottom="0",n.style["text-shadow"]="0 0 2px #000000",n.style.color="#ffffff",n.style["font-size"]="10px",n.style["padding-right"]="5px",t.parentNode.appendChild(n)),c(i)||(i=t.parentNode),this._id=Wr(),this._jobScheduler=new Sh,this._frameState=new _Be(s,new ki(n," \u2022 ",i),this._jobScheduler),this._frameState.scene3DOnly=y(e.scene3DOnly,!1),this._removeCreditContainer=!r,this._creditContainer=n,this._canvas=t,this._context=s,this._computeEngine=new yC(s),this._globe=void 0,this._globeTranslucencyState=new Wp,this._primitives=new eo,this._groundPrimitives=new eo,this._globeHeight=void 0,this._globeHeightDirty=!0,this._cameraUnderground=!1,this._removeUpdateHeightCallback=void 0,this._logDepthBuffer=gn.defaultLogDepthBuffer&&s.fragmentDepth,this._logDepthBufferDirty=!0,this._tweens=new Wc,this._shaderFrameCount=0,this._sunPostProcess=void 0,this._computeCommandList=[],this._overlayCommandList=[],this._useOIT=y(e.orderIndependentTranslucency,!0),this._executeOITFunction=void 0,this._depthPlane=new lb(e.depthPlaneEllipsoidOffset),this._clearColorCommand=new bi({color:new z,stencil:0,owner:this}),this._depthClearCommand=new bi({depth:1,owner:this}),this._stencilClearCommand=new bi({stencil:0}),this._classificationStencilClearCommand=new bi({stencil:0,renderState:Ue.fromCache({stencilMask:At.CLASSIFICATION_MASK})}),this._depthOnlyRenderStateCache={},this._transitioner=new Qp(this),this._preUpdate=new Le,this._postUpdate=new Le,this._renderError=new Le,this._preRender=new Le,this._postRender=new Le,this._minimumDisableDepthTestDistance=0,this._debugInspector=new V6,this._msaaSamples=y(e.msaaSamples,1),this.rethrowRenderErrors=!1,this.completeMorphOnUserInput=!0,this.morphStart=new Le,this.morphComplete=new Le,this.skyBox=void 0,this.skyAtmosphere=void 0,this.sun=void 0,this.sunBloom=!0,this._sunBloom=void 0,this.moon=void 0,this.backgroundColor=z.clone(z.BLACK),this._mode=oe.SCENE3D,this._mapProjection=c(e.mapProjection)?e.mapProjection:new co,this.morphTime=1,this.farToNearRatio=1e3,this.logarithmicDepthFarToNearRatio=1e9,this.nearToFarDistance2D=175e4,this.verticalExaggeration=1,this.verticalExaggerationRelativeHeight=0,this.debugCommandFilter=void 0,this.debugShowCommands=!1,this.debugShowFrustums=!1,this.debugShowFramesPerSecond=!1,this.debugShowDepthFrustum=1,this.debugShowFrustumPlanes=!1,this._debugShowFrustumPlanes=!1,this._debugFrustumPlanes=void 0,this.useDepthPicking=!0,this.pickTranslucentDepth=!1,this.cameraEventWaitTime=500,this.atmosphere=new OMe,this.fog=new RW,this._shadowMapCamera=new Ye(this),this.shadowMap=new Wa({context:s,lightCamera:this._shadowMapCamera,enabled:y(e.shadows,!1)}),this.invertClassification=!1,this.invertClassificationColor=z.clone(z.WHITE),this._actualInvertClassificationColor=z.clone(this._invertClassificationColor),this._invertClassification=new kl,this.focalLength=void 0,this.eyeSeparation=void 0,this.postProcessStages=new js,this._brdfLutGenerator=new ab,this._performanceDisplay=void 0,this._debugVolume=void 0,this._screenSpaceCameraController=new fb(this),this._cameraUnderground=!1,this._mapMode2D=y(e.mapMode2D,Wh.INFINITE_SCROLL),this._environmentState={skyBoxCommand:void 0,skyAtmosphereCommand:void 0,sunDrawCommand:void 0,sunComputeCommand:void 0,moonCommand:void 0,isSunVisible:!1,isMoonVisible:!1,isReadyForAtmosphere:!1,isSkyAtmosphereVisible:!1,clearGlobeDepth:!1,useDepthPl
${t}
${m}`);const b=document.createElement("div");b.className="cesium-widget-errorPanel-message-details collapsed";const T=document.createElement("span");T.className="cesium-widget-errorPanel-more-details",T.appendChild(document.createTextNode("See more...")),b.appendChild(T),b.onclick=function(x){b.removeChild(T),b.appendChild(document.createTextNode(m)),b.className="cesium-widget-errorPanel-message-details",r.className="cesium-widget-errorPanel-content expanded",b.onclick=void 0},a.appendChild(b)}g.innerHTML=`<p>${t}</p>`}const f=document.createElement("div");f.className="cesium-widget-errorPanel-buttonPanel",r.appendChild(f);const _=document.createElement("button");_.setAttribute("type","button"),_.className="cesium-button",_.appendChild(document.createTextNode("OK")),_.onclick=function(){c(l)&&c(window.removeEventListener)&&window.removeEventListener("resize",l,!1),i.removeChild(o)},f.appendChild(_),i.appendChild(o)};Kp.prototype.isDestroyed=function(){return!1};Kp.prototype.destroy=function(){c(this._scene)&&(this._scene.renderError.removeEventListener(this._onRenderError),this._scene=this._scene.destroy()),this._container.removeChild(this._element),this._creditContainer.removeChild(this._innerCreditContainer),ve(this)};Kp.prototype.resize=function(){const e=this._canvas;!this._forceResize&&this._canvasClientWidth===e.clientWidth&&this._canvasClientHeight===e.clientHeight&&this._lastDevicePixelRatio===window.devicePixelRatio||(this._forceResize=!1,sq(this),aq(this),this._scene.requestRender())};Kp.prototype.render=function(){if(this._canRender){this._scene.initializeFrame();const e=this._clock.tick();this._scene.render(e)}else this._clock.tick()};function ad(e,t){this._tilingScheme=e,this._maximumLevel=t,this._rootNodes=[]}const zf=new ce;function e8e(e,t,n,i){const o=i.length;for(let r=0;r<o;++r){const s=i[r];if(s.x===t&&s.y===n&&s.level===e)return!0}return!1}ad.prototype.addAvailableTileRange=function(e,t,n,i,o){const r=this._tilingScheme,s=this._rootNodes;if(e===0)for(let _=n;_<=o;++_)for(let g=t;g<=i;++g)e8e(e,g,_,s)||s.push(new Hm(r,void 0,0,g,_));r.tileXYToRectangle(t,n,e,zf);const a=zf.west,l=zf.north;r.tileXYToRectangle(i,o,e,zf);const u=zf.east,h=zf.south,f=new r8e(e,a,h,u,l);for(let _=0;_<s.length;++_){const g=s[_];tL(g.extent,f)&&s8e(this._maximumLevel,g,f)}};ad.prototype.computeMaximumLevelAtPosition=function(e){let t;for(let n=0;n<this._rootNodes.length;++n){const i=this._rootNodes[n];if(Gm(i.extent,e)){t=i;break}}return c(t)?Cy(void 0,t,e):-1};const t8e=[],n8e=[],i8e=new ce,o8e=new ce;ad.prototype.computeBestAvailableLevelOverRectangle=function(e){const t=t8e;t.length=0,e.east<e.west?(t.push(ce.fromRadians(-Math.PI,e.south,e.east,e.north,i8e)),t.push(ce.fromRadians(e.west,e.south,Math.PI,e.north,o8e))):t.push(e);const n=n8e;n.length=0;let i;for(i=0;i<this._rootNodes.length;++i)Ey(n,this._rootNodes[i],t);for(i=n.length-1;i>=0;--i)if(c(n[i])&&n[i].length===0)return i;return 0};const Bz=new he;ad.prototype.isTileAvailable=function(e,t,n){const i=this._tilingScheme.tileXYToRectangle(t,n,e,zf);return ce.center(i,Bz),this.computeMaximumLevelAtPosition(Bz)>=e};ad.prototype.computeChildMaskForTile=function(e,t,n){const i=e+1;if(i>=this._maximumLevel)return 0;let o=0;return o|=this.isTileAvailable(i,2*t,2*n+1)?1:0,o|=this.isTileAvailable(i,2*t+1,2*n+1)?2:0,o|=this.isTileAvailable(i,2*t,2*n)?4:0,o|=this.isTileAvailable(i,2*t+1,2*n)?8:0,o};function Hm(e,t,n,i,o){this.tilingScheme=e,this.parent=t,this.level=n,this.x=i,this.y=o,this.extent=e.tileXYToRectangle(i,o,n),this.rectangles=[],this._sw=void 0,this._se=void 0,this._nw=void 0,this._ne=void 0}Object.defineProperties(Hm.prototype,{nw:{get:function(){return this._nw||(this._nw=new Hm(this.tilingScheme,this,this.level+1,this.x*2,this.y*2)),this._nw}},ne:{get:function(){return this._ne||(this._ne=new Hm(this.tilingScheme,this,this.level+1,this.x*2+1,this.y*2)),this._ne}},sw:{get:function(){return this._sw||(this._sw=new Hm(this.tilingScheme,this,this.level+1,this.x*2,this.y*2+1)),this._sw}},se:{get:function(){return this._se||(this._se=new Hm(this.tilingScheme,this,th
${t.message}`),e.previousError=Er.reportError(e.previousError,n,c(n)?n._errorEvent:void 0,i),e.previousError.retry)return nL(e,n);throw new Te(i)}async function b8e(e,t,n){await fq(e,t,n);const i=e.overallAvailability.length;if(i>0){const o=e.availability=new ad(e.tilingScheme,e.overallMaxZoom);for(let r=0;r<i;++r){const s=e.overallAvailability[r];for(let a=0;a<s.length;++a){const l=s[a];o.addAvailableTileRange(r,l[0],l[1],l[2],l[3])}}}if(e.attribution.length>0){const o=new Wt(e.attribution);e.tileCredits.push(o)}return!0}async function nL(e,t){try{const n=await e.layerJsonResource.fetchJson();return b8e(e,n,t)}catch(n){return c(n)&&n.statusCode===404?(await fq(e,{tilejson:"2.1.0",format:"heightmap-1.0",version:"1.0.0",scheme:"tms",tiles:["{z}/{x}/{y}.terrain?v={version}"]},t),!0):y8e(e,n,t)}}function zc(e){e=y(e,y.EMPTY_OBJECT),this._heightmapWidth=void 0,this._heightmapStructure=void 0,this._hasWaterMask=!1,this._hasVertexNormals=!1,this._hasMetadata=!1,this._scheme=void 0,this._ellipsoid=e.ellipsoid,this._requestVertexNormals=y(e.requestVertexNormals,!1),this._requestWaterMask=y(e.requestWaterMask,!1),this._requestMetadata=y(e.requestMetadata,!0),this._errorEvent=new Le;let t=e.credit;typeof t=="string"&&(t=new Wt(t)),this._credit=t,this._availability=void 0,this._tilingScheme=void 0,this._levelZeroMaximumGeometricError=void 0,this._layers=void 0,this._tileCredits=void 0}const Kv={OCT_VERTEX_NORMALS:1,WATER_MASK:2,METADATA:4};function zz(e){return!c(e)||e.length===0?{Accept:"application/vnd.quantized-mesh,application/octet-stream;q=0.9,*/*;q=0.01"}:{Accept:`application/vnd.quantized-mesh;extensions=${e.join("-")},application/octet-stream;q=0.9,*/*;q=0.01`}}function T8e(e,t,n,i,o){const r=new Uint16Array(t,0,e._heightmapWidth*e._heightmapWidth);return new Cl({buffer:r,childTileMask:new Uint8Array(t,r.byteLength,1)[0],waterMask:new Uint8Array(t,r.byteLength+1,t.byteLength-r.byteLength-1),width:e._heightmapWidth,height:e._heightmapWidth,structure:e._heightmapStructure,credits:e._tileCredits})}function A8e(e,t,n,i,o,r){const s=r.littleEndianExtensionSize;let a=0;const l=3,u=l+1,h=Float64Array.BYTES_PER_ELEMENT*l,f=Float64Array.BYTES_PER_ELEMENT*u,_=3,g=Uint16Array.BYTES_PER_ELEMENT*_,m=3;let b=Uint16Array.BYTES_PER_ELEMENT,T=b*m;const x=new DataView(t),C=new d(x.getFloat64(a,!0),x.getFloat64(a+8,!0),x.getFloat64(a+16,!0));a+=h;const w=x.getFloat32(a,!0);a+=Float32Array.BYTES_PER_ELEMENT;const v=x.getFloat32(a,!0);a+=Float32Array.BYTES_PER_ELEMENT;const P=new se(new d(x.getFloat64(a,!0),x.getFloat64(a+8,!0),x.getFloat64(a+16,!0)),x.getFloat64(a+h,!0));a+=f;const N=new d(x.getFloat64(a,!0),x.getFloat64(a+8,!0),x.getFloat64(a+16,!0));a+=h;const k=x.getUint32(a,!0);a+=Uint32Array.BYTES_PER_ELEMENT;const M=new Uint16Array(t,a,k*3);a+=k*g,k>64*1024&&(b=Uint32Array.BYTES_PER_ELEMENT,T=b*m);const U=M.subarray(0,k),B=M.subarray(k,2*k),S=M.subarray(k*2,3*k);En.zigZagDeltaDecode(U,B,S),a%b!==0&&(a+=b-a%b);const D=x.getUint32(a,!0);a+=Uint32Array.BYTES_PER_ELEMENT;const p=je.createTypedArrayFromArrayBuffer(k,t,a,D*m);a+=D*T;let I=0;const O=p.length;for(let re=0;re<O;++re){const de=p[re];p[re]=I-de,de===0&&++I}const F=x.getUint32(a,!0);a+=Uint32Array.BYTES_PER_ELEMENT;const V=je.createTypedArrayFromArrayBuffer(k,t,a,F);a+=F*b;const G=x.getUint32(a,!0);a+=Uint32Array.BYTES_PER_ELEMENT;const j=je.createTypedArrayFromArrayBuffer(k,t,a,G);a+=G*b;const W=x.getUint32(a,!0);a+=Uint32Array.BYTES_PER_ELEMENT;const X=je.createTypedArrayFromArrayBuffer(k,t,a,W);a+=W*b;const q=x.getUint32(a,!0);a+=Uint32Array.BYTES_PER_ELEMENT;const ee=je.createTypedArrayFromArrayBuffer(k,t,a,q);a+=q*b;let Y,ne;for(;a<x.byteLength;){const re=x.getUint8(a,!0);a+=Uint8Array.BYTES_PER_ELEMENT;const de=x.getUint32(a,s);if(a+=Uint32Array.BYTES_PER_ELEMENT,re===Kv.OCT_VERTEX_NORMALS&&e._requestVertexNormals)Y=new Uint8Array(t,a,k*2);else if(re===Kv.WATER_MASK&&e._requestWaterMask)ne=new Uint8Array(t,a,de);else if(re===Kv.METADATA&&e._requestMetadata){const fe=x.getUint32(a,!0);if(fe>0){const Ce=sa(new Uint8Array(t),a+Uint32Array.BYTES_PER_ELEMENT,fe).available;if(c(Ce
vec4 clippingPlanesEdgeColor = vec4(1.0);
clippingPlanesEdgeColor.rgb = ${n}.rgb;
float clippingPlanesEdgeWidth = ${n}.a;
if (clipDistance > 0.0 && clipDistance < clippingPlanesEdgeWidth)
{
out_FragColor = clippingPlanesEdgeColor;
}
`}const O8e={modifyFragmentShader:function(t){return t=Oe.replaceMain(t,"czm_splitter_main"),t+=`uniform float czm_splitDirection;
void main()
{
#ifndef SHADOW_MAP
if (czm_splitDirection < 0.0 && gl_FragCoord.x > czm_splitPosition) discard;
if (czm_splitDirection > 0.0 && gl_FragCoord.x < czm_splitPosition) discard;
#endif
czm_splitter_main();
}
`,t},addUniforms:function(t,n){n.czm_splitDirection=function(){return t.splitDirection}}},_q=O8e,Gf={NEEDS_DECODE:0,DECODING:1,READY:2,FAILED:3};function gb(e){A.typeOf.object("options",e),A.typeOf.object("options.arrayBuffer",e.arrayBuffer),this._parsedContent=void 0,this._drawCommand=void 0,this._isTranslucent=!1,this._styleTranslucent=!1,this._constantColor=z.clone(z.DARKGRAY),this._highlightColor=z.clone(z.WHITE),this._pointSize=1,this._rtcCenter=void 0,this._quantizedVolumeScale=void 0,this._quantizedVolumeOffset=void 0,this._styleableShaderAttributes=void 0,this._isQuantized=!1,this._isOctEncoded16P=!1,this._isRGB565=!1,this._hasColors=!1,this._hasNormals=!1,this._hasBatchIds=!1,this._decodingState=Gf.READY,this._dequantizeInShader=!0,this._isQuantizedDraco=!1,this._isOctEncodedDraco=!1,this._quantizedRange=0,this._octEncodedRange=0,this.backFaceCulling=!1,this._backFaceCulling=!1,this.normalShading=!0,this._normalShading=!0,this._opaqueRenderState=void 0,this._translucentRenderState=void 0,this._mode=void 0,this._ready=!1,this._pointsLength=0,this._geometryByteLength=0,this._vertexShaderLoaded=e.vertexShaderLoaded,this._fragmentShaderLoaded=e.fragmentShaderLoaded,this._uniformMapLoaded=e.uniformMapLoaded,this._batchTableLoaded=e.batchTableLoaded,this._pickIdLoaded=e.pickIdLoaded,this._opaquePass=y(e.opaquePass,xe.OPAQUE),this._cull=y(e.cull,!0),this.style=void 0,this._style=void 0,this.styleDirty=!1,this.modelMatrix=L.clone(L.IDENTITY),this._modelMatrix=L.clone(L.IDENTITY),this.time=0,this.shadows=Vi.ENABLED,this._boundingSphere=void 0,this.clippingPlanes=void 0,this.isClipped=!1,this.clippingPlanesDirty=!1,this.clippingPlanesOriginMatrix=void 0,this.attenuation=!1,this._attenuation=!1,this.geometricError=0,this.geometricErrorScale=1,this.maximumAttenuation=this._pointSize,this.splitDirection=y(e.splitDirection,zp.NONE),this._splittingEnabled=!1,this._error=void 0,L8e(this,e)}Object.defineProperties(gb.prototype,{pointsLength:{get:function(){return this._pointsLength}},geometryByteLength:{get:function(){return this._geometryByteLength}},ready:{get:function(){return this._ready}},color:{get:function(){return z.clone(this._highlightColor)},set:function(e){this._highlightColor=z.clone(e,this._highlightColor)}},boundingSphere:{get:function(){if(c(this._drawCommand))return this._drawCommand.boundingVolume},set:function(e){this._boundingSphere=se.clone(e,this._boundingSphere)}}});function L8e(e,t){const n=U5.parse(t.arrayBuffer,t.byteOffset);if(e._parsedContent=n,e._rtcCenter=n.rtcCenter,e._hasNormals=n.hasNormals,e._hasColors=n.hasColors,e._hasBatchIds=n.hasBatchIds,e._isTranslucent=n.isTranslucent,!n.hasBatchIds&&c(n.batchTableBinary)&&(n.styleableProperties=Hn.getBinaryProperties(n.pointsLength,n.batchTableJson,n.batchTableBinary)),c(n.draco)){const a=n.draco;e._decodingState=Gf.NEEDS_DECODE,a.dequantizeInShader=e._dequantizeInShader}const i=n.positions;c(i)&&(e._isQuantized=i.isQuantized,e._quantizedVolumeScale=i.quantizedVolumeScale,e._quantizedVolumeOffset=i.quantizedVolumeOffset,e._quantizedRange=i.quantizedRange);const o=n.normals;c(o)&&(e._isOctEncoded16P=o.octEncoded);const r=n.colors;c(r)&&(c(r.constantColor)&&(e._constantColor=z.clone(r.constantColor,e._constantColor),e._hasColors=!1),e._isRGB565=r.isRGB565);const s=n.batchIds;c(n.batchIds)&&(s.name="BATCH_ID",s.semantic="BATCH_ID",s.setIndex=void 0),n.hasBatchIds&&e._batchTableLoaded(n.batchLength,n.batchTableJson,n.batchTableBinary),e._pointsLength=n.pointsLength}const R8e=new d,N8e=new d,M8e=new d;let Vz,EA;function F8e(e){if(!c(EA)){Vz=new fC(0),EA=new Array(e);for(let t=0;t<e;++t)EA[t]=Vz.random()}return EA}function B8e(e){const n=e.length/3,i=Math.min(n,20),o=F8e(20),r=Number.MAX_VALUE,s=-Number.MAX_VALUE,a=d.fromElements(r,r,r,R8e),l=d.fromElements(s,s,s,N8e);for(let h=0;h<i;++h){const f=Math.floor(o[h]*n),_=d.unpack(e,f*3,M8e);d.minimumByComponent(a,_,a),d.maximumByComponent(l,_,l)}const u=se.fromCornerPoints(a,l);return u.radius+=R.EPSILON2,u}function Hz(e,t){const n=Z.fromTypedArray(e);return n===Z.INT||n===Z.UNSIGNED_INT||n===Z.DOUBLE?($n("Cast p
`));const n=/czm_3dtiles_builtin_property_(\w+)/g;let i=n.exec(e);for(;i!==null;){const o=i[1];t.indexOf(o)===-1&&t.push(o),i=n.exec(e)}}function nI(e,t){const n=e.numberOfAttributes;for(let i=0;i<n;++i){const o=e.getAttribute(i);if(o.index===t)return o}}const W8e={POSITION:"czm_3dtiles_builtin_property_POSITION",POSITION_ABSOLUTE:"czm_3dtiles_builtin_property_POSITION_ABSOLUTE",COLOR:"czm_3dtiles_builtin_property_COLOR",NORMAL:"czm_3dtiles_builtin_property_NORMAL"};function q8e(e,t,n){let i,o,r;const s=t.context,a=c(n),l=e._isQuantized,u=e._isQuantizedDraco,h=e._isOctEncoded16P,f=e._isOctEncodedDraco,_=e._isRGB565,g=e._isTranslucent,m=e._hasColors,b=e._hasNormals,T=e._hasBatchIds,x=e._backFaceCulling,C=e._normalShading,w=e._drawCommand.vertexArray,v=e.clippingPlanes,P=e._attenuation;let N,k,M,U=g;const B=Je(W8e),S={},D=e._styleableShaderAttributes;for(o in D)D.hasOwnProperty(o)&&(r=D[o],B[o]=`czm_3dtiles_property_${r.location}`,S[r.location]=r);if(a){const re={translucent:!1},de="(vec3 czm_3dtiles_builtin_property_POSITION, vec3 czm_3dtiles_builtin_property_POSITION_ABSOLUTE, vec4 czm_3dtiles_builtin_property_COLOR, vec3 czm_3dtiles_builtin_property_NORMAL)";N=n.getColorShaderFunction(`getColorFromStyle${de}`,B,re),k=n.getShowShaderFunction(`getShowFromStyle${de}`,B,re),M=n.getPointSizeShaderFunction(`getPointSizeFromStyle${de}`,B,re),c(N)&&re.translucent&&(U=!0)}e._styleTranslucent=U;const p=c(N),I=c(k),O=c(M),F=e.isClipped,V=[],G=[];p&&(eI(N,V),tI(N,G)),I&&(eI(k,V),tI(k,G)),O&&(eI(M,V),tI(M,G));const j=G.indexOf("COLOR")>=0,W=G.indexOf("NORMAL")>=0;if(W&&!b)throw new Te("Style references the NORMAL semantic but the point cloud does not have normals");for(o in D)if(D.hasOwnProperty(o)){r=D[o];const re=V.indexOf(r.location)>=0,de=nI(w,r.location);de.enabled=re}const X=m&&(!p||j);if(m){const re=nI(w,dC);re.enabled=X}const q=b&&(C||x||W);if(b){const re=nI(w,uP);re.enabled=q}const ee={a_position:gq};X&&(ee.a_color=dC),q&&(ee.a_normal=uP),T&&(ee.a_batchId=yq);let Y="";const ne=V.length;for(i=0;i<ne;++i){const re=V[i];r=S[re];const de=r.componentCount,fe=`czm_3dtiles_property_${re}`;let ye;de===1?ye="float":ye=`vec${de}`,Y+=`in ${ye} ${fe};
`,ee[fe]=r.location}j8e(e,t);let Q=`in vec3 a_position;
out vec4 v_color;
uniform vec4 u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier;
uniform vec4 u_constantColor;
uniform vec4 u_highlightColor;
`;Q+=`float u_pointSize;
float tiles3d_tileset_time;
`,P&&(Q+=`float u_geometricError;
float u_depthMultiplier;
`),Q+=Y,X&&(g?Q+=`in vec4 a_color;
`:_?Q+=`in float a_color;
const float SHIFT_RIGHT_11 = 1.0 / 2048.0;
const float SHIFT_RIGHT_5 = 1.0 / 32.0;
const float SHIFT_LEFT_11 = 2048.0;
const float SHIFT_LEFT_5 = 32.0;
const float NORMALIZE_6 = 1.0 / 64.0;
const float NORMALIZE_5 = 1.0 / 32.0;
`:Q+=`in vec3 a_color;
`),q&&(h||f?Q+=`in vec2 a_normal;
`:Q+=`in vec3 a_normal;
`),T&&(Q+=`in float a_batchId;
`),(l||u||f)&&(Q+=`uniform vec4 u_quantizedVolumeScaleAndOctEncodedRange;
`),p&&(Q+=N),I&&(Q+=k),O&&(Q+=M),Q+=`void main()
{
u_pointSize = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.x;
tiles3d_tileset_time = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.y;
`,P&&(Q+=` u_geometricError = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.z;
u_depthMultiplier = u_pointSizeAndTimeAndGeometricErrorAndDepthMultiplier.w;
`),X?g?Q+=` vec4 color = a_color;
`:_?Q+=` float compressed = a_color;
float r = floor(compressed * SHIFT_RIGHT_11);
compressed -= r * SHIFT_LEFT_11;
float g = floor(compressed * SHIFT_RIGHT_5);
compressed -= g * SHIFT_LEFT_5;
float b = compressed;
vec3 rgb = vec3(r * NORMALIZE_5, g * NORMALIZE_6, b * NORMALIZE_5);
vec4 color = vec4(rgb, 1.0);
`:Q+=` vec4 color = vec4(a_color, 1.0);
`:Q+=` vec4 color = u_constantColor;
`,l||u?Q+=` vec3 position = a_position * u_quantizedVolumeScaleAndOctEncodedRange.xyz;
`:Q+=` vec3 position = a_position;
`,Q+=` vec3 position_absolute = vec3(czm_model * vec4(position, 1.0));
`,q?(h?Q+=` vec3 normal = czm_octDecode(a_normal);
`:f?Q+=` vec3 normal = czm_octDecode(a_normal, u_quantizedVolumeScaleAndOctEncodedRange.w).zxy;
`:Q+=` vec3 normal = a_normal;
`,Q+=` vec3 normalEC = czm_normal * normal;
`):Q+=` vec3 normal = vec3(1.0);
`,p&&(Q+=` color = getColorFromStyle(position, position_absolute, color, normal);
`),I&&(Q+=` float show = float(getShowFromStyle(position, position_absolute, color, normal));
`),O?Q+=` gl_PointSize = getPointSizeFromStyle(position, position_absolute, color, normal) * czm_pixelRatio;
`:P?Q+=` vec4 positionEC = czm_modelView * vec4(position, 1.0);
float depth = -positionEC.z;
gl_PointSize = min((u_geometricError / depth) * u_depthMultiplier, u_pointSize);
`:Q+=` gl_PointSize = u_pointSize;
`,Q+=` color = color * u_highlightColor;
`,q&&C&&(Q+=` float diffuseStrength = czm_getLambertDiffuse(czm_lightDirectionEC, normalEC);
diffuseStrength = max(diffuseStrength, 0.4);
color.xyz *= diffuseStrength * czm_lightColor;
`),Q+=` v_color = color;
gl_Position = czm_modelViewProjection * vec4(position, 1.0);
`,q&&x&&(Q+=` float visible = step(-normalEC.z, 0.0);
gl_Position *= visible;
gl_PointSize *= visible;
`),I&&(Q+=` gl_Position.w *= float(show);
gl_PointSize *= float(show);
`),Q+=`}
`;let le=`in vec4 v_color;
`;F&&(le+=`uniform highp sampler2D u_clippingPlanes;
uniform mat4 u_clippingPlanesMatrix;
uniform vec4 u_clippingPlanesEdgeStyle;
`,le+=`
`,le+=p1(v,s),le+=`
`),le+=`void main()
{
out_FragColor = czm_gammaCorrect(v_color);
`,F&&(le+=P8e("u_clippingPlanes","u_clippingPlanesMatrix","u_clippingPlanesEdgeStyle")),le+=`}
`,e.splitDirection!==zp.NONE&&(le=_q.modifyFragmentShader(le)),c(e._vertexShaderLoaded)&&(Q=e._vertexShaderLoaded(Q)),c(e._fragmentShaderLoaded)&&(le=e._fragmentShaderLoaded(le));const pe=e._drawCommand;c(pe.shaderProgram)&&pe.shaderProgram.destroy(),pe.shaderProgram=Jt.fromCache({context:s,vertexShaderSource:Q,fragmentShaderSource:le,attributeLocations:ee});try{pe.shaderProgram._bind()}catch{throw new Te("Error generating style shader: this may be caused by a type mismatch, index out-of-bounds, or other syntax error.")}}function Y8e(e,t){if(e._decodingState===Gf.READY)return!1;if(e._decodingState===Gf.NEEDS_DECODE){const n=e._parsedContent,i=n.draco,o=Fi.decodePointCloud(i,t);c(o)&&(e._decodingState=Gf.DECODING,o.then(function(r){e._decodingState=Gf.READY;const s=c(r.POSITION)?r.POSITION.array:void 0,a=c(r.RGB)?r.RGB.array:void 0,l=c(r.RGBA)?r.RGBA.array:void 0,u=c(r.NORMAL)?r.NORMAL.array:void 0,h=c(r.BATCH_ID)?r.BATCH_ID.array:void 0,f=c(s)&&c(r.POSITION.data.quantization),_=c(u)&&c(r.NORMAL.data.quantization);if(f){const T=r.POSITION.data.quantization,x=T.range;e._quantizedVolumeScale=d.fromElements(x,x,x),e._quantizedVolumeOffset=d.unpack(T.minValues),e._quantizedRange=(1<<T.quantizationBits)-1,e._isQuantizedDraco=!0}_&&(e._octEncodedRange=(1<<r.NORMAL.data.quantization.quantizationBits)-1,e._isOctEncodedDraco=!0);let g=n.styleableProperties;const m=i.batchTableProperties;for(const T in m)if(m.hasOwnProperty(T)){const x=r[T];c(g)||(g={}),g[T]={typedArray:x.array,componentCount:x.data.componentsPerAttribute}}c(s)&&(n.positions={typedArray:s});const b=y(l,a);c(b)&&(n.colors={typedArray:b}),c(u)&&(n.normals={typedArray:u}),c(h)&&(n.batchIds={typedArray:h}),n.styleableProperties=g}).catch(function(r){e._decodingState=Gf.FAILED,e._error=r}))}return!0}const $8e=new te,X8e=new d;gb.prototype.update=function(e){const t=e.context;if(c(this._error)){const u=this._error;throw this._error=void 0,u}if(Y8e(this,t))return;let i=!1,o=!L.equals(this._modelMatrix,this.modelMatrix);if(this._mode!==e.mode&&(this._mode=e.mode,o=!0),c(this._drawCommand)||(G8e(this,e),o=!0,i=!0,this._ready=!0,this._parsedContent=void 0),o){L.clone(this.modelMatrix,this._modelMatrix);const u=this._drawCommand.modelMatrix;if(L.clone(this._modelMatrix,u),c(this._rtcCenter)&&L.multiplyByTranslation(u,this._rtcCenter,u),c(this._quantizedVolumeOffset)&&L.multiplyByTranslation(u,this._quantizedVolumeOffset,u),e.mode!==oe.SCENE3D){const f=e.mapProjection,_=L.getColumn(u,3,$8e);te.equals(_,te.UNIT_W)||zt.basisTo2D(f,u,u)}const h=this._drawCommand.boundingVolume;if(se.clone(this._boundingSphere,h),this._cull){const f=h.center;L.multiplyByPoint(u,f,f);const _=L.getScale(u,X8e);h.radius*=d.maximumComponent(_)}}this.clippingPlanesDirty&&(this.clippingPlanesDirty=!1,i=!0),this._attenuation!==this.attenuation&&(this._attenuation=this.attenuation,i=!0),this.backFaceCulling!==this._backFaceCulling&&(this._backFaceCulling=this.backFaceCulling,i=!0),this.normalShading!==this._normalShading&&(this._normalShading=this.normalShading,i=!0),(this._style!==this.style||this.styleDirty)&&(this._style=this.style,this.styleDirty=!1,i=!0);const r=this.splitDirection!==zp.NONE;this._splittingEnabled!==r&&(this._splittingEnabled=r,i=!0),i&&q8e(this,e,this._style),this._drawCommand.castShadows=Vi.castShadows(this.shadows),this._drawCommand.receiveShadows=Vi.receiveShadows(this.shadows);const s=this._highlightColor.alpha<1||this._constantColor.alpha<1||this._styleTranslucent;this._drawCommand.renderState=s?this._translucentRenderState:this._opaqueRenderState,this._drawCommand.pass=s?xe.TRANSLUCENT:this._opaquePass;const a=e.commandList,l=e.passes;(l.render||l.pick)&&a.push(this._drawCommand)};gb.prototype.isDestroyed=function(){return!1};gb.prototype.destroy=function(){const e=this._drawCommand;return c(e)&&(e.vertexArray=e.vertexArray&&e.vertexArray.destroy(),e.shaderProgram=e.shaderProgram&&e.shaderProgram.destroy()),ve(this)};function U_(e){A.typeOf.object("terrainProviderPromise",e),this._ready=!1,this._provider=void 0,this._errorEvent=new Le,this._readyEvent=new Le,K8e(this,e)}Objec
${e}`}function J8e(e){return function(t){return jt(t,{czm_pickColor:function(){return e._pickId.color}})}}function eGe(){return"czm_pickColor"}af.prototype.makeStyleDirty=function(){this._styleDirty=!0};af.prototype._getAverageLoadTime=function(){return this._runningLength===0?.05:this._runningAverage};const tGe=new ie;function cL(e){const t=e._clock,n=t.canAnimate&&t.shouldAnimate,i=t.multiplier;return n?i:0}function vp(e,t){return e._intervals.indexOf(t.start)}function nGe(e,t){const n=e._intervals,i=e._clock,o=cL(e);if(o===0)return;const r=e._getAverageLoadTime(),s=ie.addSeconds(i.currentTime,r*o,tGe);let a=n.indexOf(s);const l=vp(e,t);return a===l&&(o>=0?++a:--a),n.get(a)}function iGe(e){const t=e._intervals,i=e._clock.currentTime,o=t.indexOf(i);return t.get(o)}function oGe(e,t,n){const i=cL(e),o=vp(e,t),r=vp(e,n);return i>=0?o>=r:o<=r}function bq(e,t){return function(n){const i=c(n.message)?n.message:n.toString();e.frameFailed.numberOfListeners>0?e.frameFailed.raiseEvent({uri:t,message:i}):(console.log(`A frame failed to load: ${t}`),console.log(`Error: ${i}`))}}function rGe(e,t,n){const i=vp(e,t),o=e._frames;let r=o[i];if(!c(r)){const s=t.data.transform,a=c(s)?L.fromArray(s):void 0,l=t.data.uri;r={pointCloud:void 0,transform:a,timestamp:xo(),sequential:!0,ready:!1,touchedFrameNumber:n.frameNumber,uri:l},o[i]=r,Ae.fetchArrayBuffer({url:l}).then(function(u){r.pointCloud=new gb({arrayBuffer:u,cull:!0,fragmentShaderLoaded:Z8e,uniformMapLoaded:J8e(e),pickIdLoaded:eGe})}).catch(bq(e,l))}return r}function sGe(e,t){e._runningSum+=t,e._runningSum-=e._runningSamples[e._runningIndex],e._runningSamples[e._runningIndex]=t,e._runningLength=Math.min(e._runningLength+1,e._runningSamples.length),e._runningIndex=(e._runningIndex+1)%e._runningSamples.length,e._runningAverage=e._runningSum/e._runningLength}function aGe(e,t,n,i){t.touchedFrameNumber<i.frameNumber-1&&(t.sequential=!1);const o=t.pointCloud;if(c(o)&&!t.ready){const r=i.commandList,s=r.length;if(Tq(e,t,n,i),o.ready&&(t.ready=!0,e._totalMemoryUsageInBytes+=o.geometryByteLength,r.length=s,t.sequential)){const a=(xo()-t.timestamp)/1e3;sGe(e,a)}}t.touchedFrameNumber=i.frameNumber}const cGe=new L;function lGe(e,t){const n=e.shading;return c(n)&&c(n.baseResolution)?n.baseResolution:c(t.boundingSphere)?R.cbrt(t.boundingSphere.volume()/t.pointsLength):0}function uGe(e){const t=e.shading;return c(t)&&c(t.maximumAttenuation)?t.maximumAttenuation:10}const dGe=new q0;function Tq(e,t,n,i){const o=y(e.shading,dGe),r=t.pointCloud,s=y(t.transform,L.IDENTITY);r.modelMatrix=L.multiplyTransformation(e.modelMatrix,s,cGe),r.style=e.style,r.time=n.timeSinceLoad,r.shadows=e.shadows,r.clippingPlanes=e._clippingPlanes,r.isClipped=n.isClipped,r.attenuation=o.attenuation,r.backFaceCulling=o.backFaceCulling,r.normalShading=o.normalShading,r.geometricError=lGe(e,r),r.geometricErrorScale=o.geometricErrorScale,r.maximumAttenuation=uGe(e);try{r.update(i)}catch(a){bq(e,t.uri)(a)}t.touchedFrameNumber=i.frameNumber}function dP(e,t,n,i){const o=rGe(e,t,i);aGe(e,o,n,i)}function hGe(e){return function(t){return t.touchedFrameNumber<e.frameNumber}}function Aq(e,t){const n=e._frames,i=n.length;for(let o=0;o<i;++o){const r=n[o];if(c(r)&&(!c(t)||t(r))){const s=r.pointCloud;r.ready&&(e._totalMemoryUsageInBytes-=s.geometryByteLength),c(s)&&s.destroy(),r===e._lastRenderedFrame&&(e._lastRenderedFrame=void 0),n[o]=void 0}}}function fGe(e,t){const n=vp(e,t),i=e._frames[n];if(c(i)&&i.ready)return i}function Gz(e,t,n,i,o){return c(n)?n.ready?!0:(dP(e,t,i,o),n.ready):!1}function pGe(e,t,n,i,o){let r,s,a;const l=e._intervals,u=e._frames,h=vp(e,n),f=vp(e,t);if(h>=f){for(r=h;r>=f;--r)if(s=l.get(r),a=u[r],Gz(e,s,a,i,o))return s}else for(r=h;r<=f;++r)if(s=l.get(r),a=u[r],Gz(e,s,a,i,o))return s;return t}function mGe(e,t,n){const i=e._frames,o=i.length;for(let r=0;r<o;++r){const s=i[r];c(s)&&c(s.pointCloud)&&(s.pointCloud.clippingPlanesDirty=t,s.pointCloud.styleDirty=n)}}const Rm={timeSinceLoad:0,isClipped:!1,clippingPlanesDirty:!1};af.prototype.update=function(e){if(e.mode===oe.MORPHING||!this.show)return;c(this._pickId)||(this
* Knockout JavaScript library v3.5.1
* (c) The Knockout.js team - http://knockoutjs.com/
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/(function(){(function(e){var t=this||(0,eval)("this"),n=t.document,i=t.navigator,o=t.jQuery,r=t.JSON;o||typeof jQuery>"u"||(o=jQuery),function(s){s(t.ko={})}(function(s,a){function l(S,D){return S===null||typeof S in b?S===D:!1}function u(S,D){var p;return function(){p||(p=m.a.setTimeout(function(){p=e,S()},D))}}function h(S,D){var p;return function(){clearTimeout(p),p=m.a.setTimeout(S,D)}}function f(S,D){D&&D!=="change"?D==="beforeChange"?this.pc(S):this.gb(S,D):this.qc(S)}function _(S,D){D!==null&&D.s&&D.s()}function g(S,D){var p=this.qd,I=p[v];I.ra||(this.Qb&&this.mb[D]?(p.uc(D,S,this.mb[D]),this.mb[D]=null,--this.Qb):I.I[D]||p.uc(D,S,I.J?{da:S}:p.$c(S)),S.Ja&&S.gd())}var m=typeof s<"u"?s:{};m.b=function(S,D){for(var p=S.split("."),I=m,O=0;O<p.length-1;O++)I=I[p[O]];I[p[p.length-1]]=D},m.L=function(S,D,p){S[D]=p},m.version="3.5.1",m.b("version",m.version),m.options={deferUpdates:!1,useOnlyNativeEvents:!1,foreachHidesDestroyed:!1},m.a=function(){function S(Y,ne){for(var Q in Y)O.call(Y,Q)&&ne(Q,Y[Q])}function D(Y,ne){if(ne)for(var Q in ne)O.call(ne,Q)&&(Y[Q]=ne[Q]);return Y}function p(Y,ne){return Y.__proto__=ne,Y}function I(Y,ne,Q,le){var pe=Y[ne].match(q)||[];m.a.D(Q.match(q),function(re){m.a.Na(pe,re,le)}),Y[ne]=pe.join(" ")}var O=Object.prototype.hasOwnProperty,F={__proto__:[]}instanceof Array,V=typeof Symbol=="function",G={},j={};G[i&&/Firefox\/2/i.test(i.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"],G.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" "),S(G,function(Y,ne){if(ne.length)for(var Q=0,le=ne.length;Q<le;Q++)j[ne[Q]]=Y});var W={propertychange:!0},X=n&&function(){for(var Y=3,ne=n.createElement("div"),Q=ne.getElementsByTagName("i");ne.innerHTML="<!--[if gt IE "+ ++Y+"]><i></i><![endif]-->",Q[0];);return 4<Y?Y:e}(),q=/\S+/g,ee;return{Jc:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],D:function(Y,ne,Q){for(var le=0,pe=Y.length;le<pe;le++)ne.call(Q,Y[le],le,Y)},A:typeof Array.prototype.indexOf=="function"?function(Y,ne){return Array.prototype.indexOf.call(Y,ne)}:function(Y,ne){for(var Q=0,le=Y.length;Q<le;Q++)if(Y[Q]===ne)return Q;return-1},Lb:function(Y,ne,Q){for(var le=0,pe=Y.length;le<pe;le++)if(ne.call(Q,Y[le],le,Y))return Y[le];return e},Pa:function(Y,ne){var Q=m.a.A(Y,ne);0<Q?Y.splice(Q,1):Q===0&&Y.shift()},wc:function(Y){var ne=[];return Y&&m.a.D(Y,function(Q){0>m.a.A(ne,Q)&&ne.push(Q)}),ne},Mb:function(Y,ne,Q){var le=[];if(Y)for(var pe=0,re=Y.length;pe<re;pe++)le.push(ne.call(Q,Y[pe],pe));return le},jb:function(Y,ne,Q){var le=[];if(Y)for(var pe=0,re=Y.length;pe<re;pe++)ne.call(Q,Y[pe],pe)&&le.push(Y[pe]);return le},Nb:function(Y,ne){if(ne instanceof Array)Y.push.apply(Y,ne);else for(var Q=0,le=ne.length;Q<le;Q++)Y.push(ne[Q]);return Y},Na:function(Y,ne,Q){var le=m.a.A(m.a.bc(Y),ne);0>le?Q&&Y.push(ne):Q||Y.splice(le,1)},Ba:F,extend:D,setPrototypeOf:p,Ab:F?p:D,P:S,Ga:function(Y,ne,Q){if(!Y)return Y;var le={},pe;for(pe in Y)O.call(Y,pe)&&(le[pe]=ne.call(Q,Y[pe],pe,Y));return le},Tb:function(Y){for(;Y.firstChild;)m.removeNode(Y.firstChild)},Yb:function(Y){Y=m.a.la(Y);for(var ne=(Y[0]&&Y[0].ownerDocument||n).createElement("div"),Q=0,le=Y.length;Q<le;Q++)ne.appendChild(m.oa(Y[Q]));return ne},Ca:function(Y,ne){for(var Q=0,le=Y.length,pe=[];Q<le;Q++){var re=Y[Q].cloneNode(!0);pe.push(ne?m.oa(re):re)}return pe},va:function(Y,ne){if(m.a.Tb(Y),ne)for(var Q=0,le=ne.length;Q<le;Q++)Y.appendChild(ne[Q])},Xc:function(Y,ne){var Q=Y.nodeType?[Y]:Y;if(0<Q.length){for(var le=Q[0],pe=le.parentNode,re=0,de=ne.length;re<de;re++)pe.insertBefore(ne[re],le);for(re=0,de=Q.length;re<de;re++)m.removeNode(Q[re])}},Ua:function(Y,ne){if(Y.length){for(ne=ne.nodeType===8&&ne.parentNode||ne;Y.length&&Y[0].parentNode!==ne;)Y.splice(0,1);for(;1<Y.length&&Y[Y.length-1].parentNode!==ne;)Y.length--;if(1<Y.length){var Q=Y[0],le=Y[Y.length-1];for(Y.length=0;Q!==le;)Y.push(Q),Q=Q.nextSibling;Y.push(le)}}return Y},Zc:function(Y,ne){7>X?Y.setAttribute("selected",ne):Y.selected=ne},Db:function(Y){return Y===null||Y===e?"":Y.trim?Y.trim():Y.toString(
,`;var j=[],W=G.match(I),X,q=[],ee=0;if(1<W.length){for(var Y=0,ne;ne=W[Y];++Y){var Q=ne.charCodeAt(0);if(Q===44){if(0>=ee){j.push(X&&q.length?{key:X,value:q.join("")}:{unknown:X||q.join("")}),X=ee=0,q=[];continue}}else if(Q===58){if(!ee&&!X&&q.length===1){X=q.pop();continue}}else{if(Q===47&&1<ne.length&&(ne.charCodeAt(1)===47||ne.charCodeAt(1)===42))continue;Q===47&&Y&&1<ne.length?(Q=W[Y-1].match(O))&&!F[Q[0]]&&(G=G.substr(G.indexOf(ne)+1),W=G.match(I),Y=-1,ne="/"):Q===40||Q===123||Q===91?++ee:Q===41||Q===125||Q===93?--ee:X||q.length||Q!==34&&Q!==39||(ne=ne.slice(1,-1))}q.push(ne)}if(0<ee)throw Error("Unbalanced parentheses, braces, or brackets")}return j}var D=["true","false","null","undefined"],p=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i,I=RegExp(`"(?:\\\\.|[^"])*"|'(?:\\\\.|[^'])*'|\`(?:\\\\.|[^\`])*\`|/\\*(?:[^*]|\\*+[^*/])*\\*+/|//.*
|/(?:\\\\.|[^/])+/w*|[^\\s:,/][^,"'\`{}()/:[\\]]*[^\\s,"'\`{}()/:[\\]]|[^\\s]`,"g"),O=/[\])"'A-Za-z0-9_$]+$/,F={in:1,return:1,typeof:1},V={};return{Ra:[],wa:V,ac:S,vb:function(G,j){function W(Q,le){var pe;if(!Y){var re=m.getBindingHandler(Q);if(re&&re.preprocess&&!(le=re.preprocess(le,Q,W)))return;(re=V[Q])&&(pe=le,0<=m.a.A(D,pe)?pe=!1:(re=pe.match(p),pe=re===null?!1:re[1]?"Object("+re[1]+")"+re[2]:pe),re=pe),re&&q.push("'"+(typeof V[Q]=="string"?V[Q]:Q)+"':function(_z){"+pe+"=_z}")}ee&&(le="function(){return "+le+" }"),X.push("'"+Q+"':"+le)}j=j||{};var X=[],q=[],ee=j.valueAccessors,Y=j.bindingParams,ne=typeof G=="string"?S(G):G;return m.a.D(ne,function(Q){W(Q.key||Q.unknown,Q.value)}),q.length&&W("_ko_property_writers","{"+q.join(",")+" }"),X.join(",")},Id:function(G,j){for(var W=0;W<G.length;W++)if(G[W].key==j)return!0;return!1},eb:function(G,j,W,X,q){G&&m.O(G)?!m.Za(G)||q&&G.v()===X||G(X):(G=j.get("_ko_property_writers"))&&G[W]&&G[W](X)}}}(),m.b("expressionRewriting",m.m),m.b("expressionRewriting.bindingRewriteValidators",m.m.Ra),m.b("expressionRewriting.parseObjectLiteral",m.m.ac),m.b("expressionRewriting.preProcessBindings",m.m.vb),m.b("expressionRewriting._twoWayBindings",m.m.wa),m.b("jsonExpressionRewriting",m.m),m.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",m.m.vb),function(){function S(W){return W.nodeType==8&&F.test(O?W.text:W.nodeValue)}function D(W){return W.nodeType==8&&V.test(O?W.text:W.nodeValue)}function p(W,X){for(var q=W,ee=1,Y=[];q=q.nextSibling;){if(D(q)&&(m.a.g.set(q,j,!0),ee--,ee===0))return Y;Y.push(q),S(q)&&ee++}if(!X)throw Error("Cannot find closing comment tag to match: "+W.nodeValue);return null}function I(W,X){var q=p(W,X);return q?0<q.length?q[q.length-1].nextSibling:W.nextSibling:null}var O=n&&n.createComment("test").text==="<!--test-->",F=O?/^\x3c!--\s*ko(?:\s+([\s\S]+))?\s*--\x3e$/:/^\s*ko(?:\s+([\s\S]+))?\s*$/,V=O?/^\x3c!--\s*\/ko\s*--\x3e$/:/^\s*\/ko\s*$/,G={ul:!0,ol:!0},j="__ko_matchedEndComment__";m.h={ea:{},childNodes:function(W){return S(W)?p(W):W.childNodes},Ea:function(W){if(S(W)){W=m.h.childNodes(W);for(var X=0,q=W.length;X<q;X++)m.removeNode(W[X])}else m.a.Tb(W)},va:function(W,X){if(S(W)){m.h.Ea(W);for(var q=W.nextSibling,ee=0,Y=X.length;ee<Y;ee++)q.parentNode.insertBefore(X[ee],q)}else m.a.va(W,X)},Vc:function(W,X){var q;S(W)?(q=W.nextSibling,W=W.parentNode):q=W.firstChild,q?X!==q&&W.insertBefore(X,q):W.appendChild(X)},Wb:function(W,X,q){q?(q=q.nextSibling,S(W)&&(W=W.parentNode),q?X!==q&&W.insertBefore(X,q):W.appendChild(X)):m.h.Vc(W,X)},firstChild:function(W){if(S(W))return!W.nextSibling||D(W.nextSibling)?null:W.nextSibling;if(W.firstChild&&D(W.firstChild))throw Error("Found invalid end comment, as the first child of "+W);return W.firstChild},nextSibling:function(W){if(S(W)&&(W=I(W)),W.nextSibling&&D(W.nextSibling)){var X=W.nextSibling;if(D(X)&&!m.a.g.get(X,j))throw Error("Found end comment without a matching opening comment, as child of "+W);return null}return W.nextSibling},Cd:S,Vd:function(W){return(W=(O?W.text:W.nodeValue).match(F))?W[1]:null},Sc:function(W){if(G[m.a.R(W)]){var X=W.firstChild;if(X)do if(X.nodeType===1){var q;q=X.firstChild;var ee=null;if(q)do if(ee)ee.push(q);else if(S(q)){var Y=I(q,!0);Y?q=Y:ee=[q]}else D(q)&&(ee=[q]);while(q=q.nextSibling);if(q=ee)for(ee=X.nextSibling,Y=0;Y<q.length;Y++)ee?W.insertBefore(q[Y],ee):W.appendChild(q[Y])}while(X=X.nextSibling)}}}}(),m.b("virtualElements",m.h),m.b("virtualElements.allowedBindings",m.h.ea),m.b("virtualElements.emptyNode",m.h.Ea),m.b("virtualElements.insertAfter",m.h.Wb),m.b("virtualElements.prepend",m.h.Vc),m.b("virtualElements.setDomNodeChildren",m.h.va),function(){m.ga=function(){this.nd={}},m.a.extend(m.ga.prototype,{nodeHasBindings:function(S){switch(S.nodeType){case 1:return S.getAttribute("data-bind")!=null||m.j.getComponentNameForNode(S);case 8:return m.h.Cd(S);default:return!1}},getBindings:function(S,D){var p=this.getBindingsString(S,D),p=p?this.parseBindingsString(p,D,S):null;return m.j.tc(p,S,D,!1)},getBindingAccessors:function(S,D){var p=this.getBindingsString(S,D),p=p?this.parseBind
Bindings value: `+S+`
Message: `+W.message,W}}}),m.ga.instance=new m.ga}(),m.b("bindingProvider",m.ga),function(){function S(re){var de=(re=m.a.g.get(re,pe))&&re.N;de&&(re.N=null,de.Tc())}function D(re,de,fe){this.node=re,this.yc=de,this.kb=[],this.H=!1,de.N||m.a.K.za(re,S),fe&&fe.N&&(fe.N.kb.push(re),this.Kb=fe)}function p(re){return function(){return re}}function I(re){return re()}function O(re){return m.a.Ga(m.u.G(re),function(de,fe){return function(){return re()[fe]}})}function F(re,de,fe){return typeof re=="function"?O(re.bind(null,de,fe)):m.a.Ga(re,p)}function V(re,de){return O(this.getBindings.bind(this,re,de))}function G(re,de){var fe=m.h.firstChild(de);if(fe){var ye,Ce=m.ga.instance,we=Ce.preprocessNode;if(we){for(;ye=fe;)fe=m.h.nextSibling(ye),we.call(Ce,ye);fe=m.h.firstChild(de)}for(;ye=fe;)fe=m.h.nextSibling(ye),j(re,ye)}m.i.ma(de,m.i.H)}function j(re,de){var fe=re,ye=de.nodeType===1;ye&&m.h.Sc(de),(ye||m.ga.instance.nodeHasBindings(de))&&(fe=X(de,null,re).bindingContextForDescendants),fe&&!Q[m.a.R(de)]&&G(fe,de)}function W(re){var de=[],fe={},ye=[];return m.a.P(re,function Ce(we){if(!fe[we]){var Pe=m.getBindingHandler(we);Pe&&(Pe.after&&(ye.push(we),m.a.D(Pe.after,function(lt){if(re[lt]){if(m.a.A(ye,lt)!==-1)throw Error("Cannot combine the following bindings, because they have a cyclic dependency: "+ye.join(", "));Ce(lt)}}),ye.length--),de.push({key:we,Mc:Pe})),fe[we]=!0}}),de}function X(re,de,fe){var ye=m.a.g.Ub(re,pe,{}),Ce=ye.hd;if(!de){if(Ce)throw Error("You cannot apply bindings multiple times to the same element.");ye.hd=!0}Ce||(ye.context=fe),ye.Zb||(ye.Zb={});var we;if(de&&typeof de!="function")we=de;else{var Pe=m.ga.instance,lt=Pe.getBindingAccessors||V,ft=m.$(function(){return(we=de?de(fe,re):lt.call(Pe,re,fe))&&(fe[ee]&&fe[ee](),fe[ne]&&fe[ne]()),we},null,{l:re});we&&ft.ja()||(ft=null)}var We=fe,Fe;if(we){var Dt=function(){return m.a.Ga(ft?ft():we,I)},st=ft?function(et){return function(){return I(ft()[et])}}:function(et){return we[et]};Dt.get=function(et){return we[et]&&I(st(et))},Dt.has=function(et){return et in we},m.i.H in we&&m.i.subscribe(re,m.i.H,function(){var et=(0,we[m.i.H])();if(et){var hn=m.h.childNodes(re);hn.length&&et(hn,m.Ec(hn[0]))}}),m.i.pa in we&&(We=m.i.Cb(re,fe),m.i.subscribe(re,m.i.pa,function(){var et=(0,we[m.i.pa])();et&&m.h.firstChild(re)&&et(re)})),ye=W(we),m.a.D(ye,function(et){var hn=et.Mc.init,ot=et.Mc.update,at=et.key;if(re.nodeType===8&&!m.h.ea[at])throw Error("The binding '"+at+"' cannot be used with virtual elements");try{typeof hn=="function"&&m.u.G(function(){var Xt=hn(re,st(at),Dt,We.$data,We);if(Xt&&Xt.controlsDescendantBindings){if(Fe!==e)throw Error("Multiple bindings ("+Fe+" and "+at+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");Fe=at}}),typeof ot=="function"&&m.$(function(){ot(re,st(at),Dt,We.$data,We)},null,{l:re})}catch(Xt){throw Xt.message='Unable to process binding "'+at+": "+we[at]+`"
Message: `+Xt.message,Xt}})}return ye=Fe===e,{shouldBindDescendants:ye,bindingContextForDescendants:ye&&We}}function q(re,de){return re&&re instanceof m.fa?re:new m.fa(re,e,e,de)}var ee=m.a.Da("_subscribable"),Y=m.a.Da("_ancestorBindingInfo"),ne=m.a.Da("_dataDependency");m.c={};var Q={script:!0,textarea:!0,template:!0};m.getBindingHandler=function(re){return m.c[re]};var le={};m.fa=function(re,de,fe,ye,Ce){function we(){var st=We?ft():ft,et=m.a.f(st);return de?(m.a.extend(Pe,de),Y in de&&(Pe[Y]=de[Y])):(Pe.$parents=[],Pe.$root=et,Pe.ko=m),Pe[ee]=Fe,lt?et=Pe.$data:(Pe.$rawData=st,Pe.$data=et),fe&&(Pe[fe]=et),ye&&ye(Pe,de,et),de&&de[ee]&&!m.S.o().Vb(de[ee])&&de[ee](),Dt&&(Pe[ne]=Dt),Pe.$data}var Pe=this,lt=re===le,ft=lt?e:re,We=typeof ft=="function"&&!m.O(ft),Fe,Dt=Ce&&Ce.dataDependency;Ce&&Ce.exportDependencies?we():(Fe=m.xb(we),Fe.v(),Fe.ja()?Fe.equalityComparer=null:Pe[ee]=e)},m.fa.prototype.createChildContext=function(re,de,fe,ye){if(!ye&&de&&typeof de=="object"&&(ye=de,de=ye.as,fe=ye.extend),de&&ye&&ye.noChildContext){var Ce=typeof re=="function"&&!m.O(re);return new m.fa(le,this,null,function(we){fe&&fe(we),we[de]=Ce?re():re},ye)}return new m.fa(re,this,de,function(we,Pe){we.$parentContext=Pe,we.$parent=Pe.$data,we.$parents=(Pe.$parents||[]).slice(0),we.$parents.unshift(we.$parent),fe&&fe(we)},ye)},m.fa.prototype.extend=function(re,de){return new m.fa(le,this,null,function(fe){m.a.extend(fe,typeof re=="function"?re(fe):re)},de)};var pe=m.a.g.Z();D.prototype.Tc=function(){this.Kb&&this.Kb.N&&this.Kb.N.sd(this.node)},D.prototype.sd=function(re){m.a.Pa(this.kb,re),!this.kb.length&&this.H&&this.Cc()},D.prototype.Cc=function(){this.H=!0,this.yc.N&&!this.kb.length&&(this.yc.N=null,m.a.K.yb(this.node,S),m.i.ma(this.node,m.i.pa),this.Tc())},m.i={H:"childrenComplete",pa:"descendantsComplete",subscribe:function(re,de,fe,ye,Ce){var we=m.a.g.Ub(re,pe,{});return we.Fa||(we.Fa=new m.T),Ce&&Ce.notifyImmediately&&we.Zb[de]&&m.u.G(fe,ye,[re]),we.Fa.subscribe(fe,ye,de)},ma:function(re,de){var fe=m.a.g.get(re,pe);if(fe&&(fe.Zb[de]=!0,fe.Fa&&fe.Fa.notifySubscribers(re,de),de==m.i.H)){if(fe.N)fe.N.Cc();else if(fe.N===e&&fe.Fa&&fe.Fa.Wa(m.i.pa))throw Error("descendantsComplete event not supported for bindings on this node")}},Cb:function(re,de){var fe=m.a.g.Ub(re,pe,{});return fe.N||(fe.N=new D(re,fe,de[Y])),de[Y]==fe?de:de.extend(function(ye){ye[Y]=fe})}},m.Td=function(re){return(re=m.a.g.get(re,pe))&&re.context},m.ib=function(re,de,fe){return re.nodeType===1&&m.h.Sc(re),X(re,de,q(fe))},m.ld=function(re,de,fe){return fe=q(fe),m.ib(re,F(de,fe,re),fe)},m.Oa=function(re,de){de.nodeType!==1&&de.nodeType!==8||G(q(re),de)},m.vc=function(re,de,fe){if(!o&&t.jQuery&&(o=t.jQuery),2>arguments.length){if(de=n.body,!de)throw Error("ko.applyBindings: could not find document.body; has the document been loaded?")}else if(!de||de.nodeType!==1&&de.nodeType!==8)throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");j(q(re,fe),de)},m.Dc=function(re){return!re||re.nodeType!==1&&re.nodeType!==8?e:m.Td(re)},m.Ec=function(re){return(re=m.Dc(re))?re.$data:e},m.b("bindingHandlers",m.c),m.b("bindingEvent",m.i),m.b("bindingEvent.subscribe",m.i.subscribe),m.b("bindingEvent.startPossiblyAsyncContentBinding",m.i.Cb),m.b("applyBindings",m.vc),m.b("applyBindingsToDescendants",m.Oa),m.b("applyBindingAccessorsToNode",m.ib),m.b("applyBindingsToNode",m.ld),m.b("contextFor",m.Dc),m.b("dataFor",m.Ec)}(),function(S){function D(V,G){var j=Object.prototype.hasOwnProperty.call(O,V)?O[V]:S,W;j?j.subscribe(G):(j=O[V]=new m.T,j.subscribe(G),p(V,function(X,q){var ee=!(!q||!q.synchronous);F[V]={definition:X,Gd:ee},delete O[V],W||ee?j.notifySubscribers(X):m.na.zb(function(){j.notifySubscribers(X)})}),W=!0)}function p(V,G){I("getConfig",[V],function(j){j?I("loadComponent",[V,j],function(W){G(W,j)}):G(null,null)})}function I(V,G,j,W){W||(W=m.j.loaders.slice(0));var X=W.shift();if(X){var q=X[V];if(q){var ee=!1;if(q.apply(X,G.concat(function(Y){ee?j(null):Y!==null?j(Y):I(V,G,j,W)}))!==S&&(ee=!0,!X.suppressLoaderExceptions))throw E
* @license
* Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5
* Copyright (c) Steve Sanderson
* MIT license
*/var hP="__knockoutObservables",fP="__knockoutSubscribable";function xq(e,t){if(!e)throw new Error("When calling ko.track, you must pass an object as the first parameter.");var n=this,i=Cq(e,!0);return t=t||Object.getOwnPropertyNames(e),t.forEach(function(o){if(!(o===hP||o===fP)&&!(o in i)){var r=e[o],s=r instanceof Array,a=n.isObservable(r)?r:s?n.observableArray(r):n.observable(r);Object.defineProperty(e,o,{configurable:!0,enumerable:!0,get:a,set:n.isWriteableObservable(a)?a:void 0}),i[o]=a,s&&yGe(n,a)}}),e}function Cq(e,t){var n=e[hP];return!n&&t&&(n={},Object.defineProperty(e,hP,{value:n})),n}function gGe(e,t,n){var i=this,o={owner:e,deferEvaluation:!0};if(typeof n=="function")o.read=n;else{if("value"in n)throw new Error('For ko.defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');if(typeof n.get!="function")throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');o.read=n.get,o.write=n.set}return e[t]=i.computed(o),xq.call(i,e,[t]),e}function yGe(e,t){var n=null;e.computed(function(){n&&(n.dispose(),n=null);var i=t();i instanceof Array&&(n=bGe(e,t,i))})}function bGe(e,t,n){var i=TGe(e,n);return i.subscribe(t)}function TGe(e,t){var n=t[fP];if(!n){n=new e.subscribable,Object.defineProperty(t,fP,{value:n});var i={};AGe(t,n,i),xGe(e,t,n,i)}return n}function AGe(e,t,n){["pop","push","reverse","shift","sort","splice","unshift"].forEach(function(i){var o=e[i];e[i]=function(){var r=o.apply(this,arguments);return n.pause!==!0&&t.notifySubscribers(this),r}})}function xGe(e,t,n,i){["remove","removeAll","destroy","destroyAll","replace"].forEach(function(o){Object.defineProperty(t,o,{enumerable:!1,value:function(){var r;i.pause=!0;try{r=e.observableArray.fn[o].apply(e.observableArray(t),arguments)}finally{i.pause=!1}return n.notifySubscribers(t),r}})})}function Eq(e,t){if(!e)return null;var n=Cq(e,!1);return n&&n[t]||null}function CGe(e,t){var n=Eq(e,t);n&&n.valueHasMutated()}function EGe(e){e.track=xq,e.getObservable=Eq,e.valueHasMutated=CGe,e.defineProperty=gGe}const wGe={attachToKo:EGe},jz="http://www.w3.org/2000/svg",Wz="cesium-svgPath-svg",SGe={register:function(e){e.bindingHandlers.cesiumSvgPath={init:function(t,n){const i=document.createElementNS(jz,"svg:svg");i.setAttribute("class",Wz);const o=document.createElementNS(jz,"path");return i.appendChild(o),e.virtualElements.setDomNodeChildren(t,[i]),e.computed({read:function(){const r=e.unwrap(n());o.setAttribute("d",e.unwrap(r.path));const s=e.unwrap(r.width),a=e.unwrap(r.height);i.setAttribute("width",s),i.setAttribute("height",a),i.setAttribute("viewBox",`0 0 ${s} ${a}`),r.css&&i.setAttribute("class",`${Wz} ${e.unwrap(r.css)}`)},disposeWhenNodeIsRemoved:t}),{controlsDescendantBindings:!0}}},e.virtualElements.allowedBindings.cesiumSvgPath=!0}},vGe=SGe;wGe.attachToKo(He);vGe.register(He);function yb(e){c(e)||(e=new tb),this._clock=e,this._eventHelper=new Tu,this._eventHelper.add(e.onTick,this.synchronize,this),this.systemTime=He.observable(ie.now()),this.systemTime.equalityComparer=ie.equals,this.startTime=He.observable(e.startTime),this.startTime.equalityComparer=ie.equals,this.startTime.subscribe(function(t){e.startTime=t,this.synchronize()},this),this.stopTime=He.observable(e.stopTime),this.stopTime.equalityComparer=ie.equals,this.stopTime.subscribe(function(t){e.stopTime=t,this.synchronize()},this),this.currentTime=He.observable(e.currentTime),this.currentTime.equalityComparer=ie.equals,this.currentTime.subscribe(function(t){e.currentTime=t,this.synchronize()},this),this.multiplier=He.observable(e.multiplier),this.multiplier.subscribe(function(t){e.multiplier=t,this.synchronize()},this),this.clockStep=He.observable(e.clockStep),this.clockStep.subscribe(function(t){e.clockStep=t,this.synchronize()},this),this.clockRange=He.observable(e.clockRange),this.clockRange.subscribe(function(t){e.clockRange=t,this.synchronize()},this),this.canAnimate=He.observable(e.canAnimate),this.canAnimate.subscribe(function(t){e.canAnimate=t,th
${m}`:c(g)?g:m}),this.buttonImageUrl=void 0,He.defineProperty(this,"buttonImageUrl",function(){const f=this.selectedImagery;if(c(f))return f.iconUrl}),this.selectedImagery=void 0;const l=He.observable();this._currentImageryLayers=[],He.defineProperty(this,"selectedImagery",{get:function(){return l()},set:function(f){if(l()===f){this.dropDownVisible=!1;return}let _;const g=this._currentImageryLayers,m=g.length,b=this._globe.imageryLayers;let T=!1;for(_=0;_<m;_++){const x=b.length;for(let C=0;C<x;C++){const w=b.get(C);if(w===g[_]){b.remove(w),T=!0;break}}}if(c(f)){const x=f.creationCommand();if(Array.isArray(x)){const C=x.length;for(this._currentImageryLayers=[],_=C-1;_>=0;_--){const w=Qt.fromProviderAsync(x[_]);b.add(w,0),this._currentImageryLayers.push(w)}}else{this._currentImageryLayers=[];const C=Qt.fromProviderAsync(x);if(C.name=f.name,T)b.add(C,0);else{const w=b.get(0);c(w)&&b.remove(w),b.add(C,0)}this._currentImageryLayers.push(C)}}l(f),this.dropDownVisible=!1}}),this.selectedTerrain=void 0;const u=He.observable();He.defineProperty(this,"selectedTerrain",{get:function(){return u()},set:function(f){if(u()===f){this.dropDownVisible=!1;return}let _;if(c(f)&&(_=f.creationCommand()),c(_)&&!c(_.then))this._globe.depthTestAgainstTerrain=!(_ instanceof _d),this._globe.terrainProvider=_;else if(c(_)){let g=!1;const m=this._globe.terrainProviderChanged.addEventListener(()=>{g=!0,m()}),T=new U_(_).readyEvent.addEventListener(x=>{g||(this._globe.depthTestAgainstTerrain=!(x instanceof _d),this._globe.terrainProvider=x,T())})}u(f),this.dropDownVisible=!1}});const h=this;this._toggleDropDown=mo(function(){h.dropDownVisible=!h.dropDownVisible}),this.selectedImagery=y(e.selectedImageryProviderViewModel,n[0]),this.selectedTerrain=y(e.selectedTerrainProviderViewModel,i[0])}Object.defineProperties(wq.prototype,{toggleDropDown:{get:function(){return this._toggleDropDown}},globe:{get:function(){return this._globe}}});function gE(e,t){if(!c(e))throw new E("container is required.");e=Do(e);const n=new wq(t),i=document.createElement("button");i.type="button",i.className="cesium-button cesium-toolbar-button",i.setAttribute("data-bind","attr: { title: buttonTooltip },click: toggleDropDown"),e.appendChild(i);const o=document.createElement("img");o.setAttribute("draggable","false"),o.className="cesium-baseLayerPicker-selected",o.setAttribute("data-bind","attr: { src: buttonImageUrl }, visible: !!buttonImageUrl"),i.appendChild(o);const r=document.createElement("div");r.className="cesium-baseLayerPicker-dropDown",r.setAttribute("data-bind",'css: { "cesium-baseLayerPicker-dropDown-visible" : dropDownVisible }'),e.appendChild(r);const s=document.createElement("div");s.className="cesium-baseLayerPicker-sectionTitle",s.setAttribute("data-bind","visible: imageryProviderViewModels.length > 0"),s.innerHTML="Imagery",r.appendChild(s);const a=document.createElement("div");a.className="cesium-baseLayerPicker-section",a.setAttribute("data-bind","foreach: _imageryProviders"),r.appendChild(a);const l=document.createElement("div");l.className="cesium-baseLayerPicker-category",a.appendChild(l);const u=document.createElement("div");u.className="cesium-baseLayerPicker-categoryTitle",u.setAttribute("data-bind","text: name"),l.appendChild(u);const h=document.createElement("div");h.className="cesium-baseLayerPicker-choices",h.setAttribute("data-bind","foreach: providers"),l.appendChild(h);const f=document.createElement("div");f.className="cesium-baseLayerPicker-item",f.setAttribute("data-bind",'css: { "cesium-baseLayerPicker-selectedItem" : $data === $parents[1].selectedImagery },attr: { title: tooltip },visible: creationCommand.canExecute,click: function($data) { $parents[1].selectedImagery = $data; }'),h.appendChild(f);const _=document.createElement("img");_.className="cesium-baseLayerPicker-itemIcon",_.setAttribute("data-bind","attr: { src: iconUrl }"),_.setAttribute("draggable","false"),f.appendChild(_);const g=document.createElement("div");g.className="cesium-baseLayerPicker-itemLabel",g.setAttribute("data-bind","text: name"),f.appendChild(g);const m=document.
https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9`,category:"Other",creationFunction:function(){return Oa.fromBasemapType(g_.SATELLITE,{enablePickFeatures:!1})}})),e.push(new yr({name:"ArcGIS World Hillshade",iconUrl:Zt("Widgets/Images/ImageryProviders/ArcGisMapServiceWorldHillshade.png"),tooltip:`ArcGIS World Hillshade map portrays elevation as an artistic hillshade. This map is designed to be used as a backdrop for topographical, soil, hydro, landcover or other outdoor recreational maps. The map was compiled from a variety of sources from several data providers. The basemap has global coverage down to a scale of ~1:72k. In select areas of the United States and Europe, coverage is available down to ~1:9k. For more information on this map, including the terms of use, visit us online at
https://www.arcgis.com/home/item.html?id=1b243539f4514b6ba35e7d995890db1d`,category:"Other",creationFunction:function(){return Oa.fromBasemapType(g_.HILLSHADE,{enablePickFeatures:!1})}})),e.push(new yr({name:"Esri World Ocean",iconUrl:Zt("Widgets/Images/ImageryProviders/ArcGisMapServiceWorldOcean.png"),tooltip:`ArcGIS World Ocean map is designed to be used as a base map by marine GIS professionals and as a reference map by anyone interested in ocean data. The base map features marine bathymetry. Land features include inland waters and roads overlaid on land cover and shaded relief imagery. The map was compiled from a variety of best available sources from several data providers, including General Bathymetric Chart of the Oceans GEBCO_08 Grid, National Oceanic and Atmospheric Administration (NOAA), and National Geographic, Garmin, HERE, Geonames.org, and Esri, and various other contributors. The base map currently provides coverage for the world down to a scale of ~1:577k, and coverage down to 1:72k in US coastal areas, and various other areas. Coverage down to ~ 1:9k is available limited areas based on regional hydrographic survey data. The base map was designed and developed by Esri. For more information on this map, including our terms of use, visit us online at
https://www.arcgis.com/home/item.html?id=1e126e7520f9466c9ca28b8f28b5e500`,category:"Other",creationFunction:function(){return Oa.fromBasemapType(g_.OCEANS,{enablePickFeatures:!1})}})),e.push(new yr({name:"Open\xADStreet\xADMap",iconUrl:Zt("Widgets/Images/ImageryProviders/openStreetMap.png"),tooltip:`OpenStreetMap (OSM) is a collaborative project to create a free editable map of the world.
http://www.openstreetmap.org`,category:"Other",creationFunction:function(){return new ch({url:"https://tile.openstreetmap.org/"})}})),e.push(new yr({name:"Stadia x Stamen Watercolor",iconUrl:Zt("Widgets/Images/ImageryProviders/stamenWatercolor.png"),tooltip:`Based on the original basemaps created for the Knight Foundation and reminiscent of hand drawn maps, the watercolor maps from Stamen Design apply raster effect area washes and organic edges over a paper texture to add warm pop to any map.
https://docs.stadiamaps.com/map-styles/stamen-watercolor/`,category:"Other",creationFunction:function(){return new ch({url:"https://tiles.stadiamaps.com/tiles/stamen_watercolor/",fileExtension:"jpg",credit:`&copy; <a href="https://stamen.com/" target="_blank">Stamen Design</a>
&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a>
&copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a>
&copy; <a href="https://www.openstreetmap.org/about/" target="_blank">OpenStreetMap contributors</a>`})}})),e.push(new yr({name:"Stadia x Stamen Toner",iconUrl:Zt("Widgets/Images/ImageryProviders/stamenToner.png"),tooltip:`Based on the original basemaps created for the Knight Foundation and the most popular of the excellent styles from Stamen Design, these high-contrast B+W (black and white) maps are the perfect backdrop for your colorful and eye-catching overlays.
https://docs.stadiamaps.com/map-styles/stamen-toner/`,category:"Other",creationFunction:function(){return new ch({url:"https://tiles.stadiamaps.com/tiles/stamen_toner/",retinaTiles:t,credit:`&copy; <a href="https://stamen.com/" target="_blank">Stamen Design</a>
&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a>
&copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a>
&copy; <a href="https://www.openstreetmap.org/about/" target="_blank">OpenStreetMap contributors</a>`})}})),e.push(new yr({name:"Stadia Alidade Smooth",iconUrl:Zt("Widgets/Images/ImageryProviders/stadiaAlidadeSmooth.png"),tooltip:`Stadia's custom Alidade Smooth style is designed for maps that use a lot of markers or overlays. It features a muted color scheme and fewer points of interest to allow your added data to shine.
https://docs.stadiamaps.com/map-styles/alidade-smooth/`,category:"Other",creationFunction:function(){return new ch({url:"https://tiles.stadiamaps.com/tiles/alidade_smooth/",retinaTiles:t,credit:`&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a>
&copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a>
&copy; <a href="https://www.openstreetmap.org/about/" target="_blank">OpenStreetMap contributors</a>`})}})),e.push(new yr({name:"Stadia Alidade Smooth Dark",iconUrl:Zt("Widgets/Images/ImageryProviders/stadiaAlidadeSmoothDark.png"),tooltip:`Stadia Alidade Smooth Dark, like its lighter cousin, is also designed to stay out of the way. It just flips the dark mode switch on the color scheme. With the lights out, your data can now literally shine.
https://docs.stadiamaps.com/map-styles/alidade-smooth-dark/`,category:"Other",creationFunction:function(){return new ch({url:"https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/",retinaTiles:t,credit:`&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a>
&copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a>
&copy; <a href="https://www.openstreetmap.org/about/" target="_blank">OpenStreetMap contributors</a>`})}})),e.push(new yr({name:"Sentinel-2",iconUrl:Zt("Widgets/Images/ImageryProviders/sentinel-2.png"),tooltip:"Sentinel-2 cloudless by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2016 and 2017).",category:"Cesium ion",creationFunction:function(){return xa.fromAssetId(3954)}})),e.push(new yr({name:"Blue Marble",iconUrl:Zt("Widgets/Images/ImageryProviders/blueMarble.png"),tooltip:"Blue Marble Next Generation July, 2004 imagery from NASA.",category:"Cesium ion",creationFunction:function(){return xa.fromAssetId(3845)}})),e.push(new yr({name:"Earth at night",iconUrl:Zt("Widgets/Images/ImageryProviders/earthAtNight.png"),tooltip:"The Earth at night, also known as The Black Marble, is a 500 meter resolution global composite imagery layer released by NASA.",category:"Cesium ion",creationFunction:function(){return xa.fromAssetId(3812)}})),e.push(new yr({name:"Natural Earth\xA0II",iconUrl:Zt("Widgets/Images/ImageryProviders/naturalEarthII.png"),tooltip:`Natural Earth II, darkened for contrast.
http://www.naturalearthdata.com/`,category:"Cesium ion",creationFunction:function(){return ra.fromUrl(Zt("Assets/Textures/NaturalEarthII"))}})),e}function DGe(){const e=[];return e.push(new yr({name:"WGS84 Ellipsoid",iconUrl:Zt("Widgets/Images/TerrainProviders/Ellipsoid.png"),tooltip:"WGS84 standard ellipsoid, also known as EPSG:4326",category:"Cesium ion",creationFunction:function(){return new _d}})),e.push(new yr({name:"Cesium World Terrain",iconUrl:Zt("Widgets/Images/TerrainProviders/CesiumWorldTerrain.png"),tooltip:"High-resolution global terrain tileset curated from several datasources and hosted by Cesium ion",category:"Cesium ion",creationFunction:function(){return mq({requestWaterMask:!0,requestVertexNormals:!0})}})),e}const $f="http://www.w3.org/2000/svg",Sq="http://www.w3.org/1999/xlink";let wA;const uy=z.fromCssColorString("rgba(247,250,255,0.384)"),SA=z.fromCssColorString("rgba(143,191,255,0.216)"),iI=z.fromCssColorString("rgba(153,197,255,0.098)"),vA=z.fromCssColorString("rgba(255,255,255,0.086)"),PGe=z.fromCssColorString("rgba(255,255,255,0.267)"),OGe=z.fromCssColorString("rgba(255,255,255,0)"),qz=z.fromCssColorString("rgba(66,67,68,0.3)"),Yz=z.fromCssColorString("rgba(0,0,0,0.5)");function Kd(e){return z.fromCssColorString(window.getComputedStyle(e).getPropertyValue("color"))}const O0={animation_pathReset:{tagName:"path",transform:"translate(16,16) scale(0.85) translate(-16,-16)",d:"M24.316,5.318,9.833,13.682,9.833,5.5,5.5,5.5,5.5,25.5,9.833,25.5,9.833,17.318,24.316,25.682z"},animation_pathPause:{tagName:"path",transform:"translate(16,16) scale(0.85) translate(-16,-16)",d:"M13,5.5,7.5,5.5,7.5,25.5,13,25.5zM24.5,5.5,19,5.5,19,25.5,24.5,25.5z"},animation_pathPlay:{tagName:"path",transform:"translate(16,16) scale(0.85) translate(-16,-16)",d:"M6.684,25.682L24.316,15.5L6.684,5.318V25.682z"},animation_pathPlayReverse:{tagName:"path",transform:"translate(16,16) scale(-0.85,0.85) translate(-16,-16)",d:"M6.684,25.682L24.316,15.5L6.684,5.318V25.682z"},animation_pathLoop:{tagName:"path",transform:"translate(16,16) scale(0.85) translate(-16,-16)",d:"M24.249,15.499c-0.009,4.832-3.918,8.741-8.75,8.75c-2.515,0-4.768-1.064-6.365-2.763l2.068-1.442l-7.901-3.703l0.744,8.694l2.193-1.529c2.244,2.594,5.562,4.242,9.26,4.242c6.767,0,12.249-5.482,12.249-12.249H24.249zM15.499,6.75c2.516,0,4.769,1.065,6.367,2.764l-2.068,1.443l7.901,3.701l-0.746-8.693l-2.192,1.529c-2.245-2.594-5.562-4.245-9.262-4.245C8.734,3.25,3.25,8.734,3.249,15.499H6.75C6.758,10.668,10.668,6.758,15.499,6.75z"},animation_pathClock:{tagName:"path",transform:"translate(16,16) scale(0.85) translate(-16,-15.5)",d:"M15.5,2.374C8.251,2.375,2.376,8.251,2.374,15.5C2.376,22.748,8.251,28.623,15.5,28.627c7.249-0.004,13.124-5.879,13.125-13.127C28.624,8.251,22.749,2.375,15.5,2.374zM15.5,25.623C9.909,25.615,5.385,21.09,5.375,15.5C5.385,9.909,9.909,5.384,15.5,5.374c5.59,0.01,10.115,4.535,10.124,10.125C25.615,21.09,21.091,25.615,15.5,25.623zM8.625,15.5c-0.001-0.552-0.448-0.999-1.001-1c-0.553,0-1,0.448-1,1c0,0.553,0.449,1,1,1C8.176,16.5,8.624,16.053,8.625,15.5zM8.179,18.572c-0.478,0.277-0.642,0.889-0.365,1.367c0.275,0.479,0.889,0.641,1.365,0.365c0.479-0.275,0.643-0.887,0.367-1.367C9.27,18.461,8.658,18.297,8.179,18.572zM9.18,10.696c-0.479-0.276-1.09-0.112-1.366,0.366s-0.111,1.09,0.365,1.366c0.479,0.276,1.09,0.113,1.367-0.366C9.821,11.584,9.657,10.973,9.18,10.696zM22.822,12.428c0.478-0.275,0.643-0.888,0.366-1.366c-0.275-0.478-0.89-0.642-1.366-0.366c-0.479,0.278-0.642,0.89-0.366,1.367C21.732,12.54,22.344,12.705,22.822,12.428zM12.062,21.455c-0.478-0.275-1.089-0.111-1.366,0.367c-0.275,0.479-0.111,1.09,0.366,1.365c0.478,0.277,1.091,0.111,1.365-0.365C12.704,22.344,12.54,21.732,12.062,21.455zM12.062,9.545c0.479-0.276,0.642-0.888,0.366-1.366c-0.276-0.478-0.888-0.642-1.366-0.366s-0.642,0.888-0.366,1.366C10.973,9.658,11.584,9.822,12.062,9.545zM22.823,18.572c-0.48-0.275-1.092-0.111-1.367,0.365c-0.275,0.479-0.112,1.092,0.367,1.367c0.477,0.275,1.089,0.113,1.365-0.365C23.464,19.461,23.3,18.848,22.823,18.572zM19.938,7.813c-0.477-0.276-1.091-0.111-1.365,0.366c-0.275,0.48-0.111,1.091,0.366,1.367s1.
NoSleep enabled for older iOS devices. This can interrupt
active or long-running network requests from completing successfully.
See https://github.com/richtr/NoSleep.js/issues/15 for more details.
`),this.noSleepTimer=window.setInterval(()=>{document.hidden||(window.location.href=window.location.href.split("#")[0],window.setTimeout(window.stop,0))},15e3),this.enabled=!0,Promise.resolve()):this.noSleepVideo.play().then(n=>(this.enabled=!0,n)).catch(n=>{throw this.enabled=!1,n})}disable(){uI()?(this._wakeLock&&this._wakeLock.release(),this._wakeLock=null):lI()?this.noSleepTimer&&(console.warn(`
NoSleep now disabled for older iOS devices.
`),window.clearInterval(this.noSleepTimer),this.noSleepTimer=null):this.noSleepVideo.pause(),this.enabled=!1}}var mje=pje;function _je(e){let t=!1;const n=window.screen;return c(n)&&(c(n.lockOrientation)?t=n.lockOrientation(e):c(n.mozLockOrientation)?t=n.mozLockOrientation(e):c(n.msLockOrientation)?t=n.msLockOrientation(e):c(n.orientation&&n.orientation.lock)&&(t=n.orientation.lock(e))),t}function Nq(){const e=window.screen;c(e)&&(c(e.unlockOrientation)?e.unlockOrientation():c(e.mozUnlockOrientation)?e.mozUnlockOrientation():c(e.msUnlockOrientation)?e.msUnlockOrientation():c(e.orientation&&e.orientation.unlock)&&e.orientation.unlock())}function gje(e,t,n,i){i()||(n()?(t.useWebVR=!1,e._locked&&(Nq(),e._locked=!1),e._noSleep.disable(),Tr.exitFullscreen(),n(!1)):(Tr.fullscreen||Tr.requestFullscreen(e._vrElement),e._noSleep.enable(),e._locked||(e._locked=_je("landscape")),t.useWebVR=!0,n(!0)))}function DE(e,t){if(!c(e))throw new E("scene is required.");const n=this,i=He.observable(Tr.enabled),o=He.observable(!1);this.isVRMode=void 0,He.defineProperty(this,"isVRMode",{get:function(){return o()}}),this.isVREnabled=void 0,He.defineProperty(this,"isVREnabled",{get:function(){return i()},set:function(s){i(s&&Tr.enabled)}}),this.tooltip=void 0,He.defineProperty(this,"tooltip",function(){return i()?o()?"Exit VR mode":"Enter VR mode":"VR mode is unavailable"});const r=He.observable(!1);this._isOrthographic=void 0,He.defineProperty(this,"_isOrthographic",{get:function(){return r()}}),this._eventHelper=new Tu,this._eventHelper.add(e.preRender,function(){r(e.camera.frustum instanceof It)}),this._locked=!1,this._noSleep=new mje,this._command=mo(function(){gje(n,e,o,r)},He.getObservable(this,"isVREnabled")),this._vrElement=y(Do(t),document.body),this._callback=function(){!Tr.fullscreen&&o()&&(e.useWebVR=!1,n._locked&&(Nq(),n._locked=!1),n._noSleep.disable(),o(!1))},document.addEventListener(Tr.changeEventName,this._callback)}Object.defineProperties(DE.prototype,{vrElement:{get:function(){return this._vrElement},set:function(e){if(!(e instanceof Element))throw new E("value must be a valid Element.");this._vrElement=e}},command:{get:function(){return this._command}}});DE.prototype.isDestroyed=function(){return!1};DE.prototype.destroy=function(){this._eventHelper.removeAll(),document.removeEventListener(Tr.changeEventName,this._callback),ve(this)};const yje="M 5.3125 6.375 C 4.008126 6.375 2.96875 7.4141499 2.96875 8.71875 L 2.96875 19.5 C 2.96875 20.8043 4.008126 21.875 5.3125 21.875 L 13.65625 21.875 C 13.71832 20.0547 14.845166 18.59375 16.21875 18.59375 C 17.592088 18.59375 18.71881 20.0552 18.78125 21.875 L 27.09375 21.875 C 28.398125 21.875 29.4375 20.8043 29.4375 19.5 L 29.4375 8.71875 C 29.4375 7.4141499 28.398125 6.375 27.09375 6.375 L 5.3125 6.375 z M 9.625 10.4375 C 11.55989 10.4375 13.125 12.03385 13.125 13.96875 C 13.125 15.90365 11.55989 17.46875 9.625 17.46875 C 7.69011 17.46875 6.125 15.90365 6.125 13.96875 C 6.125 12.03385 7.69011 10.4375 9.625 10.4375 z M 22.46875 10.4375 C 24.40364 10.4375 25.96875 12.03385 25.96875 13.96875 C 25.96875 15.90365 24.40364 17.46875 22.46875 17.46875 C 20.53386 17.46875 18.96875 15.90365 18.96875 13.96875 C 18.96875 12.03385 20.53386 10.4375 22.46875 10.4375 z",bje="M 25.770585,2.4552065 C 15.72282,13.962707 10.699956,19.704407 8.1768352,22.580207 c -1.261561,1.4379 -1.902282,2.1427 -2.21875,2.5 -0.141624,0.1599 -0.208984,0.2355 -0.25,0.2813 l 0.6875,0.75 c 10e-5,-10e-5 0.679191,0.727 0.6875,0.7187 0.01662,-0.016 0.02451,-0.024 0.03125,-0.031 0.01348,-0.014 0.04013,-0.038 0.0625,-0.062 0.04474,-0.05 0.120921,-0.1315 0.28125,-0.3126 0.320657,-0.3619 0.956139,-1.0921 2.2187499,-2.5312 2.5252219,-2.8781 7.5454589,-8.6169 17.5937499,-20.1250005 l -1.5,-1.3125 z m -20.5624998,3.9063 c -1.304375,0 -2.34375,1.0391 -2.34375,2.3437 l 0,10.8125005 c 0,1.3043 1.039375,2.375 2.34375,2.375 l 2.25,0 c 1.9518039,-2.2246 7.4710958,-8.5584 13.5624998,-15.5312005 l -15.8124998,0 z m 21.1249998,0 c -1.855467,2.1245 -2.114296,2.4005 -3.59375,4.0936995 1.767282,0.1815 3.15625,1.685301 3.15625,3.500001 0,