createPolygonOutlineGeometry.js 1.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761
  1. /**
  2. * Cesium - https://github.com/AnalyticalGraphicsInc/cesium
  3. *
  4. * Copyright 2011-2016 Cesium Contributors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * Columbus View (Pat. Pend.)
  19. *
  20. * Portions licensed separately.
  21. * See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
  22. */
  23. (function () {
  24. /*global define*/
  25. define('Core/defined',[],function() {
  26. 'use strict';
  27. /**
  28. * @exports defined
  29. *
  30. * @param {Object} value The object.
  31. * @returns {Boolean} Returns true if the object is defined, returns false otherwise.
  32. *
  33. * @example
  34. * if (Cesium.defined(positions)) {
  35. * doSomething();
  36. * } else {
  37. * doSomethingElse();
  38. * }
  39. */
  40. function defined(value) {
  41. return value !== undefined && value !== null;
  42. }
  43. return defined;
  44. });
  45. /*global define*/
  46. define('Core/freezeObject',[
  47. './defined'
  48. ], function(
  49. defined) {
  50. 'use strict';
  51. /**
  52. * Freezes an object, using Object.freeze if available, otherwise returns
  53. * the object unchanged. This function should be used in setup code to prevent
  54. * errors from completely halting JavaScript execution in legacy browsers.
  55. *
  56. * @private
  57. *
  58. * @exports freezeObject
  59. */
  60. var freezeObject = Object.freeze;
  61. if (!defined(freezeObject)) {
  62. freezeObject = function(o) {
  63. return o;
  64. };
  65. }
  66. return freezeObject;
  67. });
  68. /*global define*/
  69. define('Core/defaultValue',[
  70. './freezeObject'
  71. ], function(
  72. freezeObject) {
  73. 'use strict';
  74. /**
  75. * Returns the first parameter if not undefined, otherwise the second parameter.
  76. * Useful for setting a default value for a parameter.
  77. *
  78. * @exports defaultValue
  79. *
  80. * @param {*} a
  81. * @param {*} b
  82. * @returns {*} Returns the first parameter if not undefined, otherwise the second parameter.
  83. *
  84. * @example
  85. * param = Cesium.defaultValue(param, 'default');
  86. */
  87. function defaultValue(a, b) {
  88. if (a !== undefined) {
  89. return a;
  90. }
  91. return b;
  92. }
  93. /**
  94. * A frozen empty object that can be used as the default value for options passed as
  95. * an object literal.
  96. */
  97. defaultValue.EMPTY_OBJECT = freezeObject({});
  98. return defaultValue;
  99. });
  100. /*global define*/
  101. define('Core/DeveloperError',[
  102. './defined'
  103. ], function(
  104. defined) {
  105. 'use strict';
  106. /**
  107. * Constructs an exception object that is thrown due to a developer error, e.g., invalid argument,
  108. * argument out of range, etc. This exception should only be thrown during development;
  109. * it usually indicates a bug in the calling code. This exception should never be
  110. * caught; instead the calling code should strive not to generate it.
  111. * <br /><br />
  112. * On the other hand, a {@link RuntimeError} indicates an exception that may
  113. * be thrown at runtime, e.g., out of memory, that the calling code should be prepared
  114. * to catch.
  115. *
  116. * @alias DeveloperError
  117. * @constructor
  118. * @extends Error
  119. *
  120. * @param {String} [message] The error message for this exception.
  121. *
  122. * @see RuntimeError
  123. */
  124. function DeveloperError(message) {
  125. /**
  126. * 'DeveloperError' indicating that this exception was thrown due to a developer error.
  127. * @type {String}
  128. * @readonly
  129. */
  130. this.name = 'DeveloperError';
  131. /**
  132. * The explanation for why this exception was thrown.
  133. * @type {String}
  134. * @readonly
  135. */
  136. this.message = message;
  137. //Browsers such as IE don't have a stack property until you actually throw the error.
  138. var stack;
  139. try {
  140. throw new Error();
  141. } catch (e) {
  142. stack = e.stack;
  143. }
  144. /**
  145. * The stack trace of this exception, if available.
  146. * @type {String}
  147. * @readonly
  148. */
  149. this.stack = stack;
  150. }
  151. if (defined(Object.create)) {
  152. DeveloperError.prototype = Object.create(Error.prototype);
  153. DeveloperError.prototype.constructor = DeveloperError;
  154. }
  155. DeveloperError.prototype.toString = function() {
  156. var str = this.name + ': ' + this.message;
  157. if (defined(this.stack)) {
  158. str += '\n' + this.stack.toString();
  159. }
  160. return str;
  161. };
  162. /**
  163. * @private
  164. */
  165. DeveloperError.throwInstantiationError = function() {
  166. throw new DeveloperError('This function defines an interface and should not be called directly.');
  167. };
  168. return DeveloperError;
  169. });
  170. /*global define*/
  171. define('Core/isArray',[
  172. './defined'
  173. ], function(
  174. defined) {
  175. 'use strict';
  176. /**
  177. * Tests an object to see if it is an array.
  178. * @exports isArray
  179. *
  180. * @param {Object} value The value to test.
  181. * @returns {Boolean} true if the value is an array, false otherwise.
  182. */
  183. var isArray = Array.isArray;
  184. if (!defined(isArray)) {
  185. isArray = function(value) {
  186. return Object.prototype.toString.call(value) === '[object Array]';
  187. };
  188. }
  189. return isArray;
  190. });
  191. /*global define*/
  192. define('Core/Check',[
  193. './defaultValue',
  194. './defined',
  195. './DeveloperError',
  196. './isArray'
  197. ], function(
  198. defaultValue,
  199. defined,
  200. DeveloperError,
  201. isArray) {
  202. 'use strict';
  203. /**
  204. * Contains functions for checking that supplied arguments are of a specified type
  205. * or meet specified conditions
  206. * @private
  207. */
  208. var Check = {};
  209. /**
  210. * Contains type checking functions, all using the typeof operator
  211. */
  212. Check.typeOf = {};
  213. /**
  214. * Contains functions for checking numeric conditions such as minimum and maximum values
  215. */
  216. Check.numeric = {};
  217. function getUndefinedErrorMessage(name) {
  218. return name + ' was required but undefined.';
  219. }
  220. function getFailedTypeErrorMessage(actual, expected, name) {
  221. return 'Expected ' + name + ' to be typeof ' + expected + ', got ' + actual;
  222. }
  223. /**
  224. * Throws if test is not defined
  225. *
  226. * @param {*} test The value that is to be checked
  227. * @param {String} name The name of the variable being tested
  228. * @exception {DeveloperError} test must be defined
  229. */
  230. Check.defined = function (test, name) {
  231. if (!defined(test)) {
  232. throw new DeveloperError(getUndefinedErrorMessage(name));
  233. }
  234. };
  235. /**
  236. * Throws if test is greater than maximum
  237. *
  238. * @param {Number} test The value to test
  239. * @param {Number} maximum The maximum allowed value
  240. * @exception {DeveloperError} test must not be greater than maximum
  241. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  242. */
  243. Check.numeric.maximum = function (test, maximum) {
  244. Check.typeOf.number(test);
  245. Check.typeOf.number(maximum);
  246. if (test > maximum) {
  247. throw new DeveloperError('Expected ' + test + ' to be at most ' + maximum);
  248. }
  249. };
  250. /**
  251. * Throws if test is less than minimum
  252. *
  253. * @param {Number} test The value to test
  254. * @param {Number} minimum The minimum allowed value
  255. * @exception {DeveloperError} test must not be less than mininum
  256. * @exception {DeveloperError} Both test and maximum must be typeof 'number'
  257. */
  258. Check.numeric.minimum = function (test, minimum) {
  259. Check.typeOf.number(test);
  260. Check.typeOf.number(minimum);
  261. if (test < minimum) {
  262. throw new DeveloperError('Expected ' + test + ' to be at least ' + minimum);
  263. }
  264. };
  265. /**
  266. * Throws if test is not typeof 'function'
  267. *
  268. * @param {*} test The value to test
  269. * @param {String} name The name of the variable being tested
  270. * @exception {DeveloperError} test must be typeof 'function'
  271. */
  272. Check.typeOf.function = function (test, name) {
  273. if (typeof test !== 'function') {
  274. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'function', name));
  275. }
  276. };
  277. /**
  278. * Throws if test is not typeof 'string'
  279. *
  280. * @param {*} test The value to test
  281. * @param {String} name The name of the variable being tested
  282. * @exception {DeveloperError} test must be typeof 'string'
  283. */
  284. Check.typeOf.string = function (test, name) {
  285. if (typeof test !== 'string') {
  286. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'string', name));
  287. }
  288. };
  289. /**
  290. * Throws if test is not typeof 'number'
  291. *
  292. * @param {*} test The value to test
  293. * @param {String} name The name of the variable being tested
  294. * @exception {DeveloperError} test must be typeof 'number'
  295. */
  296. Check.typeOf.number = function (test, name) {
  297. if (typeof test !== 'number') {
  298. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'number', name));
  299. }
  300. };
  301. /**
  302. * Throws if test is not typeof 'object'
  303. *
  304. * @param {*} test The value to test
  305. * @param {String} name The name of the variable being tested
  306. * @exception {DeveloperError} test must be typeof 'object'
  307. */
  308. Check.typeOf.object = function (test, name) {
  309. if (typeof test !== 'object') {
  310. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'object', name));
  311. }
  312. };
  313. /**
  314. * Throws if test is not typeof 'boolean'
  315. *
  316. * @param {*} test The value to test
  317. * @param {String} name The name of the variable being tested
  318. * @exception {DeveloperError} test must be typeof 'boolean'
  319. */
  320. Check.typeOf.boolean = function (test, name) {
  321. if (typeof test !== 'boolean') {
  322. throw new DeveloperError(getFailedTypeErrorMessage(typeof test, 'boolean', name));
  323. }
  324. };
  325. return Check;
  326. });
  327. /*
  328. I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
  329. so it's better encapsulated. Now you can have multiple random number generators
  330. and they won't stomp all over eachother's state.
  331. If you want to use this as a substitute for Math.random(), use the random()
  332. method like so:
  333. var m = new MersenneTwister();
  334. var randomNumber = m.random();
  335. You can also call the other genrand_{foo}() methods on the instance.
  336. If you want to use a specific seed in order to get a repeatable random
  337. sequence, pass an integer into the constructor:
  338. var m = new MersenneTwister(123);
  339. and that will always produce the same random sequence.
  340. Sean McCullough (banksean@gmail.com)
  341. */
  342. /*
  343. A C-program for MT19937, with initialization improved 2002/1/26.
  344. Coded by Takuji Nishimura and Makoto Matsumoto.
  345. Before using, initialize the state by using init_genrand(seed)
  346. or init_by_array(init_key, key_length).
  347. */
  348. /**
  349. @license
  350. mersenne-twister.js - https://gist.github.com/banksean/300494
  351. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  352. All rights reserved.
  353. Redistribution and use in source and binary forms, with or without
  354. modification, are permitted provided that the following conditions
  355. are met:
  356. 1. Redistributions of source code must retain the above copyright
  357. notice, this list of conditions and the following disclaimer.
  358. 2. Redistributions in binary form must reproduce the above copyright
  359. notice, this list of conditions and the following disclaimer in the
  360. documentation and/or other materials provided with the distribution.
  361. 3. The names of its contributors may not be used to endorse or promote
  362. products derived from this software without specific prior written
  363. permission.
  364. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  365. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  366. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  367. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  368. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  369. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  370. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  371. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  372. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  373. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  374. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  375. */
  376. /*
  377. Any feedback is very welcome.
  378. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
  379. email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
  380. */
  381. define('ThirdParty/mersenne-twister',[],function() {
  382. var MersenneTwister = function(seed) {
  383. if (seed == undefined) {
  384. seed = new Date().getTime();
  385. }
  386. /* Period parameters */
  387. this.N = 624;
  388. this.M = 397;
  389. this.MATRIX_A = 0x9908b0df; /* constant vector a */
  390. this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
  391. this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
  392. this.mt = new Array(this.N); /* the array for the state vector */
  393. this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */
  394. this.init_genrand(seed);
  395. }
  396. /* initializes mt[N] with a seed */
  397. MersenneTwister.prototype.init_genrand = function(s) {
  398. this.mt[0] = s >>> 0;
  399. for (this.mti=1; this.mti<this.N; this.mti++) {
  400. var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
  401. this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
  402. + this.mti;
  403. /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  404. /* In the previous versions, MSBs of the seed affect */
  405. /* only MSBs of the array mt[]. */
  406. /* 2002/01/09 modified by Makoto Matsumoto */
  407. this.mt[this.mti] >>>= 0;
  408. /* for >32 bit machines */
  409. }
  410. }
  411. /* initialize by an array with array-length */
  412. /* init_key is the array for initializing keys */
  413. /* key_length is its length */
  414. /* slight change for C++, 2004/2/26 */
  415. //MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
  416. // var i, j, k;
  417. // this.init_genrand(19650218);
  418. // i=1; j=0;
  419. // k = (this.N>key_length ? this.N : key_length);
  420. // for (; k; k--) {
  421. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
  422. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
  423. // + init_key[j] + j; /* non linear */
  424. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  425. // i++; j++;
  426. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  427. // if (j>=key_length) j=0;
  428. // }
  429. // for (k=this.N-1; k; k--) {
  430. // var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
  431. // this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
  432. // - i; /* non linear */
  433. // this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
  434. // i++;
  435. // if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  436. // }
  437. //
  438. // this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
  439. //}
  440. /* generates a random number on [0,0xffffffff]-interval */
  441. MersenneTwister.prototype.genrand_int32 = function() {
  442. var y;
  443. var mag01 = new Array(0x0, this.MATRIX_A);
  444. /* mag01[x] = x * MATRIX_A for x=0,1 */
  445. if (this.mti >= this.N) { /* generate N words at one time */
  446. var kk;
  447. if (this.mti == this.N+1) /* if init_genrand() has not been called, */
  448. this.init_genrand(5489); /* a default initial seed is used */
  449. for (kk=0;kk<this.N-this.M;kk++) {
  450. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  451. this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
  452. }
  453. for (;kk<this.N-1;kk++) {
  454. y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
  455. this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
  456. }
  457. y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
  458. this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];
  459. this.mti = 0;
  460. }
  461. y = this.mt[this.mti++];
  462. /* Tempering */
  463. y ^= (y >>> 11);
  464. y ^= (y << 7) & 0x9d2c5680;
  465. y ^= (y << 15) & 0xefc60000;
  466. y ^= (y >>> 18);
  467. return y >>> 0;
  468. }
  469. /* generates a random number on [0,0x7fffffff]-interval */
  470. //MersenneTwister.prototype.genrand_int31 = function() {
  471. // return (this.genrand_int32()>>>1);
  472. //}
  473. /* generates a random number on [0,1]-real-interval */
  474. //MersenneTwister.prototype.genrand_real1 = function() {
  475. // return this.genrand_int32()*(1.0/4294967295.0);
  476. // /* divided by 2^32-1 */
  477. //}
  478. /* generates a random number on [0,1)-real-interval */
  479. MersenneTwister.prototype.random = function() {
  480. return this.genrand_int32()*(1.0/4294967296.0);
  481. /* divided by 2^32 */
  482. }
  483. /* generates a random number on (0,1)-real-interval */
  484. //MersenneTwister.prototype.genrand_real3 = function() {
  485. // return (this.genrand_int32() + 0.5)*(1.0/4294967296.0);
  486. // /* divided by 2^32 */
  487. //}
  488. /* generates a random number on [0,1) with 53-bit resolution*/
  489. //MersenneTwister.prototype.genrand_res53 = function() {
  490. // var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
  491. // return(a*67108864.0+b)*(1.0/9007199254740992.0);
  492. //}
  493. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  494. return MersenneTwister;
  495. });
  496. /*global define*/
  497. define('Core/Math',[
  498. '../ThirdParty/mersenne-twister',
  499. './defaultValue',
  500. './defined',
  501. './DeveloperError'
  502. ], function(
  503. MersenneTwister,
  504. defaultValue,
  505. defined,
  506. DeveloperError) {
  507. 'use strict';
  508. /**
  509. * Math functions.
  510. *
  511. * @exports CesiumMath
  512. */
  513. var CesiumMath = {};
  514. /**
  515. * 0.1
  516. * @type {Number}
  517. * @constant
  518. */
  519. CesiumMath.EPSILON1 = 0.1;
  520. /**
  521. * 0.01
  522. * @type {Number}
  523. * @constant
  524. */
  525. CesiumMath.EPSILON2 = 0.01;
  526. /**
  527. * 0.001
  528. * @type {Number}
  529. * @constant
  530. */
  531. CesiumMath.EPSILON3 = 0.001;
  532. /**
  533. * 0.0001
  534. * @type {Number}
  535. * @constant
  536. */
  537. CesiumMath.EPSILON4 = 0.0001;
  538. /**
  539. * 0.00001
  540. * @type {Number}
  541. * @constant
  542. */
  543. CesiumMath.EPSILON5 = 0.00001;
  544. /**
  545. * 0.000001
  546. * @type {Number}
  547. * @constant
  548. */
  549. CesiumMath.EPSILON6 = 0.000001;
  550. /**
  551. * 0.0000001
  552. * @type {Number}
  553. * @constant
  554. */
  555. CesiumMath.EPSILON7 = 0.0000001;
  556. /**
  557. * 0.00000001
  558. * @type {Number}
  559. * @constant
  560. */
  561. CesiumMath.EPSILON8 = 0.00000001;
  562. /**
  563. * 0.000000001
  564. * @type {Number}
  565. * @constant
  566. */
  567. CesiumMath.EPSILON9 = 0.000000001;
  568. /**
  569. * 0.0000000001
  570. * @type {Number}
  571. * @constant
  572. */
  573. CesiumMath.EPSILON10 = 0.0000000001;
  574. /**
  575. * 0.00000000001
  576. * @type {Number}
  577. * @constant
  578. */
  579. CesiumMath.EPSILON11 = 0.00000000001;
  580. /**
  581. * 0.000000000001
  582. * @type {Number}
  583. * @constant
  584. */
  585. CesiumMath.EPSILON12 = 0.000000000001;
  586. /**
  587. * 0.0000000000001
  588. * @type {Number}
  589. * @constant
  590. */
  591. CesiumMath.EPSILON13 = 0.0000000000001;
  592. /**
  593. * 0.00000000000001
  594. * @type {Number}
  595. * @constant
  596. */
  597. CesiumMath.EPSILON14 = 0.00000000000001;
  598. /**
  599. * 0.000000000000001
  600. * @type {Number}
  601. * @constant
  602. */
  603. CesiumMath.EPSILON15 = 0.000000000000001;
  604. /**
  605. * 0.0000000000000001
  606. * @type {Number}
  607. * @constant
  608. */
  609. CesiumMath.EPSILON16 = 0.0000000000000001;
  610. /**
  611. * 0.00000000000000001
  612. * @type {Number}
  613. * @constant
  614. */
  615. CesiumMath.EPSILON17 = 0.00000000000000001;
  616. /**
  617. * 0.000000000000000001
  618. * @type {Number}
  619. * @constant
  620. */
  621. CesiumMath.EPSILON18 = 0.000000000000000001;
  622. /**
  623. * 0.0000000000000000001
  624. * @type {Number}
  625. * @constant
  626. */
  627. CesiumMath.EPSILON19 = 0.0000000000000000001;
  628. /**
  629. * 0.00000000000000000001
  630. * @type {Number}
  631. * @constant
  632. */
  633. CesiumMath.EPSILON20 = 0.00000000000000000001;
  634. /**
  635. * 3.986004418e14
  636. * @type {Number}
  637. * @constant
  638. */
  639. CesiumMath.GRAVITATIONALPARAMETER = 3.986004418e14;
  640. /**
  641. * Radius of the sun in meters: 6.955e8
  642. * @type {Number}
  643. * @constant
  644. */
  645. CesiumMath.SOLAR_RADIUS = 6.955e8;
  646. /**
  647. * The mean radius of the moon, according to the "Report of the IAU/IAG Working Group on
  648. * Cartographic Coordinates and Rotational Elements of the Planets and satellites: 2000",
  649. * Celestial Mechanics 82: 83-110, 2002.
  650. * @type {Number}
  651. * @constant
  652. */
  653. CesiumMath.LUNAR_RADIUS = 1737400.0;
  654. /**
  655. * 64 * 1024
  656. * @type {Number}
  657. * @constant
  658. */
  659. CesiumMath.SIXTY_FOUR_KILOBYTES = 64 * 1024;
  660. /**
  661. * Returns the sign of the value; 1 if the value is positive, -1 if the value is
  662. * negative, or 0 if the value is 0.
  663. *
  664. * @param {Number} value The value to return the sign of.
  665. * @returns {Number} The sign of value.
  666. */
  667. CesiumMath.sign = function(value) {
  668. if (value > 0) {
  669. return 1;
  670. }
  671. if (value < 0) {
  672. return -1;
  673. }
  674. return 0;
  675. };
  676. /**
  677. * Returns 1.0 if the given value is positive or zero, and -1.0 if it is negative.
  678. * This is similar to {@link CesiumMath#sign} except that returns 1.0 instead of
  679. * 0.0 when the input value is 0.0.
  680. * @param {Number} value The value to return the sign of.
  681. * @returns {Number} The sign of value.
  682. */
  683. CesiumMath.signNotZero = function(value) {
  684. return value < 0.0 ? -1.0 : 1.0;
  685. };
  686. /**
  687. * Converts a scalar value in the range [-1.0, 1.0] to a SNORM in the range [0, rangeMax]
  688. * @param {Number} value The scalar value in the range [-1.0, 1.0]
  689. * @param {Number} [rangeMax=255] The maximum value in the mapped range, 255 by default.
  690. * @returns {Number} A SNORM value, where 0 maps to -1.0 and rangeMax maps to 1.0.
  691. *
  692. * @see CesiumMath.fromSNorm
  693. */
  694. CesiumMath.toSNorm = function(value, rangeMax) {
  695. rangeMax = defaultValue(rangeMax, 255);
  696. return Math.round((CesiumMath.clamp(value, -1.0, 1.0) * 0.5 + 0.5) * rangeMax);
  697. };
  698. /**
  699. * Converts a SNORM value in the range [0, rangeMax] to a scalar in the range [-1.0, 1.0].
  700. * @param {Number} value SNORM value in the range [0, 255]
  701. * @param {Number} [rangeMax=255] The maximum value in the SNORM range, 255 by default.
  702. * @returns {Number} Scalar in the range [-1.0, 1.0].
  703. *
  704. * @see CesiumMath.toSNorm
  705. */
  706. CesiumMath.fromSNorm = function(value, rangeMax) {
  707. rangeMax = defaultValue(rangeMax, 255);
  708. return CesiumMath.clamp(value, 0.0, rangeMax) / rangeMax * 2.0 - 1.0;
  709. };
  710. /**
  711. * Returns the hyperbolic sine of a number.
  712. * The hyperbolic sine of <em>value</em> is defined to be
  713. * (<em>e<sup>x</sup>&nbsp;-&nbsp;e<sup>-x</sup></em>)/2.0
  714. * where <i>e</i> is Euler's number, approximately 2.71828183.
  715. *
  716. * <p>Special cases:
  717. * <ul>
  718. * <li>If the argument is NaN, then the result is NaN.</li>
  719. *
  720. * <li>If the argument is infinite, then the result is an infinity
  721. * with the same sign as the argument.</li>
  722. *
  723. * <li>If the argument is zero, then the result is a zero with the
  724. * same sign as the argument.</li>
  725. * </ul>
  726. *</p>
  727. *
  728. * @param {Number} value The number whose hyperbolic sine is to be returned.
  729. * @returns {Number} The hyperbolic sine of <code>value</code>.
  730. */
  731. CesiumMath.sinh = function(value) {
  732. var part1 = Math.pow(Math.E, value);
  733. var part2 = Math.pow(Math.E, -1.0 * value);
  734. return (part1 - part2) * 0.5;
  735. };
  736. /**
  737. * Returns the hyperbolic cosine of a number.
  738. * The hyperbolic cosine of <strong>value</strong> is defined to be
  739. * (<em>e<sup>x</sup>&nbsp;+&nbsp;e<sup>-x</sup></em>)/2.0
  740. * where <i>e</i> is Euler's number, approximately 2.71828183.
  741. *
  742. * <p>Special cases:
  743. * <ul>
  744. * <li>If the argument is NaN, then the result is NaN.</li>
  745. *
  746. * <li>If the argument is infinite, then the result is positive infinity.</li>
  747. *
  748. * <li>If the argument is zero, then the result is 1.0.</li>
  749. * </ul>
  750. *</p>
  751. *
  752. * @param {Number} value The number whose hyperbolic cosine is to be returned.
  753. * @returns {Number} The hyperbolic cosine of <code>value</code>.
  754. */
  755. CesiumMath.cosh = function(value) {
  756. var part1 = Math.pow(Math.E, value);
  757. var part2 = Math.pow(Math.E, -1.0 * value);
  758. return (part1 + part2) * 0.5;
  759. };
  760. /**
  761. * Computes the linear interpolation of two values.
  762. *
  763. * @param {Number} p The start value to interpolate.
  764. * @param {Number} q The end value to interpolate.
  765. * @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
  766. * @returns {Number} The linearly interpolated value.
  767. *
  768. * @example
  769. * var n = Cesium.Math.lerp(0.0, 2.0, 0.5); // returns 1.0
  770. */
  771. CesiumMath.lerp = function(p, q, time) {
  772. return ((1.0 - time) * p) + (time * q);
  773. };
  774. /**
  775. * pi
  776. *
  777. * @type {Number}
  778. * @constant
  779. */
  780. CesiumMath.PI = Math.PI;
  781. /**
  782. * 1/pi
  783. *
  784. * @type {Number}
  785. * @constant
  786. */
  787. CesiumMath.ONE_OVER_PI = 1.0 / Math.PI;
  788. /**
  789. * pi/2
  790. *
  791. * @type {Number}
  792. * @constant
  793. */
  794. CesiumMath.PI_OVER_TWO = Math.PI * 0.5;
  795. /**
  796. * pi/3
  797. *
  798. * @type {Number}
  799. * @constant
  800. */
  801. CesiumMath.PI_OVER_THREE = Math.PI / 3.0;
  802. /**
  803. * pi/4
  804. *
  805. * @type {Number}
  806. * @constant
  807. */
  808. CesiumMath.PI_OVER_FOUR = Math.PI / 4.0;
  809. /**
  810. * pi/6
  811. *
  812. * @type {Number}
  813. * @constant
  814. */
  815. CesiumMath.PI_OVER_SIX = Math.PI / 6.0;
  816. /**
  817. * 3pi/2
  818. *
  819. * @type {Number}
  820. * @constant
  821. */
  822. CesiumMath.THREE_PI_OVER_TWO = (3.0 * Math.PI) * 0.5;
  823. /**
  824. * 2pi
  825. *
  826. * @type {Number}
  827. * @constant
  828. */
  829. CesiumMath.TWO_PI = 2.0 * Math.PI;
  830. /**
  831. * 1/2pi
  832. *
  833. * @type {Number}
  834. * @constant
  835. */
  836. CesiumMath.ONE_OVER_TWO_PI = 1.0 / (2.0 * Math.PI);
  837. /**
  838. * The number of radians in a degree.
  839. *
  840. * @type {Number}
  841. * @constant
  842. * @default Math.PI / 180.0
  843. */
  844. CesiumMath.RADIANS_PER_DEGREE = Math.PI / 180.0;
  845. /**
  846. * The number of degrees in a radian.
  847. *
  848. * @type {Number}
  849. * @constant
  850. * @default 180.0 / Math.PI
  851. */
  852. CesiumMath.DEGREES_PER_RADIAN = 180.0 / Math.PI;
  853. /**
  854. * The number of radians in an arc second.
  855. *
  856. * @type {Number}
  857. * @constant
  858. * @default {@link CesiumMath.RADIANS_PER_DEGREE} / 3600.0
  859. */
  860. CesiumMath.RADIANS_PER_ARCSECOND = CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  861. /**
  862. * Converts degrees to radians.
  863. * @param {Number} degrees The angle to convert in degrees.
  864. * @returns {Number} The corresponding angle in radians.
  865. */
  866. CesiumMath.toRadians = function(degrees) {
  867. if (!defined(degrees)) {
  868. throw new DeveloperError('degrees is required.');
  869. }
  870. return degrees * CesiumMath.RADIANS_PER_DEGREE;
  871. };
  872. /**
  873. * Converts radians to degrees.
  874. * @param {Number} radians The angle to convert in radians.
  875. * @returns {Number} The corresponding angle in degrees.
  876. */
  877. CesiumMath.toDegrees = function(radians) {
  878. if (!defined(radians)) {
  879. throw new DeveloperError('radians is required.');
  880. }
  881. return radians * CesiumMath.DEGREES_PER_RADIAN;
  882. };
  883. /**
  884. * Converts a longitude value, in radians, to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  885. *
  886. * @param {Number} angle The longitude value, in radians, to convert to the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  887. * @returns {Number} The equivalent longitude value in the range [<code>-Math.PI</code>, <code>Math.PI</code>).
  888. *
  889. * @example
  890. * // Convert 270 degrees to -90 degrees longitude
  891. * var longitude = Cesium.Math.convertLongitudeRange(Cesium.Math.toRadians(270.0));
  892. */
  893. CesiumMath.convertLongitudeRange = function(angle) {
  894. if (!defined(angle)) {
  895. throw new DeveloperError('angle is required.');
  896. }
  897. var twoPi = CesiumMath.TWO_PI;
  898. var simplified = angle - Math.floor(angle / twoPi) * twoPi;
  899. if (simplified < -Math.PI) {
  900. return simplified + twoPi;
  901. }
  902. if (simplified >= Math.PI) {
  903. return simplified - twoPi;
  904. }
  905. return simplified;
  906. };
  907. /**
  908. * Convenience function that clamps a latitude value, in radians, to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  909. * Useful for sanitizing data before use in objects requiring correct range.
  910. *
  911. * @param {Number} angle The latitude value, in radians, to clamp to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  912. * @returns {Number} The latitude value clamped to the range [<code>-Math.PI/2</code>, <code>Math.PI/2</code>).
  913. *
  914. * @example
  915. * // Clamp 108 degrees latitude to 90 degrees latitude
  916. * var latitude = Cesium.Math.clampToLatitudeRange(Cesium.Math.toRadians(108.0));
  917. */
  918. CesiumMath.clampToLatitudeRange = function(angle) {
  919. if (!defined(angle)) {
  920. throw new DeveloperError('angle is required.');
  921. }
  922. return CesiumMath.clamp(angle, -1*CesiumMath.PI_OVER_TWO, CesiumMath.PI_OVER_TWO);
  923. };
  924. /**
  925. * Produces an angle in the range -Pi <= angle <= Pi which is equivalent to the provided angle.
  926. *
  927. * @param {Number} angle in radians
  928. * @returns {Number} The angle in the range [<code>-CesiumMath.PI</code>, <code>CesiumMath.PI</code>].
  929. */
  930. CesiumMath.negativePiToPi = function(x) {
  931. if (!defined(x)) {
  932. throw new DeveloperError('x is required.');
  933. }
  934. return CesiumMath.zeroToTwoPi(x + CesiumMath.PI) - CesiumMath.PI;
  935. };
  936. /**
  937. * Produces an angle in the range 0 <= angle <= 2Pi which is equivalent to the provided angle.
  938. *
  939. * @param {Number} angle in radians
  940. * @returns {Number} The angle in the range [0, <code>CesiumMath.TWO_PI</code>].
  941. */
  942. CesiumMath.zeroToTwoPi = function(x) {
  943. if (!defined(x)) {
  944. throw new DeveloperError('x is required.');
  945. }
  946. var mod = CesiumMath.mod(x, CesiumMath.TWO_PI);
  947. if (Math.abs(mod) < CesiumMath.EPSILON14 && Math.abs(x) > CesiumMath.EPSILON14) {
  948. return CesiumMath.TWO_PI;
  949. }
  950. return mod;
  951. };
  952. /**
  953. * The modulo operation that also works for negative dividends.
  954. *
  955. * @param {Number} m The dividend.
  956. * @param {Number} n The divisor.
  957. * @returns {Number} The remainder.
  958. */
  959. CesiumMath.mod = function(m, n) {
  960. if (!defined(m)) {
  961. throw new DeveloperError('m is required.');
  962. }
  963. if (!defined(n)) {
  964. throw new DeveloperError('n is required.');
  965. }
  966. return ((m % n) + n) % n;
  967. };
  968. /**
  969. * Determines if two values are equal using an absolute or relative tolerance test. This is useful
  970. * to avoid problems due to roundoff error when comparing floating-point values directly. The values are
  971. * first compared using an absolute tolerance test. If that fails, a relative tolerance test is performed.
  972. * Use this test if you are unsure of the magnitudes of left and right.
  973. *
  974. * @param {Number} left The first value to compare.
  975. * @param {Number} right The other value to compare.
  976. * @param {Number} relativeEpsilon The maximum inclusive delta between <code>left</code> and <code>right</code> for the relative tolerance test.
  977. * @param {Number} [absoluteEpsilon=relativeEpsilon] The maximum inclusive delta between <code>left</code> and <code>right</code> for the absolute tolerance test.
  978. * @returns {Boolean} <code>true</code> if the values are equal within the epsilon; otherwise, <code>false</code>.
  979. *
  980. * @example
  981. * var a = Cesium.Math.equalsEpsilon(0.0, 0.01, Cesium.Math.EPSILON2); // true
  982. * var b = Cesium.Math.equalsEpsilon(0.0, 0.1, Cesium.Math.EPSILON2); // false
  983. * var c = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON7); // true
  984. * var d = Cesium.Math.equalsEpsilon(3699175.1634344, 3699175.2, Cesium.Math.EPSILON9); // false
  985. */
  986. CesiumMath.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  987. if (!defined(left)) {
  988. throw new DeveloperError('left is required.');
  989. }
  990. if (!defined(right)) {
  991. throw new DeveloperError('right is required.');
  992. }
  993. if (!defined(relativeEpsilon)) {
  994. throw new DeveloperError('relativeEpsilon is required.');
  995. }
  996. absoluteEpsilon = defaultValue(absoluteEpsilon, relativeEpsilon);
  997. var absDiff = Math.abs(left - right);
  998. return absDiff <= absoluteEpsilon || absDiff <= relativeEpsilon * Math.max(Math.abs(left), Math.abs(right));
  999. };
  1000. var factorials = [1];
  1001. /**
  1002. * Computes the factorial of the provided number.
  1003. *
  1004. * @param {Number} n The number whose factorial is to be computed.
  1005. * @returns {Number} The factorial of the provided number or undefined if the number is less than 0.
  1006. *
  1007. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1008. *
  1009. *
  1010. * @example
  1011. * //Compute 7!, which is equal to 5040
  1012. * var computedFactorial = Cesium.Math.factorial(7);
  1013. *
  1014. * @see {@link http://en.wikipedia.org/wiki/Factorial|Factorial on Wikipedia}
  1015. */
  1016. CesiumMath.factorial = function(n) {
  1017. if (typeof n !== 'number' || n < 0) {
  1018. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1019. }
  1020. var length = factorials.length;
  1021. if (n >= length) {
  1022. var sum = factorials[length - 1];
  1023. for (var i = length; i <= n; i++) {
  1024. factorials.push(sum * i);
  1025. }
  1026. }
  1027. return factorials[n];
  1028. };
  1029. /**
  1030. * Increments a number with a wrapping to a minimum value if the number exceeds the maximum value.
  1031. *
  1032. * @param {Number} [n] The number to be incremented.
  1033. * @param {Number} [maximumValue] The maximum incremented value before rolling over to the minimum value.
  1034. * @param {Number} [minimumValue=0.0] The number reset to after the maximum value has been exceeded.
  1035. * @returns {Number} The incremented number.
  1036. *
  1037. * @exception {DeveloperError} Maximum value must be greater than minimum value.
  1038. *
  1039. * @example
  1040. * var n = Cesium.Math.incrementWrap(5, 10, 0); // returns 6
  1041. * var n = Cesium.Math.incrementWrap(10, 10, 0); // returns 0
  1042. */
  1043. CesiumMath.incrementWrap = function(n, maximumValue, minimumValue) {
  1044. minimumValue = defaultValue(minimumValue, 0.0);
  1045. if (!defined(n)) {
  1046. throw new DeveloperError('n is required.');
  1047. }
  1048. if (maximumValue <= minimumValue) {
  1049. throw new DeveloperError('maximumValue must be greater than minimumValue.');
  1050. }
  1051. ++n;
  1052. if (n > maximumValue) {
  1053. n = minimumValue;
  1054. }
  1055. return n;
  1056. };
  1057. /**
  1058. * Determines if a positive integer is a power of two.
  1059. *
  1060. * @param {Number} n The positive integer to test.
  1061. * @returns {Boolean} <code>true</code> if the number if a power of two; otherwise, <code>false</code>.
  1062. *
  1063. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1064. *
  1065. * @example
  1066. * var t = Cesium.Math.isPowerOfTwo(16); // true
  1067. * var f = Cesium.Math.isPowerOfTwo(20); // false
  1068. */
  1069. CesiumMath.isPowerOfTwo = function(n) {
  1070. if (typeof n !== 'number' || n < 0) {
  1071. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1072. }
  1073. return (n !== 0) && ((n & (n - 1)) === 0);
  1074. };
  1075. /**
  1076. * Computes the next power-of-two integer greater than or equal to the provided positive integer.
  1077. *
  1078. * @param {Number} n The positive integer to test.
  1079. * @returns {Number} The next power-of-two integer.
  1080. *
  1081. * @exception {DeveloperError} A number greater than or equal to 0 is required.
  1082. *
  1083. * @example
  1084. * var n = Cesium.Math.nextPowerOfTwo(29); // 32
  1085. * var m = Cesium.Math.nextPowerOfTwo(32); // 32
  1086. */
  1087. CesiumMath.nextPowerOfTwo = function(n) {
  1088. if (typeof n !== 'number' || n < 0) {
  1089. throw new DeveloperError('A number greater than or equal to 0 is required.');
  1090. }
  1091. // From http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
  1092. --n;
  1093. n |= n >> 1;
  1094. n |= n >> 2;
  1095. n |= n >> 4;
  1096. n |= n >> 8;
  1097. n |= n >> 16;
  1098. ++n;
  1099. return n;
  1100. };
  1101. /**
  1102. * Constraint a value to lie between two values.
  1103. *
  1104. * @param {Number} value The value to constrain.
  1105. * @param {Number} min The minimum value.
  1106. * @param {Number} max The maximum value.
  1107. * @returns {Number} The value clamped so that min <= value <= max.
  1108. */
  1109. CesiumMath.clamp = function(value, min, max) {
  1110. if (!defined(value)) {
  1111. throw new DeveloperError('value is required');
  1112. }
  1113. if (!defined(min)) {
  1114. throw new DeveloperError('min is required.');
  1115. }
  1116. if (!defined(max)) {
  1117. throw new DeveloperError('max is required.');
  1118. }
  1119. return value < min ? min : value > max ? max : value;
  1120. };
  1121. var randomNumberGenerator = new MersenneTwister();
  1122. /**
  1123. * Sets the seed used by the random number generator
  1124. * in {@link CesiumMath#nextRandomNumber}.
  1125. *
  1126. * @param {Number} seed An integer used as the seed.
  1127. */
  1128. CesiumMath.setRandomNumberSeed = function(seed) {
  1129. if (!defined(seed)) {
  1130. throw new DeveloperError('seed is required.');
  1131. }
  1132. randomNumberGenerator = new MersenneTwister(seed);
  1133. };
  1134. /**
  1135. * Generates a random number in the range of [0.0, 1.0)
  1136. * using a Mersenne twister.
  1137. *
  1138. * @returns {Number} A random number in the range of [0.0, 1.0).
  1139. *
  1140. * @see CesiumMath.setRandomNumberSeed
  1141. * @see {@link http://en.wikipedia.org/wiki/Mersenne_twister|Mersenne twister on Wikipedia}
  1142. */
  1143. CesiumMath.nextRandomNumber = function() {
  1144. return randomNumberGenerator.random();
  1145. };
  1146. /**
  1147. * Computes <code>Math.acos(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  1148. * so that the function will never return NaN.
  1149. *
  1150. * @param {Number} value The value for which to compute acos.
  1151. * @returns {Number} The acos of the value if the value is in the range [-1.0, 1.0], or the acos of -1.0 or 1.0,
  1152. * whichever is closer, if the value is outside the range.
  1153. */
  1154. CesiumMath.acosClamped = function(value) {
  1155. if (!defined(value)) {
  1156. throw new DeveloperError('value is required.');
  1157. }
  1158. return Math.acos(CesiumMath.clamp(value, -1.0, 1.0));
  1159. };
  1160. /**
  1161. * Computes <code>Math.asin(value)</acode>, but first clamps <code>value</code> to the range [-1.0, 1.0]
  1162. * so that the function will never return NaN.
  1163. *
  1164. * @param {Number} value The value for which to compute asin.
  1165. * @returns {Number} The asin of the value if the value is in the range [-1.0, 1.0], or the asin of -1.0 or 1.0,
  1166. * whichever is closer, if the value is outside the range.
  1167. */
  1168. CesiumMath.asinClamped = function(value) {
  1169. if (!defined(value)) {
  1170. throw new DeveloperError('value is required.');
  1171. }
  1172. return Math.asin(CesiumMath.clamp(value, -1.0, 1.0));
  1173. };
  1174. /**
  1175. * Finds the chord length between two points given the circle's radius and the angle between the points.
  1176. *
  1177. * @param {Number} angle The angle between the two points.
  1178. * @param {Number} radius The radius of the circle.
  1179. * @returns {Number} The chord length.
  1180. */
  1181. CesiumMath.chordLength = function(angle, radius) {
  1182. if (!defined(angle)) {
  1183. throw new DeveloperError('angle is required.');
  1184. }
  1185. if (!defined(radius)) {
  1186. throw new DeveloperError('radius is required.');
  1187. }
  1188. return 2.0 * radius * Math.sin(angle * 0.5);
  1189. };
  1190. /**
  1191. * Finds the logarithm of a number to a base.
  1192. *
  1193. * @param {Number} number The number.
  1194. * @param {Number} base The base.
  1195. * @returns {Number} The result.
  1196. */
  1197. CesiumMath.logBase = function(number, base) {
  1198. if (!defined(number)) {
  1199. throw new DeveloperError('number is required.');
  1200. }
  1201. if (!defined(base)) {
  1202. throw new DeveloperError('base is required.');
  1203. }
  1204. return Math.log(number) / Math.log(base);
  1205. };
  1206. /**
  1207. * @private
  1208. */
  1209. CesiumMath.fog = function(distanceToCamera, density) {
  1210. var scalar = distanceToCamera * density;
  1211. return 1.0 - Math.exp(-(scalar * scalar));
  1212. };
  1213. return CesiumMath;
  1214. });
  1215. /*global define*/
  1216. define('Core/Cartesian3',[
  1217. './Check',
  1218. './defaultValue',
  1219. './defined',
  1220. './DeveloperError',
  1221. './freezeObject',
  1222. './Math'
  1223. ], function(
  1224. Check,
  1225. defaultValue,
  1226. defined,
  1227. DeveloperError,
  1228. freezeObject,
  1229. CesiumMath) {
  1230. 'use strict';
  1231. /**
  1232. * A 3D Cartesian point.
  1233. * @alias Cartesian3
  1234. * @constructor
  1235. *
  1236. * @param {Number} [x=0.0] The X component.
  1237. * @param {Number} [y=0.0] The Y component.
  1238. * @param {Number} [z=0.0] The Z component.
  1239. *
  1240. * @see Cartesian2
  1241. * @see Cartesian4
  1242. * @see Packable
  1243. */
  1244. function Cartesian3(x, y, z) {
  1245. /**
  1246. * The X component.
  1247. * @type {Number}
  1248. * @default 0.0
  1249. */
  1250. this.x = defaultValue(x, 0.0);
  1251. /**
  1252. * The Y component.
  1253. * @type {Number}
  1254. * @default 0.0
  1255. */
  1256. this.y = defaultValue(y, 0.0);
  1257. /**
  1258. * The Z component.
  1259. * @type {Number}
  1260. * @default 0.0
  1261. */
  1262. this.z = defaultValue(z, 0.0);
  1263. }
  1264. /**
  1265. * Converts the provided Spherical into Cartesian3 coordinates.
  1266. *
  1267. * @param {Spherical} spherical The Spherical to be converted to Cartesian3.
  1268. * @param {Cartesian3} [result] The object onto which to store the result.
  1269. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1270. */
  1271. Cartesian3.fromSpherical = function(spherical, result) {
  1272. Check.typeOf.object(spherical, 'spherical');
  1273. if (!defined(result)) {
  1274. result = new Cartesian3();
  1275. }
  1276. var clock = spherical.clock;
  1277. var cone = spherical.cone;
  1278. var magnitude = defaultValue(spherical.magnitude, 1.0);
  1279. var radial = magnitude * Math.sin(cone);
  1280. result.x = radial * Math.cos(clock);
  1281. result.y = radial * Math.sin(clock);
  1282. result.z = magnitude * Math.cos(cone);
  1283. return result;
  1284. };
  1285. /**
  1286. * Creates a Cartesian3 instance from x, y and z coordinates.
  1287. *
  1288. * @param {Number} x The x coordinate.
  1289. * @param {Number} y The y coordinate.
  1290. * @param {Number} z The z coordinate.
  1291. * @param {Cartesian3} [result] The object onto which to store the result.
  1292. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1293. */
  1294. Cartesian3.fromElements = function(x, y, z, result) {
  1295. if (!defined(result)) {
  1296. return new Cartesian3(x, y, z);
  1297. }
  1298. result.x = x;
  1299. result.y = y;
  1300. result.z = z;
  1301. return result;
  1302. };
  1303. /**
  1304. * Duplicates a Cartesian3 instance.
  1305. *
  1306. * @param {Cartesian3} cartesian The Cartesian to duplicate.
  1307. * @param {Cartesian3} [result] The object onto which to store the result.
  1308. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. (Returns undefined if cartesian is undefined)
  1309. */
  1310. Cartesian3.clone = function(cartesian, result) {
  1311. if (!defined(cartesian)) {
  1312. return undefined;
  1313. }
  1314. if (!defined(result)) {
  1315. return new Cartesian3(cartesian.x, cartesian.y, cartesian.z);
  1316. }
  1317. result.x = cartesian.x;
  1318. result.y = cartesian.y;
  1319. result.z = cartesian.z;
  1320. return result;
  1321. };
  1322. /**
  1323. * Creates a Cartesian3 instance from an existing Cartesian4. This simply takes the
  1324. * x, y, and z properties of the Cartesian4 and drops w.
  1325. * @function
  1326. *
  1327. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian3 instance from.
  1328. * @param {Cartesian3} [result] The object onto which to store the result.
  1329. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1330. */
  1331. Cartesian3.fromCartesian4 = Cartesian3.clone;
  1332. /**
  1333. * The number of elements used to pack the object into an array.
  1334. * @type {Number}
  1335. */
  1336. Cartesian3.packedLength = 3;
  1337. /**
  1338. * Stores the provided instance into the provided array.
  1339. *
  1340. * @param {Cartesian3} value The value to pack.
  1341. * @param {Number[]} array The array to pack into.
  1342. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  1343. *
  1344. * @returns {Number[]} The array that was packed into
  1345. */
  1346. Cartesian3.pack = function(value, array, startingIndex) {
  1347. Check.typeOf.object(value, 'value');
  1348. Check.defined(array, 'array');
  1349. startingIndex = defaultValue(startingIndex, 0);
  1350. array[startingIndex++] = value.x;
  1351. array[startingIndex++] = value.y;
  1352. array[startingIndex] = value.z;
  1353. return array;
  1354. };
  1355. /**
  1356. * Retrieves an instance from a packed array.
  1357. *
  1358. * @param {Number[]} array The packed array.
  1359. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  1360. * @param {Cartesian3} [result] The object into which to store the result.
  1361. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1362. */
  1363. Cartesian3.unpack = function(array, startingIndex, result) {
  1364. Check.defined(array, 'array');
  1365. startingIndex = defaultValue(startingIndex, 0);
  1366. if (!defined(result)) {
  1367. result = new Cartesian3();
  1368. }
  1369. result.x = array[startingIndex++];
  1370. result.y = array[startingIndex++];
  1371. result.z = array[startingIndex];
  1372. return result;
  1373. };
  1374. /**
  1375. * Flattens an array of Cartesian3s into an array of components.
  1376. *
  1377. * @param {Cartesian3[]} array The array of cartesians to pack.
  1378. * @param {Number[]} result The array onto which to store the result.
  1379. * @returns {Number[]} The packed array.
  1380. */
  1381. Cartesian3.packArray = function(array, result) {
  1382. Check.defined(array, 'array');
  1383. var length = array.length;
  1384. if (!defined(result)) {
  1385. result = new Array(length * 3);
  1386. } else {
  1387. result.length = length * 3;
  1388. }
  1389. for (var i = 0; i < length; ++i) {
  1390. Cartesian3.pack(array[i], result, i * 3);
  1391. }
  1392. return result;
  1393. };
  1394. /**
  1395. * Unpacks an array of cartesian components into an array of Cartesian3s.
  1396. *
  1397. * @param {Number[]} array The array of components to unpack.
  1398. * @param {Cartesian3[]} result The array onto which to store the result.
  1399. * @returns {Cartesian3[]} The unpacked array.
  1400. */
  1401. Cartesian3.unpackArray = function(array, result) {
  1402. Check.defined(array, 'array');
  1403. Check.numeric.minimum(array.length, 3);
  1404. if (array.length % 3 !== 0) {
  1405. throw new DeveloperError('array length must be a multiple of 3.');
  1406. }
  1407. var length = array.length;
  1408. if (!defined(result)) {
  1409. result = new Array(length / 3);
  1410. } else {
  1411. result.length = length / 3;
  1412. }
  1413. for (var i = 0; i < length; i += 3) {
  1414. var index = i / 3;
  1415. result[index] = Cartesian3.unpack(array, i, result[index]);
  1416. }
  1417. return result;
  1418. };
  1419. /**
  1420. * Creates a Cartesian3 from three consecutive elements in an array.
  1421. * @function
  1422. *
  1423. * @param {Number[]} array The array whose three consecutive elements correspond to the x, y, and z components, respectively.
  1424. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  1425. * @param {Cartesian3} [result] The object onto which to store the result.
  1426. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  1427. *
  1428. * @example
  1429. * // Create a Cartesian3 with (1.0, 2.0, 3.0)
  1430. * var v = [1.0, 2.0, 3.0];
  1431. * var p = Cesium.Cartesian3.fromArray(v);
  1432. *
  1433. * // Create a Cartesian3 with (1.0, 2.0, 3.0) using an offset into an array
  1434. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0];
  1435. * var p2 = Cesium.Cartesian3.fromArray(v2, 2);
  1436. */
  1437. Cartesian3.fromArray = Cartesian3.unpack;
  1438. /**
  1439. * Computes the value of the maximum component for the supplied Cartesian.
  1440. *
  1441. * @param {Cartesian3} cartesian The cartesian to use.
  1442. * @returns {Number} The value of the maximum component.
  1443. */
  1444. Cartesian3.maximumComponent = function(cartesian) {
  1445. Check.typeOf.object(cartesian, 'cartesian');
  1446. return Math.max(cartesian.x, cartesian.y, cartesian.z);
  1447. };
  1448. /**
  1449. * Computes the value of the minimum component for the supplied Cartesian.
  1450. *
  1451. * @param {Cartesian3} cartesian The cartesian to use.
  1452. * @returns {Number} The value of the minimum component.
  1453. */
  1454. Cartesian3.minimumComponent = function(cartesian) {
  1455. Check.typeOf.object(cartesian, 'cartesian');
  1456. return Math.min(cartesian.x, cartesian.y, cartesian.z);
  1457. };
  1458. /**
  1459. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  1460. *
  1461. * @param {Cartesian3} first A cartesian to compare.
  1462. * @param {Cartesian3} second A cartesian to compare.
  1463. * @param {Cartesian3} result The object into which to store the result.
  1464. * @returns {Cartesian3} A cartesian with the minimum components.
  1465. */
  1466. Cartesian3.minimumByComponent = function(first, second, result) {
  1467. Check.typeOf.object(first, 'first');
  1468. Check.typeOf.object(second, 'second');
  1469. Check.typeOf.object(result, 'result');
  1470. result.x = Math.min(first.x, second.x);
  1471. result.y = Math.min(first.y, second.y);
  1472. result.z = Math.min(first.z, second.z);
  1473. return result;
  1474. };
  1475. /**
  1476. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  1477. *
  1478. * @param {Cartesian3} first A cartesian to compare.
  1479. * @param {Cartesian3} second A cartesian to compare.
  1480. * @param {Cartesian3} result The object into which to store the result.
  1481. * @returns {Cartesian3} A cartesian with the maximum components.
  1482. */
  1483. Cartesian3.maximumByComponent = function(first, second, result) {
  1484. Check.typeOf.object(first, 'first');
  1485. Check.typeOf.object(second, 'second');
  1486. Check.typeOf.object(result, 'result');
  1487. result.x = Math.max(first.x, second.x);
  1488. result.y = Math.max(first.y, second.y);
  1489. result.z = Math.max(first.z, second.z);
  1490. return result;
  1491. };
  1492. /**
  1493. * Computes the provided Cartesian's squared magnitude.
  1494. *
  1495. * @param {Cartesian3} cartesian The Cartesian instance whose squared magnitude is to be computed.
  1496. * @returns {Number} The squared magnitude.
  1497. */
  1498. Cartesian3.magnitudeSquared = function(cartesian) {
  1499. Check.typeOf.object(cartesian, 'cartesian');
  1500. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z;
  1501. };
  1502. /**
  1503. * Computes the Cartesian's magnitude (length).
  1504. *
  1505. * @param {Cartesian3} cartesian The Cartesian instance whose magnitude is to be computed.
  1506. * @returns {Number} The magnitude.
  1507. */
  1508. Cartesian3.magnitude = function(cartesian) {
  1509. return Math.sqrt(Cartesian3.magnitudeSquared(cartesian));
  1510. };
  1511. var distanceScratch = new Cartesian3();
  1512. /**
  1513. * Computes the distance between two points.
  1514. *
  1515. * @param {Cartesian3} left The first point to compute the distance from.
  1516. * @param {Cartesian3} right The second point to compute the distance to.
  1517. * @returns {Number} The distance between two points.
  1518. *
  1519. * @example
  1520. * // Returns 1.0
  1521. * var d = Cesium.Cartesian3.distance(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(2.0, 0.0, 0.0));
  1522. */
  1523. Cartesian3.distance = function(left, right) {
  1524. Check.typeOf.object(left, 'left');
  1525. Check.typeOf.object(right, 'right');
  1526. Cartesian3.subtract(left, right, distanceScratch);
  1527. return Cartesian3.magnitude(distanceScratch);
  1528. };
  1529. /**
  1530. * Computes the squared distance between two points. Comparing squared distances
  1531. * using this function is more efficient than comparing distances using {@link Cartesian3#distance}.
  1532. *
  1533. * @param {Cartesian3} left The first point to compute the distance from.
  1534. * @param {Cartesian3} right The second point to compute the distance to.
  1535. * @returns {Number} The distance between two points.
  1536. *
  1537. * @example
  1538. * // Returns 4.0, not 2.0
  1539. * var d = Cesium.Cartesian3.distanceSquared(new Cesium.Cartesian3(1.0, 0.0, 0.0), new Cesium.Cartesian3(3.0, 0.0, 0.0));
  1540. */
  1541. Cartesian3.distanceSquared = function(left, right) {
  1542. Check.typeOf.object(left, 'left');
  1543. Check.typeOf.object(right, 'right');
  1544. Cartesian3.subtract(left, right, distanceScratch);
  1545. return Cartesian3.magnitudeSquared(distanceScratch);
  1546. };
  1547. /**
  1548. * Computes the normalized form of the supplied Cartesian.
  1549. *
  1550. * @param {Cartesian3} cartesian The Cartesian to be normalized.
  1551. * @param {Cartesian3} result The object onto which to store the result.
  1552. * @returns {Cartesian3} The modified result parameter.
  1553. */
  1554. Cartesian3.normalize = function(cartesian, result) {
  1555. Check.typeOf.object(cartesian, 'cartesian');
  1556. Check.typeOf.object(result, 'result');
  1557. var magnitude = Cartesian3.magnitude(cartesian);
  1558. result.x = cartesian.x / magnitude;
  1559. result.y = cartesian.y / magnitude;
  1560. result.z = cartesian.z / magnitude;
  1561. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z)) {
  1562. throw new DeveloperError('normalized result is not a number');
  1563. }
  1564. return result;
  1565. };
  1566. /**
  1567. * Computes the dot (scalar) product of two Cartesians.
  1568. *
  1569. * @param {Cartesian3} left The first Cartesian.
  1570. * @param {Cartesian3} right The second Cartesian.
  1571. * @returns {Number} The dot product.
  1572. */
  1573. Cartesian3.dot = function(left, right) {
  1574. Check.typeOf.object(left, 'left');
  1575. Check.typeOf.object(right, 'right');
  1576. return left.x * right.x + left.y * right.y + left.z * right.z;
  1577. };
  1578. /**
  1579. * Computes the componentwise product of two Cartesians.
  1580. *
  1581. * @param {Cartesian3} left The first Cartesian.
  1582. * @param {Cartesian3} right The second Cartesian.
  1583. * @param {Cartesian3} result The object onto which to store the result.
  1584. * @returns {Cartesian3} The modified result parameter.
  1585. */
  1586. Cartesian3.multiplyComponents = function(left, right, result) {
  1587. Check.typeOf.object(left, 'left');
  1588. Check.typeOf.object(right, 'right');
  1589. Check.typeOf.object(result, 'result');
  1590. result.x = left.x * right.x;
  1591. result.y = left.y * right.y;
  1592. result.z = left.z * right.z;
  1593. return result;
  1594. };
  1595. /**
  1596. * Computes the componentwise quotient of two Cartesians.
  1597. *
  1598. * @param {Cartesian3} left The first Cartesian.
  1599. * @param {Cartesian3} right The second Cartesian.
  1600. * @param {Cartesian3} result The object onto which to store the result.
  1601. * @returns {Cartesian3} The modified result parameter.
  1602. */
  1603. Cartesian3.divideComponents = function(left, right, result) {
  1604. if (!defined(left)) {
  1605. throw new DeveloperError('left is required');
  1606. }
  1607. if (!defined(right)) {
  1608. throw new DeveloperError('right is required');
  1609. }
  1610. if (!defined(result)) {
  1611. throw new DeveloperError('result is required');
  1612. }
  1613. result.x = left.x / right.x;
  1614. result.y = left.y / right.y;
  1615. result.z = left.z / right.z;
  1616. return result;
  1617. };
  1618. /**
  1619. * Computes the componentwise sum of two Cartesians.
  1620. *
  1621. * @param {Cartesian3} left The first Cartesian.
  1622. * @param {Cartesian3} right The second Cartesian.
  1623. * @param {Cartesian3} result The object onto which to store the result.
  1624. * @returns {Cartesian3} The modified result parameter.
  1625. */
  1626. Cartesian3.add = function(left, right, result) {
  1627. Check.typeOf.object(left, 'left');
  1628. Check.typeOf.object(right, 'right');
  1629. Check.typeOf.object(result, 'result');
  1630. result.x = left.x + right.x;
  1631. result.y = left.y + right.y;
  1632. result.z = left.z + right.z;
  1633. return result;
  1634. };
  1635. /**
  1636. * Computes the componentwise difference of two Cartesians.
  1637. *
  1638. * @param {Cartesian3} left The first Cartesian.
  1639. * @param {Cartesian3} right The second Cartesian.
  1640. * @param {Cartesian3} result The object onto which to store the result.
  1641. * @returns {Cartesian3} The modified result parameter.
  1642. */
  1643. Cartesian3.subtract = function(left, right, result) {
  1644. Check.typeOf.object(left, 'left');
  1645. Check.typeOf.object(right, 'right');
  1646. Check.typeOf.object(result, 'result');
  1647. result.x = left.x - right.x;
  1648. result.y = left.y - right.y;
  1649. result.z = left.z - right.z;
  1650. return result;
  1651. };
  1652. /**
  1653. * Multiplies the provided Cartesian componentwise by the provided scalar.
  1654. *
  1655. * @param {Cartesian3} cartesian The Cartesian to be scaled.
  1656. * @param {Number} scalar The scalar to multiply with.
  1657. * @param {Cartesian3} result The object onto which to store the result.
  1658. * @returns {Cartesian3} The modified result parameter.
  1659. */
  1660. Cartesian3.multiplyByScalar = function(cartesian, scalar, result) {
  1661. Check.typeOf.object(cartesian, 'cartesian');
  1662. Check.typeOf.number(scalar, 'scalar');
  1663. Check.typeOf.object(result, 'result');
  1664. result.x = cartesian.x * scalar;
  1665. result.y = cartesian.y * scalar;
  1666. result.z = cartesian.z * scalar;
  1667. return result;
  1668. };
  1669. /**
  1670. * Divides the provided Cartesian componentwise by the provided scalar.
  1671. *
  1672. * @param {Cartesian3} cartesian The Cartesian to be divided.
  1673. * @param {Number} scalar The scalar to divide by.
  1674. * @param {Cartesian3} result The object onto which to store the result.
  1675. * @returns {Cartesian3} The modified result parameter.
  1676. */
  1677. Cartesian3.divideByScalar = function(cartesian, scalar, result) {
  1678. Check.typeOf.object(cartesian, 'cartesian');
  1679. Check.typeOf.number(scalar, 'scalar');
  1680. Check.typeOf.object(result, 'result');
  1681. result.x = cartesian.x / scalar;
  1682. result.y = cartesian.y / scalar;
  1683. result.z = cartesian.z / scalar;
  1684. return result;
  1685. };
  1686. /**
  1687. * Negates the provided Cartesian.
  1688. *
  1689. * @param {Cartesian3} cartesian The Cartesian to be negated.
  1690. * @param {Cartesian3} result The object onto which to store the result.
  1691. * @returns {Cartesian3} The modified result parameter.
  1692. */
  1693. Cartesian3.negate = function(cartesian, result) {
  1694. Check.typeOf.object(cartesian, 'cartesian');
  1695. Check.typeOf.object(result, 'result');
  1696. result.x = -cartesian.x;
  1697. result.y = -cartesian.y;
  1698. result.z = -cartesian.z;
  1699. return result;
  1700. };
  1701. /**
  1702. * Computes the absolute value of the provided Cartesian.
  1703. *
  1704. * @param {Cartesian3} cartesian The Cartesian whose absolute value is to be computed.
  1705. * @param {Cartesian3} result The object onto which to store the result.
  1706. * @returns {Cartesian3} The modified result parameter.
  1707. */
  1708. Cartesian3.abs = function(cartesian, result) {
  1709. Check.typeOf.object(cartesian, 'cartesian');
  1710. Check.typeOf.object(result, 'result');
  1711. result.x = Math.abs(cartesian.x);
  1712. result.y = Math.abs(cartesian.y);
  1713. result.z = Math.abs(cartesian.z);
  1714. return result;
  1715. };
  1716. var lerpScratch = new Cartesian3();
  1717. /**
  1718. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  1719. *
  1720. * @param {Cartesian3} start The value corresponding to t at 0.0.
  1721. * @param {Cartesian3} end The value corresponding to t at 1.0.
  1722. * @param {Number} t The point along t at which to interpolate.
  1723. * @param {Cartesian3} result The object onto which to store the result.
  1724. * @returns {Cartesian3} The modified result parameter.
  1725. */
  1726. Cartesian3.lerp = function(start, end, t, result) {
  1727. Check.typeOf.object(start, 'start');
  1728. Check.typeOf.object(end, 'end');
  1729. Check.typeOf.number(t, 't');
  1730. Check.typeOf.object(result, 'result');
  1731. Cartesian3.multiplyByScalar(end, t, lerpScratch);
  1732. result = Cartesian3.multiplyByScalar(start, 1.0 - t, result);
  1733. return Cartesian3.add(lerpScratch, result, result);
  1734. };
  1735. var angleBetweenScratch = new Cartesian3();
  1736. var angleBetweenScratch2 = new Cartesian3();
  1737. /**
  1738. * Returns the angle, in radians, between the provided Cartesians.
  1739. *
  1740. * @param {Cartesian3} left The first Cartesian.
  1741. * @param {Cartesian3} right The second Cartesian.
  1742. * @returns {Number} The angle between the Cartesians.
  1743. */
  1744. Cartesian3.angleBetween = function(left, right) {
  1745. Check.typeOf.object(left, 'left');
  1746. Check.typeOf.object(right, 'right');
  1747. Cartesian3.normalize(left, angleBetweenScratch);
  1748. Cartesian3.normalize(right, angleBetweenScratch2);
  1749. var cosine = Cartesian3.dot(angleBetweenScratch, angleBetweenScratch2);
  1750. var sine = Cartesian3.magnitude(Cartesian3.cross(angleBetweenScratch, angleBetweenScratch2, angleBetweenScratch));
  1751. return Math.atan2(sine, cosine);
  1752. };
  1753. var mostOrthogonalAxisScratch = new Cartesian3();
  1754. /**
  1755. * Returns the axis that is most orthogonal to the provided Cartesian.
  1756. *
  1757. * @param {Cartesian3} cartesian The Cartesian on which to find the most orthogonal axis.
  1758. * @param {Cartesian3} result The object onto which to store the result.
  1759. * @returns {Cartesian3} The most orthogonal axis.
  1760. */
  1761. Cartesian3.mostOrthogonalAxis = function(cartesian, result) {
  1762. Check.typeOf.object(cartesian, 'cartesian');
  1763. Check.typeOf.object(result, 'result');
  1764. var f = Cartesian3.normalize(cartesian, mostOrthogonalAxisScratch);
  1765. Cartesian3.abs(f, f);
  1766. if (f.x <= f.y) {
  1767. if (f.x <= f.z) {
  1768. result = Cartesian3.clone(Cartesian3.UNIT_X, result);
  1769. } else {
  1770. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  1771. }
  1772. } else {
  1773. if (f.y <= f.z) {
  1774. result = Cartesian3.clone(Cartesian3.UNIT_Y, result);
  1775. } else {
  1776. result = Cartesian3.clone(Cartesian3.UNIT_Z, result);
  1777. }
  1778. }
  1779. return result;
  1780. };
  1781. /**
  1782. * Compares the provided Cartesians componentwise and returns
  1783. * <code>true</code> if they are equal, <code>false</code> otherwise.
  1784. *
  1785. * @param {Cartesian3} [left] The first Cartesian.
  1786. * @param {Cartesian3} [right] The second Cartesian.
  1787. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  1788. */
  1789. Cartesian3.equals = function(left, right) {
  1790. return (left === right) ||
  1791. ((defined(left)) &&
  1792. (defined(right)) &&
  1793. (left.x === right.x) &&
  1794. (left.y === right.y) &&
  1795. (left.z === right.z));
  1796. };
  1797. /**
  1798. * @private
  1799. */
  1800. Cartesian3.equalsArray = function(cartesian, array, offset) {
  1801. return cartesian.x === array[offset] &&
  1802. cartesian.y === array[offset + 1] &&
  1803. cartesian.z === array[offset + 2];
  1804. };
  1805. /**
  1806. * Compares the provided Cartesians componentwise and returns
  1807. * <code>true</code> if they pass an absolute or relative tolerance test,
  1808. * <code>false</code> otherwise.
  1809. *
  1810. * @param {Cartesian3} [left] The first Cartesian.
  1811. * @param {Cartesian3} [right] The second Cartesian.
  1812. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  1813. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  1814. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  1815. */
  1816. Cartesian3.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  1817. return (left === right) ||
  1818. (defined(left) &&
  1819. defined(right) &&
  1820. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  1821. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  1822. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon));
  1823. };
  1824. /**
  1825. * Computes the cross (outer) product of two Cartesians.
  1826. *
  1827. * @param {Cartesian3} left The first Cartesian.
  1828. * @param {Cartesian3} right The second Cartesian.
  1829. * @param {Cartesian3} result The object onto which to store the result.
  1830. * @returns {Cartesian3} The cross product.
  1831. */
  1832. Cartesian3.cross = function(left, right, result) {
  1833. Check.typeOf.object(left, 'left');
  1834. Check.typeOf.object(right, 'right');
  1835. Check.typeOf.object(result, 'result');
  1836. var leftX = left.x;
  1837. var leftY = left.y;
  1838. var leftZ = left.z;
  1839. var rightX = right.x;
  1840. var rightY = right.y;
  1841. var rightZ = right.z;
  1842. var x = leftY * rightZ - leftZ * rightY;
  1843. var y = leftZ * rightX - leftX * rightZ;
  1844. var z = leftX * rightY - leftY * rightX;
  1845. result.x = x;
  1846. result.y = y;
  1847. result.z = z;
  1848. return result;
  1849. };
  1850. /**
  1851. * Returns a Cartesian3 position from longitude and latitude values given in degrees.
  1852. *
  1853. * @param {Number} longitude The longitude, in degrees
  1854. * @param {Number} latitude The latitude, in degrees
  1855. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  1856. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1857. * @param {Cartesian3} [result] The object onto which to store the result.
  1858. * @returns {Cartesian3} The position
  1859. *
  1860. * @example
  1861. * var position = Cesium.Cartesian3.fromDegrees(-115.0, 37.0);
  1862. */
  1863. Cartesian3.fromDegrees = function(longitude, latitude, height, ellipsoid, result) {
  1864. Check.typeOf.number(longitude, 'longitude');
  1865. Check.typeOf.number(latitude, 'latitude');
  1866. longitude = CesiumMath.toRadians(longitude);
  1867. latitude = CesiumMath.toRadians(latitude);
  1868. return Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result);
  1869. };
  1870. var scratchN = new Cartesian3();
  1871. var scratchK = new Cartesian3();
  1872. var wgs84RadiiSquared = new Cartesian3(6378137.0 * 6378137.0, 6378137.0 * 6378137.0, 6356752.3142451793 * 6356752.3142451793);
  1873. /**
  1874. * Returns a Cartesian3 position from longitude and latitude values given in radians.
  1875. *
  1876. * @param {Number} longitude The longitude, in radians
  1877. * @param {Number} latitude The latitude, in radians
  1878. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  1879. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1880. * @param {Cartesian3} [result] The object onto which to store the result.
  1881. * @returns {Cartesian3} The position
  1882. *
  1883. * @example
  1884. * var position = Cesium.Cartesian3.fromRadians(-2.007, 0.645);
  1885. */
  1886. Cartesian3.fromRadians = function(longitude, latitude, height, ellipsoid, result) {
  1887. Check.typeOf.number(longitude, 'longitude');
  1888. Check.typeOf.number(latitude, 'latitude');
  1889. height = defaultValue(height, 0.0);
  1890. var radiiSquared = defined(ellipsoid) ? ellipsoid.radiiSquared : wgs84RadiiSquared;
  1891. var cosLatitude = Math.cos(latitude);
  1892. scratchN.x = cosLatitude * Math.cos(longitude);
  1893. scratchN.y = cosLatitude * Math.sin(longitude);
  1894. scratchN.z = Math.sin(latitude);
  1895. scratchN = Cartesian3.normalize(scratchN, scratchN);
  1896. Cartesian3.multiplyComponents(radiiSquared, scratchN, scratchK);
  1897. var gamma = Math.sqrt(Cartesian3.dot(scratchN, scratchK));
  1898. scratchK = Cartesian3.divideByScalar(scratchK, gamma, scratchK);
  1899. scratchN = Cartesian3.multiplyByScalar(scratchN, height, scratchN);
  1900. if (!defined(result)) {
  1901. result = new Cartesian3();
  1902. }
  1903. return Cartesian3.add(scratchK, scratchN, result);
  1904. };
  1905. /**
  1906. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in degrees.
  1907. *
  1908. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  1909. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  1910. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1911. * @returns {Cartesian3[]} The array of positions.
  1912. *
  1913. * @example
  1914. * var positions = Cesium.Cartesian3.fromDegreesArray([-115.0, 37.0, -107.0, 33.0]);
  1915. */
  1916. Cartesian3.fromDegreesArray = function(coordinates, ellipsoid, result) {
  1917. Check.defined(coordinates, 'coordinates');
  1918. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  1919. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  1920. }
  1921. var length = coordinates.length;
  1922. if (!defined(result)) {
  1923. result = new Array(length / 2);
  1924. } else {
  1925. result.length = length / 2;
  1926. }
  1927. for (var i = 0; i < length; i += 2) {
  1928. var longitude = coordinates[i];
  1929. var latitude = coordinates[i + 1];
  1930. var index = i / 2;
  1931. result[index] = Cartesian3.fromDegrees(longitude, latitude, 0, ellipsoid, result[index]);
  1932. }
  1933. return result;
  1934. };
  1935. /**
  1936. * Returns an array of Cartesian3 positions given an array of longitude and latitude values given in radians.
  1937. *
  1938. * @param {Number[]} coordinates A list of longitude and latitude values. Values alternate [longitude, latitude, longitude, latitude...].
  1939. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the coordinates lie.
  1940. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1941. * @returns {Cartesian3[]} The array of positions.
  1942. *
  1943. * @example
  1944. * var positions = Cesium.Cartesian3.fromRadiansArray([-2.007, 0.645, -1.867, .575]);
  1945. */
  1946. Cartesian3.fromRadiansArray = function(coordinates, ellipsoid, result) {
  1947. Check.defined(coordinates, 'coordinates');
  1948. if (coordinates.length < 2 || coordinates.length % 2 !== 0) {
  1949. throw new DeveloperError('the number of coordinates must be a multiple of 2 and at least 2');
  1950. }
  1951. var length = coordinates.length;
  1952. if (!defined(result)) {
  1953. result = new Array(length / 2);
  1954. } else {
  1955. result.length = length / 2;
  1956. }
  1957. for (var i = 0; i < length; i += 2) {
  1958. var longitude = coordinates[i];
  1959. var latitude = coordinates[i + 1];
  1960. var index = i / 2;
  1961. result[index] = Cartesian3.fromRadians(longitude, latitude, 0, ellipsoid, result[index]);
  1962. }
  1963. return result;
  1964. };
  1965. /**
  1966. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in degrees.
  1967. *
  1968. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  1969. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  1970. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  1971. * @returns {Cartesian3[]} The array of positions.
  1972. *
  1973. * @example
  1974. * var positions = Cesium.Cartesian3.fromDegreesArrayHeights([-115.0, 37.0, 100000.0, -107.0, 33.0, 150000.0]);
  1975. */
  1976. Cartesian3.fromDegreesArrayHeights = function(coordinates, ellipsoid, result) {
  1977. Check.defined(coordinates, 'coordinates');
  1978. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  1979. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  1980. }
  1981. var length = coordinates.length;
  1982. if (!defined(result)) {
  1983. result = new Array(length / 3);
  1984. } else {
  1985. result.length = length / 3;
  1986. }
  1987. for (var i = 0; i < length; i += 3) {
  1988. var longitude = coordinates[i];
  1989. var latitude = coordinates[i + 1];
  1990. var height = coordinates[i + 2];
  1991. var index = i / 3;
  1992. result[index] = Cartesian3.fromDegrees(longitude, latitude, height, ellipsoid, result[index]);
  1993. }
  1994. return result;
  1995. };
  1996. /**
  1997. * Returns an array of Cartesian3 positions given an array of longitude, latitude and height values where longitude and latitude are given in radians.
  1998. *
  1999. * @param {Number[]} coordinates A list of longitude, latitude and height values. Values alternate [longitude, latitude, height, longitude, latitude, height...].
  2000. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2001. * @param {Cartesian3[]} [result] An array of Cartesian3 objects to store the result.
  2002. * @returns {Cartesian3[]} The array of positions.
  2003. *
  2004. * @example
  2005. * var positions = Cesium.Cartesian3.fromRadiansArrayHeights([-2.007, 0.645, 100000.0, -1.867, .575, 150000.0]);
  2006. */
  2007. Cartesian3.fromRadiansArrayHeights = function(coordinates, ellipsoid, result) {
  2008. Check.defined(coordinates, 'coordinates');
  2009. if (coordinates.length < 3 || coordinates.length % 3 !== 0) {
  2010. throw new DeveloperError('the number of coordinates must be a multiple of 3 and at least 3');
  2011. }
  2012. var length = coordinates.length;
  2013. if (!defined(result)) {
  2014. result = new Array(length / 3);
  2015. } else {
  2016. result.length = length / 3;
  2017. }
  2018. for (var i = 0; i < length; i += 3) {
  2019. var longitude = coordinates[i];
  2020. var latitude = coordinates[i + 1];
  2021. var height = coordinates[i + 2];
  2022. var index = i / 3;
  2023. result[index] = Cartesian3.fromRadians(longitude, latitude, height, ellipsoid, result[index]);
  2024. }
  2025. return result;
  2026. };
  2027. /**
  2028. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 0.0).
  2029. *
  2030. * @type {Cartesian3}
  2031. * @constant
  2032. */
  2033. Cartesian3.ZERO = freezeObject(new Cartesian3(0.0, 0.0, 0.0));
  2034. /**
  2035. * An immutable Cartesian3 instance initialized to (1.0, 0.0, 0.0).
  2036. *
  2037. * @type {Cartesian3}
  2038. * @constant
  2039. */
  2040. Cartesian3.UNIT_X = freezeObject(new Cartesian3(1.0, 0.0, 0.0));
  2041. /**
  2042. * An immutable Cartesian3 instance initialized to (0.0, 1.0, 0.0).
  2043. *
  2044. * @type {Cartesian3}
  2045. * @constant
  2046. */
  2047. Cartesian3.UNIT_Y = freezeObject(new Cartesian3(0.0, 1.0, 0.0));
  2048. /**
  2049. * An immutable Cartesian3 instance initialized to (0.0, 0.0, 1.0).
  2050. *
  2051. * @type {Cartesian3}
  2052. * @constant
  2053. */
  2054. Cartesian3.UNIT_Z = freezeObject(new Cartesian3(0.0, 0.0, 1.0));
  2055. /**
  2056. * Duplicates this Cartesian3 instance.
  2057. *
  2058. * @param {Cartesian3} [result] The object onto which to store the result.
  2059. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  2060. */
  2061. Cartesian3.prototype.clone = function(result) {
  2062. return Cartesian3.clone(this, result);
  2063. };
  2064. /**
  2065. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2066. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2067. *
  2068. * @param {Cartesian3} [right] The right hand side Cartesian.
  2069. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  2070. */
  2071. Cartesian3.prototype.equals = function(right) {
  2072. return Cartesian3.equals(this, right);
  2073. };
  2074. /**
  2075. * Compares this Cartesian against the provided Cartesian componentwise and returns
  2076. * <code>true</code> if they pass an absolute or relative tolerance test,
  2077. * <code>false</code> otherwise.
  2078. *
  2079. * @param {Cartesian3} [right] The right hand side Cartesian.
  2080. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  2081. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  2082. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  2083. */
  2084. Cartesian3.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  2085. return Cartesian3.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  2086. };
  2087. /**
  2088. * Creates a string representing this Cartesian in the format '(x, y, z)'.
  2089. *
  2090. * @returns {String} A string representing this Cartesian in the format '(x, y, z)'.
  2091. */
  2092. Cartesian3.prototype.toString = function() {
  2093. return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
  2094. };
  2095. return Cartesian3;
  2096. });
  2097. /*global define*/
  2098. define('Core/scaleToGeodeticSurface',[
  2099. './Cartesian3',
  2100. './defined',
  2101. './DeveloperError',
  2102. './Math'
  2103. ], function(
  2104. Cartesian3,
  2105. defined,
  2106. DeveloperError,
  2107. CesiumMath) {
  2108. 'use strict';
  2109. var scaleToGeodeticSurfaceIntersection = new Cartesian3();
  2110. var scaleToGeodeticSurfaceGradient = new Cartesian3();
  2111. /**
  2112. * Scales the provided Cartesian position along the geodetic surface normal
  2113. * so that it is on the surface of this ellipsoid. If the position is
  2114. * at the center of the ellipsoid, this function returns undefined.
  2115. *
  2116. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2117. * @param {Cartesian3} oneOverRadii One over radii of the ellipsoid.
  2118. * @param {Cartesian3} oneOverRadiiSquared One over radii squared of the ellipsoid.
  2119. * @param {Number} centerToleranceSquared Tolerance for closeness to the center.
  2120. * @param {Cartesian3} [result] The object onto which to store the result.
  2121. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  2122. *
  2123. * @exports scaleToGeodeticSurface
  2124. *
  2125. * @private
  2126. */
  2127. function scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, result) {
  2128. if (!defined(cartesian)) {
  2129. throw new DeveloperError('cartesian is required.');
  2130. }
  2131. if (!defined(oneOverRadii)) {
  2132. throw new DeveloperError('oneOverRadii is required.');
  2133. }
  2134. if (!defined(oneOverRadiiSquared)) {
  2135. throw new DeveloperError('oneOverRadiiSquared is required.');
  2136. }
  2137. if (!defined(centerToleranceSquared)) {
  2138. throw new DeveloperError('centerToleranceSquared is required.');
  2139. }
  2140. var positionX = cartesian.x;
  2141. var positionY = cartesian.y;
  2142. var positionZ = cartesian.z;
  2143. var oneOverRadiiX = oneOverRadii.x;
  2144. var oneOverRadiiY = oneOverRadii.y;
  2145. var oneOverRadiiZ = oneOverRadii.z;
  2146. var x2 = positionX * positionX * oneOverRadiiX * oneOverRadiiX;
  2147. var y2 = positionY * positionY * oneOverRadiiY * oneOverRadiiY;
  2148. var z2 = positionZ * positionZ * oneOverRadiiZ * oneOverRadiiZ;
  2149. // Compute the squared ellipsoid norm.
  2150. var squaredNorm = x2 + y2 + z2;
  2151. var ratio = Math.sqrt(1.0 / squaredNorm);
  2152. // As an initial approximation, assume that the radial intersection is the projection point.
  2153. var intersection = Cartesian3.multiplyByScalar(cartesian, ratio, scaleToGeodeticSurfaceIntersection);
  2154. // If the position is near the center, the iteration will not converge.
  2155. if (squaredNorm < centerToleranceSquared) {
  2156. return !isFinite(ratio) ? undefined : Cartesian3.clone(intersection, result);
  2157. }
  2158. var oneOverRadiiSquaredX = oneOverRadiiSquared.x;
  2159. var oneOverRadiiSquaredY = oneOverRadiiSquared.y;
  2160. var oneOverRadiiSquaredZ = oneOverRadiiSquared.z;
  2161. // Use the gradient at the intersection point in place of the true unit normal.
  2162. // The difference in magnitude will be absorbed in the multiplier.
  2163. var gradient = scaleToGeodeticSurfaceGradient;
  2164. gradient.x = intersection.x * oneOverRadiiSquaredX * 2.0;
  2165. gradient.y = intersection.y * oneOverRadiiSquaredY * 2.0;
  2166. gradient.z = intersection.z * oneOverRadiiSquaredZ * 2.0;
  2167. // Compute the initial guess at the normal vector multiplier, lambda.
  2168. var lambda = (1.0 - ratio) * Cartesian3.magnitude(cartesian) / (0.5 * Cartesian3.magnitude(gradient));
  2169. var correction = 0.0;
  2170. var func;
  2171. var denominator;
  2172. var xMultiplier;
  2173. var yMultiplier;
  2174. var zMultiplier;
  2175. var xMultiplier2;
  2176. var yMultiplier2;
  2177. var zMultiplier2;
  2178. var xMultiplier3;
  2179. var yMultiplier3;
  2180. var zMultiplier3;
  2181. do {
  2182. lambda -= correction;
  2183. xMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredX);
  2184. yMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredY);
  2185. zMultiplier = 1.0 / (1.0 + lambda * oneOverRadiiSquaredZ);
  2186. xMultiplier2 = xMultiplier * xMultiplier;
  2187. yMultiplier2 = yMultiplier * yMultiplier;
  2188. zMultiplier2 = zMultiplier * zMultiplier;
  2189. xMultiplier3 = xMultiplier2 * xMultiplier;
  2190. yMultiplier3 = yMultiplier2 * yMultiplier;
  2191. zMultiplier3 = zMultiplier2 * zMultiplier;
  2192. func = x2 * xMultiplier2 + y2 * yMultiplier2 + z2 * zMultiplier2 - 1.0;
  2193. // "denominator" here refers to the use of this expression in the velocity and acceleration
  2194. // computations in the sections to follow.
  2195. denominator = x2 * xMultiplier3 * oneOverRadiiSquaredX + y2 * yMultiplier3 * oneOverRadiiSquaredY + z2 * zMultiplier3 * oneOverRadiiSquaredZ;
  2196. var derivative = -2.0 * denominator;
  2197. correction = func / derivative;
  2198. } while (Math.abs(func) > CesiumMath.EPSILON12);
  2199. if (!defined(result)) {
  2200. return new Cartesian3(positionX * xMultiplier, positionY * yMultiplier, positionZ * zMultiplier);
  2201. }
  2202. result.x = positionX * xMultiplier;
  2203. result.y = positionY * yMultiplier;
  2204. result.z = positionZ * zMultiplier;
  2205. return result;
  2206. }
  2207. return scaleToGeodeticSurface;
  2208. });
  2209. /*global define*/
  2210. define('Core/Cartographic',[
  2211. './Cartesian3',
  2212. './defaultValue',
  2213. './defined',
  2214. './DeveloperError',
  2215. './freezeObject',
  2216. './Math',
  2217. './scaleToGeodeticSurface'
  2218. ], function(
  2219. Cartesian3,
  2220. defaultValue,
  2221. defined,
  2222. DeveloperError,
  2223. freezeObject,
  2224. CesiumMath,
  2225. scaleToGeodeticSurface) {
  2226. 'use strict';
  2227. /**
  2228. * A position defined by longitude, latitude, and height.
  2229. * @alias Cartographic
  2230. * @constructor
  2231. *
  2232. * @param {Number} [longitude=0.0] The longitude, in radians.
  2233. * @param {Number} [latitude=0.0] The latitude, in radians.
  2234. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2235. *
  2236. * @see Ellipsoid
  2237. */
  2238. function Cartographic(longitude, latitude, height) {
  2239. /**
  2240. * The longitude, in radians.
  2241. * @type {Number}
  2242. * @default 0.0
  2243. */
  2244. this.longitude = defaultValue(longitude, 0.0);
  2245. /**
  2246. * The latitude, in radians.
  2247. * @type {Number}
  2248. * @default 0.0
  2249. */
  2250. this.latitude = defaultValue(latitude, 0.0);
  2251. /**
  2252. * The height, in meters, above the ellipsoid.
  2253. * @type {Number}
  2254. * @default 0.0
  2255. */
  2256. this.height = defaultValue(height, 0.0);
  2257. }
  2258. /**
  2259. * Creates a new Cartographic instance from longitude and latitude
  2260. * specified in radians.
  2261. *
  2262. * @param {Number} longitude The longitude, in radians.
  2263. * @param {Number} latitude The latitude, in radians.
  2264. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2265. * @param {Cartographic} [result] The object onto which to store the result.
  2266. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2267. */
  2268. Cartographic.fromRadians = function(longitude, latitude, height, result) {
  2269. if (!defined(longitude)) {
  2270. throw new DeveloperError('longitude is required.');
  2271. }
  2272. if (!defined(latitude)) {
  2273. throw new DeveloperError('latitude is required.');
  2274. }
  2275. height = defaultValue(height, 0.0);
  2276. if (!defined(result)) {
  2277. return new Cartographic(longitude, latitude, height);
  2278. }
  2279. result.longitude = longitude;
  2280. result.latitude = latitude;
  2281. result.height = height;
  2282. return result;
  2283. };
  2284. /**
  2285. * Creates a new Cartographic instance from longitude and latitude
  2286. * specified in degrees. The values in the resulting object will
  2287. * be in radians.
  2288. *
  2289. * @param {Number} longitude The longitude, in degrees.
  2290. * @param {Number} latitude The latitude, in degrees.
  2291. * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
  2292. * @param {Cartographic} [result] The object onto which to store the result.
  2293. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2294. */
  2295. Cartographic.fromDegrees = function(longitude, latitude, height, result) {
  2296. if (!defined(longitude)) {
  2297. throw new DeveloperError('longitude is required.');
  2298. }
  2299. if (!defined(latitude)) {
  2300. throw new DeveloperError('latitude is required.');
  2301. }
  2302. longitude = CesiumMath.toRadians(longitude);
  2303. latitude = CesiumMath.toRadians(latitude);
  2304. return Cartographic.fromRadians(longitude, latitude, height, result);
  2305. };
  2306. var cartesianToCartographicN = new Cartesian3();
  2307. var cartesianToCartographicP = new Cartesian3();
  2308. var cartesianToCartographicH = new Cartesian3();
  2309. var wgs84OneOverRadii = new Cartesian3(1.0 / 6378137.0, 1.0 / 6378137.0, 1.0 / 6356752.3142451793);
  2310. var wgs84OneOverRadiiSquared = new Cartesian3(1.0 / (6378137.0 * 6378137.0), 1.0 / (6378137.0 * 6378137.0), 1.0 / (6356752.3142451793 * 6356752.3142451793));
  2311. var wgs84CenterToleranceSquared = CesiumMath.EPSILON1;
  2312. /**
  2313. * Creates a new Cartographic instance from a Cartesian position. The values in the
  2314. * resulting object will be in radians.
  2315. *
  2316. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  2317. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
  2318. * @param {Cartographic} [result] The object onto which to store the result.
  2319. * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
  2320. */
  2321. Cartographic.fromCartesian = function(cartesian, ellipsoid, result) {
  2322. var oneOverRadii = defined(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
  2323. var oneOverRadiiSquared = defined(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
  2324. var centerToleranceSquared = defined(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;
  2325. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  2326. var p = scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP);
  2327. if (!defined(p)) {
  2328. return undefined;
  2329. }
  2330. var n = Cartesian3.multiplyComponents(p, oneOverRadiiSquared, cartesianToCartographicN);
  2331. n = Cartesian3.normalize(n, n);
  2332. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  2333. var longitude = Math.atan2(n.y, n.x);
  2334. var latitude = Math.asin(n.z);
  2335. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  2336. if (!defined(result)) {
  2337. return new Cartographic(longitude, latitude, height);
  2338. }
  2339. result.longitude = longitude;
  2340. result.latitude = latitude;
  2341. result.height = height;
  2342. return result;
  2343. };
  2344. /**
  2345. * Duplicates a Cartographic instance.
  2346. *
  2347. * @param {Cartographic} cartographic The cartographic to duplicate.
  2348. * @param {Cartographic} [result] The object onto which to store the result.
  2349. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
  2350. */
  2351. Cartographic.clone = function(cartographic, result) {
  2352. if (!defined(cartographic)) {
  2353. return undefined;
  2354. }
  2355. if (!defined(result)) {
  2356. return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
  2357. }
  2358. result.longitude = cartographic.longitude;
  2359. result.latitude = cartographic.latitude;
  2360. result.height = cartographic.height;
  2361. return result;
  2362. };
  2363. /**
  2364. * Compares the provided cartographics componentwise and returns
  2365. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2366. *
  2367. * @param {Cartographic} [left] The first cartographic.
  2368. * @param {Cartographic} [right] The second cartographic.
  2369. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2370. */
  2371. Cartographic.equals = function(left, right) {
  2372. return (left === right) ||
  2373. ((defined(left)) &&
  2374. (defined(right)) &&
  2375. (left.longitude === right.longitude) &&
  2376. (left.latitude === right.latitude) &&
  2377. (left.height === right.height));
  2378. };
  2379. /**
  2380. * Compares the provided cartographics componentwise and returns
  2381. * <code>true</code> if they are within the provided epsilon,
  2382. * <code>false</code> otherwise.
  2383. *
  2384. * @param {Cartographic} [left] The first cartographic.
  2385. * @param {Cartographic} [right] The second cartographic.
  2386. * @param {Number} epsilon The epsilon to use for equality testing.
  2387. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2388. */
  2389. Cartographic.equalsEpsilon = function(left, right, epsilon) {
  2390. if (typeof epsilon !== 'number') {
  2391. throw new DeveloperError('epsilon is required and must be a number.');
  2392. }
  2393. return (left === right) ||
  2394. ((defined(left)) &&
  2395. (defined(right)) &&
  2396. (Math.abs(left.longitude - right.longitude) <= epsilon) &&
  2397. (Math.abs(left.latitude - right.latitude) <= epsilon) &&
  2398. (Math.abs(left.height - right.height) <= epsilon));
  2399. };
  2400. /**
  2401. * An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
  2402. *
  2403. * @type {Cartographic}
  2404. * @constant
  2405. */
  2406. Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));
  2407. /**
  2408. * Duplicates this instance.
  2409. *
  2410. * @param {Cartographic} [result] The object onto which to store the result.
  2411. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
  2412. */
  2413. Cartographic.prototype.clone = function(result) {
  2414. return Cartographic.clone(this, result);
  2415. };
  2416. /**
  2417. * Compares the provided against this cartographic componentwise and returns
  2418. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2419. *
  2420. * @param {Cartographic} [right] The second cartographic.
  2421. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  2422. */
  2423. Cartographic.prototype.equals = function(right) {
  2424. return Cartographic.equals(this, right);
  2425. };
  2426. /**
  2427. * Compares the provided against this cartographic componentwise and returns
  2428. * <code>true</code> if they are within the provided epsilon,
  2429. * <code>false</code> otherwise.
  2430. *
  2431. * @param {Cartographic} [right] The second cartographic.
  2432. * @param {Number} epsilon The epsilon to use for equality testing.
  2433. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  2434. */
  2435. Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
  2436. return Cartographic.equalsEpsilon(this, right, epsilon);
  2437. };
  2438. /**
  2439. * Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
  2440. *
  2441. * @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
  2442. */
  2443. Cartographic.prototype.toString = function() {
  2444. return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
  2445. };
  2446. return Cartographic;
  2447. });
  2448. /*global define*/
  2449. define('Core/defineProperties',[
  2450. './defined'
  2451. ], function(
  2452. defined) {
  2453. 'use strict';
  2454. var definePropertyWorks = (function() {
  2455. try {
  2456. return 'x' in Object.defineProperty({}, 'x', {});
  2457. } catch (e) {
  2458. return false;
  2459. }
  2460. })();
  2461. /**
  2462. * Defines properties on an object, using Object.defineProperties if available,
  2463. * otherwise returns the object unchanged. This function should be used in
  2464. * setup code to prevent errors from completely halting JavaScript execution
  2465. * in legacy browsers.
  2466. *
  2467. * @private
  2468. *
  2469. * @exports defineProperties
  2470. */
  2471. var defineProperties = Object.defineProperties;
  2472. if (!definePropertyWorks || !defined(defineProperties)) {
  2473. defineProperties = function(o) {
  2474. return o;
  2475. };
  2476. }
  2477. return defineProperties;
  2478. });
  2479. /*global define*/
  2480. define('Core/Ellipsoid',[
  2481. './Cartesian3',
  2482. './Cartographic',
  2483. './defaultValue',
  2484. './defined',
  2485. './defineProperties',
  2486. './DeveloperError',
  2487. './freezeObject',
  2488. './Math',
  2489. './scaleToGeodeticSurface'
  2490. ], function(
  2491. Cartesian3,
  2492. Cartographic,
  2493. defaultValue,
  2494. defined,
  2495. defineProperties,
  2496. DeveloperError,
  2497. freezeObject,
  2498. CesiumMath,
  2499. scaleToGeodeticSurface) {
  2500. 'use strict';
  2501. function initialize(ellipsoid, x, y, z) {
  2502. x = defaultValue(x, 0.0);
  2503. y = defaultValue(y, 0.0);
  2504. z = defaultValue(z, 0.0);
  2505. if (x < 0.0 || y < 0.0 || z < 0.0) {
  2506. throw new DeveloperError('All radii components must be greater than or equal to zero.');
  2507. }
  2508. ellipsoid._radii = new Cartesian3(x, y, z);
  2509. ellipsoid._radiiSquared = new Cartesian3(x * x,
  2510. y * y,
  2511. z * z);
  2512. ellipsoid._radiiToTheFourth = new Cartesian3(x * x * x * x,
  2513. y * y * y * y,
  2514. z * z * z * z);
  2515. ellipsoid._oneOverRadii = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / x,
  2516. y === 0.0 ? 0.0 : 1.0 / y,
  2517. z === 0.0 ? 0.0 : 1.0 / z);
  2518. ellipsoid._oneOverRadiiSquared = new Cartesian3(x === 0.0 ? 0.0 : 1.0 / (x * x),
  2519. y === 0.0 ? 0.0 : 1.0 / (y * y),
  2520. z === 0.0 ? 0.0 : 1.0 / (z * z));
  2521. ellipsoid._minimumRadius = Math.min(x, y, z);
  2522. ellipsoid._maximumRadius = Math.max(x, y, z);
  2523. ellipsoid._centerToleranceSquared = CesiumMath.EPSILON1;
  2524. if (ellipsoid._radiiSquared.z !== 0) {
  2525. ellipsoid._sqauredXOverSquaredZ = ellipsoid._radiiSquared.x / ellipsoid._radiiSquared.z;
  2526. }
  2527. }
  2528. /**
  2529. * A quadratic surface defined in Cartesian coordinates by the equation
  2530. * <code>(x / a)^2 + (y / b)^2 + (z / c)^2 = 1</code>. Primarily used
  2531. * by Cesium to represent the shape of planetary bodies.
  2532. *
  2533. * Rather than constructing this object directly, one of the provided
  2534. * constants is normally used.
  2535. * @alias Ellipsoid
  2536. * @constructor
  2537. *
  2538. * @param {Number} [x=0] The radius in the x direction.
  2539. * @param {Number} [y=0] The radius in the y direction.
  2540. * @param {Number} [z=0] The radius in the z direction.
  2541. *
  2542. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  2543. *
  2544. * @see Ellipsoid.fromCartesian3
  2545. * @see Ellipsoid.WGS84
  2546. * @see Ellipsoid.UNIT_SPHERE
  2547. */
  2548. function Ellipsoid(x, y, z) {
  2549. this._radii = undefined;
  2550. this._radiiSquared = undefined;
  2551. this._radiiToTheFourth = undefined;
  2552. this._oneOverRadii = undefined;
  2553. this._oneOverRadiiSquared = undefined;
  2554. this._minimumRadius = undefined;
  2555. this._maximumRadius = undefined;
  2556. this._centerToleranceSquared = undefined;
  2557. this._sqauredXOverSquaredZ = undefined;
  2558. initialize(this, x, y, z);
  2559. }
  2560. defineProperties(Ellipsoid.prototype, {
  2561. /**
  2562. * Gets the radii of the ellipsoid.
  2563. * @memberof Ellipsoid.prototype
  2564. * @type {Cartesian3}
  2565. * @readonly
  2566. */
  2567. radii : {
  2568. get: function() {
  2569. return this._radii;
  2570. }
  2571. },
  2572. /**
  2573. * Gets the squared radii of the ellipsoid.
  2574. * @memberof Ellipsoid.prototype
  2575. * @type {Cartesian3}
  2576. * @readonly
  2577. */
  2578. radiiSquared : {
  2579. get : function() {
  2580. return this._radiiSquared;
  2581. }
  2582. },
  2583. /**
  2584. * Gets the radii of the ellipsoid raise to the fourth power.
  2585. * @memberof Ellipsoid.prototype
  2586. * @type {Cartesian3}
  2587. * @readonly
  2588. */
  2589. radiiToTheFourth : {
  2590. get : function() {
  2591. return this._radiiToTheFourth;
  2592. }
  2593. },
  2594. /**
  2595. * Gets one over the radii of the ellipsoid.
  2596. * @memberof Ellipsoid.prototype
  2597. * @type {Cartesian3}
  2598. * @readonly
  2599. */
  2600. oneOverRadii : {
  2601. get : function() {
  2602. return this._oneOverRadii;
  2603. }
  2604. },
  2605. /**
  2606. * Gets one over the squared radii of the ellipsoid.
  2607. * @memberof Ellipsoid.prototype
  2608. * @type {Cartesian3}
  2609. * @readonly
  2610. */
  2611. oneOverRadiiSquared : {
  2612. get : function() {
  2613. return this._oneOverRadiiSquared;
  2614. }
  2615. },
  2616. /**
  2617. * Gets the minimum radius of the ellipsoid.
  2618. * @memberof Ellipsoid.prototype
  2619. * @type {Number}
  2620. * @readonly
  2621. */
  2622. minimumRadius : {
  2623. get : function() {
  2624. return this._minimumRadius;
  2625. }
  2626. },
  2627. /**
  2628. * Gets the maximum radius of the ellipsoid.
  2629. * @memberof Ellipsoid.prototype
  2630. * @type {Number}
  2631. * @readonly
  2632. */
  2633. maximumRadius : {
  2634. get : function() {
  2635. return this._maximumRadius;
  2636. }
  2637. }
  2638. });
  2639. /**
  2640. * Duplicates an Ellipsoid instance.
  2641. *
  2642. * @param {Ellipsoid} ellipsoid The ellipsoid to duplicate.
  2643. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  2644. * instance should be created.
  2645. * @returns {Ellipsoid} The cloned Ellipsoid. (Returns undefined if ellipsoid is undefined)
  2646. */
  2647. Ellipsoid.clone = function(ellipsoid, result) {
  2648. if (!defined(ellipsoid)) {
  2649. return undefined;
  2650. }
  2651. var radii = ellipsoid._radii;
  2652. if (!defined(result)) {
  2653. return new Ellipsoid(radii.x, radii.y, radii.z);
  2654. }
  2655. Cartesian3.clone(radii, result._radii);
  2656. Cartesian3.clone(ellipsoid._radiiSquared, result._radiiSquared);
  2657. Cartesian3.clone(ellipsoid._radiiToTheFourth, result._radiiToTheFourth);
  2658. Cartesian3.clone(ellipsoid._oneOverRadii, result._oneOverRadii);
  2659. Cartesian3.clone(ellipsoid._oneOverRadiiSquared, result._oneOverRadiiSquared);
  2660. result._minimumRadius = ellipsoid._minimumRadius;
  2661. result._maximumRadius = ellipsoid._maximumRadius;
  2662. result._centerToleranceSquared = ellipsoid._centerToleranceSquared;
  2663. return result;
  2664. };
  2665. /**
  2666. * Computes an Ellipsoid from a Cartesian specifying the radii in x, y, and z directions.
  2667. *
  2668. * @param {Cartesian3} [radii=Cartesian3.ZERO] The ellipsoid's radius in the x, y, and z directions.
  2669. * @returns {Ellipsoid} A new Ellipsoid instance.
  2670. *
  2671. * @exception {DeveloperError} All radii components must be greater than or equal to zero.
  2672. *
  2673. * @see Ellipsoid.WGS84
  2674. * @see Ellipsoid.UNIT_SPHERE
  2675. */
  2676. Ellipsoid.fromCartesian3 = function(cartesian, result) {
  2677. if (!defined(result)) {
  2678. result = new Ellipsoid();
  2679. }
  2680. if (!defined(cartesian)) {
  2681. return result;
  2682. }
  2683. initialize(result, cartesian.x, cartesian.y, cartesian.z);
  2684. return result;
  2685. };
  2686. /**
  2687. * An Ellipsoid instance initialized to the WGS84 standard.
  2688. *
  2689. * @type {Ellipsoid}
  2690. * @constant
  2691. */
  2692. Ellipsoid.WGS84 = freezeObject(new Ellipsoid(6378137.0, 6378137.0, 6356752.3142451793));
  2693. /**
  2694. * An Ellipsoid instance initialized to radii of (1.0, 1.0, 1.0).
  2695. *
  2696. * @type {Ellipsoid}
  2697. * @constant
  2698. */
  2699. Ellipsoid.UNIT_SPHERE = freezeObject(new Ellipsoid(1.0, 1.0, 1.0));
  2700. /**
  2701. * An Ellipsoid instance initialized to a sphere with the lunar radius.
  2702. *
  2703. * @type {Ellipsoid}
  2704. * @constant
  2705. */
  2706. Ellipsoid.MOON = freezeObject(new Ellipsoid(CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS, CesiumMath.LUNAR_RADIUS));
  2707. /**
  2708. * Duplicates an Ellipsoid instance.
  2709. *
  2710. * @param {Ellipsoid} [result] The object onto which to store the result, or undefined if a new
  2711. * instance should be created.
  2712. * @returns {Ellipsoid} The cloned Ellipsoid.
  2713. */
  2714. Ellipsoid.prototype.clone = function(result) {
  2715. return Ellipsoid.clone(this, result);
  2716. };
  2717. /**
  2718. * The number of elements used to pack the object into an array.
  2719. * @type {Number}
  2720. */
  2721. Ellipsoid.packedLength = Cartesian3.packedLength;
  2722. /**
  2723. * Stores the provided instance into the provided array.
  2724. *
  2725. * @param {Ellipsoid} value The value to pack.
  2726. * @param {Number[]} array The array to pack into.
  2727. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  2728. *
  2729. * @returns {Number[]} The array that was packed into
  2730. */
  2731. Ellipsoid.pack = function(value, array, startingIndex) {
  2732. if (!defined(value)) {
  2733. throw new DeveloperError('value is required');
  2734. }
  2735. if (!defined(array)) {
  2736. throw new DeveloperError('array is required');
  2737. }
  2738. startingIndex = defaultValue(startingIndex, 0);
  2739. Cartesian3.pack(value._radii, array, startingIndex);
  2740. return array;
  2741. };
  2742. /**
  2743. * Retrieves an instance from a packed array.
  2744. *
  2745. * @param {Number[]} array The packed array.
  2746. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  2747. * @param {Ellipsoid} [result] The object into which to store the result.
  2748. * @returns {Ellipsoid} The modified result parameter or a new Ellipsoid instance if one was not provided.
  2749. */
  2750. Ellipsoid.unpack = function(array, startingIndex, result) {
  2751. if (!defined(array)) {
  2752. throw new DeveloperError('array is required');
  2753. }
  2754. startingIndex = defaultValue(startingIndex, 0);
  2755. var radii = Cartesian3.unpack(array, startingIndex);
  2756. return Ellipsoid.fromCartesian3(radii, result);
  2757. };
  2758. /**
  2759. * Computes the unit vector directed from the center of this ellipsoid toward the provided Cartesian position.
  2760. * @function
  2761. *
  2762. * @param {Cartesian3} cartesian The Cartesian for which to to determine the geocentric normal.
  2763. * @param {Cartesian3} [result] The object onto which to store the result.
  2764. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2765. */
  2766. Ellipsoid.prototype.geocentricSurfaceNormal = Cartesian3.normalize;
  2767. /**
  2768. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  2769. *
  2770. * @param {Cartographic} cartographic The cartographic position for which to to determine the geodetic normal.
  2771. * @param {Cartesian3} [result] The object onto which to store the result.
  2772. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2773. */
  2774. Ellipsoid.prototype.geodeticSurfaceNormalCartographic = function(cartographic, result) {
  2775. if (!defined(cartographic)) {
  2776. throw new DeveloperError('cartographic is required.');
  2777. }
  2778. var longitude = cartographic.longitude;
  2779. var latitude = cartographic.latitude;
  2780. var cosLatitude = Math.cos(latitude);
  2781. var x = cosLatitude * Math.cos(longitude);
  2782. var y = cosLatitude * Math.sin(longitude);
  2783. var z = Math.sin(latitude);
  2784. if (!defined(result)) {
  2785. result = new Cartesian3();
  2786. }
  2787. result.x = x;
  2788. result.y = y;
  2789. result.z = z;
  2790. return Cartesian3.normalize(result, result);
  2791. };
  2792. /**
  2793. * Computes the normal of the plane tangent to the surface of the ellipsoid at the provided position.
  2794. *
  2795. * @param {Cartesian3} cartesian The Cartesian position for which to to determine the surface normal.
  2796. * @param {Cartesian3} [result] The object onto which to store the result.
  2797. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2798. */
  2799. Ellipsoid.prototype.geodeticSurfaceNormal = function(cartesian, result) {
  2800. if (!defined(result)) {
  2801. result = new Cartesian3();
  2802. }
  2803. result = Cartesian3.multiplyComponents(cartesian, this._oneOverRadiiSquared, result);
  2804. return Cartesian3.normalize(result, result);
  2805. };
  2806. var cartographicToCartesianNormal = new Cartesian3();
  2807. var cartographicToCartesianK = new Cartesian3();
  2808. /**
  2809. * Converts the provided cartographic to Cartesian representation.
  2810. *
  2811. * @param {Cartographic} cartographic The cartographic position.
  2812. * @param {Cartesian3} [result] The object onto which to store the result.
  2813. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2814. *
  2815. * @example
  2816. * //Create a Cartographic and determine it's Cartesian representation on a WGS84 ellipsoid.
  2817. * var position = new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 5000);
  2818. * var cartesianPosition = Cesium.Ellipsoid.WGS84.cartographicToCartesian(position);
  2819. */
  2820. Ellipsoid.prototype.cartographicToCartesian = function(cartographic, result) {
  2821. //`cartographic is required` is thrown from geodeticSurfaceNormalCartographic.
  2822. var n = cartographicToCartesianNormal;
  2823. var k = cartographicToCartesianK;
  2824. this.geodeticSurfaceNormalCartographic(cartographic, n);
  2825. Cartesian3.multiplyComponents(this._radiiSquared, n, k);
  2826. var gamma = Math.sqrt(Cartesian3.dot(n, k));
  2827. Cartesian3.divideByScalar(k, gamma, k);
  2828. Cartesian3.multiplyByScalar(n, cartographic.height, n);
  2829. if (!defined(result)) {
  2830. result = new Cartesian3();
  2831. }
  2832. return Cartesian3.add(k, n, result);
  2833. };
  2834. /**
  2835. * Converts the provided array of cartographics to an array of Cartesians.
  2836. *
  2837. * @param {Cartographic[]} cartographics An array of cartographic positions.
  2838. * @param {Cartesian3[]} [result] The object onto which to store the result.
  2839. * @returns {Cartesian3[]} The modified result parameter or a new Array instance if none was provided.
  2840. *
  2841. * @example
  2842. * //Convert an array of Cartographics and determine their Cartesian representation on a WGS84 ellipsoid.
  2843. * var positions = [new Cesium.Cartographic(Cesium.Math.toRadians(21), Cesium.Math.toRadians(78), 0),
  2844. * new Cesium.Cartographic(Cesium.Math.toRadians(21.321), Cesium.Math.toRadians(78.123), 100),
  2845. * new Cesium.Cartographic(Cesium.Math.toRadians(21.645), Cesium.Math.toRadians(78.456), 250)];
  2846. * var cartesianPositions = Cesium.Ellipsoid.WGS84.cartographicArrayToCartesianArray(positions);
  2847. */
  2848. Ellipsoid.prototype.cartographicArrayToCartesianArray = function(cartographics, result) {
  2849. if (!defined(cartographics)) {
  2850. throw new DeveloperError('cartographics is required.');
  2851. }
  2852. var length = cartographics.length;
  2853. if (!defined(result)) {
  2854. result = new Array(length);
  2855. } else {
  2856. result.length = length;
  2857. }
  2858. for ( var i = 0; i < length; i++) {
  2859. result[i] = this.cartographicToCartesian(cartographics[i], result[i]);
  2860. }
  2861. return result;
  2862. };
  2863. var cartesianToCartographicN = new Cartesian3();
  2864. var cartesianToCartographicP = new Cartesian3();
  2865. var cartesianToCartographicH = new Cartesian3();
  2866. /**
  2867. * Converts the provided cartesian to cartographic representation.
  2868. * The cartesian is undefined at the center of the ellipsoid.
  2869. *
  2870. * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
  2871. * @param {Cartographic} [result] The object onto which to store the result.
  2872. * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
  2873. *
  2874. * @example
  2875. * //Create a Cartesian and determine it's Cartographic representation on a WGS84 ellipsoid.
  2876. * var position = new Cesium.Cartesian3(17832.12, 83234.52, 952313.73);
  2877. * var cartographicPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
  2878. */
  2879. Ellipsoid.prototype.cartesianToCartographic = function(cartesian, result) {
  2880. //`cartesian is required.` is thrown from scaleToGeodeticSurface
  2881. var p = this.scaleToGeodeticSurface(cartesian, cartesianToCartographicP);
  2882. if (!defined(p)) {
  2883. return undefined;
  2884. }
  2885. var n = this.geodeticSurfaceNormal(p, cartesianToCartographicN);
  2886. var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);
  2887. var longitude = Math.atan2(n.y, n.x);
  2888. var latitude = Math.asin(n.z);
  2889. var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);
  2890. if (!defined(result)) {
  2891. return new Cartographic(longitude, latitude, height);
  2892. }
  2893. result.longitude = longitude;
  2894. result.latitude = latitude;
  2895. result.height = height;
  2896. return result;
  2897. };
  2898. /**
  2899. * Converts the provided array of cartesians to an array of cartographics.
  2900. *
  2901. * @param {Cartesian3[]} cartesians An array of Cartesian positions.
  2902. * @param {Cartographic[]} [result] The object onto which to store the result.
  2903. * @returns {Cartographic[]} The modified result parameter or a new Array instance if none was provided.
  2904. *
  2905. * @example
  2906. * //Create an array of Cartesians and determine their Cartographic representation on a WGS84 ellipsoid.
  2907. * var positions = [new Cesium.Cartesian3(17832.12, 83234.52, 952313.73),
  2908. * new Cesium.Cartesian3(17832.13, 83234.53, 952313.73),
  2909. * new Cesium.Cartesian3(17832.14, 83234.54, 952313.73)]
  2910. * var cartographicPositions = Cesium.Ellipsoid.WGS84.cartesianArrayToCartographicArray(positions);
  2911. */
  2912. Ellipsoid.prototype.cartesianArrayToCartographicArray = function(cartesians, result) {
  2913. if (!defined(cartesians)) {
  2914. throw new DeveloperError('cartesians is required.');
  2915. }
  2916. var length = cartesians.length;
  2917. if (!defined(result)) {
  2918. result = new Array(length);
  2919. } else {
  2920. result.length = length;
  2921. }
  2922. for ( var i = 0; i < length; ++i) {
  2923. result[i] = this.cartesianToCartographic(cartesians[i], result[i]);
  2924. }
  2925. return result;
  2926. };
  2927. /**
  2928. * Scales the provided Cartesian position along the geodetic surface normal
  2929. * so that it is on the surface of this ellipsoid. If the position is
  2930. * at the center of the ellipsoid, this function returns undefined.
  2931. *
  2932. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2933. * @param {Cartesian3} [result] The object onto which to store the result.
  2934. * @returns {Cartesian3} The modified result parameter, a new Cartesian3 instance if none was provided, or undefined if the position is at the center.
  2935. */
  2936. Ellipsoid.prototype.scaleToGeodeticSurface = function(cartesian, result) {
  2937. return scaleToGeodeticSurface(cartesian, this._oneOverRadii, this._oneOverRadiiSquared, this._centerToleranceSquared, result);
  2938. };
  2939. /**
  2940. * Scales the provided Cartesian position along the geocentric surface normal
  2941. * so that it is on the surface of this ellipsoid.
  2942. *
  2943. * @param {Cartesian3} cartesian The Cartesian position to scale.
  2944. * @param {Cartesian3} [result] The object onto which to store the result.
  2945. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if none was provided.
  2946. */
  2947. Ellipsoid.prototype.scaleToGeocentricSurface = function(cartesian, result) {
  2948. if (!defined(cartesian)) {
  2949. throw new DeveloperError('cartesian is required.');
  2950. }
  2951. if (!defined(result)) {
  2952. result = new Cartesian3();
  2953. }
  2954. var positionX = cartesian.x;
  2955. var positionY = cartesian.y;
  2956. var positionZ = cartesian.z;
  2957. var oneOverRadiiSquared = this._oneOverRadiiSquared;
  2958. var beta = 1.0 / Math.sqrt((positionX * positionX) * oneOverRadiiSquared.x +
  2959. (positionY * positionY) * oneOverRadiiSquared.y +
  2960. (positionZ * positionZ) * oneOverRadiiSquared.z);
  2961. return Cartesian3.multiplyByScalar(cartesian, beta, result);
  2962. };
  2963. /**
  2964. * Transforms a Cartesian X, Y, Z position to the ellipsoid-scaled space by multiplying
  2965. * its components by the result of {@link Ellipsoid#oneOverRadii}.
  2966. *
  2967. * @param {Cartesian3} position The position to transform.
  2968. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  2969. * return a new instance.
  2970. * @returns {Cartesian3} The position expressed in the scaled space. The returned instance is the
  2971. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  2972. */
  2973. Ellipsoid.prototype.transformPositionToScaledSpace = function(position, result) {
  2974. if (!defined(result)) {
  2975. result = new Cartesian3();
  2976. }
  2977. return Cartesian3.multiplyComponents(position, this._oneOverRadii, result);
  2978. };
  2979. /**
  2980. * Transforms a Cartesian X, Y, Z position from the ellipsoid-scaled space by multiplying
  2981. * its components by the result of {@link Ellipsoid#radii}.
  2982. *
  2983. * @param {Cartesian3} position The position to transform.
  2984. * @param {Cartesian3} [result] The position to which to copy the result, or undefined to create and
  2985. * return a new instance.
  2986. * @returns {Cartesian3} The position expressed in the unscaled space. The returned instance is the
  2987. * one passed as the result parameter if it is not undefined, or a new instance of it is.
  2988. */
  2989. Ellipsoid.prototype.transformPositionFromScaledSpace = function(position, result) {
  2990. if (!defined(result)) {
  2991. result = new Cartesian3();
  2992. }
  2993. return Cartesian3.multiplyComponents(position, this._radii, result);
  2994. };
  2995. /**
  2996. * Compares this Ellipsoid against the provided Ellipsoid componentwise and returns
  2997. * <code>true</code> if they are equal, <code>false</code> otherwise.
  2998. *
  2999. * @param {Ellipsoid} [right] The other Ellipsoid.
  3000. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3001. */
  3002. Ellipsoid.prototype.equals = function(right) {
  3003. return (this === right) ||
  3004. (defined(right) &&
  3005. Cartesian3.equals(this._radii, right._radii));
  3006. };
  3007. /**
  3008. * Creates a string representing this Ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  3009. *
  3010. * @returns {String} A string representing this ellipsoid in the format '(radii.x, radii.y, radii.z)'.
  3011. */
  3012. Ellipsoid.prototype.toString = function() {
  3013. return this._radii.toString();
  3014. };
  3015. /**
  3016. * Computes a point which is the intersection of the surface normal with the z-axis.
  3017. *
  3018. * @param {Cartesian3} position the position. must be on the surface of the ellipsoid.
  3019. * @param {Number} [buffer = 0.0] A buffer to subtract from the ellipsoid size when checking if the point is inside the ellipsoid.
  3020. * In earth case, with common earth datums, there is no need for this buffer since the intersection point is always (relatively) very close to the center.
  3021. * In WGS84 datum, intersection point is at max z = +-42841.31151331382 (0.673% of z-axis).
  3022. * Intersection point could be outside the ellipsoid if the ratio of MajorAxis / AxisOfRotation is bigger than the square root of 2
  3023. * @param {Cartesian} [result] The cartesian to which to copy the result, or undefined to create and
  3024. * return a new instance.
  3025. * @returns {Cartesian | undefined} the intersection point if it's inside the ellipsoid, undefined otherwise
  3026. *
  3027. * @exception {DeveloperError} position is required.
  3028. * @exception {DeveloperError} Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y).
  3029. * @exception {DeveloperError} Ellipsoid.radii.z must be greater than 0.
  3030. */
  3031. Ellipsoid.prototype.getSurfaceNormalIntersectionWithZAxis = function(position, buffer, result) {
  3032. if (!defined(position)) {
  3033. throw new DeveloperError('position is required.');
  3034. }
  3035. if (!CesiumMath.equalsEpsilon(this._radii.x, this._radii.y, CesiumMath.EPSILON15)) {
  3036. throw new DeveloperError('Ellipsoid must be an ellipsoid of revolution (radii.x == radii.y)');
  3037. }
  3038. if (this._radii.z === 0) {
  3039. throw new DeveloperError('Ellipsoid.radii.z must be greater than 0');
  3040. }
  3041. buffer = defaultValue(buffer, 0.0);
  3042. var sqauredXOverSquaredZ = this._sqauredXOverSquaredZ;
  3043. if (!defined(result)) {
  3044. result = new Cartesian3();
  3045. }
  3046. result.x = 0.0;
  3047. result.y = 0.0;
  3048. result.z = position.z * (1 - sqauredXOverSquaredZ);
  3049. if (Math.abs(result.z) >= this._radii.z - buffer) {
  3050. return undefined;
  3051. }
  3052. return result;
  3053. };
  3054. return Ellipsoid;
  3055. });
  3056. /*global define*/
  3057. define('Core/arrayRemoveDuplicates',[
  3058. './defaultValue',
  3059. './defined',
  3060. './DeveloperError',
  3061. './Math'
  3062. ], function(
  3063. defaultValue,
  3064. defined,
  3065. DeveloperError,
  3066. CesiumMath) {
  3067. 'use strict';
  3068. var removeDuplicatesEpsilon = CesiumMath.EPSILON10;
  3069. /**
  3070. * Removes adjacent duplicate values in an array of values.
  3071. *
  3072. * @param {Object[]} [values] The array of values.
  3073. * @param {Function} equalsEpsilon Function to compare values with an epsilon. Boolean equalsEpsilon(left, right, epsilon).
  3074. * @param {Boolean} [wrapAround=false] Compare the last value in the array against the first value.
  3075. * @returns {Object[]|undefined} A new array of values with no adjacent duplicate values or the input array if no duplicates were found.
  3076. *
  3077. * @example
  3078. * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0), (1.0, 1.0, 1.0)]
  3079. * var values = [
  3080. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3081. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3082. * new Cesium.Cartesian3(2.0, 2.0, 2.0),
  3083. * new Cesium.Cartesian3(3.0, 3.0, 3.0),
  3084. * new Cesium.Cartesian3(1.0, 1.0, 1.0)];
  3085. * var nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon);
  3086. *
  3087. * @example
  3088. * // Returns [(1.0, 1.0, 1.0), (2.0, 2.0, 2.0), (3.0, 3.0, 3.0)]
  3089. * var values = [
  3090. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3091. * new Cesium.Cartesian3(1.0, 1.0, 1.0),
  3092. * new Cesium.Cartesian3(2.0, 2.0, 2.0),
  3093. * new Cesium.Cartesian3(3.0, 3.0, 3.0),
  3094. * new Cesium.Cartesian3(1.0, 1.0, 1.0)];
  3095. * var nonDuplicatevalues = Cesium.PolylinePipeline.removeDuplicates(values, Cartesian3.equalsEpsilon, true);
  3096. *
  3097. * @private
  3098. */
  3099. function arrayRemoveDuplicates(values, equalsEpsilon, wrapAround) {
  3100. if (!defined(equalsEpsilon)) {
  3101. throw new DeveloperError('equalsEpsilon is required.');
  3102. }
  3103. if (!defined(values)) {
  3104. return undefined;
  3105. }
  3106. wrapAround = defaultValue(wrapAround, false);
  3107. var length = values.length;
  3108. if (length < 2) {
  3109. return values;
  3110. }
  3111. var i;
  3112. var v0;
  3113. var v1;
  3114. for (i = 1; i < length; ++i) {
  3115. v0 = values[i - 1];
  3116. v1 = values[i];
  3117. if (equalsEpsilon(v0, v1, removeDuplicatesEpsilon)) {
  3118. break;
  3119. }
  3120. }
  3121. if (i === length) {
  3122. if (wrapAround && equalsEpsilon(values[0], values[values.length - 1], removeDuplicatesEpsilon)) {
  3123. return values.slice(1);
  3124. }
  3125. return values;
  3126. }
  3127. var cleanedvalues = values.slice(0, i);
  3128. for (; i < length; ++i) {
  3129. // v0 is set by either the previous loop, or the previous clean point.
  3130. v1 = values[i];
  3131. if (!equalsEpsilon(v0, v1, removeDuplicatesEpsilon)) {
  3132. cleanedvalues.push(v1);
  3133. v0 = v1;
  3134. }
  3135. }
  3136. if (wrapAround && cleanedvalues.length > 1 && equalsEpsilon(cleanedvalues[0], cleanedvalues[cleanedvalues.length - 1], removeDuplicatesEpsilon)) {
  3137. cleanedvalues.shift();
  3138. }
  3139. return cleanedvalues;
  3140. }
  3141. return arrayRemoveDuplicates;
  3142. });
  3143. /*global define*/
  3144. define('Core/GeographicProjection',[
  3145. './Cartesian3',
  3146. './Cartographic',
  3147. './defaultValue',
  3148. './defined',
  3149. './defineProperties',
  3150. './DeveloperError',
  3151. './Ellipsoid'
  3152. ], function(
  3153. Cartesian3,
  3154. Cartographic,
  3155. defaultValue,
  3156. defined,
  3157. defineProperties,
  3158. DeveloperError,
  3159. Ellipsoid) {
  3160. 'use strict';
  3161. /**
  3162. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  3163. * them by the {@link Ellipsoid#maximumRadius}. This projection
  3164. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  3165. * is also known as EPSG:4326.
  3166. *
  3167. * @alias GeographicProjection
  3168. * @constructor
  3169. *
  3170. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  3171. *
  3172. * @see WebMercatorProjection
  3173. */
  3174. function GeographicProjection(ellipsoid) {
  3175. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  3176. this._semimajorAxis = this._ellipsoid.maximumRadius;
  3177. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  3178. }
  3179. defineProperties(GeographicProjection.prototype, {
  3180. /**
  3181. * Gets the {@link Ellipsoid}.
  3182. *
  3183. * @memberof GeographicProjection.prototype
  3184. *
  3185. * @type {Ellipsoid}
  3186. * @readonly
  3187. */
  3188. ellipsoid : {
  3189. get : function() {
  3190. return this._ellipsoid;
  3191. }
  3192. }
  3193. });
  3194. /**
  3195. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  3196. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  3197. * ellipsoid. Z is the unmodified height.
  3198. *
  3199. * @param {Cartographic} cartographic The coordinates to project.
  3200. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  3201. * undefined, a new instance is created and returned.
  3202. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  3203. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3204. * created and returned.
  3205. */
  3206. GeographicProjection.prototype.project = function(cartographic, result) {
  3207. // Actually this is the special case of equidistant cylindrical called the plate carree
  3208. var semimajorAxis = this._semimajorAxis;
  3209. var x = cartographic.longitude * semimajorAxis;
  3210. var y = cartographic.latitude * semimajorAxis;
  3211. var z = cartographic.height;
  3212. if (!defined(result)) {
  3213. return new Cartesian3(x, y, z);
  3214. }
  3215. result.x = x;
  3216. result.y = y;
  3217. result.z = z;
  3218. return result;
  3219. };
  3220. /**
  3221. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  3222. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  3223. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  3224. *
  3225. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  3226. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  3227. * undefined, a new instance is created and returned.
  3228. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  3229. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3230. * created and returned.
  3231. */
  3232. GeographicProjection.prototype.unproject = function(cartesian, result) {
  3233. if (!defined(cartesian)) {
  3234. throw new DeveloperError('cartesian is required');
  3235. }
  3236. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  3237. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  3238. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  3239. var height = cartesian.z;
  3240. if (!defined(result)) {
  3241. return new Cartographic(longitude, latitude, height);
  3242. }
  3243. result.longitude = longitude;
  3244. result.latitude = latitude;
  3245. result.height = height;
  3246. return result;
  3247. };
  3248. return GeographicProjection;
  3249. });
  3250. /*global define*/
  3251. define('Core/Intersect',[
  3252. './freezeObject'
  3253. ], function(
  3254. freezeObject) {
  3255. 'use strict';
  3256. /**
  3257. * This enumerated type is used in determining where, relative to the frustum, an
  3258. * object is located. The object can either be fully contained within the frustum (INSIDE),
  3259. * partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
  3260. * outside of the frustum's 6 planes (OUTSIDE).
  3261. *
  3262. * @exports Intersect
  3263. */
  3264. var Intersect = {
  3265. /**
  3266. * Represents that an object is not contained within the frustum.
  3267. *
  3268. * @type {Number}
  3269. * @constant
  3270. */
  3271. OUTSIDE : -1,
  3272. /**
  3273. * Represents that an object intersects one of the frustum's planes.
  3274. *
  3275. * @type {Number}
  3276. * @constant
  3277. */
  3278. INTERSECTING : 0,
  3279. /**
  3280. * Represents that an object is fully within the frustum.
  3281. *
  3282. * @type {Number}
  3283. * @constant
  3284. */
  3285. INSIDE : 1
  3286. };
  3287. return freezeObject(Intersect);
  3288. });
  3289. /*global define*/
  3290. define('Core/Interval',[
  3291. './defaultValue'
  3292. ], function(
  3293. defaultValue) {
  3294. 'use strict';
  3295. /**
  3296. * Represents the closed interval [start, stop].
  3297. * @alias Interval
  3298. * @constructor
  3299. *
  3300. * @param {Number} [start=0.0] The beginning of the interval.
  3301. * @param {Number} [stop=0.0] The end of the interval.
  3302. */
  3303. function Interval(start, stop) {
  3304. /**
  3305. * The beginning of the interval.
  3306. * @type {Number}
  3307. * @default 0.0
  3308. */
  3309. this.start = defaultValue(start, 0.0);
  3310. /**
  3311. * The end of the interval.
  3312. * @type {Number}
  3313. * @default 0.0
  3314. */
  3315. this.stop = defaultValue(stop, 0.0);
  3316. }
  3317. return Interval;
  3318. });
  3319. /*global define*/
  3320. define('Core/Matrix3',[
  3321. './Cartesian3',
  3322. './defaultValue',
  3323. './defined',
  3324. './defineProperties',
  3325. './DeveloperError',
  3326. './freezeObject',
  3327. './Math'
  3328. ], function(
  3329. Cartesian3,
  3330. defaultValue,
  3331. defined,
  3332. defineProperties,
  3333. DeveloperError,
  3334. freezeObject,
  3335. CesiumMath) {
  3336. 'use strict';
  3337. /**
  3338. * A 3x3 matrix, indexable as a column-major order array.
  3339. * Constructor parameters are in row-major order for code readability.
  3340. * @alias Matrix3
  3341. * @constructor
  3342. *
  3343. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  3344. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  3345. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  3346. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  3347. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  3348. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  3349. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  3350. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  3351. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  3352. *
  3353. * @see Matrix3.fromColumnMajorArray
  3354. * @see Matrix3.fromRowMajorArray
  3355. * @see Matrix3.fromQuaternion
  3356. * @see Matrix3.fromScale
  3357. * @see Matrix3.fromUniformScale
  3358. * @see Matrix2
  3359. * @see Matrix4
  3360. */
  3361. function Matrix3(column0Row0, column1Row0, column2Row0,
  3362. column0Row1, column1Row1, column2Row1,
  3363. column0Row2, column1Row2, column2Row2) {
  3364. this[0] = defaultValue(column0Row0, 0.0);
  3365. this[1] = defaultValue(column0Row1, 0.0);
  3366. this[2] = defaultValue(column0Row2, 0.0);
  3367. this[3] = defaultValue(column1Row0, 0.0);
  3368. this[4] = defaultValue(column1Row1, 0.0);
  3369. this[5] = defaultValue(column1Row2, 0.0);
  3370. this[6] = defaultValue(column2Row0, 0.0);
  3371. this[7] = defaultValue(column2Row1, 0.0);
  3372. this[8] = defaultValue(column2Row2, 0.0);
  3373. }
  3374. /**
  3375. * The number of elements used to pack the object into an array.
  3376. * @type {Number}
  3377. */
  3378. Matrix3.packedLength = 9;
  3379. /**
  3380. * Stores the provided instance into the provided array.
  3381. *
  3382. * @param {Matrix3} value The value to pack.
  3383. * @param {Number[]} array The array to pack into.
  3384. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  3385. *
  3386. * @returns {Number[]} The array that was packed into
  3387. */
  3388. Matrix3.pack = function(value, array, startingIndex) {
  3389. if (!defined(value)) {
  3390. throw new DeveloperError('value is required');
  3391. }
  3392. if (!defined(array)) {
  3393. throw new DeveloperError('array is required');
  3394. }
  3395. startingIndex = defaultValue(startingIndex, 0);
  3396. array[startingIndex++] = value[0];
  3397. array[startingIndex++] = value[1];
  3398. array[startingIndex++] = value[2];
  3399. array[startingIndex++] = value[3];
  3400. array[startingIndex++] = value[4];
  3401. array[startingIndex++] = value[5];
  3402. array[startingIndex++] = value[6];
  3403. array[startingIndex++] = value[7];
  3404. array[startingIndex++] = value[8];
  3405. return array;
  3406. };
  3407. /**
  3408. * Retrieves an instance from a packed array.
  3409. *
  3410. * @param {Number[]} array The packed array.
  3411. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  3412. * @param {Matrix3} [result] The object into which to store the result.
  3413. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  3414. */
  3415. Matrix3.unpack = function(array, startingIndex, result) {
  3416. if (!defined(array)) {
  3417. throw new DeveloperError('array is required');
  3418. }
  3419. startingIndex = defaultValue(startingIndex, 0);
  3420. if (!defined(result)) {
  3421. result = new Matrix3();
  3422. }
  3423. result[0] = array[startingIndex++];
  3424. result[1] = array[startingIndex++];
  3425. result[2] = array[startingIndex++];
  3426. result[3] = array[startingIndex++];
  3427. result[4] = array[startingIndex++];
  3428. result[5] = array[startingIndex++];
  3429. result[6] = array[startingIndex++];
  3430. result[7] = array[startingIndex++];
  3431. result[8] = array[startingIndex++];
  3432. return result;
  3433. };
  3434. /**
  3435. * Duplicates a Matrix3 instance.
  3436. *
  3437. * @param {Matrix3} matrix The matrix to duplicate.
  3438. * @param {Matrix3} [result] The object onto which to store the result.
  3439. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  3440. */
  3441. Matrix3.clone = function(values, result) {
  3442. if (!defined(values)) {
  3443. return undefined;
  3444. }
  3445. if (!defined(result)) {
  3446. return new Matrix3(values[0], values[3], values[6],
  3447. values[1], values[4], values[7],
  3448. values[2], values[5], values[8]);
  3449. }
  3450. result[0] = values[0];
  3451. result[1] = values[1];
  3452. result[2] = values[2];
  3453. result[3] = values[3];
  3454. result[4] = values[4];
  3455. result[5] = values[5];
  3456. result[6] = values[6];
  3457. result[7] = values[7];
  3458. result[8] = values[8];
  3459. return result;
  3460. };
  3461. /**
  3462. * Creates a Matrix3 from 9 consecutive elements in an array.
  3463. *
  3464. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  3465. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  3466. * @param {Matrix3} [result] The object onto which to store the result.
  3467. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  3468. *
  3469. * @example
  3470. * // Create the Matrix3:
  3471. * // [1.0, 2.0, 3.0]
  3472. * // [1.0, 2.0, 3.0]
  3473. * // [1.0, 2.0, 3.0]
  3474. *
  3475. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  3476. * var m = Cesium.Matrix3.fromArray(v);
  3477. *
  3478. * // Create same Matrix3 with using an offset into an array
  3479. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  3480. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  3481. */
  3482. Matrix3.fromArray = function(array, startingIndex, result) {
  3483. if (!defined(array)) {
  3484. throw new DeveloperError('array is required');
  3485. }
  3486. startingIndex = defaultValue(startingIndex, 0);
  3487. if (!defined(result)) {
  3488. result = new Matrix3();
  3489. }
  3490. result[0] = array[startingIndex];
  3491. result[1] = array[startingIndex + 1];
  3492. result[2] = array[startingIndex + 2];
  3493. result[3] = array[startingIndex + 3];
  3494. result[4] = array[startingIndex + 4];
  3495. result[5] = array[startingIndex + 5];
  3496. result[6] = array[startingIndex + 6];
  3497. result[7] = array[startingIndex + 7];
  3498. result[8] = array[startingIndex + 8];
  3499. return result;
  3500. };
  3501. /**
  3502. * Creates a Matrix3 instance from a column-major order array.
  3503. *
  3504. * @param {Number[]} values The column-major order array.
  3505. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3506. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3507. */
  3508. Matrix3.fromColumnMajorArray = function(values, result) {
  3509. if (!defined(values)) {
  3510. throw new DeveloperError('values parameter is required');
  3511. }
  3512. return Matrix3.clone(values, result);
  3513. };
  3514. /**
  3515. * Creates a Matrix3 instance from a row-major order array.
  3516. * The resulting matrix will be in column-major order.
  3517. *
  3518. * @param {Number[]} values The row-major order array.
  3519. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3520. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3521. */
  3522. Matrix3.fromRowMajorArray = function(values, result) {
  3523. if (!defined(values)) {
  3524. throw new DeveloperError('values is required.');
  3525. }
  3526. if (!defined(result)) {
  3527. return new Matrix3(values[0], values[1], values[2],
  3528. values[3], values[4], values[5],
  3529. values[6], values[7], values[8]);
  3530. }
  3531. result[0] = values[0];
  3532. result[1] = values[3];
  3533. result[2] = values[6];
  3534. result[3] = values[1];
  3535. result[4] = values[4];
  3536. result[5] = values[7];
  3537. result[6] = values[2];
  3538. result[7] = values[5];
  3539. result[8] = values[8];
  3540. return result;
  3541. };
  3542. /**
  3543. * Computes a 3x3 rotation matrix from the provided quaternion.
  3544. *
  3545. * @param {Quaternion} quaternion the quaternion to use.
  3546. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3547. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  3548. */
  3549. Matrix3.fromQuaternion = function(quaternion, result) {
  3550. if (!defined(quaternion)) {
  3551. throw new DeveloperError('quaternion is required');
  3552. }
  3553. var x2 = quaternion.x * quaternion.x;
  3554. var xy = quaternion.x * quaternion.y;
  3555. var xz = quaternion.x * quaternion.z;
  3556. var xw = quaternion.x * quaternion.w;
  3557. var y2 = quaternion.y * quaternion.y;
  3558. var yz = quaternion.y * quaternion.z;
  3559. var yw = quaternion.y * quaternion.w;
  3560. var z2 = quaternion.z * quaternion.z;
  3561. var zw = quaternion.z * quaternion.w;
  3562. var w2 = quaternion.w * quaternion.w;
  3563. var m00 = x2 - y2 - z2 + w2;
  3564. var m01 = 2.0 * (xy - zw);
  3565. var m02 = 2.0 * (xz + yw);
  3566. var m10 = 2.0 * (xy + zw);
  3567. var m11 = -x2 + y2 - z2 + w2;
  3568. var m12 = 2.0 * (yz - xw);
  3569. var m20 = 2.0 * (xz - yw);
  3570. var m21 = 2.0 * (yz + xw);
  3571. var m22 = -x2 - y2 + z2 + w2;
  3572. if (!defined(result)) {
  3573. return new Matrix3(m00, m01, m02,
  3574. m10, m11, m12,
  3575. m20, m21, m22);
  3576. }
  3577. result[0] = m00;
  3578. result[1] = m10;
  3579. result[2] = m20;
  3580. result[3] = m01;
  3581. result[4] = m11;
  3582. result[5] = m21;
  3583. result[6] = m02;
  3584. result[7] = m12;
  3585. result[8] = m22;
  3586. return result;
  3587. };
  3588. /**
  3589. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  3590. *
  3591. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  3592. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3593. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  3594. */
  3595. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  3596. if (!defined(headingPitchRoll)) {
  3597. throw new DeveloperError('headingPitchRoll is required');
  3598. }
  3599. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  3600. var cosPsi = Math.cos(-headingPitchRoll.heading);
  3601. var cosPhi = Math.cos(headingPitchRoll.roll);
  3602. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  3603. var sinPsi = Math.sin(-headingPitchRoll.heading);
  3604. var sinPhi = Math.sin(headingPitchRoll.roll);
  3605. var m00 = cosTheta * cosPsi;
  3606. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  3607. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  3608. var m10 = cosTheta * sinPsi;
  3609. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  3610. var m12 = -sinTheta * cosPhi + cosPhi * sinTheta * sinPsi;
  3611. var m20 = -sinTheta;
  3612. var m21 = sinPhi * cosTheta;
  3613. var m22 = cosPhi * cosTheta;
  3614. if (!defined(result)) {
  3615. return new Matrix3(m00, m01, m02,
  3616. m10, m11, m12,
  3617. m20, m21, m22);
  3618. }
  3619. result[0] = m00;
  3620. result[1] = m10;
  3621. result[2] = m20;
  3622. result[3] = m01;
  3623. result[4] = m11;
  3624. result[5] = m21;
  3625. result[6] = m02;
  3626. result[7] = m12;
  3627. result[8] = m22;
  3628. return result;
  3629. };
  3630. /**
  3631. * Computes a Matrix3 instance representing a non-uniform scale.
  3632. *
  3633. * @param {Cartesian3} scale The x, y, and z scale factors.
  3634. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3635. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3636. *
  3637. * @example
  3638. * // Creates
  3639. * // [7.0, 0.0, 0.0]
  3640. * // [0.0, 8.0, 0.0]
  3641. * // [0.0, 0.0, 9.0]
  3642. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  3643. */
  3644. Matrix3.fromScale = function(scale, result) {
  3645. if (!defined(scale)) {
  3646. throw new DeveloperError('scale is required.');
  3647. }
  3648. if (!defined(result)) {
  3649. return new Matrix3(
  3650. scale.x, 0.0, 0.0,
  3651. 0.0, scale.y, 0.0,
  3652. 0.0, 0.0, scale.z);
  3653. }
  3654. result[0] = scale.x;
  3655. result[1] = 0.0;
  3656. result[2] = 0.0;
  3657. result[3] = 0.0;
  3658. result[4] = scale.y;
  3659. result[5] = 0.0;
  3660. result[6] = 0.0;
  3661. result[7] = 0.0;
  3662. result[8] = scale.z;
  3663. return result;
  3664. };
  3665. /**
  3666. * Computes a Matrix3 instance representing a uniform scale.
  3667. *
  3668. * @param {Number} scale The uniform scale factor.
  3669. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3670. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3671. *
  3672. * @example
  3673. * // Creates
  3674. * // [2.0, 0.0, 0.0]
  3675. * // [0.0, 2.0, 0.0]
  3676. * // [0.0, 0.0, 2.0]
  3677. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  3678. */
  3679. Matrix3.fromUniformScale = function(scale, result) {
  3680. if (typeof scale !== 'number') {
  3681. throw new DeveloperError('scale is required.');
  3682. }
  3683. if (!defined(result)) {
  3684. return new Matrix3(
  3685. scale, 0.0, 0.0,
  3686. 0.0, scale, 0.0,
  3687. 0.0, 0.0, scale);
  3688. }
  3689. result[0] = scale;
  3690. result[1] = 0.0;
  3691. result[2] = 0.0;
  3692. result[3] = 0.0;
  3693. result[4] = scale;
  3694. result[5] = 0.0;
  3695. result[6] = 0.0;
  3696. result[7] = 0.0;
  3697. result[8] = scale;
  3698. return result;
  3699. };
  3700. /**
  3701. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  3702. *
  3703. * @param {Cartesian3} the vector on the left hand side of the cross product operation.
  3704. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3705. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3706. *
  3707. * @example
  3708. * // Creates
  3709. * // [0.0, -9.0, 8.0]
  3710. * // [9.0, 0.0, -7.0]
  3711. * // [-8.0, 7.0, 0.0]
  3712. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  3713. */
  3714. Matrix3.fromCrossProduct = function(vector, result) {
  3715. if (!defined(vector)) {
  3716. throw new DeveloperError('vector is required.');
  3717. }
  3718. if (!defined(result)) {
  3719. return new Matrix3(
  3720. 0.0, -vector.z, vector.y,
  3721. vector.z, 0.0, -vector.x,
  3722. -vector.y, vector.x, 0.0);
  3723. }
  3724. result[0] = 0.0;
  3725. result[1] = vector.z;
  3726. result[2] = -vector.y;
  3727. result[3] = -vector.z;
  3728. result[4] = 0.0;
  3729. result[5] = vector.x;
  3730. result[6] = vector.y;
  3731. result[7] = -vector.x;
  3732. result[8] = 0.0;
  3733. return result;
  3734. };
  3735. /**
  3736. * Creates a rotation matrix around the x-axis.
  3737. *
  3738. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3739. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3740. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3741. *
  3742. * @example
  3743. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  3744. * var p = new Cesium.Cartesian3(5, 6, 7);
  3745. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  3746. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3747. */
  3748. Matrix3.fromRotationX = function(angle, result) {
  3749. if (!defined(angle)) {
  3750. throw new DeveloperError('angle is required.');
  3751. }
  3752. var cosAngle = Math.cos(angle);
  3753. var sinAngle = Math.sin(angle);
  3754. if (!defined(result)) {
  3755. return new Matrix3(
  3756. 1.0, 0.0, 0.0,
  3757. 0.0, cosAngle, -sinAngle,
  3758. 0.0, sinAngle, cosAngle);
  3759. }
  3760. result[0] = 1.0;
  3761. result[1] = 0.0;
  3762. result[2] = 0.0;
  3763. result[3] = 0.0;
  3764. result[4] = cosAngle;
  3765. result[5] = sinAngle;
  3766. result[6] = 0.0;
  3767. result[7] = -sinAngle;
  3768. result[8] = cosAngle;
  3769. return result;
  3770. };
  3771. /**
  3772. * Creates a rotation matrix around the y-axis.
  3773. *
  3774. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3775. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3776. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3777. *
  3778. * @example
  3779. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  3780. * var p = new Cesium.Cartesian3(5, 6, 7);
  3781. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  3782. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3783. */
  3784. Matrix3.fromRotationY = function(angle, result) {
  3785. if (!defined(angle)) {
  3786. throw new DeveloperError('angle is required.');
  3787. }
  3788. var cosAngle = Math.cos(angle);
  3789. var sinAngle = Math.sin(angle);
  3790. if (!defined(result)) {
  3791. return new Matrix3(
  3792. cosAngle, 0.0, sinAngle,
  3793. 0.0, 1.0, 0.0,
  3794. -sinAngle, 0.0, cosAngle);
  3795. }
  3796. result[0] = cosAngle;
  3797. result[1] = 0.0;
  3798. result[2] = -sinAngle;
  3799. result[3] = 0.0;
  3800. result[4] = 1.0;
  3801. result[5] = 0.0;
  3802. result[6] = sinAngle;
  3803. result[7] = 0.0;
  3804. result[8] = cosAngle;
  3805. return result;
  3806. };
  3807. /**
  3808. * Creates a rotation matrix around the z-axis.
  3809. *
  3810. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  3811. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  3812. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  3813. *
  3814. * @example
  3815. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  3816. * var p = new Cesium.Cartesian3(5, 6, 7);
  3817. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  3818. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  3819. */
  3820. Matrix3.fromRotationZ = function(angle, result) {
  3821. if (!defined(angle)) {
  3822. throw new DeveloperError('angle is required.');
  3823. }
  3824. var cosAngle = Math.cos(angle);
  3825. var sinAngle = Math.sin(angle);
  3826. if (!defined(result)) {
  3827. return new Matrix3(
  3828. cosAngle, -sinAngle, 0.0,
  3829. sinAngle, cosAngle, 0.0,
  3830. 0.0, 0.0, 1.0);
  3831. }
  3832. result[0] = cosAngle;
  3833. result[1] = sinAngle;
  3834. result[2] = 0.0;
  3835. result[3] = -sinAngle;
  3836. result[4] = cosAngle;
  3837. result[5] = 0.0;
  3838. result[6] = 0.0;
  3839. result[7] = 0.0;
  3840. result[8] = 1.0;
  3841. return result;
  3842. };
  3843. /**
  3844. * Creates an Array from the provided Matrix3 instance.
  3845. * The array will be in column-major order.
  3846. *
  3847. * @param {Matrix3} matrix The matrix to use..
  3848. * @param {Number[]} [result] The Array onto which to store the result.
  3849. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  3850. */
  3851. Matrix3.toArray = function(matrix, result) {
  3852. if (!defined(matrix)) {
  3853. throw new DeveloperError('matrix is required');
  3854. }
  3855. if (!defined(result)) {
  3856. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  3857. }
  3858. result[0] = matrix[0];
  3859. result[1] = matrix[1];
  3860. result[2] = matrix[2];
  3861. result[3] = matrix[3];
  3862. result[4] = matrix[4];
  3863. result[5] = matrix[5];
  3864. result[6] = matrix[6];
  3865. result[7] = matrix[7];
  3866. result[8] = matrix[8];
  3867. return result;
  3868. };
  3869. /**
  3870. * Computes the array index of the element at the provided row and column.
  3871. *
  3872. * @param {Number} row The zero-based index of the row.
  3873. * @param {Number} column The zero-based index of the column.
  3874. * @returns {Number} The index of the element at the provided row and column.
  3875. *
  3876. * @exception {DeveloperError} row must be 0, 1, or 2.
  3877. * @exception {DeveloperError} column must be 0, 1, or 2.
  3878. *
  3879. * @example
  3880. * var myMatrix = new Cesium.Matrix3();
  3881. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  3882. * var column1Row0 = myMatrix[column1Row0Index]
  3883. * myMatrix[column1Row0Index] = 10.0;
  3884. */
  3885. Matrix3.getElementIndex = function(column, row) {
  3886. if (typeof row !== 'number' || row < 0 || row > 2) {
  3887. throw new DeveloperError('row must be 0, 1, or 2.');
  3888. }
  3889. if (typeof column !== 'number' || column < 0 || column > 2) {
  3890. throw new DeveloperError('column must be 0, 1, or 2.');
  3891. }
  3892. return column * 3 + row;
  3893. };
  3894. /**
  3895. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  3896. *
  3897. * @param {Matrix3} matrix The matrix to use.
  3898. * @param {Number} index The zero-based index of the column to retrieve.
  3899. * @param {Cartesian3} result The object onto which to store the result.
  3900. * @returns {Cartesian3} The modified result parameter.
  3901. *
  3902. * @exception {DeveloperError} index must be 0, 1, or 2.
  3903. */
  3904. Matrix3.getColumn = function(matrix, index, result) {
  3905. if (!defined(matrix)) {
  3906. throw new DeveloperError('matrix is required.');
  3907. }
  3908. if (typeof index !== 'number' || index < 0 || index > 2) {
  3909. throw new DeveloperError('index must be 0, 1, or 2.');
  3910. }
  3911. if (!defined(result)) {
  3912. throw new DeveloperError('result is required');
  3913. }
  3914. var startIndex = index * 3;
  3915. var x = matrix[startIndex];
  3916. var y = matrix[startIndex + 1];
  3917. var z = matrix[startIndex + 2];
  3918. result.x = x;
  3919. result.y = y;
  3920. result.z = z;
  3921. return result;
  3922. };
  3923. /**
  3924. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  3925. *
  3926. * @param {Matrix3} matrix The matrix to use.
  3927. * @param {Number} index The zero-based index of the column to set.
  3928. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  3929. * @param {Matrix3} result The object onto which to store the result.
  3930. * @returns {Matrix3} The modified result parameter.
  3931. *
  3932. * @exception {DeveloperError} index must be 0, 1, or 2.
  3933. */
  3934. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  3935. if (!defined(matrix)) {
  3936. throw new DeveloperError('matrix is required');
  3937. }
  3938. if (!defined(cartesian)) {
  3939. throw new DeveloperError('cartesian is required');
  3940. }
  3941. if (typeof index !== 'number' || index < 0 || index > 2) {
  3942. throw new DeveloperError('index must be 0, 1, or 2.');
  3943. }
  3944. if (!defined(result)) {
  3945. throw new DeveloperError('result is required');
  3946. }
  3947. result = Matrix3.clone(matrix, result);
  3948. var startIndex = index * 3;
  3949. result[startIndex] = cartesian.x;
  3950. result[startIndex + 1] = cartesian.y;
  3951. result[startIndex + 2] = cartesian.z;
  3952. return result;
  3953. };
  3954. /**
  3955. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  3956. *
  3957. * @param {Matrix3} matrix The matrix to use.
  3958. * @param {Number} index The zero-based index of the row to retrieve.
  3959. * @param {Cartesian3} result The object onto which to store the result.
  3960. * @returns {Cartesian3} The modified result parameter.
  3961. *
  3962. * @exception {DeveloperError} index must be 0, 1, or 2.
  3963. */
  3964. Matrix3.getRow = function(matrix, index, result) {
  3965. if (!defined(matrix)) {
  3966. throw new DeveloperError('matrix is required.');
  3967. }
  3968. if (typeof index !== 'number' || index < 0 || index > 2) {
  3969. throw new DeveloperError('index must be 0, 1, or 2.');
  3970. }
  3971. if (!defined(result)) {
  3972. throw new DeveloperError('result is required');
  3973. }
  3974. var x = matrix[index];
  3975. var y = matrix[index + 3];
  3976. var z = matrix[index + 6];
  3977. result.x = x;
  3978. result.y = y;
  3979. result.z = z;
  3980. return result;
  3981. };
  3982. /**
  3983. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  3984. *
  3985. * @param {Matrix3} matrix The matrix to use.
  3986. * @param {Number} index The zero-based index of the row to set.
  3987. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  3988. * @param {Matrix3} result The object onto which to store the result.
  3989. * @returns {Matrix3} The modified result parameter.
  3990. *
  3991. * @exception {DeveloperError} index must be 0, 1, or 2.
  3992. */
  3993. Matrix3.setRow = function(matrix, index, cartesian, result) {
  3994. if (!defined(matrix)) {
  3995. throw new DeveloperError('matrix is required');
  3996. }
  3997. if (!defined(cartesian)) {
  3998. throw new DeveloperError('cartesian is required');
  3999. }
  4000. if (typeof index !== 'number' || index < 0 || index > 2) {
  4001. throw new DeveloperError('index must be 0, 1, or 2.');
  4002. }
  4003. if (!defined(result)) {
  4004. throw new DeveloperError('result is required');
  4005. }
  4006. result = Matrix3.clone(matrix, result);
  4007. result[index] = cartesian.x;
  4008. result[index + 3] = cartesian.y;
  4009. result[index + 6] = cartesian.z;
  4010. return result;
  4011. };
  4012. var scratchColumn = new Cartesian3();
  4013. /**
  4014. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  4015. *
  4016. * @param {Matrix3} matrix The matrix.
  4017. * @param {Cartesian3} result The object onto which to store the result.
  4018. * @returns {Cartesian3} The modified result parameter.
  4019. */
  4020. Matrix3.getScale = function(matrix, result) {
  4021. if (!defined(matrix)) {
  4022. throw new DeveloperError('matrix is required.');
  4023. }
  4024. if (!defined(result)) {
  4025. throw new DeveloperError('result is required');
  4026. }
  4027. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  4028. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  4029. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  4030. return result;
  4031. };
  4032. var scratchScale = new Cartesian3();
  4033. /**
  4034. * Computes the maximum scale assuming the matrix is an affine transformation.
  4035. * The maximum scale is the maximum length of the column vectors.
  4036. *
  4037. * @param {Matrix3} matrix The matrix.
  4038. * @returns {Number} The maximum scale.
  4039. */
  4040. Matrix3.getMaximumScale = function(matrix) {
  4041. Matrix3.getScale(matrix, scratchScale);
  4042. return Cartesian3.maximumComponent(scratchScale);
  4043. };
  4044. /**
  4045. * Computes the product of two matrices.
  4046. *
  4047. * @param {Matrix3} left The first matrix.
  4048. * @param {Matrix3} right The second matrix.
  4049. * @param {Matrix3} result The object onto which to store the result.
  4050. * @returns {Matrix3} The modified result parameter.
  4051. */
  4052. Matrix3.multiply = function(left, right, result) {
  4053. if (!defined(left)) {
  4054. throw new DeveloperError('left is required');
  4055. }
  4056. if (!defined(right)) {
  4057. throw new DeveloperError('right is required');
  4058. }
  4059. if (!defined(result)) {
  4060. throw new DeveloperError('result is required');
  4061. }
  4062. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  4063. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  4064. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  4065. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  4066. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  4067. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  4068. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  4069. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  4070. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  4071. result[0] = column0Row0;
  4072. result[1] = column0Row1;
  4073. result[2] = column0Row2;
  4074. result[3] = column1Row0;
  4075. result[4] = column1Row1;
  4076. result[5] = column1Row2;
  4077. result[6] = column2Row0;
  4078. result[7] = column2Row1;
  4079. result[8] = column2Row2;
  4080. return result;
  4081. };
  4082. /**
  4083. * Computes the sum of two matrices.
  4084. *
  4085. * @param {Matrix3} left The first matrix.
  4086. * @param {Matrix3} right The second matrix.
  4087. * @param {Matrix3} result The object onto which to store the result.
  4088. * @returns {Matrix3} The modified result parameter.
  4089. */
  4090. Matrix3.add = function(left, right, result) {
  4091. if (!defined(left)) {
  4092. throw new DeveloperError('left is required');
  4093. }
  4094. if (!defined(right)) {
  4095. throw new DeveloperError('right is required');
  4096. }
  4097. if (!defined(result)) {
  4098. throw new DeveloperError('result is required');
  4099. }
  4100. result[0] = left[0] + right[0];
  4101. result[1] = left[1] + right[1];
  4102. result[2] = left[2] + right[2];
  4103. result[3] = left[3] + right[3];
  4104. result[4] = left[4] + right[4];
  4105. result[5] = left[5] + right[5];
  4106. result[6] = left[6] + right[6];
  4107. result[7] = left[7] + right[7];
  4108. result[8] = left[8] + right[8];
  4109. return result;
  4110. };
  4111. /**
  4112. * Computes the difference of two matrices.
  4113. *
  4114. * @param {Matrix3} left The first matrix.
  4115. * @param {Matrix3} right The second matrix.
  4116. * @param {Matrix3} result The object onto which to store the result.
  4117. * @returns {Matrix3} The modified result parameter.
  4118. */
  4119. Matrix3.subtract = function(left, right, result) {
  4120. if (!defined(left)) {
  4121. throw new DeveloperError('left is required');
  4122. }
  4123. if (!defined(right)) {
  4124. throw new DeveloperError('right is required');
  4125. }
  4126. if (!defined(result)) {
  4127. throw new DeveloperError('result is required');
  4128. }
  4129. result[0] = left[0] - right[0];
  4130. result[1] = left[1] - right[1];
  4131. result[2] = left[2] - right[2];
  4132. result[3] = left[3] - right[3];
  4133. result[4] = left[4] - right[4];
  4134. result[5] = left[5] - right[5];
  4135. result[6] = left[6] - right[6];
  4136. result[7] = left[7] - right[7];
  4137. result[8] = left[8] - right[8];
  4138. return result;
  4139. };
  4140. /**
  4141. * Computes the product of a matrix and a column vector.
  4142. *
  4143. * @param {Matrix3} matrix The matrix.
  4144. * @param {Cartesian3} cartesian The column.
  4145. * @param {Cartesian3} result The object onto which to store the result.
  4146. * @returns {Cartesian3} The modified result parameter.
  4147. */
  4148. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  4149. if (!defined(matrix)) {
  4150. throw new DeveloperError('matrix is required');
  4151. }
  4152. if (!defined(cartesian)) {
  4153. throw new DeveloperError('cartesian is required');
  4154. }
  4155. if (!defined(result)) {
  4156. throw new DeveloperError('result is required');
  4157. }
  4158. var vX = cartesian.x;
  4159. var vY = cartesian.y;
  4160. var vZ = cartesian.z;
  4161. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  4162. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  4163. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  4164. result.x = x;
  4165. result.y = y;
  4166. result.z = z;
  4167. return result;
  4168. };
  4169. /**
  4170. * Computes the product of a matrix and a scalar.
  4171. *
  4172. * @param {Matrix3} matrix The matrix.
  4173. * @param {Number} scalar The number to multiply by.
  4174. * @param {Matrix3} result The object onto which to store the result.
  4175. * @returns {Matrix3} The modified result parameter.
  4176. */
  4177. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  4178. if (!defined(matrix)) {
  4179. throw new DeveloperError('matrix is required');
  4180. }
  4181. if (typeof scalar !== 'number') {
  4182. throw new DeveloperError('scalar must be a number');
  4183. }
  4184. if (!defined(result)) {
  4185. throw new DeveloperError('result is required');
  4186. }
  4187. result[0] = matrix[0] * scalar;
  4188. result[1] = matrix[1] * scalar;
  4189. result[2] = matrix[2] * scalar;
  4190. result[3] = matrix[3] * scalar;
  4191. result[4] = matrix[4] * scalar;
  4192. result[5] = matrix[5] * scalar;
  4193. result[6] = matrix[6] * scalar;
  4194. result[7] = matrix[7] * scalar;
  4195. result[8] = matrix[8] * scalar;
  4196. return result;
  4197. };
  4198. /**
  4199. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  4200. *
  4201. * @param {Matrix3} matrix The matrix on the left-hand side.
  4202. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  4203. * @param {Matrix3} result The object onto which to store the result.
  4204. * @returns {Matrix3} The modified result parameter.
  4205. *
  4206. *
  4207. * @example
  4208. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  4209. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  4210. *
  4211. * @see Matrix3.fromScale
  4212. * @see Matrix3.multiplyByUniformScale
  4213. */
  4214. Matrix3.multiplyByScale = function(matrix, scale, result) {
  4215. if (!defined(matrix)) {
  4216. throw new DeveloperError('matrix is required');
  4217. }
  4218. if (!defined(scale)) {
  4219. throw new DeveloperError('scale is required');
  4220. }
  4221. if (!defined(result)) {
  4222. throw new DeveloperError('result is required');
  4223. }
  4224. result[0] = matrix[0] * scale.x;
  4225. result[1] = matrix[1] * scale.x;
  4226. result[2] = matrix[2] * scale.x;
  4227. result[3] = matrix[3] * scale.y;
  4228. result[4] = matrix[4] * scale.y;
  4229. result[5] = matrix[5] * scale.y;
  4230. result[6] = matrix[6] * scale.z;
  4231. result[7] = matrix[7] * scale.z;
  4232. result[8] = matrix[8] * scale.z;
  4233. return result;
  4234. };
  4235. /**
  4236. * Creates a negated copy of the provided matrix.
  4237. *
  4238. * @param {Matrix3} matrix The matrix to negate.
  4239. * @param {Matrix3} result The object onto which to store the result.
  4240. * @returns {Matrix3} The modified result parameter.
  4241. */
  4242. Matrix3.negate = function(matrix, result) {
  4243. if (!defined(matrix)) {
  4244. throw new DeveloperError('matrix is required');
  4245. }
  4246. if (!defined(result)) {
  4247. throw new DeveloperError('result is required');
  4248. }
  4249. result[0] = -matrix[0];
  4250. result[1] = -matrix[1];
  4251. result[2] = -matrix[2];
  4252. result[3] = -matrix[3];
  4253. result[4] = -matrix[4];
  4254. result[5] = -matrix[5];
  4255. result[6] = -matrix[6];
  4256. result[7] = -matrix[7];
  4257. result[8] = -matrix[8];
  4258. return result;
  4259. };
  4260. /**
  4261. * Computes the transpose of the provided matrix.
  4262. *
  4263. * @param {Matrix3} matrix The matrix to transpose.
  4264. * @param {Matrix3} result The object onto which to store the result.
  4265. * @returns {Matrix3} The modified result parameter.
  4266. */
  4267. Matrix3.transpose = function(matrix, result) {
  4268. if (!defined(matrix)) {
  4269. throw new DeveloperError('matrix is required');
  4270. }
  4271. if (!defined(result)) {
  4272. throw new DeveloperError('result is required');
  4273. }
  4274. var column0Row0 = matrix[0];
  4275. var column0Row1 = matrix[3];
  4276. var column0Row2 = matrix[6];
  4277. var column1Row0 = matrix[1];
  4278. var column1Row1 = matrix[4];
  4279. var column1Row2 = matrix[7];
  4280. var column2Row0 = matrix[2];
  4281. var column2Row1 = matrix[5];
  4282. var column2Row2 = matrix[8];
  4283. result[0] = column0Row0;
  4284. result[1] = column0Row1;
  4285. result[2] = column0Row2;
  4286. result[3] = column1Row0;
  4287. result[4] = column1Row1;
  4288. result[5] = column1Row2;
  4289. result[6] = column2Row0;
  4290. result[7] = column2Row1;
  4291. result[8] = column2Row2;
  4292. return result;
  4293. };
  4294. function computeFrobeniusNorm(matrix) {
  4295. var norm = 0.0;
  4296. for (var i = 0; i < 9; ++i) {
  4297. var temp = matrix[i];
  4298. norm += temp * temp;
  4299. }
  4300. return Math.sqrt(norm);
  4301. }
  4302. var rowVal = [1, 0, 0];
  4303. var colVal = [2, 2, 1];
  4304. function offDiagonalFrobeniusNorm(matrix) {
  4305. // Computes the "off-diagonal" Frobenius norm.
  4306. // Assumes matrix is symmetric.
  4307. var norm = 0.0;
  4308. for (var i = 0; i < 3; ++i) {
  4309. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  4310. norm += 2.0 * temp * temp;
  4311. }
  4312. return Math.sqrt(norm);
  4313. }
  4314. function shurDecomposition(matrix, result) {
  4315. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  4316. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  4317. //
  4318. // The routine takes a matrix, which is assumed to be symmetric, and
  4319. // finds the largest off-diagonal term, and then creates
  4320. // a matrix (result) which can be used to help reduce it
  4321. var tolerance = CesiumMath.EPSILON15;
  4322. var maxDiagonal = 0.0;
  4323. var rotAxis = 1;
  4324. // find pivot (rotAxis) based on max diagonal of matrix
  4325. for (var i = 0; i < 3; ++i) {
  4326. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  4327. if (temp > maxDiagonal) {
  4328. rotAxis = i;
  4329. maxDiagonal = temp;
  4330. }
  4331. }
  4332. var c = 1.0;
  4333. var s = 0.0;
  4334. var p = rowVal[rotAxis];
  4335. var q = colVal[rotAxis];
  4336. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  4337. var qq = matrix[Matrix3.getElementIndex(q, q)];
  4338. var pp = matrix[Matrix3.getElementIndex(p, p)];
  4339. var qp = matrix[Matrix3.getElementIndex(q, p)];
  4340. var tau = (qq - pp) / 2.0 / qp;
  4341. var t;
  4342. if (tau < 0.0) {
  4343. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  4344. } else {
  4345. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  4346. }
  4347. c = 1.0 / Math.sqrt(1.0 + t * t);
  4348. s = t * c;
  4349. }
  4350. result = Matrix3.clone(Matrix3.IDENTITY, result);
  4351. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  4352. result[Matrix3.getElementIndex(q, p)] = s;
  4353. result[Matrix3.getElementIndex(p, q)] = -s;
  4354. return result;
  4355. }
  4356. var jMatrix = new Matrix3();
  4357. var jMatrixTranspose = new Matrix3();
  4358. /**
  4359. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  4360. * <p>
  4361. * Returns a diagonal matrix and unitary matrix such that:
  4362. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  4363. * </p>
  4364. * <p>
  4365. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  4366. * of the unitary matrix are the corresponding eigenvectors.
  4367. * </p>
  4368. *
  4369. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  4370. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  4371. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  4372. *
  4373. * @example
  4374. * var a = //... symetric matrix
  4375. * var result = {
  4376. * unitary : new Cesium.Matrix3(),
  4377. * diagonal : new Cesium.Matrix3()
  4378. * };
  4379. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  4380. *
  4381. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  4382. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  4383. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  4384. *
  4385. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  4386. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  4387. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  4388. */
  4389. Matrix3.computeEigenDecomposition = function(matrix, result) {
  4390. if (!defined(matrix)) {
  4391. throw new DeveloperError('matrix is required.');
  4392. }
  4393. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  4394. // section 8.4.3 The Classical Jacobi Algorithm
  4395. var tolerance = CesiumMath.EPSILON20;
  4396. var maxSweeps = 10;
  4397. var count = 0;
  4398. var sweep = 0;
  4399. if (!defined(result)) {
  4400. result = {};
  4401. }
  4402. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  4403. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  4404. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  4405. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  4406. shurDecomposition(diagMatrix, jMatrix);
  4407. Matrix3.transpose(jMatrix, jMatrixTranspose);
  4408. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  4409. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  4410. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  4411. if (++count > 2) {
  4412. ++sweep;
  4413. count = 0;
  4414. }
  4415. }
  4416. return result;
  4417. };
  4418. /**
  4419. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  4420. *
  4421. * @param {Matrix3} matrix The matrix with signed elements.
  4422. * @param {Matrix3} result The object onto which to store the result.
  4423. * @returns {Matrix3} The modified result parameter.
  4424. */
  4425. Matrix3.abs = function(matrix, result) {
  4426. if (!defined(matrix)) {
  4427. throw new DeveloperError('matrix is required');
  4428. }
  4429. if (!defined(result)) {
  4430. throw new DeveloperError('result is required');
  4431. }
  4432. result[0] = Math.abs(matrix[0]);
  4433. result[1] = Math.abs(matrix[1]);
  4434. result[2] = Math.abs(matrix[2]);
  4435. result[3] = Math.abs(matrix[3]);
  4436. result[4] = Math.abs(matrix[4]);
  4437. result[5] = Math.abs(matrix[5]);
  4438. result[6] = Math.abs(matrix[6]);
  4439. result[7] = Math.abs(matrix[7]);
  4440. result[8] = Math.abs(matrix[8]);
  4441. return result;
  4442. };
  4443. /**
  4444. * Computes the determinant of the provided matrix.
  4445. *
  4446. * @param {Matrix3} matrix The matrix to use.
  4447. * @returns {Number} The value of the determinant of the matrix.
  4448. */
  4449. Matrix3.determinant = function(matrix) {
  4450. if (!defined(matrix)) {
  4451. throw new DeveloperError('matrix is required');
  4452. }
  4453. var m11 = matrix[0];
  4454. var m21 = matrix[3];
  4455. var m31 = matrix[6];
  4456. var m12 = matrix[1];
  4457. var m22 = matrix[4];
  4458. var m32 = matrix[7];
  4459. var m13 = matrix[2];
  4460. var m23 = matrix[5];
  4461. var m33 = matrix[8];
  4462. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  4463. };
  4464. /**
  4465. * Computes the inverse of the provided matrix.
  4466. *
  4467. * @param {Matrix3} matrix The matrix to invert.
  4468. * @param {Matrix3} result The object onto which to store the result.
  4469. * @returns {Matrix3} The modified result parameter.
  4470. *
  4471. * @exception {DeveloperError} matrix is not invertible.
  4472. */
  4473. Matrix3.inverse = function(matrix, result) {
  4474. if (!defined(matrix)) {
  4475. throw new DeveloperError('matrix is required');
  4476. }
  4477. if (!defined(result)) {
  4478. throw new DeveloperError('result is required');
  4479. }
  4480. var m11 = matrix[0];
  4481. var m21 = matrix[1];
  4482. var m31 = matrix[2];
  4483. var m12 = matrix[3];
  4484. var m22 = matrix[4];
  4485. var m32 = matrix[5];
  4486. var m13 = matrix[6];
  4487. var m23 = matrix[7];
  4488. var m33 = matrix[8];
  4489. var determinant = Matrix3.determinant(matrix);
  4490. if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
  4491. throw new DeveloperError('matrix is not invertible');
  4492. }
  4493. result[0] = m22 * m33 - m23 * m32;
  4494. result[1] = m23 * m31 - m21 * m33;
  4495. result[2] = m21 * m32 - m22 * m31;
  4496. result[3] = m13 * m32 - m12 * m33;
  4497. result[4] = m11 * m33 - m13 * m31;
  4498. result[5] = m12 * m31 - m11 * m32;
  4499. result[6] = m12 * m23 - m13 * m22;
  4500. result[7] = m13 * m21 - m11 * m23;
  4501. result[8] = m11 * m22 - m12 * m21;
  4502. var scale = 1.0 / determinant;
  4503. return Matrix3.multiplyByScalar(result, scale, result);
  4504. };
  4505. /**
  4506. * Compares the provided matrices componentwise and returns
  4507. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4508. *
  4509. * @param {Matrix3} [left] The first matrix.
  4510. * @param {Matrix3} [right] The second matrix.
  4511. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  4512. */
  4513. Matrix3.equals = function(left, right) {
  4514. return (left === right) ||
  4515. (defined(left) &&
  4516. defined(right) &&
  4517. left[0] === right[0] &&
  4518. left[1] === right[1] &&
  4519. left[2] === right[2] &&
  4520. left[3] === right[3] &&
  4521. left[4] === right[4] &&
  4522. left[5] === right[5] &&
  4523. left[6] === right[6] &&
  4524. left[7] === right[7] &&
  4525. left[8] === right[8]);
  4526. };
  4527. /**
  4528. * Compares the provided matrices componentwise and returns
  4529. * <code>true</code> if they are within the provided epsilon,
  4530. * <code>false</code> otherwise.
  4531. *
  4532. * @param {Matrix3} [left] The first matrix.
  4533. * @param {Matrix3} [right] The second matrix.
  4534. * @param {Number} epsilon The epsilon to use for equality testing.
  4535. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  4536. */
  4537. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  4538. if (typeof epsilon !== 'number') {
  4539. throw new DeveloperError('epsilon must be a number');
  4540. }
  4541. return (left === right) ||
  4542. (defined(left) &&
  4543. defined(right) &&
  4544. Math.abs(left[0] - right[0]) <= epsilon &&
  4545. Math.abs(left[1] - right[1]) <= epsilon &&
  4546. Math.abs(left[2] - right[2]) <= epsilon &&
  4547. Math.abs(left[3] - right[3]) <= epsilon &&
  4548. Math.abs(left[4] - right[4]) <= epsilon &&
  4549. Math.abs(left[5] - right[5]) <= epsilon &&
  4550. Math.abs(left[6] - right[6]) <= epsilon &&
  4551. Math.abs(left[7] - right[7]) <= epsilon &&
  4552. Math.abs(left[8] - right[8]) <= epsilon);
  4553. };
  4554. /**
  4555. * An immutable Matrix3 instance initialized to the identity matrix.
  4556. *
  4557. * @type {Matrix3}
  4558. * @constant
  4559. */
  4560. Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
  4561. 0.0, 1.0, 0.0,
  4562. 0.0, 0.0, 1.0));
  4563. /**
  4564. * An immutable Matrix3 instance initialized to the zero matrix.
  4565. *
  4566. * @type {Matrix3}
  4567. * @constant
  4568. */
  4569. Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
  4570. 0.0, 0.0, 0.0,
  4571. 0.0, 0.0, 0.0));
  4572. /**
  4573. * The index into Matrix3 for column 0, row 0.
  4574. *
  4575. * @type {Number}
  4576. * @constant
  4577. */
  4578. Matrix3.COLUMN0ROW0 = 0;
  4579. /**
  4580. * The index into Matrix3 for column 0, row 1.
  4581. *
  4582. * @type {Number}
  4583. * @constant
  4584. */
  4585. Matrix3.COLUMN0ROW1 = 1;
  4586. /**
  4587. * The index into Matrix3 for column 0, row 2.
  4588. *
  4589. * @type {Number}
  4590. * @constant
  4591. */
  4592. Matrix3.COLUMN0ROW2 = 2;
  4593. /**
  4594. * The index into Matrix3 for column 1, row 0.
  4595. *
  4596. * @type {Number}
  4597. * @constant
  4598. */
  4599. Matrix3.COLUMN1ROW0 = 3;
  4600. /**
  4601. * The index into Matrix3 for column 1, row 1.
  4602. *
  4603. * @type {Number}
  4604. * @constant
  4605. */
  4606. Matrix3.COLUMN1ROW1 = 4;
  4607. /**
  4608. * The index into Matrix3 for column 1, row 2.
  4609. *
  4610. * @type {Number}
  4611. * @constant
  4612. */
  4613. Matrix3.COLUMN1ROW2 = 5;
  4614. /**
  4615. * The index into Matrix3 for column 2, row 0.
  4616. *
  4617. * @type {Number}
  4618. * @constant
  4619. */
  4620. Matrix3.COLUMN2ROW0 = 6;
  4621. /**
  4622. * The index into Matrix3 for column 2, row 1.
  4623. *
  4624. * @type {Number}
  4625. * @constant
  4626. */
  4627. Matrix3.COLUMN2ROW1 = 7;
  4628. /**
  4629. * The index into Matrix3 for column 2, row 2.
  4630. *
  4631. * @type {Number}
  4632. * @constant
  4633. */
  4634. Matrix3.COLUMN2ROW2 = 8;
  4635. defineProperties(Matrix3.prototype, {
  4636. /**
  4637. * Gets the number of items in the collection.
  4638. * @memberof Matrix3.prototype
  4639. *
  4640. * @type {Number}
  4641. */
  4642. length : {
  4643. get : function() {
  4644. return Matrix3.packedLength;
  4645. }
  4646. }
  4647. });
  4648. /**
  4649. * Duplicates the provided Matrix3 instance.
  4650. *
  4651. * @param {Matrix3} [result] The object onto which to store the result.
  4652. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  4653. */
  4654. Matrix3.prototype.clone = function(result) {
  4655. return Matrix3.clone(this, result);
  4656. };
  4657. /**
  4658. * Compares this matrix to the provided matrix componentwise and returns
  4659. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4660. *
  4661. * @param {Matrix3} [right] The right hand side matrix.
  4662. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  4663. */
  4664. Matrix3.prototype.equals = function(right) {
  4665. return Matrix3.equals(this, right);
  4666. };
  4667. /**
  4668. * @private
  4669. */
  4670. Matrix3.equalsArray = function(matrix, array, offset) {
  4671. return matrix[0] === array[offset] &&
  4672. matrix[1] === array[offset + 1] &&
  4673. matrix[2] === array[offset + 2] &&
  4674. matrix[3] === array[offset + 3] &&
  4675. matrix[4] === array[offset + 4] &&
  4676. matrix[5] === array[offset + 5] &&
  4677. matrix[6] === array[offset + 6] &&
  4678. matrix[7] === array[offset + 7] &&
  4679. matrix[8] === array[offset + 8];
  4680. };
  4681. /**
  4682. * Compares this matrix to the provided matrix componentwise and returns
  4683. * <code>true</code> if they are within the provided epsilon,
  4684. * <code>false</code> otherwise.
  4685. *
  4686. * @param {Matrix3} [right] The right hand side matrix.
  4687. * @param {Number} epsilon The epsilon to use for equality testing.
  4688. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  4689. */
  4690. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  4691. return Matrix3.equalsEpsilon(this, right, epsilon);
  4692. };
  4693. /**
  4694. * Creates a string representing this Matrix with each row being
  4695. * on a separate line and in the format '(column0, column1, column2)'.
  4696. *
  4697. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  4698. */
  4699. Matrix3.prototype.toString = function() {
  4700. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  4701. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  4702. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  4703. };
  4704. return Matrix3;
  4705. });
  4706. /*global define*/
  4707. define('Core/Cartesian4',[
  4708. './defaultValue',
  4709. './defined',
  4710. './DeveloperError',
  4711. './freezeObject',
  4712. './Math'
  4713. ], function(
  4714. defaultValue,
  4715. defined,
  4716. DeveloperError,
  4717. freezeObject,
  4718. CesiumMath) {
  4719. 'use strict';
  4720. /**
  4721. * A 4D Cartesian point.
  4722. * @alias Cartesian4
  4723. * @constructor
  4724. *
  4725. * @param {Number} [x=0.0] The X component.
  4726. * @param {Number} [y=0.0] The Y component.
  4727. * @param {Number} [z=0.0] The Z component.
  4728. * @param {Number} [w=0.0] The W component.
  4729. *
  4730. * @see Cartesian2
  4731. * @see Cartesian3
  4732. * @see Packable
  4733. */
  4734. function Cartesian4(x, y, z, w) {
  4735. /**
  4736. * The X component.
  4737. * @type {Number}
  4738. * @default 0.0
  4739. */
  4740. this.x = defaultValue(x, 0.0);
  4741. /**
  4742. * The Y component.
  4743. * @type {Number}
  4744. * @default 0.0
  4745. */
  4746. this.y = defaultValue(y, 0.0);
  4747. /**
  4748. * The Z component.
  4749. * @type {Number}
  4750. * @default 0.0
  4751. */
  4752. this.z = defaultValue(z, 0.0);
  4753. /**
  4754. * The W component.
  4755. * @type {Number}
  4756. * @default 0.0
  4757. */
  4758. this.w = defaultValue(w, 0.0);
  4759. }
  4760. /**
  4761. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  4762. *
  4763. * @param {Number} x The x coordinate.
  4764. * @param {Number} y The y coordinate.
  4765. * @param {Number} z The z coordinate.
  4766. * @param {Number} w The w coordinate.
  4767. * @param {Cartesian4} [result] The object onto which to store the result.
  4768. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4769. */
  4770. Cartesian4.fromElements = function(x, y, z, w, result) {
  4771. if (!defined(result)) {
  4772. return new Cartesian4(x, y, z, w);
  4773. }
  4774. result.x = x;
  4775. result.y = y;
  4776. result.z = z;
  4777. result.w = w;
  4778. return result;
  4779. };
  4780. /**
  4781. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  4782. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  4783. *
  4784. * @param {Color} color The source color.
  4785. * @param {Cartesian4} [result] The object onto which to store the result.
  4786. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4787. */
  4788. Cartesian4.fromColor = function(color, result) {
  4789. if (!defined(color)) {
  4790. throw new DeveloperError('color is required');
  4791. }
  4792. if (!defined(result)) {
  4793. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  4794. }
  4795. result.x = color.red;
  4796. result.y = color.green;
  4797. result.z = color.blue;
  4798. result.w = color.alpha;
  4799. return result;
  4800. };
  4801. /**
  4802. * Duplicates a Cartesian4 instance.
  4803. *
  4804. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  4805. * @param {Cartesian4} [result] The object onto which to store the result.
  4806. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  4807. */
  4808. Cartesian4.clone = function(cartesian, result) {
  4809. if (!defined(cartesian)) {
  4810. return undefined;
  4811. }
  4812. if (!defined(result)) {
  4813. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  4814. }
  4815. result.x = cartesian.x;
  4816. result.y = cartesian.y;
  4817. result.z = cartesian.z;
  4818. result.w = cartesian.w;
  4819. return result;
  4820. };
  4821. /**
  4822. * The number of elements used to pack the object into an array.
  4823. * @type {Number}
  4824. */
  4825. Cartesian4.packedLength = 4;
  4826. /**
  4827. * Stores the provided instance into the provided array.
  4828. *
  4829. * @param {Cartesian4} value The value to pack.
  4830. * @param {Number[]} array The array to pack into.
  4831. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4832. *
  4833. * @returns {Number[]} The array that was packed into
  4834. */
  4835. Cartesian4.pack = function(value, array, startingIndex) {
  4836. if (!defined(value)) {
  4837. throw new DeveloperError('value is required');
  4838. }
  4839. if (!defined(array)) {
  4840. throw new DeveloperError('array is required');
  4841. }
  4842. startingIndex = defaultValue(startingIndex, 0);
  4843. array[startingIndex++] = value.x;
  4844. array[startingIndex++] = value.y;
  4845. array[startingIndex++] = value.z;
  4846. array[startingIndex] = value.w;
  4847. return array;
  4848. };
  4849. /**
  4850. * Retrieves an instance from a packed array.
  4851. *
  4852. * @param {Number[]} array The packed array.
  4853. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4854. * @param {Cartesian4} [result] The object into which to store the result.
  4855. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4856. */
  4857. Cartesian4.unpack = function(array, startingIndex, result) {
  4858. if (!defined(array)) {
  4859. throw new DeveloperError('array is required');
  4860. }
  4861. startingIndex = defaultValue(startingIndex, 0);
  4862. if (!defined(result)) {
  4863. result = new Cartesian4();
  4864. }
  4865. result.x = array[startingIndex++];
  4866. result.y = array[startingIndex++];
  4867. result.z = array[startingIndex++];
  4868. result.w = array[startingIndex];
  4869. return result;
  4870. };
  4871. /**
  4872. * Flattens an array of Cartesian4s into and array of components.
  4873. *
  4874. * @param {Cartesian4[]} array The array of cartesians to pack.
  4875. * @param {Number[]} result The array onto which to store the result.
  4876. * @returns {Number[]} The packed array.
  4877. */
  4878. Cartesian4.packArray = function(array, result) {
  4879. if (!defined(array)) {
  4880. throw new DeveloperError('array is required');
  4881. }
  4882. var length = array.length;
  4883. if (!defined(result)) {
  4884. result = new Array(length * 4);
  4885. } else {
  4886. result.length = length * 4;
  4887. }
  4888. for (var i = 0; i < length; ++i) {
  4889. Cartesian4.pack(array[i], result, i * 4);
  4890. }
  4891. return result;
  4892. };
  4893. /**
  4894. * Unpacks an array of cartesian components into and array of Cartesian4s.
  4895. *
  4896. * @param {Number[]} array The array of components to unpack.
  4897. * @param {Cartesian4[]} result The array onto which to store the result.
  4898. * @returns {Cartesian4[]} The unpacked array.
  4899. */
  4900. Cartesian4.unpackArray = function(array, result) {
  4901. if (!defined(array)) {
  4902. throw new DeveloperError('array is required');
  4903. }
  4904. var length = array.length;
  4905. if (!defined(result)) {
  4906. result = new Array(length / 4);
  4907. } else {
  4908. result.length = length / 4;
  4909. }
  4910. for (var i = 0; i < length; i += 4) {
  4911. var index = i / 4;
  4912. result[index] = Cartesian4.unpack(array, i, result[index]);
  4913. }
  4914. return result;
  4915. };
  4916. /**
  4917. * Creates a Cartesian4 from four consecutive elements in an array.
  4918. * @function
  4919. *
  4920. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  4921. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  4922. * @param {Cartesian4} [result] The object onto which to store the result.
  4923. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  4924. *
  4925. * @example
  4926. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  4927. * var v = [1.0, 2.0, 3.0, 4.0];
  4928. * var p = Cesium.Cartesian4.fromArray(v);
  4929. *
  4930. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  4931. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  4932. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  4933. */
  4934. Cartesian4.fromArray = Cartesian4.unpack;
  4935. /**
  4936. * Computes the value of the maximum component for the supplied Cartesian.
  4937. *
  4938. * @param {Cartesian4} cartesian The cartesian to use.
  4939. * @returns {Number} The value of the maximum component.
  4940. */
  4941. Cartesian4.maximumComponent = function(cartesian) {
  4942. if (!defined(cartesian)) {
  4943. throw new DeveloperError('cartesian is required');
  4944. }
  4945. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  4946. };
  4947. /**
  4948. * Computes the value of the minimum component for the supplied Cartesian.
  4949. *
  4950. * @param {Cartesian4} cartesian The cartesian to use.
  4951. * @returns {Number} The value of the minimum component.
  4952. */
  4953. Cartesian4.minimumComponent = function(cartesian) {
  4954. if (!defined(cartesian)) {
  4955. throw new DeveloperError('cartesian is required');
  4956. }
  4957. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  4958. };
  4959. /**
  4960. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  4961. *
  4962. * @param {Cartesian4} first A cartesian to compare.
  4963. * @param {Cartesian4} second A cartesian to compare.
  4964. * @param {Cartesian4} result The object into which to store the result.
  4965. * @returns {Cartesian4} A cartesian with the minimum components.
  4966. */
  4967. Cartesian4.minimumByComponent = function(first, second, result) {
  4968. if (!defined(first)) {
  4969. throw new DeveloperError('first is required.');
  4970. }
  4971. if (!defined(second)) {
  4972. throw new DeveloperError('second is required.');
  4973. }
  4974. if (!defined(result)) {
  4975. throw new DeveloperError('result is required.');
  4976. }
  4977. result.x = Math.min(first.x, second.x);
  4978. result.y = Math.min(first.y, second.y);
  4979. result.z = Math.min(first.z, second.z);
  4980. result.w = Math.min(first.w, second.w);
  4981. return result;
  4982. };
  4983. /**
  4984. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  4985. *
  4986. * @param {Cartesian4} first A cartesian to compare.
  4987. * @param {Cartesian4} second A cartesian to compare.
  4988. * @param {Cartesian4} result The object into which to store the result.
  4989. * @returns {Cartesian4} A cartesian with the maximum components.
  4990. */
  4991. Cartesian4.maximumByComponent = function(first, second, result) {
  4992. if (!defined(first)) {
  4993. throw new DeveloperError('first is required.');
  4994. }
  4995. if (!defined(second)) {
  4996. throw new DeveloperError('second is required.');
  4997. }
  4998. if (!defined(result)) {
  4999. throw new DeveloperError('result is required.');
  5000. }
  5001. result.x = Math.max(first.x, second.x);
  5002. result.y = Math.max(first.y, second.y);
  5003. result.z = Math.max(first.z, second.z);
  5004. result.w = Math.max(first.w, second.w);
  5005. return result;
  5006. };
  5007. /**
  5008. * Computes the provided Cartesian's squared magnitude.
  5009. *
  5010. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  5011. * @returns {Number} The squared magnitude.
  5012. */
  5013. Cartesian4.magnitudeSquared = function(cartesian) {
  5014. if (!defined(cartesian)) {
  5015. throw new DeveloperError('cartesian is required');
  5016. }
  5017. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  5018. };
  5019. /**
  5020. * Computes the Cartesian's magnitude (length).
  5021. *
  5022. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  5023. * @returns {Number} The magnitude.
  5024. */
  5025. Cartesian4.magnitude = function(cartesian) {
  5026. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  5027. };
  5028. var distanceScratch = new Cartesian4();
  5029. /**
  5030. * Computes the 4-space distance between two points.
  5031. *
  5032. * @param {Cartesian4} left The first point to compute the distance from.
  5033. * @param {Cartesian4} right The second point to compute the distance to.
  5034. * @returns {Number} The distance between two points.
  5035. *
  5036. * @example
  5037. * // Returns 1.0
  5038. * var d = Cesium.Cartesian4.distance(
  5039. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  5040. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  5041. */
  5042. Cartesian4.distance = function(left, right) {
  5043. if (!defined(left) || !defined(right)) {
  5044. throw new DeveloperError('left and right are required.');
  5045. }
  5046. Cartesian4.subtract(left, right, distanceScratch);
  5047. return Cartesian4.magnitude(distanceScratch);
  5048. };
  5049. /**
  5050. * Computes the squared distance between two points. Comparing squared distances
  5051. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  5052. *
  5053. * @param {Cartesian4} left The first point to compute the distance from.
  5054. * @param {Cartesian4} right The second point to compute the distance to.
  5055. * @returns {Number} The distance between two points.
  5056. *
  5057. * @example
  5058. * // Returns 4.0, not 2.0
  5059. * var d = Cesium.Cartesian4.distance(
  5060. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  5061. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  5062. */
  5063. Cartesian4.distanceSquared = function(left, right) {
  5064. if (!defined(left) || !defined(right)) {
  5065. throw new DeveloperError('left and right are required.');
  5066. }
  5067. Cartesian4.subtract(left, right, distanceScratch);
  5068. return Cartesian4.magnitudeSquared(distanceScratch);
  5069. };
  5070. /**
  5071. * Computes the normalized form of the supplied Cartesian.
  5072. *
  5073. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  5074. * @param {Cartesian4} result The object onto which to store the result.
  5075. * @returns {Cartesian4} The modified result parameter.
  5076. */
  5077. Cartesian4.normalize = function(cartesian, result) {
  5078. if (!defined(cartesian)) {
  5079. throw new DeveloperError('cartesian is required');
  5080. }
  5081. if (!defined(result)) {
  5082. throw new DeveloperError('result is required');
  5083. }
  5084. var magnitude = Cartesian4.magnitude(cartesian);
  5085. result.x = cartesian.x / magnitude;
  5086. result.y = cartesian.y / magnitude;
  5087. result.z = cartesian.z / magnitude;
  5088. result.w = cartesian.w / magnitude;
  5089. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  5090. throw new DeveloperError('normalized result is not a number');
  5091. }
  5092. return result;
  5093. };
  5094. /**
  5095. * Computes the dot (scalar) product of two Cartesians.
  5096. *
  5097. * @param {Cartesian4} left The first Cartesian.
  5098. * @param {Cartesian4} right The second Cartesian.
  5099. * @returns {Number} The dot product.
  5100. */
  5101. Cartesian4.dot = function(left, right) {
  5102. if (!defined(left)) {
  5103. throw new DeveloperError('left is required');
  5104. }
  5105. if (!defined(right)) {
  5106. throw new DeveloperError('right is required');
  5107. }
  5108. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  5109. };
  5110. /**
  5111. * Computes the componentwise product of two Cartesians.
  5112. *
  5113. * @param {Cartesian4} left The first Cartesian.
  5114. * @param {Cartesian4} right The second Cartesian.
  5115. * @param {Cartesian4} result The object onto which to store the result.
  5116. * @returns {Cartesian4} The modified result parameter.
  5117. */
  5118. Cartesian4.multiplyComponents = function(left, right, result) {
  5119. if (!defined(left)) {
  5120. throw new DeveloperError('left is required');
  5121. }
  5122. if (!defined(right)) {
  5123. throw new DeveloperError('right is required');
  5124. }
  5125. if (!defined(result)) {
  5126. throw new DeveloperError('result is required');
  5127. }
  5128. result.x = left.x * right.x;
  5129. result.y = left.y * right.y;
  5130. result.z = left.z * right.z;
  5131. result.w = left.w * right.w;
  5132. return result;
  5133. };
  5134. /**
  5135. * Computes the componentwise quotient of two Cartesians.
  5136. *
  5137. * @param {Cartesian4} left The first Cartesian.
  5138. * @param {Cartesian4} right The second Cartesian.
  5139. * @param {Cartesian4} result The object onto which to store the result.
  5140. * @returns {Cartesian4} The modified result parameter.
  5141. */
  5142. Cartesian4.divideComponents = function(left, right, result) {
  5143. if (!defined(left)) {
  5144. throw new DeveloperError('left is required');
  5145. }
  5146. if (!defined(right)) {
  5147. throw new DeveloperError('right is required');
  5148. }
  5149. if (!defined(result)) {
  5150. throw new DeveloperError('result is required');
  5151. }
  5152. result.x = left.x / right.x;
  5153. result.y = left.y / right.y;
  5154. result.z = left.z / right.z;
  5155. result.w = left.w / right.w;
  5156. return result;
  5157. };
  5158. /**
  5159. * Computes the componentwise sum of two Cartesians.
  5160. *
  5161. * @param {Cartesian4} left The first Cartesian.
  5162. * @param {Cartesian4} right The second Cartesian.
  5163. * @param {Cartesian4} result The object onto which to store the result.
  5164. * @returns {Cartesian4} The modified result parameter.
  5165. */
  5166. Cartesian4.add = function(left, right, result) {
  5167. if (!defined(left)) {
  5168. throw new DeveloperError('left is required');
  5169. }
  5170. if (!defined(right)) {
  5171. throw new DeveloperError('right is required');
  5172. }
  5173. if (!defined(result)) {
  5174. throw new DeveloperError('result is required');
  5175. }
  5176. result.x = left.x + right.x;
  5177. result.y = left.y + right.y;
  5178. result.z = left.z + right.z;
  5179. result.w = left.w + right.w;
  5180. return result;
  5181. };
  5182. /**
  5183. * Computes the componentwise difference of two Cartesians.
  5184. *
  5185. * @param {Cartesian4} left The first Cartesian.
  5186. * @param {Cartesian4} right The second Cartesian.
  5187. * @param {Cartesian4} result The object onto which to store the result.
  5188. * @returns {Cartesian4} The modified result parameter.
  5189. */
  5190. Cartesian4.subtract = function(left, right, result) {
  5191. if (!defined(left)) {
  5192. throw new DeveloperError('left is required');
  5193. }
  5194. if (!defined(right)) {
  5195. throw new DeveloperError('right is required');
  5196. }
  5197. if (!defined(result)) {
  5198. throw new DeveloperError('result is required');
  5199. }
  5200. result.x = left.x - right.x;
  5201. result.y = left.y - right.y;
  5202. result.z = left.z - right.z;
  5203. result.w = left.w - right.w;
  5204. return result;
  5205. };
  5206. /**
  5207. * Multiplies the provided Cartesian componentwise by the provided scalar.
  5208. *
  5209. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  5210. * @param {Number} scalar The scalar to multiply with.
  5211. * @param {Cartesian4} result The object onto which to store the result.
  5212. * @returns {Cartesian4} The modified result parameter.
  5213. */
  5214. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  5215. if (!defined(cartesian)) {
  5216. throw new DeveloperError('cartesian is required');
  5217. }
  5218. if (typeof scalar !== 'number') {
  5219. throw new DeveloperError('scalar is required and must be a number.');
  5220. }
  5221. if (!defined(result)) {
  5222. throw new DeveloperError('result is required');
  5223. }
  5224. result.x = cartesian.x * scalar;
  5225. result.y = cartesian.y * scalar;
  5226. result.z = cartesian.z * scalar;
  5227. result.w = cartesian.w * scalar;
  5228. return result;
  5229. };
  5230. /**
  5231. * Divides the provided Cartesian componentwise by the provided scalar.
  5232. *
  5233. * @param {Cartesian4} cartesian The Cartesian to be divided.
  5234. * @param {Number} scalar The scalar to divide by.
  5235. * @param {Cartesian4} result The object onto which to store the result.
  5236. * @returns {Cartesian4} The modified result parameter.
  5237. */
  5238. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  5239. if (!defined(cartesian)) {
  5240. throw new DeveloperError('cartesian is required');
  5241. }
  5242. if (typeof scalar !== 'number') {
  5243. throw new DeveloperError('scalar is required and must be a number.');
  5244. }
  5245. if (!defined(result)) {
  5246. throw new DeveloperError('result is required');
  5247. }
  5248. result.x = cartesian.x / scalar;
  5249. result.y = cartesian.y / scalar;
  5250. result.z = cartesian.z / scalar;
  5251. result.w = cartesian.w / scalar;
  5252. return result;
  5253. };
  5254. /**
  5255. * Negates the provided Cartesian.
  5256. *
  5257. * @param {Cartesian4} cartesian The Cartesian to be negated.
  5258. * @param {Cartesian4} result The object onto which to store the result.
  5259. * @returns {Cartesian4} The modified result parameter.
  5260. */
  5261. Cartesian4.negate = function(cartesian, result) {
  5262. if (!defined(cartesian)) {
  5263. throw new DeveloperError('cartesian is required');
  5264. }
  5265. if (!defined(result)) {
  5266. throw new DeveloperError('result is required');
  5267. }
  5268. result.x = -cartesian.x;
  5269. result.y = -cartesian.y;
  5270. result.z = -cartesian.z;
  5271. result.w = -cartesian.w;
  5272. return result;
  5273. };
  5274. /**
  5275. * Computes the absolute value of the provided Cartesian.
  5276. *
  5277. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  5278. * @param {Cartesian4} result The object onto which to store the result.
  5279. * @returns {Cartesian4} The modified result parameter.
  5280. */
  5281. Cartesian4.abs = function(cartesian, result) {
  5282. if (!defined(cartesian)) {
  5283. throw new DeveloperError('cartesian is required');
  5284. }
  5285. if (!defined(result)) {
  5286. throw new DeveloperError('result is required');
  5287. }
  5288. result.x = Math.abs(cartesian.x);
  5289. result.y = Math.abs(cartesian.y);
  5290. result.z = Math.abs(cartesian.z);
  5291. result.w = Math.abs(cartesian.w);
  5292. return result;
  5293. };
  5294. var lerpScratch = new Cartesian4();
  5295. /**
  5296. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  5297. *
  5298. * @param {Cartesian4} start The value corresponding to t at 0.0.
  5299. * @param {Cartesian4}end The value corresponding to t at 1.0.
  5300. * @param {Number} t The point along t at which to interpolate.
  5301. * @param {Cartesian4} result The object onto which to store the result.
  5302. * @returns {Cartesian4} The modified result parameter.
  5303. */
  5304. Cartesian4.lerp = function(start, end, t, result) {
  5305. if (!defined(start)) {
  5306. throw new DeveloperError('start is required.');
  5307. }
  5308. if (!defined(end)) {
  5309. throw new DeveloperError('end is required.');
  5310. }
  5311. if (typeof t !== 'number') {
  5312. throw new DeveloperError('t is required and must be a number.');
  5313. }
  5314. if (!defined(result)) {
  5315. throw new DeveloperError('result is required.');
  5316. }
  5317. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  5318. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  5319. return Cartesian4.add(lerpScratch, result, result);
  5320. };
  5321. var mostOrthogonalAxisScratch = new Cartesian4();
  5322. /**
  5323. * Returns the axis that is most orthogonal to the provided Cartesian.
  5324. *
  5325. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  5326. * @param {Cartesian4} result The object onto which to store the result.
  5327. * @returns {Cartesian4} The most orthogonal axis.
  5328. */
  5329. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  5330. if (!defined(cartesian)) {
  5331. throw new DeveloperError('cartesian is required.');
  5332. }
  5333. if (!defined(result)) {
  5334. throw new DeveloperError('result is required.');
  5335. }
  5336. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  5337. Cartesian4.abs(f, f);
  5338. if (f.x <= f.y) {
  5339. if (f.x <= f.z) {
  5340. if (f.x <= f.w) {
  5341. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  5342. } else {
  5343. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5344. }
  5345. } else if (f.z <= f.w) {
  5346. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  5347. } else {
  5348. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5349. }
  5350. } else if (f.y <= f.z) {
  5351. if (f.y <= f.w) {
  5352. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  5353. } else {
  5354. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5355. }
  5356. } else if (f.z <= f.w) {
  5357. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  5358. } else {
  5359. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  5360. }
  5361. return result;
  5362. };
  5363. /**
  5364. * Compares the provided Cartesians componentwise and returns
  5365. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5366. *
  5367. * @param {Cartesian4} [left] The first Cartesian.
  5368. * @param {Cartesian4} [right] The second Cartesian.
  5369. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  5370. */
  5371. Cartesian4.equals = function(left, right) {
  5372. return (left === right) ||
  5373. ((defined(left)) &&
  5374. (defined(right)) &&
  5375. (left.x === right.x) &&
  5376. (left.y === right.y) &&
  5377. (left.z === right.z) &&
  5378. (left.w === right.w));
  5379. };
  5380. /**
  5381. * @private
  5382. */
  5383. Cartesian4.equalsArray = function(cartesian, array, offset) {
  5384. return cartesian.x === array[offset] &&
  5385. cartesian.y === array[offset + 1] &&
  5386. cartesian.z === array[offset + 2] &&
  5387. cartesian.w === array[offset + 3];
  5388. };
  5389. /**
  5390. * Compares the provided Cartesians componentwise and returns
  5391. * <code>true</code> if they pass an absolute or relative tolerance test,
  5392. * <code>false</code> otherwise.
  5393. *
  5394. * @param {Cartesian4} [left] The first Cartesian.
  5395. * @param {Cartesian4} [right] The second Cartesian.
  5396. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  5397. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  5398. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  5399. */
  5400. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  5401. return (left === right) ||
  5402. (defined(left) &&
  5403. defined(right) &&
  5404. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  5405. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  5406. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  5407. CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  5408. };
  5409. /**
  5410. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  5411. *
  5412. * @type {Cartesian4}
  5413. * @constant
  5414. */
  5415. Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  5416. /**
  5417. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  5418. *
  5419. * @type {Cartesian4}
  5420. * @constant
  5421. */
  5422. Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  5423. /**
  5424. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  5425. *
  5426. * @type {Cartesian4}
  5427. * @constant
  5428. */
  5429. Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  5430. /**
  5431. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  5432. *
  5433. * @type {Cartesian4}
  5434. * @constant
  5435. */
  5436. Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  5437. /**
  5438. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  5439. *
  5440. * @type {Cartesian4}
  5441. * @constant
  5442. */
  5443. Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  5444. /**
  5445. * Duplicates this Cartesian4 instance.
  5446. *
  5447. * @param {Cartesian4} [result] The object onto which to store the result.
  5448. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  5449. */
  5450. Cartesian4.prototype.clone = function(result) {
  5451. return Cartesian4.clone(this, result);
  5452. };
  5453. /**
  5454. * Compares this Cartesian against the provided Cartesian componentwise and returns
  5455. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5456. *
  5457. * @param {Cartesian4} [right] The right hand side Cartesian.
  5458. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5459. */
  5460. Cartesian4.prototype.equals = function(right) {
  5461. return Cartesian4.equals(this, right);
  5462. };
  5463. /**
  5464. * Compares this Cartesian against the provided Cartesian componentwise and returns
  5465. * <code>true</code> if they pass an absolute or relative tolerance test,
  5466. * <code>false</code> otherwise.
  5467. *
  5468. * @param {Cartesian4} [right] The right hand side Cartesian.
  5469. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  5470. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  5471. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  5472. */
  5473. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  5474. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  5475. };
  5476. /**
  5477. * Creates a string representing this Cartesian in the format '(x, y)'.
  5478. *
  5479. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  5480. */
  5481. Cartesian4.prototype.toString = function() {
  5482. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  5483. };
  5484. return Cartesian4;
  5485. });
  5486. /*global define*/
  5487. define('Core/RuntimeError',[
  5488. './defined'
  5489. ], function(
  5490. defined) {
  5491. 'use strict';
  5492. /**
  5493. * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
  5494. * out of memory, could not compile shader, etc. If a function may throw this
  5495. * exception, the calling code should be prepared to catch it.
  5496. * <br /><br />
  5497. * On the other hand, a {@link DeveloperError} indicates an exception due
  5498. * to a developer error, e.g., invalid argument, that usually indicates a bug in the
  5499. * calling code.
  5500. *
  5501. * @alias RuntimeError
  5502. * @constructor
  5503. * @extends Error
  5504. *
  5505. * @param {String} [message] The error message for this exception.
  5506. *
  5507. * @see DeveloperError
  5508. */
  5509. function RuntimeError(message) {
  5510. /**
  5511. * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
  5512. * @type {String}
  5513. * @readonly
  5514. */
  5515. this.name = 'RuntimeError';
  5516. /**
  5517. * The explanation for why this exception was thrown.
  5518. * @type {String}
  5519. * @readonly
  5520. */
  5521. this.message = message;
  5522. //Browsers such as IE don't have a stack property until you actually throw the error.
  5523. var stack;
  5524. try {
  5525. throw new Error();
  5526. } catch (e) {
  5527. stack = e.stack;
  5528. }
  5529. /**
  5530. * The stack trace of this exception, if available.
  5531. * @type {String}
  5532. * @readonly
  5533. */
  5534. this.stack = stack;
  5535. }
  5536. if (defined(Object.create)) {
  5537. RuntimeError.prototype = Object.create(Error.prototype);
  5538. RuntimeError.prototype.constructor = RuntimeError;
  5539. }
  5540. RuntimeError.prototype.toString = function() {
  5541. var str = this.name + ': ' + this.message;
  5542. if (defined(this.stack)) {
  5543. str += '\n' + this.stack.toString();
  5544. }
  5545. return str;
  5546. };
  5547. return RuntimeError;
  5548. });
  5549. /*global define*/
  5550. define('Core/Matrix4',[
  5551. './Cartesian3',
  5552. './Cartesian4',
  5553. './defaultValue',
  5554. './defined',
  5555. './defineProperties',
  5556. './DeveloperError',
  5557. './freezeObject',
  5558. './Math',
  5559. './Matrix3',
  5560. './RuntimeError'
  5561. ], function(
  5562. Cartesian3,
  5563. Cartesian4,
  5564. defaultValue,
  5565. defined,
  5566. defineProperties,
  5567. DeveloperError,
  5568. freezeObject,
  5569. CesiumMath,
  5570. Matrix3,
  5571. RuntimeError) {
  5572. 'use strict';
  5573. /**
  5574. * A 4x4 matrix, indexable as a column-major order array.
  5575. * Constructor parameters are in row-major order for code readability.
  5576. * @alias Matrix4
  5577. * @constructor
  5578. *
  5579. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  5580. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  5581. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  5582. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  5583. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  5584. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  5585. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  5586. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  5587. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  5588. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  5589. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  5590. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  5591. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  5592. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  5593. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  5594. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  5595. *
  5596. * @see Matrix4.fromColumnMajorArray
  5597. * @see Matrix4.fromRowMajorArray
  5598. * @see Matrix4.fromRotationTranslation
  5599. * @see Matrix4.fromTranslationRotationScale
  5600. * @see Matrix4.fromTranslationQuaternionRotationScale
  5601. * @see Matrix4.fromTranslation
  5602. * @see Matrix4.fromScale
  5603. * @see Matrix4.fromUniformScale
  5604. * @see Matrix4.fromCamera
  5605. * @see Matrix4.computePerspectiveFieldOfView
  5606. * @see Matrix4.computeOrthographicOffCenter
  5607. * @see Matrix4.computePerspectiveOffCenter
  5608. * @see Matrix4.computeInfinitePerspectiveOffCenter
  5609. * @see Matrix4.computeViewportTransformation
  5610. * @see Matrix4.computeView
  5611. * @see Matrix2
  5612. * @see Matrix3
  5613. * @see Packable
  5614. */
  5615. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  5616. column0Row1, column1Row1, column2Row1, column3Row1,
  5617. column0Row2, column1Row2, column2Row2, column3Row2,
  5618. column0Row3, column1Row3, column2Row3, column3Row3) {
  5619. this[0] = defaultValue(column0Row0, 0.0);
  5620. this[1] = defaultValue(column0Row1, 0.0);
  5621. this[2] = defaultValue(column0Row2, 0.0);
  5622. this[3] = defaultValue(column0Row3, 0.0);
  5623. this[4] = defaultValue(column1Row0, 0.0);
  5624. this[5] = defaultValue(column1Row1, 0.0);
  5625. this[6] = defaultValue(column1Row2, 0.0);
  5626. this[7] = defaultValue(column1Row3, 0.0);
  5627. this[8] = defaultValue(column2Row0, 0.0);
  5628. this[9] = defaultValue(column2Row1, 0.0);
  5629. this[10] = defaultValue(column2Row2, 0.0);
  5630. this[11] = defaultValue(column2Row3, 0.0);
  5631. this[12] = defaultValue(column3Row0, 0.0);
  5632. this[13] = defaultValue(column3Row1, 0.0);
  5633. this[14] = defaultValue(column3Row2, 0.0);
  5634. this[15] = defaultValue(column3Row3, 0.0);
  5635. }
  5636. /**
  5637. * The number of elements used to pack the object into an array.
  5638. * @type {Number}
  5639. */
  5640. Matrix4.packedLength = 16;
  5641. /**
  5642. * Stores the provided instance into the provided array.
  5643. *
  5644. * @param {Matrix4} value The value to pack.
  5645. * @param {Number[]} array The array to pack into.
  5646. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5647. *
  5648. * @returns {Number[]} The array that was packed into
  5649. */
  5650. Matrix4.pack = function(value, array, startingIndex) {
  5651. if (!defined(value)) {
  5652. throw new DeveloperError('value is required');
  5653. }
  5654. if (!defined(array)) {
  5655. throw new DeveloperError('array is required');
  5656. }
  5657. startingIndex = defaultValue(startingIndex, 0);
  5658. array[startingIndex++] = value[0];
  5659. array[startingIndex++] = value[1];
  5660. array[startingIndex++] = value[2];
  5661. array[startingIndex++] = value[3];
  5662. array[startingIndex++] = value[4];
  5663. array[startingIndex++] = value[5];
  5664. array[startingIndex++] = value[6];
  5665. array[startingIndex++] = value[7];
  5666. array[startingIndex++] = value[8];
  5667. array[startingIndex++] = value[9];
  5668. array[startingIndex++] = value[10];
  5669. array[startingIndex++] = value[11];
  5670. array[startingIndex++] = value[12];
  5671. array[startingIndex++] = value[13];
  5672. array[startingIndex++] = value[14];
  5673. array[startingIndex] = value[15];
  5674. return array;
  5675. };
  5676. /**
  5677. * Retrieves an instance from a packed array.
  5678. *
  5679. * @param {Number[]} array The packed array.
  5680. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5681. * @param {Matrix4} [result] The object into which to store the result.
  5682. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  5683. */
  5684. Matrix4.unpack = function(array, startingIndex, result) {
  5685. if (!defined(array)) {
  5686. throw new DeveloperError('array is required');
  5687. }
  5688. startingIndex = defaultValue(startingIndex, 0);
  5689. if (!defined(result)) {
  5690. result = new Matrix4();
  5691. }
  5692. result[0] = array[startingIndex++];
  5693. result[1] = array[startingIndex++];
  5694. result[2] = array[startingIndex++];
  5695. result[3] = array[startingIndex++];
  5696. result[4] = array[startingIndex++];
  5697. result[5] = array[startingIndex++];
  5698. result[6] = array[startingIndex++];
  5699. result[7] = array[startingIndex++];
  5700. result[8] = array[startingIndex++];
  5701. result[9] = array[startingIndex++];
  5702. result[10] = array[startingIndex++];
  5703. result[11] = array[startingIndex++];
  5704. result[12] = array[startingIndex++];
  5705. result[13] = array[startingIndex++];
  5706. result[14] = array[startingIndex++];
  5707. result[15] = array[startingIndex];
  5708. return result;
  5709. };
  5710. /**
  5711. * Duplicates a Matrix4 instance.
  5712. *
  5713. * @param {Matrix4} matrix The matrix to duplicate.
  5714. * @param {Matrix4} [result] The object onto which to store the result.
  5715. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  5716. */
  5717. Matrix4.clone = function(matrix, result) {
  5718. if (!defined(matrix)) {
  5719. return undefined;
  5720. }
  5721. if (!defined(result)) {
  5722. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  5723. matrix[1], matrix[5], matrix[9], matrix[13],
  5724. matrix[2], matrix[6], matrix[10], matrix[14],
  5725. matrix[3], matrix[7], matrix[11], matrix[15]);
  5726. }
  5727. result[0] = matrix[0];
  5728. result[1] = matrix[1];
  5729. result[2] = matrix[2];
  5730. result[3] = matrix[3];
  5731. result[4] = matrix[4];
  5732. result[5] = matrix[5];
  5733. result[6] = matrix[6];
  5734. result[7] = matrix[7];
  5735. result[8] = matrix[8];
  5736. result[9] = matrix[9];
  5737. result[10] = matrix[10];
  5738. result[11] = matrix[11];
  5739. result[12] = matrix[12];
  5740. result[13] = matrix[13];
  5741. result[14] = matrix[14];
  5742. result[15] = matrix[15];
  5743. return result;
  5744. };
  5745. /**
  5746. * Creates a Matrix4 from 16 consecutive elements in an array.
  5747. * @function
  5748. *
  5749. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  5750. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  5751. * @param {Matrix4} [result] The object onto which to store the result.
  5752. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  5753. *
  5754. * @example
  5755. * // Create the Matrix4:
  5756. * // [1.0, 2.0, 3.0, 4.0]
  5757. * // [1.0, 2.0, 3.0, 4.0]
  5758. * // [1.0, 2.0, 3.0, 4.0]
  5759. * // [1.0, 2.0, 3.0, 4.0]
  5760. *
  5761. * var v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
  5762. * var m = Cesium.Matrix4.fromArray(v);
  5763. *
  5764. * // Create same Matrix4 with using an offset into an array
  5765. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0];
  5766. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  5767. */
  5768. Matrix4.fromArray = Matrix4.unpack;
  5769. /**
  5770. * Computes a Matrix4 instance from a column-major order array.
  5771. *
  5772. * @param {Number[]} values The column-major order array.
  5773. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5774. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5775. */
  5776. Matrix4.fromColumnMajorArray = function(values, result) {
  5777. if (!defined(values)) {
  5778. throw new DeveloperError('values is required');
  5779. }
  5780. return Matrix4.clone(values, result);
  5781. };
  5782. /**
  5783. * Computes a Matrix4 instance from a row-major order array.
  5784. * The resulting matrix will be in column-major order.
  5785. *
  5786. * @param {Number[]} values The row-major order array.
  5787. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5788. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5789. */
  5790. Matrix4.fromRowMajorArray = function(values, result) {
  5791. if (!defined(values)) {
  5792. throw new DeveloperError('values is required.');
  5793. }
  5794. if (!defined(result)) {
  5795. return new Matrix4(values[0], values[1], values[2], values[3],
  5796. values[4], values[5], values[6], values[7],
  5797. values[8], values[9], values[10], values[11],
  5798. values[12], values[13], values[14], values[15]);
  5799. }
  5800. result[0] = values[0];
  5801. result[1] = values[4];
  5802. result[2] = values[8];
  5803. result[3] = values[12];
  5804. result[4] = values[1];
  5805. result[5] = values[5];
  5806. result[6] = values[9];
  5807. result[7] = values[13];
  5808. result[8] = values[2];
  5809. result[9] = values[6];
  5810. result[10] = values[10];
  5811. result[11] = values[14];
  5812. result[12] = values[3];
  5813. result[13] = values[7];
  5814. result[14] = values[11];
  5815. result[15] = values[15];
  5816. return result;
  5817. };
  5818. /**
  5819. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  5820. * and a Cartesian3 representing the translation.
  5821. *
  5822. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  5823. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  5824. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5825. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5826. */
  5827. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  5828. if (!defined(rotation)) {
  5829. throw new DeveloperError('rotation is required.');
  5830. }
  5831. translation = defaultValue(translation, Cartesian3.ZERO);
  5832. if (!defined(result)) {
  5833. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  5834. rotation[1], rotation[4], rotation[7], translation.y,
  5835. rotation[2], rotation[5], rotation[8], translation.z,
  5836. 0.0, 0.0, 0.0, 1.0);
  5837. }
  5838. result[0] = rotation[0];
  5839. result[1] = rotation[1];
  5840. result[2] = rotation[2];
  5841. result[3] = 0.0;
  5842. result[4] = rotation[3];
  5843. result[5] = rotation[4];
  5844. result[6] = rotation[5];
  5845. result[7] = 0.0;
  5846. result[8] = rotation[6];
  5847. result[9] = rotation[7];
  5848. result[10] = rotation[8];
  5849. result[11] = 0.0;
  5850. result[12] = translation.x;
  5851. result[13] = translation.y;
  5852. result[14] = translation.z;
  5853. result[15] = 1.0;
  5854. return result;
  5855. };
  5856. /**
  5857. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  5858. * representation with the rotation represented as a quaternion.
  5859. *
  5860. * @param {Cartesian3} translation The translation transformation.
  5861. * @param {Quaternion} rotation The rotation transformation.
  5862. * @param {Cartesian3} scale The non-uniform scale transformation.
  5863. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5864. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5865. *
  5866. * @example
  5867. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  5868. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  5869. * Cesium.Quaternion.IDENTITY, // rotation
  5870. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  5871. * result);
  5872. */
  5873. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  5874. if (!defined(translation)) {
  5875. throw new DeveloperError('translation is required.');
  5876. }
  5877. if (!defined(rotation)) {
  5878. throw new DeveloperError('rotation is required.');
  5879. }
  5880. if (!defined(scale)) {
  5881. throw new DeveloperError('scale is required.');
  5882. }
  5883. if (!defined(result)) {
  5884. result = new Matrix4();
  5885. }
  5886. var scaleX = scale.x;
  5887. var scaleY = scale.y;
  5888. var scaleZ = scale.z;
  5889. var x2 = rotation.x * rotation.x;
  5890. var xy = rotation.x * rotation.y;
  5891. var xz = rotation.x * rotation.z;
  5892. var xw = rotation.x * rotation.w;
  5893. var y2 = rotation.y * rotation.y;
  5894. var yz = rotation.y * rotation.z;
  5895. var yw = rotation.y * rotation.w;
  5896. var z2 = rotation.z * rotation.z;
  5897. var zw = rotation.z * rotation.w;
  5898. var w2 = rotation.w * rotation.w;
  5899. var m00 = x2 - y2 - z2 + w2;
  5900. var m01 = 2.0 * (xy - zw);
  5901. var m02 = 2.0 * (xz + yw);
  5902. var m10 = 2.0 * (xy + zw);
  5903. var m11 = -x2 + y2 - z2 + w2;
  5904. var m12 = 2.0 * (yz - xw);
  5905. var m20 = 2.0 * (xz - yw);
  5906. var m21 = 2.0 * (yz + xw);
  5907. var m22 = -x2 - y2 + z2 + w2;
  5908. result[0] = m00 * scaleX;
  5909. result[1] = m10 * scaleX;
  5910. result[2] = m20 * scaleX;
  5911. result[3] = 0.0;
  5912. result[4] = m01 * scaleY;
  5913. result[5] = m11 * scaleY;
  5914. result[6] = m21 * scaleY;
  5915. result[7] = 0.0;
  5916. result[8] = m02 * scaleZ;
  5917. result[9] = m12 * scaleZ;
  5918. result[10] = m22 * scaleZ;
  5919. result[11] = 0.0;
  5920. result[12] = translation.x;
  5921. result[13] = translation.y;
  5922. result[14] = translation.z;
  5923. result[15] = 1.0;
  5924. return result;
  5925. };
  5926. /**
  5927. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  5928. *
  5929. * @param {TranslationRotationScale} translationRotationScale The instance.
  5930. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5931. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5932. */
  5933. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  5934. if (!defined(translationRotationScale)) {
  5935. throw new DeveloperError('translationRotationScale is required.');
  5936. }
  5937. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  5938. };
  5939. /**
  5940. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  5941. *
  5942. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  5943. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5944. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5945. *
  5946. * @see Matrix4.multiplyByTranslation
  5947. */
  5948. Matrix4.fromTranslation = function(translation, result) {
  5949. if (!defined(translation)) {
  5950. throw new DeveloperError('translation is required.');
  5951. }
  5952. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  5953. };
  5954. /**
  5955. * Computes a Matrix4 instance representing a non-uniform scale.
  5956. *
  5957. * @param {Cartesian3} scale The x, y, and z scale factors.
  5958. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5959. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  5960. *
  5961. * @example
  5962. * // Creates
  5963. * // [7.0, 0.0, 0.0, 0.0]
  5964. * // [0.0, 8.0, 0.0, 0.0]
  5965. * // [0.0, 0.0, 9.0, 0.0]
  5966. * // [0.0, 0.0, 0.0, 1.0]
  5967. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5968. */
  5969. Matrix4.fromScale = function(scale, result) {
  5970. if (!defined(scale)) {
  5971. throw new DeveloperError('scale is required.');
  5972. }
  5973. if (!defined(result)) {
  5974. return new Matrix4(
  5975. scale.x, 0.0, 0.0, 0.0,
  5976. 0.0, scale.y, 0.0, 0.0,
  5977. 0.0, 0.0, scale.z, 0.0,
  5978. 0.0, 0.0, 0.0, 1.0);
  5979. }
  5980. result[0] = scale.x;
  5981. result[1] = 0.0;
  5982. result[2] = 0.0;
  5983. result[3] = 0.0;
  5984. result[4] = 0.0;
  5985. result[5] = scale.y;
  5986. result[6] = 0.0;
  5987. result[7] = 0.0;
  5988. result[8] = 0.0;
  5989. result[9] = 0.0;
  5990. result[10] = scale.z;
  5991. result[11] = 0.0;
  5992. result[12] = 0.0;
  5993. result[13] = 0.0;
  5994. result[14] = 0.0;
  5995. result[15] = 1.0;
  5996. return result;
  5997. };
  5998. /**
  5999. * Computes a Matrix4 instance representing a uniform scale.
  6000. *
  6001. * @param {Number} scale The uniform scale factor.
  6002. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6003. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6004. *
  6005. * @example
  6006. * // Creates
  6007. * // [2.0, 0.0, 0.0, 0.0]
  6008. * // [0.0, 2.0, 0.0, 0.0]
  6009. * // [0.0, 0.0, 2.0, 0.0]
  6010. * // [0.0, 0.0, 0.0, 1.0]
  6011. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  6012. */
  6013. Matrix4.fromUniformScale = function(scale, result) {
  6014. if (typeof scale !== 'number') {
  6015. throw new DeveloperError('scale is required.');
  6016. }
  6017. if (!defined(result)) {
  6018. return new Matrix4(scale, 0.0, 0.0, 0.0,
  6019. 0.0, scale, 0.0, 0.0,
  6020. 0.0, 0.0, scale, 0.0,
  6021. 0.0, 0.0, 0.0, 1.0);
  6022. }
  6023. result[0] = scale;
  6024. result[1] = 0.0;
  6025. result[2] = 0.0;
  6026. result[3] = 0.0;
  6027. result[4] = 0.0;
  6028. result[5] = scale;
  6029. result[6] = 0.0;
  6030. result[7] = 0.0;
  6031. result[8] = 0.0;
  6032. result[9] = 0.0;
  6033. result[10] = scale;
  6034. result[11] = 0.0;
  6035. result[12] = 0.0;
  6036. result[13] = 0.0;
  6037. result[14] = 0.0;
  6038. result[15] = 1.0;
  6039. return result;
  6040. };
  6041. var fromCameraF = new Cartesian3();
  6042. var fromCameraR = new Cartesian3();
  6043. var fromCameraU = new Cartesian3();
  6044. /**
  6045. * Computes a Matrix4 instance from a Camera.
  6046. *
  6047. * @param {Camera} camera The camera to use.
  6048. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  6049. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  6050. */
  6051. Matrix4.fromCamera = function(camera, result) {
  6052. if (!defined(camera)) {
  6053. throw new DeveloperError('camera is required.');
  6054. }
  6055. var position = camera.position;
  6056. var direction = camera.direction;
  6057. var up = camera.up;
  6058. if (!defined(position)) {
  6059. throw new DeveloperError('camera.position is required.');
  6060. }
  6061. if (!defined(direction)) {
  6062. throw new DeveloperError('camera.direction is required.');
  6063. }
  6064. if (!defined(up)) {
  6065. throw new DeveloperError('camera.up is required.');
  6066. }
  6067. Cartesian3.normalize(direction, fromCameraF);
  6068. Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  6069. Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  6070. var sX = fromCameraR.x;
  6071. var sY = fromCameraR.y;
  6072. var sZ = fromCameraR.z;
  6073. var fX = fromCameraF.x;
  6074. var fY = fromCameraF.y;
  6075. var fZ = fromCameraF.z;
  6076. var uX = fromCameraU.x;
  6077. var uY = fromCameraU.y;
  6078. var uZ = fromCameraU.z;
  6079. var positionX = position.x;
  6080. var positionY = position.y;
  6081. var positionZ = position.z;
  6082. var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
  6083. var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
  6084. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  6085. // The code below this comment is an optimized
  6086. // version of the commented lines.
  6087. // Rather that create two matrices and then multiply,
  6088. // we just bake in the multiplcation as part of creation.
  6089. // var rotation = new Matrix4(
  6090. // sX, sY, sZ, 0.0,
  6091. // uX, uY, uZ, 0.0,
  6092. // -fX, -fY, -fZ, 0.0,
  6093. // 0.0, 0.0, 0.0, 1.0);
  6094. // var translation = new Matrix4(
  6095. // 1.0, 0.0, 0.0, -position.x,
  6096. // 0.0, 1.0, 0.0, -position.y,
  6097. // 0.0, 0.0, 1.0, -position.z,
  6098. // 0.0, 0.0, 0.0, 1.0);
  6099. // return rotation.multiply(translation);
  6100. if (!defined(result)) {
  6101. return new Matrix4(
  6102. sX, sY, sZ, t0,
  6103. uX, uY, uZ, t1,
  6104. -fX, -fY, -fZ, t2,
  6105. 0.0, 0.0, 0.0, 1.0);
  6106. }
  6107. result[0] = sX;
  6108. result[1] = uX;
  6109. result[2] = -fX;
  6110. result[3] = 0.0;
  6111. result[4] = sY;
  6112. result[5] = uY;
  6113. result[6] = -fY;
  6114. result[7] = 0.0;
  6115. result[8] = sZ;
  6116. result[9] = uZ;
  6117. result[10] = -fZ;
  6118. result[11] = 0.0;
  6119. result[12] = t0;
  6120. result[13] = t1;
  6121. result[14] = t2;
  6122. result[15] = 1.0;
  6123. return result;
  6124. };
  6125. /**
  6126. * Computes a Matrix4 instance representing a perspective transformation matrix.
  6127. *
  6128. * @param {Number} fovY The field of view along the Y axis in radians.
  6129. * @param {Number} aspectRatio The aspect ratio.
  6130. * @param {Number} near The distance to the near plane in meters.
  6131. * @param {Number} far The distance to the far plane in meters.
  6132. * @param {Matrix4} result The object in which the result will be stored.
  6133. * @returns {Matrix4} The modified result parameter.
  6134. *
  6135. * @exception {DeveloperError} fovY must be in (0, PI].
  6136. * @exception {DeveloperError} aspectRatio must be greater than zero.
  6137. * @exception {DeveloperError} near must be greater than zero.
  6138. * @exception {DeveloperError} far must be greater than zero.
  6139. */
  6140. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  6141. if (fovY <= 0.0 || fovY > Math.PI) {
  6142. throw new DeveloperError('fovY must be in (0, PI].');
  6143. }
  6144. if (aspectRatio <= 0.0) {
  6145. throw new DeveloperError('aspectRatio must be greater than zero.');
  6146. }
  6147. if (near <= 0.0) {
  6148. throw new DeveloperError('near must be greater than zero.');
  6149. }
  6150. if (far <= 0.0) {
  6151. throw new DeveloperError('far must be greater than zero.');
  6152. }
  6153. if (!defined(result)) {
  6154. throw new DeveloperError('result is required');
  6155. }
  6156. var bottom = Math.tan(fovY * 0.5);
  6157. var column1Row1 = 1.0 / bottom;
  6158. var column0Row0 = column1Row1 / aspectRatio;
  6159. var column2Row2 = (far + near) / (near - far);
  6160. var column3Row2 = (2.0 * far * near) / (near - far);
  6161. result[0] = column0Row0;
  6162. result[1] = 0.0;
  6163. result[2] = 0.0;
  6164. result[3] = 0.0;
  6165. result[4] = 0.0;
  6166. result[5] = column1Row1;
  6167. result[6] = 0.0;
  6168. result[7] = 0.0;
  6169. result[8] = 0.0;
  6170. result[9] = 0.0;
  6171. result[10] = column2Row2;
  6172. result[11] = -1.0;
  6173. result[12] = 0.0;
  6174. result[13] = 0.0;
  6175. result[14] = column3Row2;
  6176. result[15] = 0.0;
  6177. return result;
  6178. };
  6179. /**
  6180. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  6181. *
  6182. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6183. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6184. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6185. * @param {Number} top The number of meters above of the camera that will be in view.
  6186. * @param {Number} near The distance to the near plane in meters.
  6187. * @param {Number} far The distance to the far plane in meters.
  6188. * @param {Matrix4} result The object in which the result will be stored.
  6189. * @returns {Matrix4} The modified result parameter.
  6190. */
  6191. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  6192. if (!defined(left)) {
  6193. throw new DeveloperError('left is required.');
  6194. }
  6195. if (!defined(right)) {
  6196. throw new DeveloperError('right is required.');
  6197. }
  6198. if (!defined(bottom)) {
  6199. throw new DeveloperError('bottom is required.');
  6200. }
  6201. if (!defined(top)) {
  6202. throw new DeveloperError('top is required.');
  6203. }
  6204. if (!defined(near)) {
  6205. throw new DeveloperError('near is required.');
  6206. }
  6207. if (!defined(far)) {
  6208. throw new DeveloperError('far is required.');
  6209. }
  6210. if (!defined(result)) {
  6211. throw new DeveloperError('result is required');
  6212. }
  6213. var a = 1.0 / (right - left);
  6214. var b = 1.0 / (top - bottom);
  6215. var c = 1.0 / (far - near);
  6216. var tx = -(right + left) * a;
  6217. var ty = -(top + bottom) * b;
  6218. var tz = -(far + near) * c;
  6219. a *= 2.0;
  6220. b *= 2.0;
  6221. c *= -2.0;
  6222. result[0] = a;
  6223. result[1] = 0.0;
  6224. result[2] = 0.0;
  6225. result[3] = 0.0;
  6226. result[4] = 0.0;
  6227. result[5] = b;
  6228. result[6] = 0.0;
  6229. result[7] = 0.0;
  6230. result[8] = 0.0;
  6231. result[9] = 0.0;
  6232. result[10] = c;
  6233. result[11] = 0.0;
  6234. result[12] = tx;
  6235. result[13] = ty;
  6236. result[14] = tz;
  6237. result[15] = 1.0;
  6238. return result;
  6239. };
  6240. /**
  6241. * Computes a Matrix4 instance representing an off center perspective transformation.
  6242. *
  6243. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6244. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6245. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6246. * @param {Number} top The number of meters above of the camera that will be in view.
  6247. * @param {Number} near The distance to the near plane in meters.
  6248. * @param {Number} far The distance to the far plane in meters.
  6249. * @param {Matrix4} result The object in which the result will be stored.
  6250. * @returns {Matrix4} The modified result parameter.
  6251. */
  6252. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  6253. if (!defined(left)) {
  6254. throw new DeveloperError('left is required.');
  6255. }
  6256. if (!defined(right)) {
  6257. throw new DeveloperError('right is required.');
  6258. }
  6259. if (!defined(bottom)) {
  6260. throw new DeveloperError('bottom is required.');
  6261. }
  6262. if (!defined(top)) {
  6263. throw new DeveloperError('top is required.');
  6264. }
  6265. if (!defined(near)) {
  6266. throw new DeveloperError('near is required.');
  6267. }
  6268. if (!defined(far)) {
  6269. throw new DeveloperError('far is required.');
  6270. }
  6271. if (!defined(result)) {
  6272. throw new DeveloperError('result is required');
  6273. }
  6274. var column0Row0 = 2.0 * near / (right - left);
  6275. var column1Row1 = 2.0 * near / (top - bottom);
  6276. var column2Row0 = (right + left) / (right - left);
  6277. var column2Row1 = (top + bottom) / (top - bottom);
  6278. var column2Row2 = -(far + near) / (far - near);
  6279. var column2Row3 = -1.0;
  6280. var column3Row2 = -2.0 * far * near / (far - near);
  6281. result[0] = column0Row0;
  6282. result[1] = 0.0;
  6283. result[2] = 0.0;
  6284. result[3] = 0.0;
  6285. result[4] = 0.0;
  6286. result[5] = column1Row1;
  6287. result[6] = 0.0;
  6288. result[7] = 0.0;
  6289. result[8] = column2Row0;
  6290. result[9] = column2Row1;
  6291. result[10] = column2Row2;
  6292. result[11] = column2Row3;
  6293. result[12] = 0.0;
  6294. result[13] = 0.0;
  6295. result[14] = column3Row2;
  6296. result[15] = 0.0;
  6297. return result;
  6298. };
  6299. /**
  6300. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  6301. *
  6302. * @param {Number} left The number of meters to the left of the camera that will be in view.
  6303. * @param {Number} right The number of meters to the right of the camera that will be in view.
  6304. * @param {Number} bottom The number of meters below of the camera that will be in view.
  6305. * @param {Number} top The number of meters above of the camera that will be in view.
  6306. * @param {Number} near The distance to the near plane in meters.
  6307. * @param {Matrix4} result The object in which the result will be stored.
  6308. * @returns {Matrix4} The modified result parameter.
  6309. */
  6310. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  6311. if (!defined(left)) {
  6312. throw new DeveloperError('left is required.');
  6313. }
  6314. if (!defined(right)) {
  6315. throw new DeveloperError('right is required.');
  6316. }
  6317. if (!defined(bottom)) {
  6318. throw new DeveloperError('bottom is required.');
  6319. }
  6320. if (!defined(top)) {
  6321. throw new DeveloperError('top is required.');
  6322. }
  6323. if (!defined(near)) {
  6324. throw new DeveloperError('near is required.');
  6325. }
  6326. if (!defined(result)) {
  6327. throw new DeveloperError('result is required');
  6328. }
  6329. var column0Row0 = 2.0 * near / (right - left);
  6330. var column1Row1 = 2.0 * near / (top - bottom);
  6331. var column2Row0 = (right + left) / (right - left);
  6332. var column2Row1 = (top + bottom) / (top - bottom);
  6333. var column2Row2 = -1.0;
  6334. var column2Row3 = -1.0;
  6335. var column3Row2 = -2.0 * near;
  6336. result[0] = column0Row0;
  6337. result[1] = 0.0;
  6338. result[2] = 0.0;
  6339. result[3] = 0.0;
  6340. result[4] = 0.0;
  6341. result[5] = column1Row1;
  6342. result[6] = 0.0;
  6343. result[7] = 0.0;
  6344. result[8] = column2Row0;
  6345. result[9] = column2Row1;
  6346. result[10] = column2Row2;
  6347. result[11] = column2Row3;
  6348. result[12] = 0.0;
  6349. result[13] = 0.0;
  6350. result[14] = column3Row2;
  6351. result[15] = 0.0;
  6352. return result;
  6353. };
  6354. /**
  6355. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  6356. *
  6357. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  6358. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  6359. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  6360. * @param {Matrix4} result The object in which the result will be stored.
  6361. * @returns {Matrix4} The modified result parameter.
  6362. *
  6363. * @example
  6364. * // Create viewport transformation using an explicit viewport and depth range.
  6365. * var m = Cesium.Matrix4.computeViewportTransformation({
  6366. * x : 0.0,
  6367. * y : 0.0,
  6368. * width : 1024.0,
  6369. * height : 768.0
  6370. * }, 0.0, 1.0, new Cesium.Matrix4());
  6371. */
  6372. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  6373. if (!defined(result)) {
  6374. throw new DeveloperError('result is required');
  6375. }
  6376. viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
  6377. var x = defaultValue(viewport.x, 0.0);
  6378. var y = defaultValue(viewport.y, 0.0);
  6379. var width = defaultValue(viewport.width, 0.0);
  6380. var height = defaultValue(viewport.height, 0.0);
  6381. nearDepthRange = defaultValue(nearDepthRange, 0.0);
  6382. farDepthRange = defaultValue(farDepthRange, 1.0);
  6383. var halfWidth = width * 0.5;
  6384. var halfHeight = height * 0.5;
  6385. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  6386. var column0Row0 = halfWidth;
  6387. var column1Row1 = halfHeight;
  6388. var column2Row2 = halfDepth;
  6389. var column3Row0 = x + halfWidth;
  6390. var column3Row1 = y + halfHeight;
  6391. var column3Row2 = nearDepthRange + halfDepth;
  6392. var column3Row3 = 1.0;
  6393. result[0] = column0Row0;
  6394. result[1] = 0.0;
  6395. result[2] = 0.0;
  6396. result[3] = 0.0;
  6397. result[4] = 0.0;
  6398. result[5] = column1Row1;
  6399. result[6] = 0.0;
  6400. result[7] = 0.0;
  6401. result[8] = 0.0;
  6402. result[9] = 0.0;
  6403. result[10] = column2Row2;
  6404. result[11] = 0.0;
  6405. result[12] = column3Row0;
  6406. result[13] = column3Row1;
  6407. result[14] = column3Row2;
  6408. result[15] = column3Row3;
  6409. return result;
  6410. };
  6411. /**
  6412. * Computes a Matrix4 instance that transforms from world space to view space.
  6413. *
  6414. * @param {Cartesian3} position The position of the camera.
  6415. * @param {Cartesian3} direction The forward direction.
  6416. * @param {Cartesian3} up The up direction.
  6417. * @param {Cartesian3} right The right direction.
  6418. * @param {Matrix4} result The object in which the result will be stored.
  6419. * @returns {Matrix4} The modified result parameter.
  6420. */
  6421. Matrix4.computeView = function(position, direction, up, right, result) {
  6422. if (!defined(position)) {
  6423. throw new DeveloperError('position is required');
  6424. }
  6425. if (!defined(direction)) {
  6426. throw new DeveloperError('direction is required');
  6427. }
  6428. if (!defined(up)) {
  6429. throw new DeveloperError('up is required');
  6430. }
  6431. if (!defined(right)) {
  6432. throw new DeveloperError('right is required');
  6433. }
  6434. if (!defined(result)) {
  6435. throw new DeveloperError('result is required');
  6436. }
  6437. result[0] = right.x;
  6438. result[1] = up.x;
  6439. result[2] = -direction.x;
  6440. result[3] = 0.0;
  6441. result[4] = right.y;
  6442. result[5] = up.y;
  6443. result[6] = -direction.y;
  6444. result[7] = 0.0;
  6445. result[8] = right.z;
  6446. result[9] = up.z;
  6447. result[10] = -direction.z;
  6448. result[11] = 0.0;
  6449. result[12] = -Cartesian3.dot(right, position);
  6450. result[13] = -Cartesian3.dot(up, position);
  6451. result[14] = Cartesian3.dot(direction, position);
  6452. result[15] = 1.0;
  6453. return result;
  6454. };
  6455. /**
  6456. * Computes an Array from the provided Matrix4 instance.
  6457. * The array will be in column-major order.
  6458. *
  6459. * @param {Matrix4} matrix The matrix to use..
  6460. * @param {Number[]} [result] The Array onto which to store the result.
  6461. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  6462. *
  6463. * @example
  6464. * //create an array from an instance of Matrix4
  6465. * // m = [10.0, 14.0, 18.0, 22.0]
  6466. * // [11.0, 15.0, 19.0, 23.0]
  6467. * // [12.0, 16.0, 20.0, 24.0]
  6468. * // [13.0, 17.0, 21.0, 25.0]
  6469. * var a = Cesium.Matrix4.toArray(m);
  6470. *
  6471. * // m remains the same
  6472. * //creates a = [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0]
  6473. */
  6474. Matrix4.toArray = function(matrix, result) {
  6475. if (!defined(matrix)) {
  6476. throw new DeveloperError('matrix is required');
  6477. }
  6478. if (!defined(result)) {
  6479. return [matrix[0], matrix[1], matrix[2], matrix[3],
  6480. matrix[4], matrix[5], matrix[6], matrix[7],
  6481. matrix[8], matrix[9], matrix[10], matrix[11],
  6482. matrix[12], matrix[13], matrix[14], matrix[15]];
  6483. }
  6484. result[0] = matrix[0];
  6485. result[1] = matrix[1];
  6486. result[2] = matrix[2];
  6487. result[3] = matrix[3];
  6488. result[4] = matrix[4];
  6489. result[5] = matrix[5];
  6490. result[6] = matrix[6];
  6491. result[7] = matrix[7];
  6492. result[8] = matrix[8];
  6493. result[9] = matrix[9];
  6494. result[10] = matrix[10];
  6495. result[11] = matrix[11];
  6496. result[12] = matrix[12];
  6497. result[13] = matrix[13];
  6498. result[14] = matrix[14];
  6499. result[15] = matrix[15];
  6500. return result;
  6501. };
  6502. /**
  6503. * Computes the array index of the element at the provided row and column.
  6504. *
  6505. * @param {Number} row The zero-based index of the row.
  6506. * @param {Number} column The zero-based index of the column.
  6507. * @returns {Number} The index of the element at the provided row and column.
  6508. *
  6509. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  6510. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  6511. *
  6512. * @example
  6513. * var myMatrix = new Cesium.Matrix4();
  6514. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  6515. * var column1Row0 = myMatrix[column1Row0Index];
  6516. * myMatrix[column1Row0Index] = 10.0;
  6517. */
  6518. Matrix4.getElementIndex = function(column, row) {
  6519. if (typeof row !== 'number' || row < 0 || row > 3) {
  6520. throw new DeveloperError('row must be 0, 1, 2, or 3.');
  6521. }
  6522. if (typeof column !== 'number' || column < 0 || column > 3) {
  6523. throw new DeveloperError('column must be 0, 1, 2, or 3.');
  6524. }
  6525. return column * 4 + row;
  6526. };
  6527. /**
  6528. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  6529. *
  6530. * @param {Matrix4} matrix The matrix to use.
  6531. * @param {Number} index The zero-based index of the column to retrieve.
  6532. * @param {Cartesian4} result The object onto which to store the result.
  6533. * @returns {Cartesian4} The modified result parameter.
  6534. *
  6535. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6536. *
  6537. * @example
  6538. * //returns a Cartesian4 instance with values from the specified column
  6539. * // m = [10.0, 11.0, 12.0, 13.0]
  6540. * // [14.0, 15.0, 16.0, 17.0]
  6541. * // [18.0, 19.0, 20.0, 21.0]
  6542. * // [22.0, 23.0, 24.0, 25.0]
  6543. *
  6544. * //Example 1: Creates an instance of Cartesian
  6545. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  6546. *
  6547. * @example
  6548. * //Example 2: Sets values for Cartesian instance
  6549. * var a = new Cesium.Cartesian4();
  6550. * Cesium.Matrix4.getColumn(m, 2, a);
  6551. *
  6552. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  6553. */
  6554. Matrix4.getColumn = function(matrix, index, result) {
  6555. if (!defined(matrix)) {
  6556. throw new DeveloperError('matrix is required.');
  6557. }
  6558. if (typeof index !== 'number' || index < 0 || index > 3) {
  6559. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6560. }
  6561. if (!defined(result)) {
  6562. throw new DeveloperError('result is required');
  6563. }
  6564. var startIndex = index * 4;
  6565. var x = matrix[startIndex];
  6566. var y = matrix[startIndex + 1];
  6567. var z = matrix[startIndex + 2];
  6568. var w = matrix[startIndex + 3];
  6569. result.x = x;
  6570. result.y = y;
  6571. result.z = z;
  6572. result.w = w;
  6573. return result;
  6574. };
  6575. /**
  6576. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  6577. *
  6578. * @param {Matrix4} matrix The matrix to use.
  6579. * @param {Number} index The zero-based index of the column to set.
  6580. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  6581. * @param {Matrix4} result The object onto which to store the result.
  6582. * @returns {Matrix4} The modified result parameter.
  6583. *
  6584. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6585. *
  6586. * @example
  6587. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  6588. * // m = [10.0, 11.0, 12.0, 13.0]
  6589. * // [14.0, 15.0, 16.0, 17.0]
  6590. * // [18.0, 19.0, 20.0, 21.0]
  6591. * // [22.0, 23.0, 24.0, 25.0]
  6592. *
  6593. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  6594. *
  6595. * // m remains the same
  6596. * // a = [10.0, 11.0, 99.0, 13.0]
  6597. * // [14.0, 15.0, 98.0, 17.0]
  6598. * // [18.0, 19.0, 97.0, 21.0]
  6599. * // [22.0, 23.0, 96.0, 25.0]
  6600. */
  6601. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  6602. if (!defined(matrix)) {
  6603. throw new DeveloperError('matrix is required');
  6604. }
  6605. if (!defined(cartesian)) {
  6606. throw new DeveloperError('cartesian is required');
  6607. }
  6608. if (typeof index !== 'number' || index < 0 || index > 3) {
  6609. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6610. }
  6611. if (!defined(result)) {
  6612. throw new DeveloperError('result is required');
  6613. }
  6614. result = Matrix4.clone(matrix, result);
  6615. var startIndex = index * 4;
  6616. result[startIndex] = cartesian.x;
  6617. result[startIndex + 1] = cartesian.y;
  6618. result[startIndex + 2] = cartesian.z;
  6619. result[startIndex + 3] = cartesian.w;
  6620. return result;
  6621. };
  6622. /**
  6623. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  6624. * matrix with the provided translation. This assumes the matrix is an affine transformation
  6625. *
  6626. * @param {Matrix4} matrix The matrix to use.
  6627. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  6628. * @param {Cartesian4} result The object onto which to store the result.
  6629. * @returns {Matrix4} The modified result parameter.
  6630. */
  6631. Matrix4.setTranslation = function(matrix, translation, result) {
  6632. if (!defined(matrix)) {
  6633. throw new DeveloperError('matrix is required');
  6634. }
  6635. if (!defined(translation)) {
  6636. throw new DeveloperError('translation is required');
  6637. }
  6638. if (!defined(result)) {
  6639. throw new DeveloperError('result is required');
  6640. }
  6641. result[0] = matrix[0];
  6642. result[1] = matrix[1];
  6643. result[2] = matrix[2];
  6644. result[3] = matrix[3];
  6645. result[4] = matrix[4];
  6646. result[5] = matrix[5];
  6647. result[6] = matrix[6];
  6648. result[7] = matrix[7];
  6649. result[8] = matrix[8];
  6650. result[9] = matrix[9];
  6651. result[10] = matrix[10];
  6652. result[11] = matrix[11];
  6653. result[12] = translation.x;
  6654. result[13] = translation.y;
  6655. result[14] = translation.z;
  6656. result[15] = matrix[15];
  6657. return result;
  6658. };
  6659. /**
  6660. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  6661. *
  6662. * @param {Matrix4} matrix The matrix to use.
  6663. * @param {Number} index The zero-based index of the row to retrieve.
  6664. * @param {Cartesian4} result The object onto which to store the result.
  6665. * @returns {Cartesian4} The modified result parameter.
  6666. *
  6667. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6668. *
  6669. * @example
  6670. * //returns a Cartesian4 instance with values from the specified column
  6671. * // m = [10.0, 11.0, 12.0, 13.0]
  6672. * // [14.0, 15.0, 16.0, 17.0]
  6673. * // [18.0, 19.0, 20.0, 21.0]
  6674. * // [22.0, 23.0, 24.0, 25.0]
  6675. *
  6676. * //Example 1: Returns an instance of Cartesian
  6677. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  6678. *
  6679. * @example
  6680. * //Example 2: Sets values for a Cartesian instance
  6681. * var a = new Cesium.Cartesian4();
  6682. * Cesium.Matrix4.getRow(m, 2, a);
  6683. *
  6684. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  6685. */
  6686. Matrix4.getRow = function(matrix, index, result) {
  6687. if (!defined(matrix)) {
  6688. throw new DeveloperError('matrix is required.');
  6689. }
  6690. if (typeof index !== 'number' || index < 0 || index > 3) {
  6691. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6692. }
  6693. if (!defined(result)) {
  6694. throw new DeveloperError('result is required');
  6695. }
  6696. var x = matrix[index];
  6697. var y = matrix[index + 4];
  6698. var z = matrix[index + 8];
  6699. var w = matrix[index + 12];
  6700. result.x = x;
  6701. result.y = y;
  6702. result.z = z;
  6703. result.w = w;
  6704. return result;
  6705. };
  6706. /**
  6707. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  6708. *
  6709. * @param {Matrix4} matrix The matrix to use.
  6710. * @param {Number} index The zero-based index of the row to set.
  6711. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  6712. * @param {Matrix4} result The object onto which to store the result.
  6713. * @returns {Matrix4} The modified result parameter.
  6714. *
  6715. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  6716. *
  6717. * @example
  6718. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  6719. * // m = [10.0, 11.0, 12.0, 13.0]
  6720. * // [14.0, 15.0, 16.0, 17.0]
  6721. * // [18.0, 19.0, 20.0, 21.0]
  6722. * // [22.0, 23.0, 24.0, 25.0]
  6723. *
  6724. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  6725. *
  6726. * // m remains the same
  6727. * // a = [10.0, 11.0, 12.0, 13.0]
  6728. * // [14.0, 15.0, 16.0, 17.0]
  6729. * // [99.0, 98.0, 97.0, 96.0]
  6730. * // [22.0, 23.0, 24.0, 25.0]
  6731. */
  6732. Matrix4.setRow = function(matrix, index, cartesian, result) {
  6733. if (!defined(matrix)) {
  6734. throw new DeveloperError('matrix is required');
  6735. }
  6736. if (!defined(cartesian)) {
  6737. throw new DeveloperError('cartesian is required');
  6738. }
  6739. if (typeof index !== 'number' || index < 0 || index > 3) {
  6740. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  6741. }
  6742. if (!defined(result)) {
  6743. throw new DeveloperError('result is required');
  6744. }
  6745. result = Matrix4.clone(matrix, result);
  6746. result[index] = cartesian.x;
  6747. result[index + 4] = cartesian.y;
  6748. result[index + 8] = cartesian.z;
  6749. result[index + 12] = cartesian.w;
  6750. return result;
  6751. };
  6752. var scratchColumn = new Cartesian3();
  6753. /**
  6754. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  6755. *
  6756. * @param {Matrix4} matrix The matrix.
  6757. * @param {Cartesian3} result The object onto which to store the result.
  6758. * @returns {Cartesian3} The modified result parameter
  6759. */
  6760. Matrix4.getScale = function(matrix, result) {
  6761. if (!defined(matrix)) {
  6762. throw new DeveloperError('matrix is required.');
  6763. }
  6764. if (!defined(result)) {
  6765. throw new DeveloperError('result is required');
  6766. }
  6767. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  6768. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
  6769. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
  6770. return result;
  6771. };
  6772. var scratchScale = new Cartesian3();
  6773. /**
  6774. * Computes the maximum scale assuming the matrix is an affine transformation.
  6775. * The maximum scale is the maximum length of the column vectors in the upper-left
  6776. * 3x3 matrix.
  6777. *
  6778. * @param {Matrix4} matrix The matrix.
  6779. * @returns {Number} The maximum scale.
  6780. */
  6781. Matrix4.getMaximumScale = function(matrix) {
  6782. Matrix4.getScale(matrix, scratchScale);
  6783. return Cartesian3.maximumComponent(scratchScale);
  6784. };
  6785. /**
  6786. * Computes the product of two matrices.
  6787. *
  6788. * @param {Matrix4} left The first matrix.
  6789. * @param {Matrix4} right The second matrix.
  6790. * @param {Matrix4} result The object onto which to store the result.
  6791. * @returns {Matrix4} The modified result parameter.
  6792. */
  6793. Matrix4.multiply = function(left, right, result) {
  6794. if (!defined(left)) {
  6795. throw new DeveloperError('left is required');
  6796. }
  6797. if (!defined(right)) {
  6798. throw new DeveloperError('right is required');
  6799. }
  6800. if (!defined(result)) {
  6801. throw new DeveloperError('result is required');
  6802. }
  6803. var left0 = left[0];
  6804. var left1 = left[1];
  6805. var left2 = left[2];
  6806. var left3 = left[3];
  6807. var left4 = left[4];
  6808. var left5 = left[5];
  6809. var left6 = left[6];
  6810. var left7 = left[7];
  6811. var left8 = left[8];
  6812. var left9 = left[9];
  6813. var left10 = left[10];
  6814. var left11 = left[11];
  6815. var left12 = left[12];
  6816. var left13 = left[13];
  6817. var left14 = left[14];
  6818. var left15 = left[15];
  6819. var right0 = right[0];
  6820. var right1 = right[1];
  6821. var right2 = right[2];
  6822. var right3 = right[3];
  6823. var right4 = right[4];
  6824. var right5 = right[5];
  6825. var right6 = right[6];
  6826. var right7 = right[7];
  6827. var right8 = right[8];
  6828. var right9 = right[9];
  6829. var right10 = right[10];
  6830. var right11 = right[11];
  6831. var right12 = right[12];
  6832. var right13 = right[13];
  6833. var right14 = right[14];
  6834. var right15 = right[15];
  6835. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  6836. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  6837. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  6838. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  6839. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  6840. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  6841. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  6842. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  6843. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  6844. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  6845. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  6846. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  6847. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  6848. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  6849. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  6850. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  6851. result[0] = column0Row0;
  6852. result[1] = column0Row1;
  6853. result[2] = column0Row2;
  6854. result[3] = column0Row3;
  6855. result[4] = column1Row0;
  6856. result[5] = column1Row1;
  6857. result[6] = column1Row2;
  6858. result[7] = column1Row3;
  6859. result[8] = column2Row0;
  6860. result[9] = column2Row1;
  6861. result[10] = column2Row2;
  6862. result[11] = column2Row3;
  6863. result[12] = column3Row0;
  6864. result[13] = column3Row1;
  6865. result[14] = column3Row2;
  6866. result[15] = column3Row3;
  6867. return result;
  6868. };
  6869. /**
  6870. * Computes the sum of two matrices.
  6871. *
  6872. * @param {Matrix4} left The first matrix.
  6873. * @param {Matrix4} right The second matrix.
  6874. * @param {Matrix4} result The object onto which to store the result.
  6875. * @returns {Matrix4} The modified result parameter.
  6876. */
  6877. Matrix4.add = function(left, right, result) {
  6878. if (!defined(left)) {
  6879. throw new DeveloperError('left is required');
  6880. }
  6881. if (!defined(right)) {
  6882. throw new DeveloperError('right is required');
  6883. }
  6884. if (!defined(result)) {
  6885. throw new DeveloperError('result is required');
  6886. }
  6887. result[0] = left[0] + right[0];
  6888. result[1] = left[1] + right[1];
  6889. result[2] = left[2] + right[2];
  6890. result[3] = left[3] + right[3];
  6891. result[4] = left[4] + right[4];
  6892. result[5] = left[5] + right[5];
  6893. result[6] = left[6] + right[6];
  6894. result[7] = left[7] + right[7];
  6895. result[8] = left[8] + right[8];
  6896. result[9] = left[9] + right[9];
  6897. result[10] = left[10] + right[10];
  6898. result[11] = left[11] + right[11];
  6899. result[12] = left[12] + right[12];
  6900. result[13] = left[13] + right[13];
  6901. result[14] = left[14] + right[14];
  6902. result[15] = left[15] + right[15];
  6903. return result;
  6904. };
  6905. /**
  6906. * Computes the difference of two matrices.
  6907. *
  6908. * @param {Matrix4} left The first matrix.
  6909. * @param {Matrix4} right The second matrix.
  6910. * @param {Matrix4} result The object onto which to store the result.
  6911. * @returns {Matrix4} The modified result parameter.
  6912. */
  6913. Matrix4.subtract = function(left, right, result) {
  6914. if (!defined(left)) {
  6915. throw new DeveloperError('left is required');
  6916. }
  6917. if (!defined(right)) {
  6918. throw new DeveloperError('right is required');
  6919. }
  6920. if (!defined(result)) {
  6921. throw new DeveloperError('result is required');
  6922. }
  6923. result[0] = left[0] - right[0];
  6924. result[1] = left[1] - right[1];
  6925. result[2] = left[2] - right[2];
  6926. result[3] = left[3] - right[3];
  6927. result[4] = left[4] - right[4];
  6928. result[5] = left[5] - right[5];
  6929. result[6] = left[6] - right[6];
  6930. result[7] = left[7] - right[7];
  6931. result[8] = left[8] - right[8];
  6932. result[9] = left[9] - right[9];
  6933. result[10] = left[10] - right[10];
  6934. result[11] = left[11] - right[11];
  6935. result[12] = left[12] - right[12];
  6936. result[13] = left[13] - right[13];
  6937. result[14] = left[14] - right[14];
  6938. result[15] = left[15] - right[15];
  6939. return result;
  6940. };
  6941. /**
  6942. * Computes the product of two matrices assuming the matrices are
  6943. * affine transformation matrices, where the upper left 3x3 elements
  6944. * are a rotation matrix, and the upper three elements in the fourth
  6945. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  6946. * The matrix is not verified to be in the proper form.
  6947. * This method is faster than computing the product for general 4x4
  6948. * matrices using {@link Matrix4.multiply}.
  6949. *
  6950. * @param {Matrix4} left The first matrix.
  6951. * @param {Matrix4} right The second matrix.
  6952. * @param {Matrix4} result The object onto which to store the result.
  6953. * @returns {Matrix4} The modified result parameter.
  6954. *
  6955. * @example
  6956. * var m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  6957. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  6958. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  6959. */
  6960. Matrix4.multiplyTransformation = function(left, right, result) {
  6961. if (!defined(left)) {
  6962. throw new DeveloperError('left is required');
  6963. }
  6964. if (!defined(right)) {
  6965. throw new DeveloperError('right is required');
  6966. }
  6967. if (!defined(result)) {
  6968. throw new DeveloperError('result is required');
  6969. }
  6970. var left0 = left[0];
  6971. var left1 = left[1];
  6972. var left2 = left[2];
  6973. var left4 = left[4];
  6974. var left5 = left[5];
  6975. var left6 = left[6];
  6976. var left8 = left[8];
  6977. var left9 = left[9];
  6978. var left10 = left[10];
  6979. var left12 = left[12];
  6980. var left13 = left[13];
  6981. var left14 = left[14];
  6982. var right0 = right[0];
  6983. var right1 = right[1];
  6984. var right2 = right[2];
  6985. var right4 = right[4];
  6986. var right5 = right[5];
  6987. var right6 = right[6];
  6988. var right8 = right[8];
  6989. var right9 = right[9];
  6990. var right10 = right[10];
  6991. var right12 = right[12];
  6992. var right13 = right[13];
  6993. var right14 = right[14];
  6994. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  6995. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  6996. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  6997. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  6998. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  6999. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  7000. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  7001. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  7002. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  7003. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  7004. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  7005. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  7006. result[0] = column0Row0;
  7007. result[1] = column0Row1;
  7008. result[2] = column0Row2;
  7009. result[3] = 0.0;
  7010. result[4] = column1Row0;
  7011. result[5] = column1Row1;
  7012. result[6] = column1Row2;
  7013. result[7] = 0.0;
  7014. result[8] = column2Row0;
  7015. result[9] = column2Row1;
  7016. result[10] = column2Row2;
  7017. result[11] = 0.0;
  7018. result[12] = column3Row0;
  7019. result[13] = column3Row1;
  7020. result[14] = column3Row2;
  7021. result[15] = 1.0;
  7022. return result;
  7023. };
  7024. /**
  7025. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7026. * by a 3x3 rotation matrix. This is an optimization
  7027. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  7028. *
  7029. * @param {Matrix4} matrix The matrix on the left-hand side.
  7030. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  7031. * @param {Matrix4} result The object onto which to store the result.
  7032. * @returns {Matrix4} The modified result parameter.
  7033. *
  7034. * @example
  7035. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  7036. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  7037. */
  7038. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  7039. if (!defined(matrix)) {
  7040. throw new DeveloperError('matrix is required');
  7041. }
  7042. if (!defined(rotation)) {
  7043. throw new DeveloperError('rotation is required');
  7044. }
  7045. if (!defined(result)) {
  7046. throw new DeveloperError('result is required');
  7047. }
  7048. var left0 = matrix[0];
  7049. var left1 = matrix[1];
  7050. var left2 = matrix[2];
  7051. var left4 = matrix[4];
  7052. var left5 = matrix[5];
  7053. var left6 = matrix[6];
  7054. var left8 = matrix[8];
  7055. var left9 = matrix[9];
  7056. var left10 = matrix[10];
  7057. var right0 = rotation[0];
  7058. var right1 = rotation[1];
  7059. var right2 = rotation[2];
  7060. var right4 = rotation[3];
  7061. var right5 = rotation[4];
  7062. var right6 = rotation[5];
  7063. var right8 = rotation[6];
  7064. var right9 = rotation[7];
  7065. var right10 = rotation[8];
  7066. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  7067. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  7068. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  7069. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  7070. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  7071. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  7072. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  7073. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  7074. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  7075. result[0] = column0Row0;
  7076. result[1] = column0Row1;
  7077. result[2] = column0Row2;
  7078. result[3] = 0.0;
  7079. result[4] = column1Row0;
  7080. result[5] = column1Row1;
  7081. result[6] = column1Row2;
  7082. result[7] = 0.0;
  7083. result[8] = column2Row0;
  7084. result[9] = column2Row1;
  7085. result[10] = column2Row2;
  7086. result[11] = 0.0;
  7087. result[12] = matrix[12];
  7088. result[13] = matrix[13];
  7089. result[14] = matrix[14];
  7090. result[15] = matrix[15];
  7091. return result;
  7092. };
  7093. /**
  7094. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7095. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  7096. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  7097. *
  7098. * @param {Matrix4} matrix The matrix on the left-hand side.
  7099. * @param {Cartesian3} translation The translation on the right-hand side.
  7100. * @param {Matrix4} result The object onto which to store the result.
  7101. * @returns {Matrix4} The modified result parameter.
  7102. *
  7103. * @example
  7104. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  7105. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  7106. */
  7107. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  7108. if (!defined(matrix)) {
  7109. throw new DeveloperError('matrix is required');
  7110. }
  7111. if (!defined(translation)) {
  7112. throw new DeveloperError('translation is required');
  7113. }
  7114. if (!defined(result)) {
  7115. throw new DeveloperError('result is required');
  7116. }
  7117. var x = translation.x;
  7118. var y = translation.y;
  7119. var z = translation.z;
  7120. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  7121. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  7122. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  7123. result[0] = matrix[0];
  7124. result[1] = matrix[1];
  7125. result[2] = matrix[2];
  7126. result[3] = matrix[3];
  7127. result[4] = matrix[4];
  7128. result[5] = matrix[5];
  7129. result[6] = matrix[6];
  7130. result[7] = matrix[7];
  7131. result[8] = matrix[8];
  7132. result[9] = matrix[9];
  7133. result[10] = matrix[10];
  7134. result[11] = matrix[11];
  7135. result[12] = tx;
  7136. result[13] = ty;
  7137. result[14] = tz;
  7138. result[15] = matrix[15];
  7139. return result;
  7140. };
  7141. var uniformScaleScratch = new Cartesian3();
  7142. /**
  7143. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7144. * by an implicit uniform scale matrix. This is an optimization
  7145. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  7146. * <code>m</code> must be an affine matrix.
  7147. * This function performs fewer allocations and arithmetic operations.
  7148. *
  7149. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  7150. * @param {Number} scale The uniform scale on the right-hand side.
  7151. * @param {Matrix4} result The object onto which to store the result.
  7152. * @returns {Matrix4} The modified result parameter.
  7153. *
  7154. *
  7155. * @example
  7156. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  7157. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  7158. *
  7159. * @see Matrix4.fromUniformScale
  7160. * @see Matrix4.multiplyByScale
  7161. */
  7162. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  7163. if (!defined(matrix)) {
  7164. throw new DeveloperError('matrix is required');
  7165. }
  7166. if (typeof scale !== 'number') {
  7167. throw new DeveloperError('scale is required');
  7168. }
  7169. if (!defined(result)) {
  7170. throw new DeveloperError('result is required');
  7171. }
  7172. uniformScaleScratch.x = scale;
  7173. uniformScaleScratch.y = scale;
  7174. uniformScaleScratch.z = scale;
  7175. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  7176. };
  7177. /**
  7178. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  7179. * by an implicit non-uniform scale matrix. This is an optimization
  7180. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  7181. * <code>m</code> must be an affine matrix.
  7182. * This function performs fewer allocations and arithmetic operations.
  7183. *
  7184. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  7185. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  7186. * @param {Matrix4} result The object onto which to store the result.
  7187. * @returns {Matrix4} The modified result parameter.
  7188. *
  7189. *
  7190. * @example
  7191. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  7192. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  7193. *
  7194. * @see Matrix4.fromScale
  7195. * @see Matrix4.multiplyByUniformScale
  7196. */
  7197. Matrix4.multiplyByScale = function(matrix, scale, result) {
  7198. if (!defined(matrix)) {
  7199. throw new DeveloperError('matrix is required');
  7200. }
  7201. if (!defined(scale)) {
  7202. throw new DeveloperError('scale is required');
  7203. }
  7204. if (!defined(result)) {
  7205. throw new DeveloperError('result is required');
  7206. }
  7207. var scaleX = scale.x;
  7208. var scaleY = scale.y;
  7209. var scaleZ = scale.z;
  7210. // Faster than Cartesian3.equals
  7211. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  7212. return Matrix4.clone(matrix, result);
  7213. }
  7214. result[0] = scaleX * matrix[0];
  7215. result[1] = scaleX * matrix[1];
  7216. result[2] = scaleX * matrix[2];
  7217. result[3] = 0.0;
  7218. result[4] = scaleY * matrix[4];
  7219. result[5] = scaleY * matrix[5];
  7220. result[6] = scaleY * matrix[6];
  7221. result[7] = 0.0;
  7222. result[8] = scaleZ * matrix[8];
  7223. result[9] = scaleZ * matrix[9];
  7224. result[10] = scaleZ * matrix[10];
  7225. result[11] = 0.0;
  7226. result[12] = matrix[12];
  7227. result[13] = matrix[13];
  7228. result[14] = matrix[14];
  7229. result[15] = 1.0;
  7230. return result;
  7231. };
  7232. /**
  7233. * Computes the product of a matrix and a column vector.
  7234. *
  7235. * @param {Matrix4} matrix The matrix.
  7236. * @param {Cartesian4} cartesian The vector.
  7237. * @param {Cartesian4} result The object onto which to store the result.
  7238. * @returns {Cartesian4} The modified result parameter.
  7239. */
  7240. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  7241. if (!defined(matrix)) {
  7242. throw new DeveloperError('matrix is required');
  7243. }
  7244. if (!defined(cartesian)) {
  7245. throw new DeveloperError('cartesian is required');
  7246. }
  7247. if (!defined(result)) {
  7248. throw new DeveloperError('result is required');
  7249. }
  7250. var vX = cartesian.x;
  7251. var vY = cartesian.y;
  7252. var vZ = cartesian.z;
  7253. var vW = cartesian.w;
  7254. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  7255. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  7256. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  7257. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  7258. result.x = x;
  7259. result.y = y;
  7260. result.z = z;
  7261. result.w = w;
  7262. return result;
  7263. };
  7264. /**
  7265. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  7266. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  7267. *
  7268. * @param {Matrix4} matrix The matrix.
  7269. * @param {Cartesian3} cartesian The point.
  7270. * @param {Cartesian3} result The object onto which to store the result.
  7271. * @returns {Cartesian3} The modified result parameter.
  7272. *
  7273. * @example
  7274. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  7275. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  7276. * // A shortcut for
  7277. * // Cartesian3 p = ...
  7278. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  7279. */
  7280. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  7281. if (!defined(matrix)) {
  7282. throw new DeveloperError('matrix is required');
  7283. }
  7284. if (!defined(cartesian)) {
  7285. throw new DeveloperError('cartesian is required');
  7286. }
  7287. if (!defined(result)) {
  7288. throw new DeveloperError('result is required');
  7289. }
  7290. var vX = cartesian.x;
  7291. var vY = cartesian.y;
  7292. var vZ = cartesian.z;
  7293. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  7294. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  7295. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  7296. result.x = x;
  7297. result.y = y;
  7298. result.z = z;
  7299. return result;
  7300. };
  7301. /**
  7302. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  7303. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  7304. *
  7305. * @param {Matrix4} matrix The matrix.
  7306. * @param {Cartesian3} cartesian The point.
  7307. * @param {Cartesian3} result The object onto which to store the result.
  7308. * @returns {Cartesian3} The modified result parameter.
  7309. *
  7310. * @example
  7311. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  7312. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  7313. */
  7314. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  7315. if (!defined(matrix)) {
  7316. throw new DeveloperError('matrix is required');
  7317. }
  7318. if (!defined(cartesian)) {
  7319. throw new DeveloperError('cartesian is required');
  7320. }
  7321. if (!defined(result)) {
  7322. throw new DeveloperError('result is required');
  7323. }
  7324. var vX = cartesian.x;
  7325. var vY = cartesian.y;
  7326. var vZ = cartesian.z;
  7327. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  7328. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  7329. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  7330. result.x = x;
  7331. result.y = y;
  7332. result.z = z;
  7333. return result;
  7334. };
  7335. /**
  7336. * Computes the product of a matrix and a scalar.
  7337. *
  7338. * @param {Matrix4} matrix The matrix.
  7339. * @param {Number} scalar The number to multiply by.
  7340. * @param {Matrix4} result The object onto which to store the result.
  7341. * @returns {Matrix4} The modified result parameter.
  7342. *
  7343. * @example
  7344. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  7345. * // m = [10.0, 11.0, 12.0, 13.0]
  7346. * // [14.0, 15.0, 16.0, 17.0]
  7347. * // [18.0, 19.0, 20.0, 21.0]
  7348. * // [22.0, 23.0, 24.0, 25.0]
  7349. *
  7350. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  7351. *
  7352. * // m remains the same
  7353. * // a = [-20.0, -22.0, -24.0, -26.0]
  7354. * // [-28.0, -30.0, -32.0, -34.0]
  7355. * // [-36.0, -38.0, -40.0, -42.0]
  7356. * // [-44.0, -46.0, -48.0, -50.0]
  7357. */
  7358. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  7359. if (!defined(matrix)) {
  7360. throw new DeveloperError('matrix is required');
  7361. }
  7362. if (typeof scalar !== 'number') {
  7363. throw new DeveloperError('scalar must be a number');
  7364. }
  7365. if (!defined(result)) {
  7366. throw new DeveloperError('result is required');
  7367. }
  7368. result[0] = matrix[0] * scalar;
  7369. result[1] = matrix[1] * scalar;
  7370. result[2] = matrix[2] * scalar;
  7371. result[3] = matrix[3] * scalar;
  7372. result[4] = matrix[4] * scalar;
  7373. result[5] = matrix[5] * scalar;
  7374. result[6] = matrix[6] * scalar;
  7375. result[7] = matrix[7] * scalar;
  7376. result[8] = matrix[8] * scalar;
  7377. result[9] = matrix[9] * scalar;
  7378. result[10] = matrix[10] * scalar;
  7379. result[11] = matrix[11] * scalar;
  7380. result[12] = matrix[12] * scalar;
  7381. result[13] = matrix[13] * scalar;
  7382. result[14] = matrix[14] * scalar;
  7383. result[15] = matrix[15] * scalar;
  7384. return result;
  7385. };
  7386. /**
  7387. * Computes a negated copy of the provided matrix.
  7388. *
  7389. * @param {Matrix4} matrix The matrix to negate.
  7390. * @param {Matrix4} result The object onto which to store the result.
  7391. * @returns {Matrix4} The modified result parameter.
  7392. *
  7393. * @example
  7394. * //create a new Matrix4 instance which is a negation of a Matrix4
  7395. * // m = [10.0, 11.0, 12.0, 13.0]
  7396. * // [14.0, 15.0, 16.0, 17.0]
  7397. * // [18.0, 19.0, 20.0, 21.0]
  7398. * // [22.0, 23.0, 24.0, 25.0]
  7399. *
  7400. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  7401. *
  7402. * // m remains the same
  7403. * // a = [-10.0, -11.0, -12.0, -13.0]
  7404. * // [-14.0, -15.0, -16.0, -17.0]
  7405. * // [-18.0, -19.0, -20.0, -21.0]
  7406. * // [-22.0, -23.0, -24.0, -25.0]
  7407. */
  7408. Matrix4.negate = function(matrix, result) {
  7409. if (!defined(matrix)) {
  7410. throw new DeveloperError('matrix is required');
  7411. }
  7412. if (!defined(result)) {
  7413. throw new DeveloperError('result is required');
  7414. }
  7415. result[0] = -matrix[0];
  7416. result[1] = -matrix[1];
  7417. result[2] = -matrix[2];
  7418. result[3] = -matrix[3];
  7419. result[4] = -matrix[4];
  7420. result[5] = -matrix[5];
  7421. result[6] = -matrix[6];
  7422. result[7] = -matrix[7];
  7423. result[8] = -matrix[8];
  7424. result[9] = -matrix[9];
  7425. result[10] = -matrix[10];
  7426. result[11] = -matrix[11];
  7427. result[12] = -matrix[12];
  7428. result[13] = -matrix[13];
  7429. result[14] = -matrix[14];
  7430. result[15] = -matrix[15];
  7431. return result;
  7432. };
  7433. /**
  7434. * Computes the transpose of the provided matrix.
  7435. *
  7436. * @param {Matrix4} matrix The matrix to transpose.
  7437. * @param {Matrix4} result The object onto which to store the result.
  7438. * @returns {Matrix4} The modified result parameter.
  7439. *
  7440. * @example
  7441. * //returns transpose of a Matrix4
  7442. * // m = [10.0, 11.0, 12.0, 13.0]
  7443. * // [14.0, 15.0, 16.0, 17.0]
  7444. * // [18.0, 19.0, 20.0, 21.0]
  7445. * // [22.0, 23.0, 24.0, 25.0]
  7446. *
  7447. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  7448. *
  7449. * // m remains the same
  7450. * // a = [10.0, 14.0, 18.0, 22.0]
  7451. * // [11.0, 15.0, 19.0, 23.0]
  7452. * // [12.0, 16.0, 20.0, 24.0]
  7453. * // [13.0, 17.0, 21.0, 25.0]
  7454. */
  7455. Matrix4.transpose = function(matrix, result) {
  7456. if (!defined(matrix)) {
  7457. throw new DeveloperError('matrix is required');
  7458. }
  7459. if (!defined(result)) {
  7460. throw new DeveloperError('result is required');
  7461. }
  7462. var matrix1 = matrix[1];
  7463. var matrix2 = matrix[2];
  7464. var matrix3 = matrix[3];
  7465. var matrix6 = matrix[6];
  7466. var matrix7 = matrix[7];
  7467. var matrix11 = matrix[11];
  7468. result[0] = matrix[0];
  7469. result[1] = matrix[4];
  7470. result[2] = matrix[8];
  7471. result[3] = matrix[12];
  7472. result[4] = matrix1;
  7473. result[5] = matrix[5];
  7474. result[6] = matrix[9];
  7475. result[7] = matrix[13];
  7476. result[8] = matrix2;
  7477. result[9] = matrix6;
  7478. result[10] = matrix[10];
  7479. result[11] = matrix[14];
  7480. result[12] = matrix3;
  7481. result[13] = matrix7;
  7482. result[14] = matrix11;
  7483. result[15] = matrix[15];
  7484. return result;
  7485. };
  7486. /**
  7487. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  7488. *
  7489. * @param {Matrix4} matrix The matrix with signed elements.
  7490. * @param {Matrix4} result The object onto which to store the result.
  7491. * @returns {Matrix4} The modified result parameter.
  7492. */
  7493. Matrix4.abs = function(matrix, result) {
  7494. if (!defined(matrix)) {
  7495. throw new DeveloperError('matrix is required');
  7496. }
  7497. if (!defined(result)) {
  7498. throw new DeveloperError('result is required');
  7499. }
  7500. result[0] = Math.abs(matrix[0]);
  7501. result[1] = Math.abs(matrix[1]);
  7502. result[2] = Math.abs(matrix[2]);
  7503. result[3] = Math.abs(matrix[3]);
  7504. result[4] = Math.abs(matrix[4]);
  7505. result[5] = Math.abs(matrix[5]);
  7506. result[6] = Math.abs(matrix[6]);
  7507. result[7] = Math.abs(matrix[7]);
  7508. result[8] = Math.abs(matrix[8]);
  7509. result[9] = Math.abs(matrix[9]);
  7510. result[10] = Math.abs(matrix[10]);
  7511. result[11] = Math.abs(matrix[11]);
  7512. result[12] = Math.abs(matrix[12]);
  7513. result[13] = Math.abs(matrix[13]);
  7514. result[14] = Math.abs(matrix[14]);
  7515. result[15] = Math.abs(matrix[15]);
  7516. return result;
  7517. };
  7518. /**
  7519. * Compares the provided matrices componentwise and returns
  7520. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7521. *
  7522. * @param {Matrix4} [left] The first matrix.
  7523. * @param {Matrix4} [right] The second matrix.
  7524. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7525. *
  7526. * @example
  7527. * //compares two Matrix4 instances
  7528. *
  7529. * // a = [10.0, 14.0, 18.0, 22.0]
  7530. * // [11.0, 15.0, 19.0, 23.0]
  7531. * // [12.0, 16.0, 20.0, 24.0]
  7532. * // [13.0, 17.0, 21.0, 25.0]
  7533. *
  7534. * // b = [10.0, 14.0, 18.0, 22.0]
  7535. * // [11.0, 15.0, 19.0, 23.0]
  7536. * // [12.0, 16.0, 20.0, 24.0]
  7537. * // [13.0, 17.0, 21.0, 25.0]
  7538. *
  7539. * if(Cesium.Matrix4.equals(a,b)) {
  7540. * console.log("Both matrices are equal");
  7541. * } else {
  7542. * console.log("They are not equal");
  7543. * }
  7544. *
  7545. * //Prints "Both matrices are equal" on the console
  7546. */
  7547. Matrix4.equals = function(left, right) {
  7548. // Given that most matrices will be transformation matrices, the elements
  7549. // are tested in order such that the test is likely to fail as early
  7550. // as possible. I _think_ this is just as friendly to the L1 cache
  7551. // as testing in index order. It is certainty faster in practice.
  7552. return (left === right) ||
  7553. (defined(left) &&
  7554. defined(right) &&
  7555. // Translation
  7556. left[12] === right[12] &&
  7557. left[13] === right[13] &&
  7558. left[14] === right[14] &&
  7559. // Rotation/scale
  7560. left[0] === right[0] &&
  7561. left[1] === right[1] &&
  7562. left[2] === right[2] &&
  7563. left[4] === right[4] &&
  7564. left[5] === right[5] &&
  7565. left[6] === right[6] &&
  7566. left[8] === right[8] &&
  7567. left[9] === right[9] &&
  7568. left[10] === right[10] &&
  7569. // Bottom row
  7570. left[3] === right[3] &&
  7571. left[7] === right[7] &&
  7572. left[11] === right[11] &&
  7573. left[15] === right[15]);
  7574. };
  7575. /**
  7576. * Compares the provided matrices componentwise and returns
  7577. * <code>true</code> if they are within the provided epsilon,
  7578. * <code>false</code> otherwise.
  7579. *
  7580. * @param {Matrix4} [left] The first matrix.
  7581. * @param {Matrix4} [right] The second matrix.
  7582. * @param {Number} epsilon The epsilon to use for equality testing.
  7583. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7584. *
  7585. * @example
  7586. * //compares two Matrix4 instances
  7587. *
  7588. * // a = [10.5, 14.5, 18.5, 22.5]
  7589. * // [11.5, 15.5, 19.5, 23.5]
  7590. * // [12.5, 16.5, 20.5, 24.5]
  7591. * // [13.5, 17.5, 21.5, 25.5]
  7592. *
  7593. * // b = [10.0, 14.0, 18.0, 22.0]
  7594. * // [11.0, 15.0, 19.0, 23.0]
  7595. * // [12.0, 16.0, 20.0, 24.0]
  7596. * // [13.0, 17.0, 21.0, 25.0]
  7597. *
  7598. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  7599. * console.log("Difference between both the matrices is less than 0.1");
  7600. * } else {
  7601. * console.log("Difference between both the matrices is not less than 0.1");
  7602. * }
  7603. *
  7604. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  7605. */
  7606. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  7607. if (typeof epsilon !== 'number') {
  7608. throw new DeveloperError('epsilon must be a number');
  7609. }
  7610. return (left === right) ||
  7611. (defined(left) &&
  7612. defined(right) &&
  7613. Math.abs(left[0] - right[0]) <= epsilon &&
  7614. Math.abs(left[1] - right[1]) <= epsilon &&
  7615. Math.abs(left[2] - right[2]) <= epsilon &&
  7616. Math.abs(left[3] - right[3]) <= epsilon &&
  7617. Math.abs(left[4] - right[4]) <= epsilon &&
  7618. Math.abs(left[5] - right[5]) <= epsilon &&
  7619. Math.abs(left[6] - right[6]) <= epsilon &&
  7620. Math.abs(left[7] - right[7]) <= epsilon &&
  7621. Math.abs(left[8] - right[8]) <= epsilon &&
  7622. Math.abs(left[9] - right[9]) <= epsilon &&
  7623. Math.abs(left[10] - right[10]) <= epsilon &&
  7624. Math.abs(left[11] - right[11]) <= epsilon &&
  7625. Math.abs(left[12] - right[12]) <= epsilon &&
  7626. Math.abs(left[13] - right[13]) <= epsilon &&
  7627. Math.abs(left[14] - right[14]) <= epsilon &&
  7628. Math.abs(left[15] - right[15]) <= epsilon);
  7629. };
  7630. /**
  7631. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  7632. *
  7633. * @param {Matrix4} matrix The matrix to use.
  7634. * @param {Cartesian3} result The object onto which to store the result.
  7635. * @returns {Cartesian3} The modified result parameter.
  7636. */
  7637. Matrix4.getTranslation = function(matrix, result) {
  7638. if (!defined(matrix)) {
  7639. throw new DeveloperError('matrix is required');
  7640. }
  7641. if (!defined(result)) {
  7642. throw new DeveloperError('result is required');
  7643. }
  7644. result.x = matrix[12];
  7645. result.y = matrix[13];
  7646. result.z = matrix[14];
  7647. return result;
  7648. };
  7649. /**
  7650. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
  7651. *
  7652. * @param {Matrix4} matrix The matrix to use.
  7653. * @param {Matrix3} result The object onto which to store the result.
  7654. * @returns {Matrix3} The modified result parameter.
  7655. *
  7656. * @example
  7657. * // returns a Matrix3 instance from a Matrix4 instance
  7658. *
  7659. * // m = [10.0, 14.0, 18.0, 22.0]
  7660. * // [11.0, 15.0, 19.0, 23.0]
  7661. * // [12.0, 16.0, 20.0, 24.0]
  7662. * // [13.0, 17.0, 21.0, 25.0]
  7663. *
  7664. * var b = new Cesium.Matrix3();
  7665. * Cesium.Matrix4.getRotation(m,b);
  7666. *
  7667. * // b = [10.0, 14.0, 18.0]
  7668. * // [11.0, 15.0, 19.0]
  7669. * // [12.0, 16.0, 20.0]
  7670. */
  7671. Matrix4.getRotation = function(matrix, result) {
  7672. if (!defined(matrix)) {
  7673. throw new DeveloperError('matrix is required');
  7674. }
  7675. if (!defined(result)) {
  7676. throw new DeveloperError('result is required');
  7677. }
  7678. result[0] = matrix[0];
  7679. result[1] = matrix[1];
  7680. result[2] = matrix[2];
  7681. result[3] = matrix[4];
  7682. result[4] = matrix[5];
  7683. result[5] = matrix[6];
  7684. result[6] = matrix[8];
  7685. result[7] = matrix[9];
  7686. result[8] = matrix[10];
  7687. return result;
  7688. };
  7689. var scratchInverseRotation = new Matrix3();
  7690. var scratchMatrix3Zero = new Matrix3();
  7691. var scratchBottomRow = new Cartesian4();
  7692. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  7693. /**
  7694. * Computes the inverse of the provided matrix using Cramers Rule.
  7695. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  7696. * If the matrix is an affine transformation matrix, it is more efficient
  7697. * to invert it with {@link Matrix4.inverseTransformation}.
  7698. *
  7699. * @param {Matrix4} matrix The matrix to invert.
  7700. * @param {Matrix4} result The object onto which to store the result.
  7701. * @returns {Matrix4} The modified result parameter.
  7702. *
  7703. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  7704. */
  7705. Matrix4.inverse = function(matrix, result) {
  7706. if (!defined(matrix)) {
  7707. throw new DeveloperError('matrix is required');
  7708. }
  7709. if (!defined(result)) {
  7710. throw new DeveloperError('result is required');
  7711. }
  7712. // Special case for a zero scale matrix that can occur, for example,
  7713. // when a model's node has a [0, 0, 0] scale.
  7714. if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
  7715. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  7716. result[0] = 0.0;
  7717. result[1] = 0.0;
  7718. result[2] = 0.0;
  7719. result[3] = 0.0;
  7720. result[4] = 0.0;
  7721. result[5] = 0.0;
  7722. result[6] = 0.0;
  7723. result[7] = 0.0;
  7724. result[8] = 0.0;
  7725. result[9] = 0.0;
  7726. result[10] = 0.0;
  7727. result[11] = 0.0;
  7728. result[12] = -matrix[12];
  7729. result[13] = -matrix[13];
  7730. result[14] = -matrix[14];
  7731. result[15] = 1.0;
  7732. return result;
  7733. }
  7734. //
  7735. // Ported from:
  7736. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  7737. //
  7738. var src0 = matrix[0];
  7739. var src1 = matrix[4];
  7740. var src2 = matrix[8];
  7741. var src3 = matrix[12];
  7742. var src4 = matrix[1];
  7743. var src5 = matrix[5];
  7744. var src6 = matrix[9];
  7745. var src7 = matrix[13];
  7746. var src8 = matrix[2];
  7747. var src9 = matrix[6];
  7748. var src10 = matrix[10];
  7749. var src11 = matrix[14];
  7750. var src12 = matrix[3];
  7751. var src13 = matrix[7];
  7752. var src14 = matrix[11];
  7753. var src15 = matrix[15];
  7754. // calculate pairs for first 8 elements (cofactors)
  7755. var tmp0 = src10 * src15;
  7756. var tmp1 = src11 * src14;
  7757. var tmp2 = src9 * src15;
  7758. var tmp3 = src11 * src13;
  7759. var tmp4 = src9 * src14;
  7760. var tmp5 = src10 * src13;
  7761. var tmp6 = src8 * src15;
  7762. var tmp7 = src11 * src12;
  7763. var tmp8 = src8 * src14;
  7764. var tmp9 = src10 * src12;
  7765. var tmp10 = src8 * src13;
  7766. var tmp11 = src9 * src12;
  7767. // calculate first 8 elements (cofactors)
  7768. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  7769. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  7770. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  7771. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  7772. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  7773. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  7774. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  7775. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  7776. // calculate pairs for second 8 elements (cofactors)
  7777. tmp0 = src2 * src7;
  7778. tmp1 = src3 * src6;
  7779. tmp2 = src1 * src7;
  7780. tmp3 = src3 * src5;
  7781. tmp4 = src1 * src6;
  7782. tmp5 = src2 * src5;
  7783. tmp6 = src0 * src7;
  7784. tmp7 = src3 * src4;
  7785. tmp8 = src0 * src6;
  7786. tmp9 = src2 * src4;
  7787. tmp10 = src0 * src5;
  7788. tmp11 = src1 * src4;
  7789. // calculate second 8 elements (cofactors)
  7790. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  7791. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  7792. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  7793. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  7794. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  7795. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  7796. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  7797. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  7798. // calculate determinant
  7799. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  7800. if (Math.abs(det) < CesiumMath.EPSILON20) {
  7801. throw new RuntimeError('matrix is not invertible because its determinate is zero.');
  7802. }
  7803. // calculate matrix inverse
  7804. det = 1.0 / det;
  7805. result[0] = dst0 * det;
  7806. result[1] = dst1 * det;
  7807. result[2] = dst2 * det;
  7808. result[3] = dst3 * det;
  7809. result[4] = dst4 * det;
  7810. result[5] = dst5 * det;
  7811. result[6] = dst6 * det;
  7812. result[7] = dst7 * det;
  7813. result[8] = dst8 * det;
  7814. result[9] = dst9 * det;
  7815. result[10] = dst10 * det;
  7816. result[11] = dst11 * det;
  7817. result[12] = dst12 * det;
  7818. result[13] = dst13 * det;
  7819. result[14] = dst14 * det;
  7820. result[15] = dst15 * det;
  7821. return result;
  7822. };
  7823. /**
  7824. * Computes the inverse of the provided matrix assuming it is
  7825. * an affine transformation matrix, where the upper left 3x3 elements
  7826. * are a rotation matrix, and the upper three elements in the fourth
  7827. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  7828. * The matrix is not verified to be in the proper form.
  7829. * This method is faster than computing the inverse for a general 4x4
  7830. * matrix using {@link Matrix4.inverse}.
  7831. *
  7832. * @param {Matrix4} matrix The matrix to invert.
  7833. * @param {Matrix4} result The object onto which to store the result.
  7834. * @returns {Matrix4} The modified result parameter.
  7835. */
  7836. Matrix4.inverseTransformation = function(matrix, result) {
  7837. if (!defined(matrix)) {
  7838. throw new DeveloperError('matrix is required');
  7839. }
  7840. if (!defined(result)) {
  7841. throw new DeveloperError('result is required');
  7842. }
  7843. //This function is an optimized version of the below 4 lines.
  7844. //var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
  7845. //var rTN = Matrix3.negate(rT);
  7846. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  7847. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  7848. var matrix0 = matrix[0];
  7849. var matrix1 = matrix[1];
  7850. var matrix2 = matrix[2];
  7851. var matrix4 = matrix[4];
  7852. var matrix5 = matrix[5];
  7853. var matrix6 = matrix[6];
  7854. var matrix8 = matrix[8];
  7855. var matrix9 = matrix[9];
  7856. var matrix10 = matrix[10];
  7857. var vX = matrix[12];
  7858. var vY = matrix[13];
  7859. var vZ = matrix[14];
  7860. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  7861. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  7862. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  7863. result[0] = matrix0;
  7864. result[1] = matrix4;
  7865. result[2] = matrix8;
  7866. result[3] = 0.0;
  7867. result[4] = matrix1;
  7868. result[5] = matrix5;
  7869. result[6] = matrix9;
  7870. result[7] = 0.0;
  7871. result[8] = matrix2;
  7872. result[9] = matrix6;
  7873. result[10] = matrix10;
  7874. result[11] = 0.0;
  7875. result[12] = x;
  7876. result[13] = y;
  7877. result[14] = z;
  7878. result[15] = 1.0;
  7879. return result;
  7880. };
  7881. /**
  7882. * An immutable Matrix4 instance initialized to the identity matrix.
  7883. *
  7884. * @type {Matrix4}
  7885. * @constant
  7886. */
  7887. Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  7888. 0.0, 1.0, 0.0, 0.0,
  7889. 0.0, 0.0, 1.0, 0.0,
  7890. 0.0, 0.0, 0.0, 1.0));
  7891. /**
  7892. * An immutable Matrix4 instance initialized to the zero matrix.
  7893. *
  7894. * @type {Matrix4}
  7895. * @constant
  7896. */
  7897. Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  7898. 0.0, 0.0, 0.0, 0.0,
  7899. 0.0, 0.0, 0.0, 0.0,
  7900. 0.0, 0.0, 0.0, 0.0));
  7901. /**
  7902. * The index into Matrix4 for column 0, row 0.
  7903. *
  7904. * @type {Number}
  7905. * @constant
  7906. */
  7907. Matrix4.COLUMN0ROW0 = 0;
  7908. /**
  7909. * The index into Matrix4 for column 0, row 1.
  7910. *
  7911. * @type {Number}
  7912. * @constant
  7913. */
  7914. Matrix4.COLUMN0ROW1 = 1;
  7915. /**
  7916. * The index into Matrix4 for column 0, row 2.
  7917. *
  7918. * @type {Number}
  7919. * @constant
  7920. */
  7921. Matrix4.COLUMN0ROW2 = 2;
  7922. /**
  7923. * The index into Matrix4 for column 0, row 3.
  7924. *
  7925. * @type {Number}
  7926. * @constant
  7927. */
  7928. Matrix4.COLUMN0ROW3 = 3;
  7929. /**
  7930. * The index into Matrix4 for column 1, row 0.
  7931. *
  7932. * @type {Number}
  7933. * @constant
  7934. */
  7935. Matrix4.COLUMN1ROW0 = 4;
  7936. /**
  7937. * The index into Matrix4 for column 1, row 1.
  7938. *
  7939. * @type {Number}
  7940. * @constant
  7941. */
  7942. Matrix4.COLUMN1ROW1 = 5;
  7943. /**
  7944. * The index into Matrix4 for column 1, row 2.
  7945. *
  7946. * @type {Number}
  7947. * @constant
  7948. */
  7949. Matrix4.COLUMN1ROW2 = 6;
  7950. /**
  7951. * The index into Matrix4 for column 1, row 3.
  7952. *
  7953. * @type {Number}
  7954. * @constant
  7955. */
  7956. Matrix4.COLUMN1ROW3 = 7;
  7957. /**
  7958. * The index into Matrix4 for column 2, row 0.
  7959. *
  7960. * @type {Number}
  7961. * @constant
  7962. */
  7963. Matrix4.COLUMN2ROW0 = 8;
  7964. /**
  7965. * The index into Matrix4 for column 2, row 1.
  7966. *
  7967. * @type {Number}
  7968. * @constant
  7969. */
  7970. Matrix4.COLUMN2ROW1 = 9;
  7971. /**
  7972. * The index into Matrix4 for column 2, row 2.
  7973. *
  7974. * @type {Number}
  7975. * @constant
  7976. */
  7977. Matrix4.COLUMN2ROW2 = 10;
  7978. /**
  7979. * The index into Matrix4 for column 2, row 3.
  7980. *
  7981. * @type {Number}
  7982. * @constant
  7983. */
  7984. Matrix4.COLUMN2ROW3 = 11;
  7985. /**
  7986. * The index into Matrix4 for column 3, row 0.
  7987. *
  7988. * @type {Number}
  7989. * @constant
  7990. */
  7991. Matrix4.COLUMN3ROW0 = 12;
  7992. /**
  7993. * The index into Matrix4 for column 3, row 1.
  7994. *
  7995. * @type {Number}
  7996. * @constant
  7997. */
  7998. Matrix4.COLUMN3ROW1 = 13;
  7999. /**
  8000. * The index into Matrix4 for column 3, row 2.
  8001. *
  8002. * @type {Number}
  8003. * @constant
  8004. */
  8005. Matrix4.COLUMN3ROW2 = 14;
  8006. /**
  8007. * The index into Matrix4 for column 3, row 3.
  8008. *
  8009. * @type {Number}
  8010. * @constant
  8011. */
  8012. Matrix4.COLUMN3ROW3 = 15;
  8013. defineProperties(Matrix4.prototype, {
  8014. /**
  8015. * Gets the number of items in the collection.
  8016. * @memberof Matrix4.prototype
  8017. *
  8018. * @type {Number}
  8019. */
  8020. length : {
  8021. get : function() {
  8022. return Matrix4.packedLength;
  8023. }
  8024. }
  8025. });
  8026. /**
  8027. * Duplicates the provided Matrix4 instance.
  8028. *
  8029. * @param {Matrix4} [result] The object onto which to store the result.
  8030. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  8031. */
  8032. Matrix4.prototype.clone = function(result) {
  8033. return Matrix4.clone(this, result);
  8034. };
  8035. /**
  8036. * Compares this matrix to the provided matrix componentwise and returns
  8037. * <code>true</code> if they are equal, <code>false</code> otherwise.
  8038. *
  8039. * @param {Matrix4} [right] The right hand side matrix.
  8040. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  8041. */
  8042. Matrix4.prototype.equals = function(right) {
  8043. return Matrix4.equals(this, right);
  8044. };
  8045. /**
  8046. * @private
  8047. */
  8048. Matrix4.equalsArray = function(matrix, array, offset) {
  8049. return matrix[0] === array[offset] &&
  8050. matrix[1] === array[offset + 1] &&
  8051. matrix[2] === array[offset + 2] &&
  8052. matrix[3] === array[offset + 3] &&
  8053. matrix[4] === array[offset + 4] &&
  8054. matrix[5] === array[offset + 5] &&
  8055. matrix[6] === array[offset + 6] &&
  8056. matrix[7] === array[offset + 7] &&
  8057. matrix[8] === array[offset + 8] &&
  8058. matrix[9] === array[offset + 9] &&
  8059. matrix[10] === array[offset + 10] &&
  8060. matrix[11] === array[offset + 11] &&
  8061. matrix[12] === array[offset + 12] &&
  8062. matrix[13] === array[offset + 13] &&
  8063. matrix[14] === array[offset + 14] &&
  8064. matrix[15] === array[offset + 15];
  8065. };
  8066. /**
  8067. * Compares this matrix to the provided matrix componentwise and returns
  8068. * <code>true</code> if they are within the provided epsilon,
  8069. * <code>false</code> otherwise.
  8070. *
  8071. * @param {Matrix4} [right] The right hand side matrix.
  8072. * @param {Number} epsilon The epsilon to use for equality testing.
  8073. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  8074. */
  8075. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  8076. return Matrix4.equalsEpsilon(this, right, epsilon);
  8077. };
  8078. /**
  8079. * Computes a string representing this Matrix with each row being
  8080. * on a separate line and in the format '(column0, column1, column2, column3)'.
  8081. *
  8082. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  8083. */
  8084. Matrix4.prototype.toString = function() {
  8085. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
  8086. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
  8087. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
  8088. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
  8089. };
  8090. return Matrix4;
  8091. });
  8092. /*global define*/
  8093. define('Core/Rectangle',[
  8094. './Cartographic',
  8095. './defaultValue',
  8096. './defined',
  8097. './defineProperties',
  8098. './DeveloperError',
  8099. './Ellipsoid',
  8100. './freezeObject',
  8101. './Math'
  8102. ], function(
  8103. Cartographic,
  8104. defaultValue,
  8105. defined,
  8106. defineProperties,
  8107. DeveloperError,
  8108. Ellipsoid,
  8109. freezeObject,
  8110. CesiumMath) {
  8111. 'use strict';
  8112. /**
  8113. * A two dimensional region specified as longitude and latitude coordinates.
  8114. *
  8115. * @alias Rectangle
  8116. * @constructor
  8117. *
  8118. * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
  8119. * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  8120. * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
  8121. * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  8122. *
  8123. * @see Packable
  8124. */
  8125. function Rectangle(west, south, east, north) {
  8126. /**
  8127. * The westernmost longitude in radians in the range [-Pi, Pi].
  8128. *
  8129. * @type {Number}
  8130. * @default 0.0
  8131. */
  8132. this.west = defaultValue(west, 0.0);
  8133. /**
  8134. * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
  8135. *
  8136. * @type {Number}
  8137. * @default 0.0
  8138. */
  8139. this.south = defaultValue(south, 0.0);
  8140. /**
  8141. * The easternmost longitude in radians in the range [-Pi, Pi].
  8142. *
  8143. * @type {Number}
  8144. * @default 0.0
  8145. */
  8146. this.east = defaultValue(east, 0.0);
  8147. /**
  8148. * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
  8149. *
  8150. * @type {Number}
  8151. * @default 0.0
  8152. */
  8153. this.north = defaultValue(north, 0.0);
  8154. }
  8155. defineProperties(Rectangle.prototype, {
  8156. /**
  8157. * Gets the width of the rectangle in radians.
  8158. * @memberof Rectangle.prototype
  8159. * @type {Number}
  8160. */
  8161. width : {
  8162. get : function() {
  8163. return Rectangle.computeWidth(this);
  8164. }
  8165. },
  8166. /**
  8167. * Gets the height of the rectangle in radians.
  8168. * @memberof Rectangle.prototype
  8169. * @type {Number}
  8170. */
  8171. height : {
  8172. get : function() {
  8173. return Rectangle.computeHeight(this);
  8174. }
  8175. }
  8176. });
  8177. /**
  8178. * The number of elements used to pack the object into an array.
  8179. * @type {Number}
  8180. */
  8181. Rectangle.packedLength = 4;
  8182. /**
  8183. * Stores the provided instance into the provided array.
  8184. *
  8185. * @param {Rectangle} value The value to pack.
  8186. * @param {Number[]} array The array to pack into.
  8187. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  8188. *
  8189. * @returns {Number[]} The array that was packed into
  8190. */
  8191. Rectangle.pack = function(value, array, startingIndex) {
  8192. if (!defined(value)) {
  8193. throw new DeveloperError('value is required');
  8194. }
  8195. if (!defined(array)) {
  8196. throw new DeveloperError('array is required');
  8197. }
  8198. startingIndex = defaultValue(startingIndex, 0);
  8199. array[startingIndex++] = value.west;
  8200. array[startingIndex++] = value.south;
  8201. array[startingIndex++] = value.east;
  8202. array[startingIndex] = value.north;
  8203. return array;
  8204. };
  8205. /**
  8206. * Retrieves an instance from a packed array.
  8207. *
  8208. * @param {Number[]} array The packed array.
  8209. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  8210. * @param {Rectangle} [result] The object into which to store the result.
  8211. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  8212. */
  8213. Rectangle.unpack = function(array, startingIndex, result) {
  8214. if (!defined(array)) {
  8215. throw new DeveloperError('array is required');
  8216. }
  8217. startingIndex = defaultValue(startingIndex, 0);
  8218. if (!defined(result)) {
  8219. result = new Rectangle();
  8220. }
  8221. result.west = array[startingIndex++];
  8222. result.south = array[startingIndex++];
  8223. result.east = array[startingIndex++];
  8224. result.north = array[startingIndex];
  8225. return result;
  8226. };
  8227. /**
  8228. * Computes the width of a rectangle in radians.
  8229. * @param {Rectangle} rectangle The rectangle to compute the width of.
  8230. * @returns {Number} The width.
  8231. */
  8232. Rectangle.computeWidth = function(rectangle) {
  8233. if (!defined(rectangle)) {
  8234. throw new DeveloperError('rectangle is required.');
  8235. }
  8236. var east = rectangle.east;
  8237. var west = rectangle.west;
  8238. if (east < west) {
  8239. east += CesiumMath.TWO_PI;
  8240. }
  8241. return east - west;
  8242. };
  8243. /**
  8244. * Computes the height of a rectangle in radians.
  8245. * @param {Rectangle} rectangle The rectangle to compute the height of.
  8246. * @returns {Number} The height.
  8247. */
  8248. Rectangle.computeHeight = function(rectangle) {
  8249. if (!defined(rectangle)) {
  8250. throw new DeveloperError('rectangle is required.');
  8251. }
  8252. return rectangle.north - rectangle.south;
  8253. };
  8254. /**
  8255. * Creates an rectangle given the boundary longitude and latitude in degrees.
  8256. *
  8257. * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
  8258. * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
  8259. * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
  8260. * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
  8261. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8262. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8263. *
  8264. * @example
  8265. * var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
  8266. */
  8267. Rectangle.fromDegrees = function(west, south, east, north, result) {
  8268. west = CesiumMath.toRadians(defaultValue(west, 0.0));
  8269. south = CesiumMath.toRadians(defaultValue(south, 0.0));
  8270. east = CesiumMath.toRadians(defaultValue(east, 0.0));
  8271. north = CesiumMath.toRadians(defaultValue(north, 0.0));
  8272. if (!defined(result)) {
  8273. return new Rectangle(west, south, east, north);
  8274. }
  8275. result.west = west;
  8276. result.south = south;
  8277. result.east = east;
  8278. result.north = north;
  8279. return result;
  8280. };
  8281. /**
  8282. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  8283. *
  8284. * @param {Cartographic[]} cartographics The list of Cartographic instances.
  8285. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8286. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8287. */
  8288. Rectangle.fromCartographicArray = function(cartographics, result) {
  8289. if (!defined(cartographics)) {
  8290. throw new DeveloperError('cartographics is required.');
  8291. }
  8292. var west = Number.MAX_VALUE;
  8293. var east = -Number.MAX_VALUE;
  8294. var westOverIDL = Number.MAX_VALUE;
  8295. var eastOverIDL = -Number.MAX_VALUE;
  8296. var south = Number.MAX_VALUE;
  8297. var north = -Number.MAX_VALUE;
  8298. for ( var i = 0, len = cartographics.length; i < len; i++) {
  8299. var position = cartographics[i];
  8300. west = Math.min(west, position.longitude);
  8301. east = Math.max(east, position.longitude);
  8302. south = Math.min(south, position.latitude);
  8303. north = Math.max(north, position.latitude);
  8304. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  8305. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  8306. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  8307. }
  8308. if(east - west > eastOverIDL - westOverIDL) {
  8309. west = westOverIDL;
  8310. east = eastOverIDL;
  8311. if (east > CesiumMath.PI) {
  8312. east = east - CesiumMath.TWO_PI;
  8313. }
  8314. if (west > CesiumMath.PI) {
  8315. west = west - CesiumMath.TWO_PI;
  8316. }
  8317. }
  8318. if (!defined(result)) {
  8319. return new Rectangle(west, south, east, north);
  8320. }
  8321. result.west = west;
  8322. result.south = south;
  8323. result.east = east;
  8324. result.north = north;
  8325. return result;
  8326. };
  8327. /**
  8328. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  8329. *
  8330. * @param {Cartesian[]} cartesians The list of Cartesian instances.
  8331. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
  8332. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8333. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8334. */
  8335. Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
  8336. if (!defined(cartesians)) {
  8337. throw new DeveloperError('cartesians is required.');
  8338. }
  8339. var west = Number.MAX_VALUE;
  8340. var east = -Number.MAX_VALUE;
  8341. var westOverIDL = Number.MAX_VALUE;
  8342. var eastOverIDL = -Number.MAX_VALUE;
  8343. var south = Number.MAX_VALUE;
  8344. var north = -Number.MAX_VALUE;
  8345. for ( var i = 0, len = cartesians.length; i < len; i++) {
  8346. var position = ellipsoid.cartesianToCartographic(cartesians[i]);
  8347. west = Math.min(west, position.longitude);
  8348. east = Math.max(east, position.longitude);
  8349. south = Math.min(south, position.latitude);
  8350. north = Math.max(north, position.latitude);
  8351. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  8352. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  8353. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  8354. }
  8355. if(east - west > eastOverIDL - westOverIDL) {
  8356. west = westOverIDL;
  8357. east = eastOverIDL;
  8358. if (east > CesiumMath.PI) {
  8359. east = east - CesiumMath.TWO_PI;
  8360. }
  8361. if (west > CesiumMath.PI) {
  8362. west = west - CesiumMath.TWO_PI;
  8363. }
  8364. }
  8365. if (!defined(result)) {
  8366. return new Rectangle(west, south, east, north);
  8367. }
  8368. result.west = west;
  8369. result.south = south;
  8370. result.east = east;
  8371. result.north = north;
  8372. return result;
  8373. };
  8374. /**
  8375. * Duplicates an Rectangle.
  8376. *
  8377. * @param {Rectangle} rectangle The rectangle to clone.
  8378. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  8379. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
  8380. */
  8381. Rectangle.clone = function(rectangle, result) {
  8382. if (!defined(rectangle)) {
  8383. return undefined;
  8384. }
  8385. if (!defined(result)) {
  8386. return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
  8387. }
  8388. result.west = rectangle.west;
  8389. result.south = rectangle.south;
  8390. result.east = rectangle.east;
  8391. result.north = rectangle.north;
  8392. return result;
  8393. };
  8394. /**
  8395. * Duplicates this Rectangle.
  8396. *
  8397. * @param {Rectangle} [result] The object onto which to store the result.
  8398. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8399. */
  8400. Rectangle.prototype.clone = function(result) {
  8401. return Rectangle.clone(this, result);
  8402. };
  8403. /**
  8404. * Compares the provided Rectangle with this Rectangle componentwise and returns
  8405. * <code>true</code> if they are equal, <code>false</code> otherwise.
  8406. *
  8407. * @param {Rectangle} [other] The Rectangle to compare.
  8408. * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
  8409. */
  8410. Rectangle.prototype.equals = function(other) {
  8411. return Rectangle.equals(this, other);
  8412. };
  8413. /**
  8414. * Compares the provided rectangles and returns <code>true</code> if they are equal,
  8415. * <code>false</code> otherwise.
  8416. *
  8417. * @param {Rectangle} [left] The first Rectangle.
  8418. * @param {Rectangle} [right] The second Rectangle.
  8419. * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
  8420. */
  8421. Rectangle.equals = function(left, right) {
  8422. return (left === right) ||
  8423. ((defined(left)) &&
  8424. (defined(right)) &&
  8425. (left.west === right.west) &&
  8426. (left.south === right.south) &&
  8427. (left.east === right.east) &&
  8428. (left.north === right.north));
  8429. };
  8430. /**
  8431. * Compares the provided Rectangle with this Rectangle componentwise and returns
  8432. * <code>true</code> if they are within the provided epsilon,
  8433. * <code>false</code> otherwise.
  8434. *
  8435. * @param {Rectangle} [other] The Rectangle to compare.
  8436. * @param {Number} epsilon The epsilon to use for equality testing.
  8437. * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
  8438. */
  8439. Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
  8440. if (typeof epsilon !== 'number') {
  8441. throw new DeveloperError('epsilon is required and must be a number.');
  8442. }
  8443. return defined(other) &&
  8444. (Math.abs(this.west - other.west) <= epsilon) &&
  8445. (Math.abs(this.south - other.south) <= epsilon) &&
  8446. (Math.abs(this.east - other.east) <= epsilon) &&
  8447. (Math.abs(this.north - other.north) <= epsilon);
  8448. };
  8449. /**
  8450. * Checks an Rectangle's properties and throws if they are not in valid ranges.
  8451. *
  8452. * @param {Rectangle} rectangle The rectangle to validate
  8453. *
  8454. * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  8455. * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  8456. * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  8457. * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  8458. */
  8459. Rectangle.validate = function(rectangle) {
  8460. if (!defined(rectangle)) {
  8461. throw new DeveloperError('rectangle is required');
  8462. }
  8463. var north = rectangle.north;
  8464. if (typeof north !== 'number') {
  8465. throw new DeveloperError('north is required to be a number.');
  8466. }
  8467. if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
  8468. throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
  8469. }
  8470. var south = rectangle.south;
  8471. if (typeof south !== 'number') {
  8472. throw new DeveloperError('south is required to be a number.');
  8473. }
  8474. if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
  8475. throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
  8476. }
  8477. var west = rectangle.west;
  8478. if (typeof west !== 'number') {
  8479. throw new DeveloperError('west is required to be a number.');
  8480. }
  8481. if (west < -Math.PI || west > Math.PI) {
  8482. throw new DeveloperError('west must be in the interval [-Pi, Pi].');
  8483. }
  8484. var east = rectangle.east;
  8485. if (typeof east !== 'number') {
  8486. throw new DeveloperError('east is required to be a number.');
  8487. }
  8488. if (east < -Math.PI || east > Math.PI) {
  8489. throw new DeveloperError('east must be in the interval [-Pi, Pi].');
  8490. }
  8491. };
  8492. /**
  8493. * Computes the southwest corner of an rectangle.
  8494. *
  8495. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8496. * @param {Cartographic} [result] The object onto which to store the result.
  8497. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8498. */
  8499. Rectangle.southwest = function(rectangle, result) {
  8500. if (!defined(rectangle)) {
  8501. throw new DeveloperError('rectangle is required');
  8502. }
  8503. if (!defined(result)) {
  8504. return new Cartographic(rectangle.west, rectangle.south);
  8505. }
  8506. result.longitude = rectangle.west;
  8507. result.latitude = rectangle.south;
  8508. result.height = 0.0;
  8509. return result;
  8510. };
  8511. /**
  8512. * Computes the northwest corner of an rectangle.
  8513. *
  8514. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8515. * @param {Cartographic} [result] The object onto which to store the result.
  8516. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8517. */
  8518. Rectangle.northwest = function(rectangle, result) {
  8519. if (!defined(rectangle)) {
  8520. throw new DeveloperError('rectangle is required');
  8521. }
  8522. if (!defined(result)) {
  8523. return new Cartographic(rectangle.west, rectangle.north);
  8524. }
  8525. result.longitude = rectangle.west;
  8526. result.latitude = rectangle.north;
  8527. result.height = 0.0;
  8528. return result;
  8529. };
  8530. /**
  8531. * Computes the northeast corner of an rectangle.
  8532. *
  8533. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8534. * @param {Cartographic} [result] The object onto which to store the result.
  8535. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8536. */
  8537. Rectangle.northeast = function(rectangle, result) {
  8538. if (!defined(rectangle)) {
  8539. throw new DeveloperError('rectangle is required');
  8540. }
  8541. if (!defined(result)) {
  8542. return new Cartographic(rectangle.east, rectangle.north);
  8543. }
  8544. result.longitude = rectangle.east;
  8545. result.latitude = rectangle.north;
  8546. result.height = 0.0;
  8547. return result;
  8548. };
  8549. /**
  8550. * Computes the southeast corner of an rectangle.
  8551. *
  8552. * @param {Rectangle} rectangle The rectangle for which to find the corner
  8553. * @param {Cartographic} [result] The object onto which to store the result.
  8554. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8555. */
  8556. Rectangle.southeast = function(rectangle, result) {
  8557. if (!defined(rectangle)) {
  8558. throw new DeveloperError('rectangle is required');
  8559. }
  8560. if (!defined(result)) {
  8561. return new Cartographic(rectangle.east, rectangle.south);
  8562. }
  8563. result.longitude = rectangle.east;
  8564. result.latitude = rectangle.south;
  8565. result.height = 0.0;
  8566. return result;
  8567. };
  8568. /**
  8569. * Computes the center of an rectangle.
  8570. *
  8571. * @param {Rectangle} rectangle The rectangle for which to find the center
  8572. * @param {Cartographic} [result] The object onto which to store the result.
  8573. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  8574. */
  8575. Rectangle.center = function(rectangle, result) {
  8576. if (!defined(rectangle)) {
  8577. throw new DeveloperError('rectangle is required');
  8578. }
  8579. var east = rectangle.east;
  8580. var west = rectangle.west;
  8581. if (east < west) {
  8582. east += CesiumMath.TWO_PI;
  8583. }
  8584. var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
  8585. var latitude = (rectangle.south + rectangle.north) * 0.5;
  8586. if (!defined(result)) {
  8587. return new Cartographic(longitude, latitude);
  8588. }
  8589. result.longitude = longitude;
  8590. result.latitude = latitude;
  8591. result.height = 0.0;
  8592. return result;
  8593. };
  8594. /**
  8595. * Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
  8596. * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
  8597. * the same angle can be represented with multiple values as well as the wrapping of longitude at the
  8598. * anti-meridian. For a simple intersection that ignores these factors and can be used with projected
  8599. * coordinates, see {@link Rectangle.simpleIntersection}.
  8600. *
  8601. * @param {Rectangle} rectangle On rectangle to find an intersection
  8602. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  8603. * @param {Rectangle} [result] The object onto which to store the result.
  8604. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  8605. */
  8606. Rectangle.intersection = function(rectangle, otherRectangle, result) {
  8607. if (!defined(rectangle)) {
  8608. throw new DeveloperError('rectangle is required');
  8609. }
  8610. if (!defined(otherRectangle)) {
  8611. throw new DeveloperError('otherRectangle is required.');
  8612. }
  8613. var rectangleEast = rectangle.east;
  8614. var rectangleWest = rectangle.west;
  8615. var otherRectangleEast = otherRectangle.east;
  8616. var otherRectangleWest = otherRectangle.west;
  8617. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  8618. rectangleEast += CesiumMath.TWO_PI;
  8619. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  8620. otherRectangleEast += CesiumMath.TWO_PI;
  8621. }
  8622. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  8623. otherRectangleWest += CesiumMath.TWO_PI;
  8624. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  8625. rectangleWest += CesiumMath.TWO_PI;
  8626. }
  8627. var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
  8628. var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
  8629. if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
  8630. return undefined;
  8631. }
  8632. var south = Math.max(rectangle.south, otherRectangle.south);
  8633. var north = Math.min(rectangle.north, otherRectangle.north);
  8634. if (south >= north) {
  8635. return undefined;
  8636. }
  8637. if (!defined(result)) {
  8638. return new Rectangle(west, south, east, north);
  8639. }
  8640. result.west = west;
  8641. result.south = south;
  8642. result.east = east;
  8643. result.north = north;
  8644. return result;
  8645. };
  8646. /**
  8647. * Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
  8648. * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
  8649. * anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
  8650. * and longitude (i.e. projected coordinates).
  8651. *
  8652. * @param {Rectangle} rectangle On rectangle to find an intersection
  8653. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  8654. * @param {Rectangle} [result] The object onto which to store the result.
  8655. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  8656. */
  8657. Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
  8658. if (!defined(rectangle)) {
  8659. throw new DeveloperError('rectangle is required');
  8660. }
  8661. if (!defined(otherRectangle)) {
  8662. throw new DeveloperError('otherRectangle is required.');
  8663. }
  8664. var west = Math.max(rectangle.west, otherRectangle.west);
  8665. var south = Math.max(rectangle.south, otherRectangle.south);
  8666. var east = Math.min(rectangle.east, otherRectangle.east);
  8667. var north = Math.min(rectangle.north, otherRectangle.north);
  8668. if (south >= north || west >= east) {
  8669. return undefined;
  8670. }
  8671. if (!defined(result)) {
  8672. return new Rectangle(west, south, east, north);
  8673. }
  8674. result.west = west;
  8675. result.south = south;
  8676. result.east = east;
  8677. result.north = north;
  8678. return result;
  8679. };
  8680. /**
  8681. * Computes a rectangle that is the union of two rectangles.
  8682. *
  8683. * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
  8684. * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
  8685. * @param {Rectangle} [result] The object onto which to store the result.
  8686. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  8687. */
  8688. Rectangle.union = function(rectangle, otherRectangle, result) {
  8689. if (!defined(rectangle)) {
  8690. throw new DeveloperError('rectangle is required');
  8691. }
  8692. if (!defined(otherRectangle)) {
  8693. throw new DeveloperError('otherRectangle is required.');
  8694. }
  8695. if (!defined(result)) {
  8696. result = new Rectangle();
  8697. }
  8698. var rectangleEast = rectangle.east;
  8699. var rectangleWest = rectangle.west;
  8700. var otherRectangleEast = otherRectangle.east;
  8701. var otherRectangleWest = otherRectangle.west;
  8702. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  8703. rectangleEast += CesiumMath.TWO_PI;
  8704. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  8705. otherRectangleEast += CesiumMath.TWO_PI;
  8706. }
  8707. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  8708. otherRectangleWest += CesiumMath.TWO_PI;
  8709. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  8710. rectangleWest += CesiumMath.TWO_PI;
  8711. }
  8712. var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
  8713. var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
  8714. result.west = west;
  8715. result.south = Math.min(rectangle.south, otherRectangle.south);
  8716. result.east = east;
  8717. result.north = Math.max(rectangle.north, otherRectangle.north);
  8718. return result;
  8719. };
  8720. /**
  8721. * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
  8722. *
  8723. * @param {Rectangle} rectangle A rectangle to expand.
  8724. * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
  8725. * @param {Rectangle} [result] The object onto which to store the result.
  8726. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  8727. */
  8728. Rectangle.expand = function(rectangle, cartographic, result) {
  8729. if (!defined(rectangle)) {
  8730. throw new DeveloperError('rectangle is required.');
  8731. }
  8732. if (!defined(cartographic)) {
  8733. throw new DeveloperError('cartographic is required.');
  8734. }
  8735. if (!defined(result)) {
  8736. result = new Rectangle();
  8737. }
  8738. result.west = Math.min(rectangle.west, cartographic.longitude);
  8739. result.south = Math.min(rectangle.south, cartographic.latitude);
  8740. result.east = Math.max(rectangle.east, cartographic.longitude);
  8741. result.north = Math.max(rectangle.north, cartographic.latitude);
  8742. return result;
  8743. };
  8744. /**
  8745. * Returns true if the cartographic is on or inside the rectangle, false otherwise.
  8746. *
  8747. * @param {Rectangle} rectangle The rectangle
  8748. * @param {Cartographic} cartographic The cartographic to test.
  8749. * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
  8750. */
  8751. Rectangle.contains = function(rectangle, cartographic) {
  8752. if (!defined(rectangle)) {
  8753. throw new DeveloperError('rectangle is required');
  8754. }
  8755. if (!defined(cartographic)) {
  8756. throw new DeveloperError('cartographic is required.');
  8757. }
  8758. var longitude = cartographic.longitude;
  8759. var latitude = cartographic.latitude;
  8760. var west = rectangle.west;
  8761. var east = rectangle.east;
  8762. if (east < west) {
  8763. east += CesiumMath.TWO_PI;
  8764. if (longitude < 0.0) {
  8765. longitude += CesiumMath.TWO_PI;
  8766. }
  8767. }
  8768. return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
  8769. (longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
  8770. latitude >= rectangle.south &&
  8771. latitude <= rectangle.north;
  8772. };
  8773. var subsampleLlaScratch = new Cartographic();
  8774. /**
  8775. * Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
  8776. * {@link BoundingSphere#fromPoints}. Sampling is necessary to account
  8777. * for rectangles that cover the poles or cross the equator.
  8778. *
  8779. * @param {Rectangle} rectangle The rectangle to subsample.
  8780. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  8781. * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
  8782. * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
  8783. * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
  8784. */
  8785. Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
  8786. if (!defined(rectangle)) {
  8787. throw new DeveloperError('rectangle is required');
  8788. }
  8789. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  8790. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  8791. if (!defined(result)) {
  8792. result = [];
  8793. }
  8794. var length = 0;
  8795. var north = rectangle.north;
  8796. var south = rectangle.south;
  8797. var east = rectangle.east;
  8798. var west = rectangle.west;
  8799. var lla = subsampleLlaScratch;
  8800. lla.height = surfaceHeight;
  8801. lla.longitude = west;
  8802. lla.latitude = north;
  8803. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8804. length++;
  8805. lla.longitude = east;
  8806. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8807. length++;
  8808. lla.latitude = south;
  8809. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8810. length++;
  8811. lla.longitude = west;
  8812. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8813. length++;
  8814. if (north < 0.0) {
  8815. lla.latitude = north;
  8816. } else if (south > 0.0) {
  8817. lla.latitude = south;
  8818. } else {
  8819. lla.latitude = 0.0;
  8820. }
  8821. for ( var i = 1; i < 8; ++i) {
  8822. lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
  8823. if (Rectangle.contains(rectangle, lla)) {
  8824. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8825. length++;
  8826. }
  8827. }
  8828. if (lla.latitude === 0.0) {
  8829. lla.longitude = west;
  8830. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8831. length++;
  8832. lla.longitude = east;
  8833. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  8834. length++;
  8835. }
  8836. result.length = length;
  8837. return result;
  8838. };
  8839. /**
  8840. * The largest possible rectangle.
  8841. *
  8842. * @type {Rectangle}
  8843. * @constant
  8844. */
  8845. Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
  8846. return Rectangle;
  8847. });
  8848. /*global define*/
  8849. define('Core/BoundingSphere',[
  8850. './Cartesian3',
  8851. './Cartographic',
  8852. './defaultValue',
  8853. './defined',
  8854. './DeveloperError',
  8855. './Ellipsoid',
  8856. './GeographicProjection',
  8857. './Intersect',
  8858. './Interval',
  8859. './Matrix3',
  8860. './Matrix4',
  8861. './Rectangle'
  8862. ], function(
  8863. Cartesian3,
  8864. Cartographic,
  8865. defaultValue,
  8866. defined,
  8867. DeveloperError,
  8868. Ellipsoid,
  8869. GeographicProjection,
  8870. Intersect,
  8871. Interval,
  8872. Matrix3,
  8873. Matrix4,
  8874. Rectangle) {
  8875. 'use strict';
  8876. /**
  8877. * A bounding sphere with a center and a radius.
  8878. * @alias BoundingSphere
  8879. * @constructor
  8880. *
  8881. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  8882. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  8883. *
  8884. * @see AxisAlignedBoundingBox
  8885. * @see BoundingRectangle
  8886. * @see Packable
  8887. */
  8888. function BoundingSphere(center, radius) {
  8889. /**
  8890. * The center point of the sphere.
  8891. * @type {Cartesian3}
  8892. * @default {@link Cartesian3.ZERO}
  8893. */
  8894. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  8895. /**
  8896. * The radius of the sphere.
  8897. * @type {Number}
  8898. * @default 0.0
  8899. */
  8900. this.radius = defaultValue(radius, 0.0);
  8901. }
  8902. var fromPointsXMin = new Cartesian3();
  8903. var fromPointsYMin = new Cartesian3();
  8904. var fromPointsZMin = new Cartesian3();
  8905. var fromPointsXMax = new Cartesian3();
  8906. var fromPointsYMax = new Cartesian3();
  8907. var fromPointsZMax = new Cartesian3();
  8908. var fromPointsCurrentPos = new Cartesian3();
  8909. var fromPointsScratch = new Cartesian3();
  8910. var fromPointsRitterCenter = new Cartesian3();
  8911. var fromPointsMinBoxPt = new Cartesian3();
  8912. var fromPointsMaxBoxPt = new Cartesian3();
  8913. var fromPointsNaiveCenterScratch = new Cartesian3();
  8914. /**
  8915. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  8916. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  8917. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  8918. *
  8919. * @param {Cartesian3[]} positions An array of points that the bounding sphere will enclose. Each point must have <code>x</code>, <code>y</code>, and <code>z</code> properties.
  8920. * @param {BoundingSphere} [result] The object onto which to store the result.
  8921. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  8922. *
  8923. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  8924. */
  8925. BoundingSphere.fromPoints = function(positions, result) {
  8926. if (!defined(result)) {
  8927. result = new BoundingSphere();
  8928. }
  8929. if (!defined(positions) || positions.length === 0) {
  8930. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  8931. result.radius = 0.0;
  8932. return result;
  8933. }
  8934. var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  8935. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  8936. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  8937. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  8938. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  8939. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  8940. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  8941. var numPositions = positions.length;
  8942. for (var i = 1; i < numPositions; i++) {
  8943. Cartesian3.clone(positions[i], currentPos);
  8944. var x = currentPos.x;
  8945. var y = currentPos.y;
  8946. var z = currentPos.z;
  8947. // Store points containing the the smallest and largest components
  8948. if (x < xMin.x) {
  8949. Cartesian3.clone(currentPos, xMin);
  8950. }
  8951. if (x > xMax.x) {
  8952. Cartesian3.clone(currentPos, xMax);
  8953. }
  8954. if (y < yMin.y) {
  8955. Cartesian3.clone(currentPos, yMin);
  8956. }
  8957. if (y > yMax.y) {
  8958. Cartesian3.clone(currentPos, yMax);
  8959. }
  8960. if (z < zMin.z) {
  8961. Cartesian3.clone(currentPos, zMin);
  8962. }
  8963. if (z > zMax.z) {
  8964. Cartesian3.clone(currentPos, zMax);
  8965. }
  8966. }
  8967. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  8968. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  8969. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  8970. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  8971. // Set the diameter endpoints to the largest span.
  8972. var diameter1 = xMin;
  8973. var diameter2 = xMax;
  8974. var maxSpan = xSpan;
  8975. if (ySpan > maxSpan) {
  8976. maxSpan = ySpan;
  8977. diameter1 = yMin;
  8978. diameter2 = yMax;
  8979. }
  8980. if (zSpan > maxSpan) {
  8981. maxSpan = zSpan;
  8982. diameter1 = zMin;
  8983. diameter2 = zMax;
  8984. }
  8985. // Calculate the center of the initial sphere found by Ritter's algorithm
  8986. var ritterCenter = fromPointsRitterCenter;
  8987. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  8988. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  8989. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  8990. // Calculate the radius of the initial sphere found by Ritter's algorithm
  8991. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  8992. var ritterRadius = Math.sqrt(radiusSquared);
  8993. // Find the center of the sphere found using the Naive method.
  8994. var minBoxPt = fromPointsMinBoxPt;
  8995. minBoxPt.x = xMin.x;
  8996. minBoxPt.y = yMin.y;
  8997. minBoxPt.z = zMin.z;
  8998. var maxBoxPt = fromPointsMaxBoxPt;
  8999. maxBoxPt.x = xMax.x;
  9000. maxBoxPt.y = yMax.y;
  9001. maxBoxPt.z = zMax.z;
  9002. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9003. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9004. var naiveRadius = 0;
  9005. for (i = 0; i < numPositions; i++) {
  9006. Cartesian3.clone(positions[i], currentPos);
  9007. // Find the furthest point from the naive center to calculate the naive radius.
  9008. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9009. if (r > naiveRadius) {
  9010. naiveRadius = r;
  9011. }
  9012. // Make adjustments to the Ritter Sphere to include all points.
  9013. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9014. if (oldCenterToPointSquared > radiusSquared) {
  9015. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9016. // Calculate new radius to include the point that lies outside
  9017. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9018. radiusSquared = ritterRadius * ritterRadius;
  9019. // Calculate center of new Ritter sphere
  9020. var oldToNew = oldCenterToPoint - ritterRadius;
  9021. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9022. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9023. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9024. }
  9025. }
  9026. if (ritterRadius < naiveRadius) {
  9027. Cartesian3.clone(ritterCenter, result.center);
  9028. result.radius = ritterRadius;
  9029. } else {
  9030. Cartesian3.clone(naiveCenter, result.center);
  9031. result.radius = naiveRadius;
  9032. }
  9033. return result;
  9034. };
  9035. var defaultProjection = new GeographicProjection();
  9036. var fromRectangle2DLowerLeft = new Cartesian3();
  9037. var fromRectangle2DUpperRight = new Cartesian3();
  9038. var fromRectangle2DSouthwest = new Cartographic();
  9039. var fromRectangle2DNortheast = new Cartographic();
  9040. /**
  9041. * Computes a bounding sphere from an rectangle projected in 2D.
  9042. *
  9043. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  9044. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  9045. * @param {BoundingSphere} [result] The object onto which to store the result.
  9046. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9047. */
  9048. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  9049. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  9050. };
  9051. /**
  9052. * Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
  9053. * object's minimum and maximum heights over the rectangle.
  9054. *
  9055. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  9056. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  9057. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  9058. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  9059. * @param {BoundingSphere} [result] The object onto which to store the result.
  9060. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9061. */
  9062. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  9063. if (!defined(result)) {
  9064. result = new BoundingSphere();
  9065. }
  9066. if (!defined(rectangle)) {
  9067. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9068. result.radius = 0.0;
  9069. return result;
  9070. }
  9071. projection = defaultValue(projection, defaultProjection);
  9072. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  9073. fromRectangle2DSouthwest.height = minimumHeight;
  9074. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  9075. fromRectangle2DNortheast.height = maximumHeight;
  9076. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  9077. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  9078. var width = upperRight.x - lowerLeft.x;
  9079. var height = upperRight.y - lowerLeft.y;
  9080. var elevation = upperRight.z - lowerLeft.z;
  9081. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  9082. var center = result.center;
  9083. center.x = lowerLeft.x + width * 0.5;
  9084. center.y = lowerLeft.y + height * 0.5;
  9085. center.z = lowerLeft.z + elevation * 0.5;
  9086. return result;
  9087. };
  9088. var fromRectangle3DScratch = [];
  9089. /**
  9090. * Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
  9091. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  9092. *
  9093. * @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
  9094. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  9095. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  9096. * @param {BoundingSphere} [result] The object onto which to store the result.
  9097. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9098. */
  9099. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  9100. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  9101. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  9102. var positions;
  9103. if (defined(rectangle)) {
  9104. positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  9105. }
  9106. return BoundingSphere.fromPoints(positions, result);
  9107. };
  9108. /**
  9109. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  9110. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  9111. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  9112. * ensure a tight fit.
  9113. *
  9114. * @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
  9115. * is formed from three elements in the array in the order X, Y, Z.
  9116. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  9117. * origin of the coordinate system. This is useful when the positions are to be used for
  9118. * relative-to-center (RTC) rendering.
  9119. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  9120. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  9121. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  9122. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  9123. * the stride is 5, however, two array elements are skipped and the next position begins at array
  9124. * index 5.
  9125. * @param {BoundingSphere} [result] The object onto which to store the result.
  9126. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9127. *
  9128. * @example
  9129. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  9130. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  9131. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  9132. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9133. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  9134. * 4.0, 5.0, 6.0, 0.1, 0.2,
  9135. * 7.0, 8.0, 9.0, 0.1, 0.2];
  9136. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  9137. *
  9138. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9139. */
  9140. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  9141. if (!defined(result)) {
  9142. result = new BoundingSphere();
  9143. }
  9144. if (!defined(positions) || positions.length === 0) {
  9145. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9146. result.radius = 0.0;
  9147. return result;
  9148. }
  9149. center = defaultValue(center, Cartesian3.ZERO);
  9150. stride = defaultValue(stride, 3);
  9151. if (stride < 3) {
  9152. throw new DeveloperError('stride must be 3 or greater.');
  9153. }
  9154. var currentPos = fromPointsCurrentPos;
  9155. currentPos.x = positions[0] + center.x;
  9156. currentPos.y = positions[1] + center.y;
  9157. currentPos.z = positions[2] + center.z;
  9158. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9159. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9160. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9161. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9162. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9163. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9164. var numElements = positions.length;
  9165. for (var i = 0; i < numElements; i += stride) {
  9166. var x = positions[i] + center.x;
  9167. var y = positions[i + 1] + center.y;
  9168. var z = positions[i + 2] + center.z;
  9169. currentPos.x = x;
  9170. currentPos.y = y;
  9171. currentPos.z = z;
  9172. // Store points containing the the smallest and largest components
  9173. if (x < xMin.x) {
  9174. Cartesian3.clone(currentPos, xMin);
  9175. }
  9176. if (x > xMax.x) {
  9177. Cartesian3.clone(currentPos, xMax);
  9178. }
  9179. if (y < yMin.y) {
  9180. Cartesian3.clone(currentPos, yMin);
  9181. }
  9182. if (y > yMax.y) {
  9183. Cartesian3.clone(currentPos, yMax);
  9184. }
  9185. if (z < zMin.z) {
  9186. Cartesian3.clone(currentPos, zMin);
  9187. }
  9188. if (z > zMax.z) {
  9189. Cartesian3.clone(currentPos, zMax);
  9190. }
  9191. }
  9192. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9193. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9194. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9195. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9196. // Set the diameter endpoints to the largest span.
  9197. var diameter1 = xMin;
  9198. var diameter2 = xMax;
  9199. var maxSpan = xSpan;
  9200. if (ySpan > maxSpan) {
  9201. maxSpan = ySpan;
  9202. diameter1 = yMin;
  9203. diameter2 = yMax;
  9204. }
  9205. if (zSpan > maxSpan) {
  9206. maxSpan = zSpan;
  9207. diameter1 = zMin;
  9208. diameter2 = zMax;
  9209. }
  9210. // Calculate the center of the initial sphere found by Ritter's algorithm
  9211. var ritterCenter = fromPointsRitterCenter;
  9212. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9213. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9214. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9215. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9216. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9217. var ritterRadius = Math.sqrt(radiusSquared);
  9218. // Find the center of the sphere found using the Naive method.
  9219. var minBoxPt = fromPointsMinBoxPt;
  9220. minBoxPt.x = xMin.x;
  9221. minBoxPt.y = yMin.y;
  9222. minBoxPt.z = zMin.z;
  9223. var maxBoxPt = fromPointsMaxBoxPt;
  9224. maxBoxPt.x = xMax.x;
  9225. maxBoxPt.y = yMax.y;
  9226. maxBoxPt.z = zMax.z;
  9227. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9228. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9229. var naiveRadius = 0;
  9230. for (i = 0; i < numElements; i += stride) {
  9231. currentPos.x = positions[i] + center.x;
  9232. currentPos.y = positions[i + 1] + center.y;
  9233. currentPos.z = positions[i + 2] + center.z;
  9234. // Find the furthest point from the naive center to calculate the naive radius.
  9235. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9236. if (r > naiveRadius) {
  9237. naiveRadius = r;
  9238. }
  9239. // Make adjustments to the Ritter Sphere to include all points.
  9240. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9241. if (oldCenterToPointSquared > radiusSquared) {
  9242. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9243. // Calculate new radius to include the point that lies outside
  9244. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9245. radiusSquared = ritterRadius * ritterRadius;
  9246. // Calculate center of new Ritter sphere
  9247. var oldToNew = oldCenterToPoint - ritterRadius;
  9248. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9249. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9250. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9251. }
  9252. }
  9253. if (ritterRadius < naiveRadius) {
  9254. Cartesian3.clone(ritterCenter, result.center);
  9255. result.radius = ritterRadius;
  9256. } else {
  9257. Cartesian3.clone(naiveCenter, result.center);
  9258. result.radius = naiveRadius;
  9259. }
  9260. return result;
  9261. };
  9262. /**
  9263. * Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
  9264. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  9265. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  9266. * ensure a tight fit.
  9267. *
  9268. * @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  9269. * is formed from three elements in the array in the order X, Y, Z.
  9270. * @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  9271. * is formed from three elements in the array in the order X, Y, Z.
  9272. * @param {BoundingSphere} [result] The object onto which to store the result.
  9273. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9274. *
  9275. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9276. */
  9277. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  9278. if (!defined(result)) {
  9279. result = new BoundingSphere();
  9280. }
  9281. if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  9282. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9283. result.radius = 0.0;
  9284. return result;
  9285. }
  9286. var currentPos = fromPointsCurrentPos;
  9287. currentPos.x = positionsHigh[0] + positionsLow[0];
  9288. currentPos.y = positionsHigh[1] + positionsLow[1];
  9289. currentPos.z = positionsHigh[2] + positionsLow[2];
  9290. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9291. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9292. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9293. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9294. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9295. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9296. var numElements = positionsHigh.length;
  9297. for (var i = 0; i < numElements; i += 3) {
  9298. var x = positionsHigh[i] + positionsLow[i];
  9299. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  9300. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  9301. currentPos.x = x;
  9302. currentPos.y = y;
  9303. currentPos.z = z;
  9304. // Store points containing the the smallest and largest components
  9305. if (x < xMin.x) {
  9306. Cartesian3.clone(currentPos, xMin);
  9307. }
  9308. if (x > xMax.x) {
  9309. Cartesian3.clone(currentPos, xMax);
  9310. }
  9311. if (y < yMin.y) {
  9312. Cartesian3.clone(currentPos, yMin);
  9313. }
  9314. if (y > yMax.y) {
  9315. Cartesian3.clone(currentPos, yMax);
  9316. }
  9317. if (z < zMin.z) {
  9318. Cartesian3.clone(currentPos, zMin);
  9319. }
  9320. if (z > zMax.z) {
  9321. Cartesian3.clone(currentPos, zMax);
  9322. }
  9323. }
  9324. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  9325. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  9326. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  9327. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  9328. // Set the diameter endpoints to the largest span.
  9329. var diameter1 = xMin;
  9330. var diameter2 = xMax;
  9331. var maxSpan = xSpan;
  9332. if (ySpan > maxSpan) {
  9333. maxSpan = ySpan;
  9334. diameter1 = yMin;
  9335. diameter2 = yMax;
  9336. }
  9337. if (zSpan > maxSpan) {
  9338. maxSpan = zSpan;
  9339. diameter1 = zMin;
  9340. diameter2 = zMax;
  9341. }
  9342. // Calculate the center of the initial sphere found by Ritter's algorithm
  9343. var ritterCenter = fromPointsRitterCenter;
  9344. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  9345. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  9346. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  9347. // Calculate the radius of the initial sphere found by Ritter's algorithm
  9348. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  9349. var ritterRadius = Math.sqrt(radiusSquared);
  9350. // Find the center of the sphere found using the Naive method.
  9351. var minBoxPt = fromPointsMinBoxPt;
  9352. minBoxPt.x = xMin.x;
  9353. minBoxPt.y = yMin.y;
  9354. minBoxPt.z = zMin.z;
  9355. var maxBoxPt = fromPointsMaxBoxPt;
  9356. maxBoxPt.x = xMax.x;
  9357. maxBoxPt.y = yMax.y;
  9358. maxBoxPt.z = zMax.z;
  9359. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  9360. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  9361. var naiveRadius = 0;
  9362. for (i = 0; i < numElements; i += 3) {
  9363. currentPos.x = positionsHigh[i] + positionsLow[i];
  9364. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  9365. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  9366. // Find the furthest point from the naive center to calculate the naive radius.
  9367. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  9368. if (r > naiveRadius) {
  9369. naiveRadius = r;
  9370. }
  9371. // Make adjustments to the Ritter Sphere to include all points.
  9372. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  9373. if (oldCenterToPointSquared > radiusSquared) {
  9374. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  9375. // Calculate new radius to include the point that lies outside
  9376. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  9377. radiusSquared = ritterRadius * ritterRadius;
  9378. // Calculate center of new Ritter sphere
  9379. var oldToNew = oldCenterToPoint - ritterRadius;
  9380. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  9381. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  9382. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  9383. }
  9384. }
  9385. if (ritterRadius < naiveRadius) {
  9386. Cartesian3.clone(ritterCenter, result.center);
  9387. result.radius = ritterRadius;
  9388. } else {
  9389. Cartesian3.clone(naiveCenter, result.center);
  9390. result.radius = naiveRadius;
  9391. }
  9392. return result;
  9393. };
  9394. /**
  9395. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  9396. * tighly and fully encompases the box.
  9397. *
  9398. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  9399. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  9400. * @param {BoundingSphere} [result] The object onto which to store the result.
  9401. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9402. *
  9403. * @example
  9404. * // Create a bounding sphere around the unit cube
  9405. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  9406. */
  9407. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  9408. if (!defined(corner) || !defined(oppositeCorner)) {
  9409. throw new DeveloperError('corner and oppositeCorner are required.');
  9410. }
  9411. if (!defined(result)) {
  9412. result = new BoundingSphere();
  9413. }
  9414. var center = result.center;
  9415. Cartesian3.add(corner, oppositeCorner, center);
  9416. Cartesian3.multiplyByScalar(center, 0.5, center);
  9417. result.radius = Cartesian3.distance(center, oppositeCorner);
  9418. return result;
  9419. };
  9420. /**
  9421. * Creates a bounding sphere encompassing an ellipsoid.
  9422. *
  9423. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  9424. * @param {BoundingSphere} [result] The object onto which to store the result.
  9425. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9426. *
  9427. * @example
  9428. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  9429. */
  9430. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  9431. if (!defined(ellipsoid)) {
  9432. throw new DeveloperError('ellipsoid is required.');
  9433. }
  9434. if (!defined(result)) {
  9435. result = new BoundingSphere();
  9436. }
  9437. Cartesian3.clone(Cartesian3.ZERO, result.center);
  9438. result.radius = ellipsoid.maximumRadius;
  9439. return result;
  9440. };
  9441. var fromBoundingSpheresScratch = new Cartesian3();
  9442. /**
  9443. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  9444. *
  9445. * @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
  9446. * @param {BoundingSphere} [result] The object onto which to store the result.
  9447. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9448. */
  9449. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  9450. if (!defined(result)) {
  9451. result = new BoundingSphere();
  9452. }
  9453. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  9454. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9455. result.radius = 0.0;
  9456. return result;
  9457. }
  9458. var length = boundingSpheres.length;
  9459. if (length === 1) {
  9460. return BoundingSphere.clone(boundingSpheres[0], result);
  9461. }
  9462. if (length === 2) {
  9463. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  9464. }
  9465. var positions = [];
  9466. for (var i = 0; i < length; i++) {
  9467. positions.push(boundingSpheres[i].center);
  9468. }
  9469. result = BoundingSphere.fromPoints(positions, result);
  9470. var center = result.center;
  9471. var radius = result.radius;
  9472. for (i = 0; i < length; i++) {
  9473. var tmp = boundingSpheres[i];
  9474. radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  9475. }
  9476. result.radius = radius;
  9477. return result;
  9478. };
  9479. var fromOrientedBoundingBoxScratchU = new Cartesian3();
  9480. var fromOrientedBoundingBoxScratchV = new Cartesian3();
  9481. var fromOrientedBoundingBoxScratchW = new Cartesian3();
  9482. /**
  9483. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  9484. *
  9485. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  9486. * @param {BoundingSphere} [result] The object onto which to store the result.
  9487. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9488. */
  9489. BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  9490. if (!defined(result)) {
  9491. result = new BoundingSphere();
  9492. }
  9493. var halfAxes = orientedBoundingBox.halfAxes;
  9494. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  9495. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  9496. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  9497. var uHalf = Cartesian3.magnitude(u);
  9498. var vHalf = Cartesian3.magnitude(v);
  9499. var wHalf = Cartesian3.magnitude(w);
  9500. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  9501. result.radius = Math.max(uHalf, vHalf, wHalf);
  9502. return result;
  9503. };
  9504. /**
  9505. * Duplicates a BoundingSphere instance.
  9506. *
  9507. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  9508. * @param {BoundingSphere} [result] The object onto which to store the result.
  9509. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  9510. */
  9511. BoundingSphere.clone = function(sphere, result) {
  9512. if (!defined(sphere)) {
  9513. return undefined;
  9514. }
  9515. if (!defined(result)) {
  9516. return new BoundingSphere(sphere.center, sphere.radius);
  9517. }
  9518. result.center = Cartesian3.clone(sphere.center, result.center);
  9519. result.radius = sphere.radius;
  9520. return result;
  9521. };
  9522. /**
  9523. * The number of elements used to pack the object into an array.
  9524. * @type {Number}
  9525. */
  9526. BoundingSphere.packedLength = 4;
  9527. /**
  9528. * Stores the provided instance into the provided array.
  9529. *
  9530. * @param {BoundingSphere} value The value to pack.
  9531. * @param {Number[]} array The array to pack into.
  9532. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  9533. *
  9534. * @returns {Number[]} The array that was packed into
  9535. */
  9536. BoundingSphere.pack = function(value, array, startingIndex) {
  9537. if (!defined(value)) {
  9538. throw new DeveloperError('value is required');
  9539. }
  9540. if (!defined(array)) {
  9541. throw new DeveloperError('array is required');
  9542. }
  9543. startingIndex = defaultValue(startingIndex, 0);
  9544. var center = value.center;
  9545. array[startingIndex++] = center.x;
  9546. array[startingIndex++] = center.y;
  9547. array[startingIndex++] = center.z;
  9548. array[startingIndex] = value.radius;
  9549. return array;
  9550. };
  9551. /**
  9552. * Retrieves an instance from a packed array.
  9553. *
  9554. * @param {Number[]} array The packed array.
  9555. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  9556. * @param {BoundingSphere} [result] The object into which to store the result.
  9557. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9558. */
  9559. BoundingSphere.unpack = function(array, startingIndex, result) {
  9560. if (!defined(array)) {
  9561. throw new DeveloperError('array is required');
  9562. }
  9563. startingIndex = defaultValue(startingIndex, 0);
  9564. if (!defined(result)) {
  9565. result = new BoundingSphere();
  9566. }
  9567. var center = result.center;
  9568. center.x = array[startingIndex++];
  9569. center.y = array[startingIndex++];
  9570. center.z = array[startingIndex++];
  9571. result.radius = array[startingIndex];
  9572. return result;
  9573. };
  9574. var unionScratch = new Cartesian3();
  9575. var unionScratchCenter = new Cartesian3();
  9576. /**
  9577. * Computes a bounding sphere that contains both the left and right bounding spheres.
  9578. *
  9579. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  9580. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  9581. * @param {BoundingSphere} [result] The object onto which to store the result.
  9582. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9583. */
  9584. BoundingSphere.union = function(left, right, result) {
  9585. if (!defined(left)) {
  9586. throw new DeveloperError('left is required.');
  9587. }
  9588. if (!defined(right)) {
  9589. throw new DeveloperError('right is required.');
  9590. }
  9591. if (!defined(result)) {
  9592. result = new BoundingSphere();
  9593. }
  9594. var leftCenter = left.center;
  9595. var leftRadius = left.radius;
  9596. var rightCenter = right.center;
  9597. var rightRadius = right.radius;
  9598. var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  9599. var centerSeparation = Cartesian3.magnitude(toRightCenter);
  9600. if (leftRadius >= (centerSeparation + rightRadius)) {
  9601. // Left sphere wins.
  9602. left.clone(result);
  9603. return result;
  9604. }
  9605. if (rightRadius >= (centerSeparation + leftRadius)) {
  9606. // Right sphere wins.
  9607. right.clone(result);
  9608. return result;
  9609. }
  9610. // There are two tangent points, one on far side of each sphere.
  9611. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  9612. // Compute the center point halfway between the two tangent points.
  9613. var center = Cartesian3.multiplyByScalar(toRightCenter,
  9614. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  9615. Cartesian3.add(center, leftCenter, center);
  9616. Cartesian3.clone(center, result.center);
  9617. result.radius = halfDistanceBetweenTangentPoints;
  9618. return result;
  9619. };
  9620. var expandScratch = new Cartesian3();
  9621. /**
  9622. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  9623. *
  9624. * @param {BoundingSphere} sphere A sphere to expand.
  9625. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  9626. * @param {BoundingSphere} [result] The object onto which to store the result.
  9627. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9628. */
  9629. BoundingSphere.expand = function(sphere, point, result) {
  9630. if (!defined(sphere)) {
  9631. throw new DeveloperError('sphere is required.');
  9632. }
  9633. if (!defined(point)) {
  9634. throw new DeveloperError('point is required.');
  9635. }
  9636. result = BoundingSphere.clone(sphere, result);
  9637. var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
  9638. if (radius > result.radius) {
  9639. result.radius = radius;
  9640. }
  9641. return result;
  9642. };
  9643. /**
  9644. * Determines which side of a plane a sphere is located.
  9645. *
  9646. * @param {BoundingSphere} sphere The bounding sphere to test.
  9647. * @param {Plane} plane The plane to test against.
  9648. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  9649. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  9650. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  9651. * intersects the plane.
  9652. */
  9653. BoundingSphere.intersectPlane = function(sphere, plane) {
  9654. if (!defined(sphere)) {
  9655. throw new DeveloperError('sphere is required.');
  9656. }
  9657. if (!defined(plane)) {
  9658. throw new DeveloperError('plane is required.');
  9659. }
  9660. var center = sphere.center;
  9661. var radius = sphere.radius;
  9662. var normal = plane.normal;
  9663. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  9664. if (distanceToPlane < -radius) {
  9665. // The center point is negative side of the plane normal
  9666. return Intersect.OUTSIDE;
  9667. } else if (distanceToPlane < radius) {
  9668. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  9669. return Intersect.INTERSECTING;
  9670. }
  9671. return Intersect.INSIDE;
  9672. };
  9673. /**
  9674. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  9675. *
  9676. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  9677. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  9678. * @param {BoundingSphere} [result] The object onto which to store the result.
  9679. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9680. */
  9681. BoundingSphere.transform = function(sphere, transform, result) {
  9682. if (!defined(sphere)) {
  9683. throw new DeveloperError('sphere is required.');
  9684. }
  9685. if (!defined(transform)) {
  9686. throw new DeveloperError('transform is required.');
  9687. }
  9688. if (!defined(result)) {
  9689. result = new BoundingSphere();
  9690. }
  9691. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  9692. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  9693. return result;
  9694. };
  9695. var distanceSquaredToScratch = new Cartesian3();
  9696. /**
  9697. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  9698. *
  9699. * @param {BoundingSphere} sphere The sphere.
  9700. * @param {Cartesian3} cartesian The point
  9701. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  9702. *
  9703. * @example
  9704. * // Sort bounding spheres from back to front
  9705. * spheres.sort(function(a, b) {
  9706. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  9707. * });
  9708. */
  9709. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  9710. if (!defined(sphere)) {
  9711. throw new DeveloperError('sphere is required.');
  9712. }
  9713. if (!defined(cartesian)) {
  9714. throw new DeveloperError('cartesian is required.');
  9715. }
  9716. var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  9717. return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  9718. };
  9719. /**
  9720. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  9721. * The transformation matrix is not verified to have a uniform scale of 1.
  9722. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  9723. *
  9724. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  9725. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  9726. * @param {BoundingSphere} [result] The object onto which to store the result.
  9727. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9728. *
  9729. * @example
  9730. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  9731. * var boundingSphere = new Cesium.BoundingSphere();
  9732. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  9733. */
  9734. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  9735. if (!defined(sphere)) {
  9736. throw new DeveloperError('sphere is required.');
  9737. }
  9738. if (!defined(transform)) {
  9739. throw new DeveloperError('transform is required.');
  9740. }
  9741. if (!defined(result)) {
  9742. result = new BoundingSphere();
  9743. }
  9744. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  9745. result.radius = sphere.radius;
  9746. return result;
  9747. };
  9748. var scratchCartesian3 = new Cartesian3();
  9749. /**
  9750. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  9751. * plus/minus the radius of the bounding sphere.
  9752. * <br>
  9753. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  9754. * closest and farthest planes from position that intersect the bounding sphere.
  9755. *
  9756. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  9757. * @param {Cartesian3} position The position to calculate the distance from.
  9758. * @param {Cartesian3} direction The direction from position.
  9759. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  9760. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  9761. */
  9762. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  9763. if (!defined(sphere)) {
  9764. throw new DeveloperError('sphere is required.');
  9765. }
  9766. if (!defined(position)) {
  9767. throw new DeveloperError('position is required.');
  9768. }
  9769. if (!defined(direction)) {
  9770. throw new DeveloperError('direction is required.');
  9771. }
  9772. if (!defined(result)) {
  9773. result = new Interval();
  9774. }
  9775. var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  9776. var mag = Cartesian3.dot(direction, toCenter);
  9777. result.start = mag - sphere.radius;
  9778. result.stop = mag + sphere.radius;
  9779. return result;
  9780. };
  9781. var projectTo2DNormalScratch = new Cartesian3();
  9782. var projectTo2DEastScratch = new Cartesian3();
  9783. var projectTo2DNorthScratch = new Cartesian3();
  9784. var projectTo2DWestScratch = new Cartesian3();
  9785. var projectTo2DSouthScratch = new Cartesian3();
  9786. var projectTo2DCartographicScratch = new Cartographic();
  9787. var projectTo2DPositionsScratch = new Array(8);
  9788. for (var n = 0; n < 8; ++n) {
  9789. projectTo2DPositionsScratch[n] = new Cartesian3();
  9790. }
  9791. var projectTo2DProjection = new GeographicProjection();
  9792. /**
  9793. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  9794. *
  9795. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  9796. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  9797. * @param {BoundingSphere} [result] The object onto which to store the result.
  9798. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9799. */
  9800. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  9801. if (!defined(sphere)) {
  9802. throw new DeveloperError('sphere is required.');
  9803. }
  9804. projection = defaultValue(projection, projectTo2DProjection);
  9805. var ellipsoid = projection.ellipsoid;
  9806. var center = sphere.center;
  9807. var radius = sphere.radius;
  9808. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  9809. var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  9810. Cartesian3.normalize(east, east);
  9811. var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  9812. Cartesian3.normalize(north, north);
  9813. Cartesian3.multiplyByScalar(normal, radius, normal);
  9814. Cartesian3.multiplyByScalar(north, radius, north);
  9815. Cartesian3.multiplyByScalar(east, radius, east);
  9816. var south = Cartesian3.negate(north, projectTo2DSouthScratch);
  9817. var west = Cartesian3.negate(east, projectTo2DWestScratch);
  9818. var positions = projectTo2DPositionsScratch;
  9819. // top NE corner
  9820. var corner = positions[0];
  9821. Cartesian3.add(normal, north, corner);
  9822. Cartesian3.add(corner, east, corner);
  9823. // top NW corner
  9824. corner = positions[1];
  9825. Cartesian3.add(normal, north, corner);
  9826. Cartesian3.add(corner, west, corner);
  9827. // top SW corner
  9828. corner = positions[2];
  9829. Cartesian3.add(normal, south, corner);
  9830. Cartesian3.add(corner, west, corner);
  9831. // top SE corner
  9832. corner = positions[3];
  9833. Cartesian3.add(normal, south, corner);
  9834. Cartesian3.add(corner, east, corner);
  9835. Cartesian3.negate(normal, normal);
  9836. // bottom NE corner
  9837. corner = positions[4];
  9838. Cartesian3.add(normal, north, corner);
  9839. Cartesian3.add(corner, east, corner);
  9840. // bottom NW corner
  9841. corner = positions[5];
  9842. Cartesian3.add(normal, north, corner);
  9843. Cartesian3.add(corner, west, corner);
  9844. // bottom SW corner
  9845. corner = positions[6];
  9846. Cartesian3.add(normal, south, corner);
  9847. Cartesian3.add(corner, west, corner);
  9848. // bottom SE corner
  9849. corner = positions[7];
  9850. Cartesian3.add(normal, south, corner);
  9851. Cartesian3.add(corner, east, corner);
  9852. var length = positions.length;
  9853. for (var i = 0; i < length; ++i) {
  9854. var position = positions[i];
  9855. Cartesian3.add(center, position, position);
  9856. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  9857. projection.project(cartographic, position);
  9858. }
  9859. result = BoundingSphere.fromPoints(positions, result);
  9860. // swizzle center components
  9861. center = result.center;
  9862. var x = center.x;
  9863. var y = center.y;
  9864. var z = center.z;
  9865. center.x = z;
  9866. center.y = x;
  9867. center.z = y;
  9868. return result;
  9869. };
  9870. /**
  9871. * Determines whether or not a sphere is hidden from view by the occluder.
  9872. *
  9873. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  9874. * @param {Occluder} occluder The occluder.
  9875. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  9876. */
  9877. BoundingSphere.isOccluded = function(sphere, occluder) {
  9878. if (!defined(sphere)) {
  9879. throw new DeveloperError('sphere is required.');
  9880. }
  9881. if (!defined(occluder)) {
  9882. throw new DeveloperError('occluder is required.');
  9883. }
  9884. return !occluder.isBoundingSphereVisible(sphere);
  9885. };
  9886. /**
  9887. * Compares the provided BoundingSphere componentwise and returns
  9888. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9889. *
  9890. * @param {BoundingSphere} [left] The first BoundingSphere.
  9891. * @param {BoundingSphere} [right] The second BoundingSphere.
  9892. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  9893. */
  9894. BoundingSphere.equals = function(left, right) {
  9895. return (left === right) ||
  9896. ((defined(left)) &&
  9897. (defined(right)) &&
  9898. Cartesian3.equals(left.center, right.center) &&
  9899. left.radius === right.radius);
  9900. };
  9901. /**
  9902. * Determines which side of a plane the sphere is located.
  9903. *
  9904. * @param {Plane} plane The plane to test against.
  9905. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  9906. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  9907. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  9908. * intersects the plane.
  9909. */
  9910. BoundingSphere.prototype.intersectPlane = function(plane) {
  9911. return BoundingSphere.intersectPlane(this, plane);
  9912. };
  9913. /**
  9914. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  9915. *
  9916. * @param {Cartesian3} cartesian The point
  9917. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  9918. *
  9919. * @example
  9920. * // Sort bounding spheres from back to front
  9921. * spheres.sort(function(a, b) {
  9922. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  9923. * });
  9924. */
  9925. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  9926. return BoundingSphere.distanceSquaredTo(this, cartesian);
  9927. };
  9928. /**
  9929. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  9930. * plus/minus the radius of the bounding sphere.
  9931. * <br>
  9932. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  9933. * closest and farthest planes from position that intersect the bounding sphere.
  9934. *
  9935. * @param {Cartesian3} position The position to calculate the distance from.
  9936. * @param {Cartesian3} direction The direction from position.
  9937. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  9938. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  9939. */
  9940. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  9941. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  9942. };
  9943. /**
  9944. * Determines whether or not a sphere is hidden from view by the occluder.
  9945. *
  9946. * @param {Occluder} occluder The occluder.
  9947. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  9948. */
  9949. BoundingSphere.prototype.isOccluded = function(occluder) {
  9950. return BoundingSphere.isOccluded(this, occluder);
  9951. };
  9952. /**
  9953. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  9954. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9955. *
  9956. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  9957. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  9958. */
  9959. BoundingSphere.prototype.equals = function(right) {
  9960. return BoundingSphere.equals(this, right);
  9961. };
  9962. /**
  9963. * Duplicates this BoundingSphere instance.
  9964. *
  9965. * @param {BoundingSphere} [result] The object onto which to store the result.
  9966. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  9967. */
  9968. BoundingSphere.prototype.clone = function(result) {
  9969. return BoundingSphere.clone(this, result);
  9970. };
  9971. return BoundingSphere;
  9972. });
  9973. /*global define*/
  9974. define('Core/Fullscreen',[
  9975. './defined',
  9976. './defineProperties'
  9977. ], function(
  9978. defined,
  9979. defineProperties) {
  9980. 'use strict';
  9981. var _supportsFullscreen;
  9982. var _names = {
  9983. requestFullscreen : undefined,
  9984. exitFullscreen : undefined,
  9985. fullscreenEnabled : undefined,
  9986. fullscreenElement : undefined,
  9987. fullscreenchange : undefined,
  9988. fullscreenerror : undefined
  9989. };
  9990. /**
  9991. * Browser-independent functions for working with the standard fullscreen API.
  9992. *
  9993. * @exports Fullscreen
  9994. *
  9995. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  9996. */
  9997. var Fullscreen = {};
  9998. defineProperties(Fullscreen, {
  9999. /**
  10000. * The element that is currently fullscreen, if any. To simply check if the
  10001. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  10002. * @memberof Fullscreen
  10003. * @type {Object}
  10004. * @readonly
  10005. */
  10006. element : {
  10007. get : function() {
  10008. if (!Fullscreen.supportsFullscreen()) {
  10009. return undefined;
  10010. }
  10011. return document[_names.fullscreenElement];
  10012. }
  10013. },
  10014. /**
  10015. * The name of the event on the document that is fired when fullscreen is
  10016. * entered or exited. This event name is intended for use with addEventListener.
  10017. * In your event handler, to determine if the browser is in fullscreen mode or not,
  10018. * use {@link Fullscreen#fullscreen}.
  10019. * @memberof Fullscreen
  10020. * @type {String}
  10021. * @readonly
  10022. */
  10023. changeEventName : {
  10024. get : function() {
  10025. if (!Fullscreen.supportsFullscreen()) {
  10026. return undefined;
  10027. }
  10028. return _names.fullscreenchange;
  10029. }
  10030. },
  10031. /**
  10032. * The name of the event that is fired when a fullscreen error
  10033. * occurs. This event name is intended for use with addEventListener.
  10034. * @memberof Fullscreen
  10035. * @type {String}
  10036. * @readonly
  10037. */
  10038. errorEventName : {
  10039. get : function() {
  10040. if (!Fullscreen.supportsFullscreen()) {
  10041. return undefined;
  10042. }
  10043. return _names.fullscreenerror;
  10044. }
  10045. },
  10046. /**
  10047. * Determine whether the browser will allow an element to be made fullscreen, or not.
  10048. * For example, by default, iframes cannot go fullscreen unless the containing page
  10049. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  10050. * @memberof Fullscreen
  10051. * @type {Boolean}
  10052. * @readonly
  10053. */
  10054. enabled : {
  10055. get : function() {
  10056. if (!Fullscreen.supportsFullscreen()) {
  10057. return undefined;
  10058. }
  10059. return document[_names.fullscreenEnabled];
  10060. }
  10061. },
  10062. /**
  10063. * Determines if the browser is currently in fullscreen mode.
  10064. * @memberof Fullscreen
  10065. * @type {Boolean}
  10066. * @readonly
  10067. */
  10068. fullscreen : {
  10069. get : function() {
  10070. if (!Fullscreen.supportsFullscreen()) {
  10071. return undefined;
  10072. }
  10073. return Fullscreen.element !== null;
  10074. }
  10075. }
  10076. });
  10077. /**
  10078. * Detects whether the browser supports the standard fullscreen API.
  10079. *
  10080. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  10081. * <code>false</code> otherwise.
  10082. */
  10083. Fullscreen.supportsFullscreen = function() {
  10084. if (defined(_supportsFullscreen)) {
  10085. return _supportsFullscreen;
  10086. }
  10087. _supportsFullscreen = false;
  10088. var body = document.body;
  10089. if (typeof body.requestFullscreen === 'function') {
  10090. // go with the unprefixed, standard set of names
  10091. _names.requestFullscreen = 'requestFullscreen';
  10092. _names.exitFullscreen = 'exitFullscreen';
  10093. _names.fullscreenEnabled = 'fullscreenEnabled';
  10094. _names.fullscreenElement = 'fullscreenElement';
  10095. _names.fullscreenchange = 'fullscreenchange';
  10096. _names.fullscreenerror = 'fullscreenerror';
  10097. _supportsFullscreen = true;
  10098. return _supportsFullscreen;
  10099. }
  10100. //check for the correct combination of prefix plus the various names that browsers use
  10101. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  10102. var name;
  10103. for (var i = 0, len = prefixes.length; i < len; ++i) {
  10104. var prefix = prefixes[i];
  10105. // casing of Fullscreen differs across browsers
  10106. name = prefix + 'RequestFullscreen';
  10107. if (typeof body[name] === 'function') {
  10108. _names.requestFullscreen = name;
  10109. _supportsFullscreen = true;
  10110. } else {
  10111. name = prefix + 'RequestFullScreen';
  10112. if (typeof body[name] === 'function') {
  10113. _names.requestFullscreen = name;
  10114. _supportsFullscreen = true;
  10115. }
  10116. }
  10117. // disagreement about whether it's "exit" as per spec, or "cancel"
  10118. name = prefix + 'ExitFullscreen';
  10119. if (typeof document[name] === 'function') {
  10120. _names.exitFullscreen = name;
  10121. } else {
  10122. name = prefix + 'CancelFullScreen';
  10123. if (typeof document[name] === 'function') {
  10124. _names.exitFullscreen = name;
  10125. }
  10126. }
  10127. // casing of Fullscreen differs across browsers
  10128. name = prefix + 'FullscreenEnabled';
  10129. if (document[name] !== undefined) {
  10130. _names.fullscreenEnabled = name;
  10131. } else {
  10132. name = prefix + 'FullScreenEnabled';
  10133. if (document[name] !== undefined) {
  10134. _names.fullscreenEnabled = name;
  10135. }
  10136. }
  10137. // casing of Fullscreen differs across browsers
  10138. name = prefix + 'FullscreenElement';
  10139. if (document[name] !== undefined) {
  10140. _names.fullscreenElement = name;
  10141. } else {
  10142. name = prefix + 'FullScreenElement';
  10143. if (document[name] !== undefined) {
  10144. _names.fullscreenElement = name;
  10145. }
  10146. }
  10147. // thankfully, event names are all lowercase per spec
  10148. name = prefix + 'fullscreenchange';
  10149. // event names do not have 'on' in the front, but the property on the document does
  10150. if (document['on' + name] !== undefined) {
  10151. //except on IE
  10152. if (prefix === 'ms') {
  10153. name = 'MSFullscreenChange';
  10154. }
  10155. _names.fullscreenchange = name;
  10156. }
  10157. name = prefix + 'fullscreenerror';
  10158. if (document['on' + name] !== undefined) {
  10159. //except on IE
  10160. if (prefix === 'ms') {
  10161. name = 'MSFullscreenError';
  10162. }
  10163. _names.fullscreenerror = name;
  10164. }
  10165. }
  10166. return _supportsFullscreen;
  10167. };
  10168. /**
  10169. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  10170. * If fullscreen mode is not supported by the browser, does nothing.
  10171. *
  10172. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  10173. * @param {HMDVRDevice} [vrDevice] The VR device.
  10174. *
  10175. * @example
  10176. * // Put the entire page into fullscreen.
  10177. * Cesium.Fullscreen.requestFullscreen(document.body)
  10178. *
  10179. * // Place only the Cesium canvas into fullscreen.
  10180. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  10181. */
  10182. Fullscreen.requestFullscreen = function(element, vrDevice) {
  10183. if (!Fullscreen.supportsFullscreen()) {
  10184. return;
  10185. }
  10186. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  10187. };
  10188. /**
  10189. * Asynchronously exits fullscreen mode. If the browser is not currently
  10190. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  10191. */
  10192. Fullscreen.exitFullscreen = function() {
  10193. if (!Fullscreen.supportsFullscreen()) {
  10194. return;
  10195. }
  10196. document[_names.exitFullscreen]();
  10197. };
  10198. return Fullscreen;
  10199. });
  10200. /*global define*/
  10201. define('Core/FeatureDetection',[
  10202. './defaultValue',
  10203. './defined',
  10204. './Fullscreen'
  10205. ], function(
  10206. defaultValue,
  10207. defined,
  10208. Fullscreen) {
  10209. 'use strict';
  10210. var theNavigator;
  10211. if (typeof navigator !== 'undefined') {
  10212. theNavigator = navigator;
  10213. } else {
  10214. theNavigator = {};
  10215. }
  10216. function extractVersion(versionString) {
  10217. var parts = versionString.split('.');
  10218. for (var i = 0, len = parts.length; i < len; ++i) {
  10219. parts[i] = parseInt(parts[i], 10);
  10220. }
  10221. return parts;
  10222. }
  10223. var isChromeResult;
  10224. var chromeVersionResult;
  10225. function isChrome() {
  10226. if (!defined(isChromeResult)) {
  10227. isChromeResult = false;
  10228. // Edge contains Chrome in the user agent too
  10229. if (!isEdge()) {
  10230. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  10231. if (fields !== null) {
  10232. isChromeResult = true;
  10233. chromeVersionResult = extractVersion(fields[1]);
  10234. }
  10235. }
  10236. }
  10237. return isChromeResult;
  10238. }
  10239. function chromeVersion() {
  10240. return isChrome() && chromeVersionResult;
  10241. }
  10242. var isSafariResult;
  10243. var safariVersionResult;
  10244. function isSafari() {
  10245. if (!defined(isSafariResult)) {
  10246. isSafariResult = false;
  10247. // Chrome and Edge contain Safari in the user agent too
  10248. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  10249. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  10250. if (fields !== null) {
  10251. isSafariResult = true;
  10252. safariVersionResult = extractVersion(fields[1]);
  10253. }
  10254. }
  10255. }
  10256. return isSafariResult;
  10257. }
  10258. function safariVersion() {
  10259. return isSafari() && safariVersionResult;
  10260. }
  10261. var isWebkitResult;
  10262. var webkitVersionResult;
  10263. function isWebkit() {
  10264. if (!defined(isWebkitResult)) {
  10265. isWebkitResult = false;
  10266. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  10267. if (fields !== null) {
  10268. isWebkitResult = true;
  10269. webkitVersionResult = extractVersion(fields[1]);
  10270. webkitVersionResult.isNightly = !!fields[2];
  10271. }
  10272. }
  10273. return isWebkitResult;
  10274. }
  10275. function webkitVersion() {
  10276. return isWebkit() && webkitVersionResult;
  10277. }
  10278. var isInternetExplorerResult;
  10279. var internetExplorerVersionResult;
  10280. function isInternetExplorer() {
  10281. if (!defined(isInternetExplorerResult)) {
  10282. isInternetExplorerResult = false;
  10283. var fields;
  10284. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  10285. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  10286. if (fields !== null) {
  10287. isInternetExplorerResult = true;
  10288. internetExplorerVersionResult = extractVersion(fields[1]);
  10289. }
  10290. } else if (theNavigator.appName === 'Netscape') {
  10291. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  10292. if (fields !== null) {
  10293. isInternetExplorerResult = true;
  10294. internetExplorerVersionResult = extractVersion(fields[1]);
  10295. }
  10296. }
  10297. }
  10298. return isInternetExplorerResult;
  10299. }
  10300. function internetExplorerVersion() {
  10301. return isInternetExplorer() && internetExplorerVersionResult;
  10302. }
  10303. var isEdgeResult;
  10304. var edgeVersionResult;
  10305. function isEdge() {
  10306. if (!defined(isEdgeResult)) {
  10307. isEdgeResult = false;
  10308. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  10309. if (fields !== null) {
  10310. isEdgeResult = true;
  10311. edgeVersionResult = extractVersion(fields[1]);
  10312. }
  10313. }
  10314. return isEdgeResult;
  10315. }
  10316. function edgeVersion() {
  10317. return isEdge() && edgeVersionResult;
  10318. }
  10319. var isFirefoxResult;
  10320. var firefoxVersionResult;
  10321. function isFirefox() {
  10322. if (!defined(isFirefoxResult)) {
  10323. isFirefoxResult = false;
  10324. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  10325. if (fields !== null) {
  10326. isFirefoxResult = true;
  10327. firefoxVersionResult = extractVersion(fields[1]);
  10328. }
  10329. }
  10330. return isFirefoxResult;
  10331. }
  10332. var isWindowsResult;
  10333. function isWindows() {
  10334. if (!defined(isWindowsResult)) {
  10335. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  10336. }
  10337. return isWindowsResult;
  10338. }
  10339. function firefoxVersion() {
  10340. return isFirefox() && firefoxVersionResult;
  10341. }
  10342. var hasPointerEvents;
  10343. function supportsPointerEvents() {
  10344. if (!defined(hasPointerEvents)) {
  10345. //While navigator.pointerEnabled is deprecated in the W3C specification
  10346. //we still need to use it if it exists in order to support browsers
  10347. //that rely on it, such as the Windows WebBrowser control which defines
  10348. //PointerEvent but sets navigator.pointerEnabled to false.
  10349. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  10350. }
  10351. return hasPointerEvents;
  10352. }
  10353. var imageRenderingValueResult;
  10354. var supportsImageRenderingPixelatedResult;
  10355. function supportsImageRenderingPixelated() {
  10356. if (!defined(supportsImageRenderingPixelatedResult)) {
  10357. var canvas = document.createElement('canvas');
  10358. canvas.setAttribute('style',
  10359. 'image-rendering: -moz-crisp-edges;' +
  10360. 'image-rendering: pixelated;');
  10361. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  10362. var tmp = canvas.style.imageRendering;
  10363. supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
  10364. if (supportsImageRenderingPixelatedResult) {
  10365. imageRenderingValueResult = tmp;
  10366. }
  10367. }
  10368. return supportsImageRenderingPixelatedResult;
  10369. }
  10370. function imageRenderingValue() {
  10371. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  10372. }
  10373. /**
  10374. * A set of functions to detect whether the current browser supports
  10375. * various features.
  10376. *
  10377. * @exports FeatureDetection
  10378. */
  10379. var FeatureDetection = {
  10380. isChrome : isChrome,
  10381. chromeVersion : chromeVersion,
  10382. isSafari : isSafari,
  10383. safariVersion : safariVersion,
  10384. isWebkit : isWebkit,
  10385. webkitVersion : webkitVersion,
  10386. isInternetExplorer : isInternetExplorer,
  10387. internetExplorerVersion : internetExplorerVersion,
  10388. isEdge : isEdge,
  10389. edgeVersion : edgeVersion,
  10390. isFirefox : isFirefox,
  10391. firefoxVersion : firefoxVersion,
  10392. isWindows : isWindows,
  10393. hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
  10394. supportsPointerEvents : supportsPointerEvents,
  10395. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  10396. imageRenderingValue: imageRenderingValue
  10397. };
  10398. /**
  10399. * Detects whether the current browser supports the full screen standard.
  10400. *
  10401. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  10402. *
  10403. * @see Fullscreen
  10404. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  10405. */
  10406. FeatureDetection.supportsFullscreen = function() {
  10407. return Fullscreen.supportsFullscreen();
  10408. };
  10409. /**
  10410. * Detects whether the current browser supports typed arrays.
  10411. *
  10412. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  10413. *
  10414. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  10415. */
  10416. FeatureDetection.supportsTypedArrays = function() {
  10417. return typeof ArrayBuffer !== 'undefined';
  10418. };
  10419. /**
  10420. * Detects whether the current browser supports Web Workers.
  10421. *
  10422. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  10423. *
  10424. * @see {@link http://www.w3.org/TR/workers/}
  10425. */
  10426. FeatureDetection.supportsWebWorkers = function() {
  10427. return typeof Worker !== 'undefined';
  10428. };
  10429. return FeatureDetection;
  10430. });
  10431. /*global define*/
  10432. define('Core/WebGLConstants',[
  10433. './freezeObject'
  10434. ], function(
  10435. freezeObject) {
  10436. 'use strict';
  10437. /**
  10438. * Enum containing WebGL Constant values by name.
  10439. * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
  10440. * (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
  10441. *
  10442. * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
  10443. * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
  10444. * specifications.
  10445. *
  10446. * @exports WebGLConstants
  10447. */
  10448. var WebGLConstants = {
  10449. DEPTH_BUFFER_BIT : 0x00000100,
  10450. STENCIL_BUFFER_BIT : 0x00000400,
  10451. COLOR_BUFFER_BIT : 0x00004000,
  10452. POINTS : 0x0000,
  10453. LINES : 0x0001,
  10454. LINE_LOOP : 0x0002,
  10455. LINE_STRIP : 0x0003,
  10456. TRIANGLES : 0x0004,
  10457. TRIANGLE_STRIP : 0x0005,
  10458. TRIANGLE_FAN : 0x0006,
  10459. ZERO : 0,
  10460. ONE : 1,
  10461. SRC_COLOR : 0x0300,
  10462. ONE_MINUS_SRC_COLOR : 0x0301,
  10463. SRC_ALPHA : 0x0302,
  10464. ONE_MINUS_SRC_ALPHA : 0x0303,
  10465. DST_ALPHA : 0x0304,
  10466. ONE_MINUS_DST_ALPHA : 0x0305,
  10467. DST_COLOR : 0x0306,
  10468. ONE_MINUS_DST_COLOR : 0x0307,
  10469. SRC_ALPHA_SATURATE : 0x0308,
  10470. FUNC_ADD : 0x8006,
  10471. BLEND_EQUATION : 0x8009,
  10472. BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
  10473. BLEND_EQUATION_ALPHA : 0x883D,
  10474. FUNC_SUBTRACT : 0x800A,
  10475. FUNC_REVERSE_SUBTRACT : 0x800B,
  10476. BLEND_DST_RGB : 0x80C8,
  10477. BLEND_SRC_RGB : 0x80C9,
  10478. BLEND_DST_ALPHA : 0x80CA,
  10479. BLEND_SRC_ALPHA : 0x80CB,
  10480. CONSTANT_COLOR : 0x8001,
  10481. ONE_MINUS_CONSTANT_COLOR : 0x8002,
  10482. CONSTANT_ALPHA : 0x8003,
  10483. ONE_MINUS_CONSTANT_ALPHA : 0x8004,
  10484. BLEND_COLOR : 0x8005,
  10485. ARRAY_BUFFER : 0x8892,
  10486. ELEMENT_ARRAY_BUFFER : 0x8893,
  10487. ARRAY_BUFFER_BINDING : 0x8894,
  10488. ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
  10489. STREAM_DRAW : 0x88E0,
  10490. STATIC_DRAW : 0x88E4,
  10491. DYNAMIC_DRAW : 0x88E8,
  10492. BUFFER_SIZE : 0x8764,
  10493. BUFFER_USAGE : 0x8765,
  10494. CURRENT_VERTEX_ATTRIB : 0x8626,
  10495. FRONT : 0x0404,
  10496. BACK : 0x0405,
  10497. FRONT_AND_BACK : 0x0408,
  10498. CULL_FACE : 0x0B44,
  10499. BLEND : 0x0BE2,
  10500. DITHER : 0x0BD0,
  10501. STENCIL_TEST : 0x0B90,
  10502. DEPTH_TEST : 0x0B71,
  10503. SCISSOR_TEST : 0x0C11,
  10504. POLYGON_OFFSET_FILL : 0x8037,
  10505. SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
  10506. SAMPLE_COVERAGE : 0x80A0,
  10507. NO_ERROR : 0,
  10508. INVALID_ENUM : 0x0500,
  10509. INVALID_VALUE : 0x0501,
  10510. INVALID_OPERATION : 0x0502,
  10511. OUT_OF_MEMORY : 0x0505,
  10512. CW : 0x0900,
  10513. CCW : 0x0901,
  10514. LINE_WIDTH : 0x0B21,
  10515. ALIASED_POINT_SIZE_RANGE : 0x846D,
  10516. ALIASED_LINE_WIDTH_RANGE : 0x846E,
  10517. CULL_FACE_MODE : 0x0B45,
  10518. FRONT_FACE : 0x0B46,
  10519. DEPTH_RANGE : 0x0B70,
  10520. DEPTH_WRITEMASK : 0x0B72,
  10521. DEPTH_CLEAR_VALUE : 0x0B73,
  10522. DEPTH_FUNC : 0x0B74,
  10523. STENCIL_CLEAR_VALUE : 0x0B91,
  10524. STENCIL_FUNC : 0x0B92,
  10525. STENCIL_FAIL : 0x0B94,
  10526. STENCIL_PASS_DEPTH_FAIL : 0x0B95,
  10527. STENCIL_PASS_DEPTH_PASS : 0x0B96,
  10528. STENCIL_REF : 0x0B97,
  10529. STENCIL_VALUE_MASK : 0x0B93,
  10530. STENCIL_WRITEMASK : 0x0B98,
  10531. STENCIL_BACK_FUNC : 0x8800,
  10532. STENCIL_BACK_FAIL : 0x8801,
  10533. STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
  10534. STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
  10535. STENCIL_BACK_REF : 0x8CA3,
  10536. STENCIL_BACK_VALUE_MASK : 0x8CA4,
  10537. STENCIL_BACK_WRITEMASK : 0x8CA5,
  10538. VIEWPORT : 0x0BA2,
  10539. SCISSOR_BOX : 0x0C10,
  10540. COLOR_CLEAR_VALUE : 0x0C22,
  10541. COLOR_WRITEMASK : 0x0C23,
  10542. UNPACK_ALIGNMENT : 0x0CF5,
  10543. PACK_ALIGNMENT : 0x0D05,
  10544. MAX_TEXTURE_SIZE : 0x0D33,
  10545. MAX_VIEWPORT_DIMS : 0x0D3A,
  10546. SUBPIXEL_BITS : 0x0D50,
  10547. RED_BITS : 0x0D52,
  10548. GREEN_BITS : 0x0D53,
  10549. BLUE_BITS : 0x0D54,
  10550. ALPHA_BITS : 0x0D55,
  10551. DEPTH_BITS : 0x0D56,
  10552. STENCIL_BITS : 0x0D57,
  10553. POLYGON_OFFSET_UNITS : 0x2A00,
  10554. POLYGON_OFFSET_FACTOR : 0x8038,
  10555. TEXTURE_BINDING_2D : 0x8069,
  10556. SAMPLE_BUFFERS : 0x80A8,
  10557. SAMPLES : 0x80A9,
  10558. SAMPLE_COVERAGE_VALUE : 0x80AA,
  10559. SAMPLE_COVERAGE_INVERT : 0x80AB,
  10560. COMPRESSED_TEXTURE_FORMATS : 0x86A3,
  10561. DONT_CARE : 0x1100,
  10562. FASTEST : 0x1101,
  10563. NICEST : 0x1102,
  10564. GENERATE_MIPMAP_HINT : 0x8192,
  10565. BYTE : 0x1400,
  10566. UNSIGNED_BYTE : 0x1401,
  10567. SHORT : 0x1402,
  10568. UNSIGNED_SHORT : 0x1403,
  10569. INT : 0x1404,
  10570. UNSIGNED_INT : 0x1405,
  10571. FLOAT : 0x1406,
  10572. DEPTH_COMPONENT : 0x1902,
  10573. ALPHA : 0x1906,
  10574. RGB : 0x1907,
  10575. RGBA : 0x1908,
  10576. LUMINANCE : 0x1909,
  10577. LUMINANCE_ALPHA : 0x190A,
  10578. UNSIGNED_SHORT_4_4_4_4 : 0x8033,
  10579. UNSIGNED_SHORT_5_5_5_1 : 0x8034,
  10580. UNSIGNED_SHORT_5_6_5 : 0x8363,
  10581. FRAGMENT_SHADER : 0x8B30,
  10582. VERTEX_SHADER : 0x8B31,
  10583. MAX_VERTEX_ATTRIBS : 0x8869,
  10584. MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
  10585. MAX_VARYING_VECTORS : 0x8DFC,
  10586. MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
  10587. MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
  10588. MAX_TEXTURE_IMAGE_UNITS : 0x8872,
  10589. MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
  10590. SHADER_TYPE : 0x8B4F,
  10591. DELETE_STATUS : 0x8B80,
  10592. LINK_STATUS : 0x8B82,
  10593. VALIDATE_STATUS : 0x8B83,
  10594. ATTACHED_SHADERS : 0x8B85,
  10595. ACTIVE_UNIFORMS : 0x8B86,
  10596. ACTIVE_ATTRIBUTES : 0x8B89,
  10597. SHADING_LANGUAGE_VERSION : 0x8B8C,
  10598. CURRENT_PROGRAM : 0x8B8D,
  10599. NEVER : 0x0200,
  10600. LESS : 0x0201,
  10601. EQUAL : 0x0202,
  10602. LEQUAL : 0x0203,
  10603. GREATER : 0x0204,
  10604. NOTEQUAL : 0x0205,
  10605. GEQUAL : 0x0206,
  10606. ALWAYS : 0x0207,
  10607. KEEP : 0x1E00,
  10608. REPLACE : 0x1E01,
  10609. INCR : 0x1E02,
  10610. DECR : 0x1E03,
  10611. INVERT : 0x150A,
  10612. INCR_WRAP : 0x8507,
  10613. DECR_WRAP : 0x8508,
  10614. VENDOR : 0x1F00,
  10615. RENDERER : 0x1F01,
  10616. VERSION : 0x1F02,
  10617. NEAREST : 0x2600,
  10618. LINEAR : 0x2601,
  10619. NEAREST_MIPMAP_NEAREST : 0x2700,
  10620. LINEAR_MIPMAP_NEAREST : 0x2701,
  10621. NEAREST_MIPMAP_LINEAR : 0x2702,
  10622. LINEAR_MIPMAP_LINEAR : 0x2703,
  10623. TEXTURE_MAG_FILTER : 0x2800,
  10624. TEXTURE_MIN_FILTER : 0x2801,
  10625. TEXTURE_WRAP_S : 0x2802,
  10626. TEXTURE_WRAP_T : 0x2803,
  10627. TEXTURE_2D : 0x0DE1,
  10628. TEXTURE : 0x1702,
  10629. TEXTURE_CUBE_MAP : 0x8513,
  10630. TEXTURE_BINDING_CUBE_MAP : 0x8514,
  10631. TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
  10632. TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
  10633. TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
  10634. TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
  10635. TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
  10636. TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
  10637. MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
  10638. TEXTURE0 : 0x84C0,
  10639. TEXTURE1 : 0x84C1,
  10640. TEXTURE2 : 0x84C2,
  10641. TEXTURE3 : 0x84C3,
  10642. TEXTURE4 : 0x84C4,
  10643. TEXTURE5 : 0x84C5,
  10644. TEXTURE6 : 0x84C6,
  10645. TEXTURE7 : 0x84C7,
  10646. TEXTURE8 : 0x84C8,
  10647. TEXTURE9 : 0x84C9,
  10648. TEXTURE10 : 0x84CA,
  10649. TEXTURE11 : 0x84CB,
  10650. TEXTURE12 : 0x84CC,
  10651. TEXTURE13 : 0x84CD,
  10652. TEXTURE14 : 0x84CE,
  10653. TEXTURE15 : 0x84CF,
  10654. TEXTURE16 : 0x84D0,
  10655. TEXTURE17 : 0x84D1,
  10656. TEXTURE18 : 0x84D2,
  10657. TEXTURE19 : 0x84D3,
  10658. TEXTURE20 : 0x84D4,
  10659. TEXTURE21 : 0x84D5,
  10660. TEXTURE22 : 0x84D6,
  10661. TEXTURE23 : 0x84D7,
  10662. TEXTURE24 : 0x84D8,
  10663. TEXTURE25 : 0x84D9,
  10664. TEXTURE26 : 0x84DA,
  10665. TEXTURE27 : 0x84DB,
  10666. TEXTURE28 : 0x84DC,
  10667. TEXTURE29 : 0x84DD,
  10668. TEXTURE30 : 0x84DE,
  10669. TEXTURE31 : 0x84DF,
  10670. ACTIVE_TEXTURE : 0x84E0,
  10671. REPEAT : 0x2901,
  10672. CLAMP_TO_EDGE : 0x812F,
  10673. MIRRORED_REPEAT : 0x8370,
  10674. FLOAT_VEC2 : 0x8B50,
  10675. FLOAT_VEC3 : 0x8B51,
  10676. FLOAT_VEC4 : 0x8B52,
  10677. INT_VEC2 : 0x8B53,
  10678. INT_VEC3 : 0x8B54,
  10679. INT_VEC4 : 0x8B55,
  10680. BOOL : 0x8B56,
  10681. BOOL_VEC2 : 0x8B57,
  10682. BOOL_VEC3 : 0x8B58,
  10683. BOOL_VEC4 : 0x8B59,
  10684. FLOAT_MAT2 : 0x8B5A,
  10685. FLOAT_MAT3 : 0x8B5B,
  10686. FLOAT_MAT4 : 0x8B5C,
  10687. SAMPLER_2D : 0x8B5E,
  10688. SAMPLER_CUBE : 0x8B60,
  10689. VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
  10690. VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
  10691. VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
  10692. VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
  10693. VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
  10694. VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
  10695. VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
  10696. IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
  10697. IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
  10698. COMPILE_STATUS : 0x8B81,
  10699. LOW_FLOAT : 0x8DF0,
  10700. MEDIUM_FLOAT : 0x8DF1,
  10701. HIGH_FLOAT : 0x8DF2,
  10702. LOW_INT : 0x8DF3,
  10703. MEDIUM_INT : 0x8DF4,
  10704. HIGH_INT : 0x8DF5,
  10705. FRAMEBUFFER : 0x8D40,
  10706. RENDERBUFFER : 0x8D41,
  10707. RGBA4 : 0x8056,
  10708. RGB5_A1 : 0x8057,
  10709. RGB565 : 0x8D62,
  10710. DEPTH_COMPONENT16 : 0x81A5,
  10711. STENCIL_INDEX : 0x1901,
  10712. STENCIL_INDEX8 : 0x8D48,
  10713. DEPTH_STENCIL : 0x84F9,
  10714. RENDERBUFFER_WIDTH : 0x8D42,
  10715. RENDERBUFFER_HEIGHT : 0x8D43,
  10716. RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
  10717. RENDERBUFFER_RED_SIZE : 0x8D50,
  10718. RENDERBUFFER_GREEN_SIZE : 0x8D51,
  10719. RENDERBUFFER_BLUE_SIZE : 0x8D52,
  10720. RENDERBUFFER_ALPHA_SIZE : 0x8D53,
  10721. RENDERBUFFER_DEPTH_SIZE : 0x8D54,
  10722. RENDERBUFFER_STENCIL_SIZE : 0x8D55,
  10723. FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
  10724. FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
  10725. FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
  10726. FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
  10727. COLOR_ATTACHMENT0 : 0x8CE0,
  10728. DEPTH_ATTACHMENT : 0x8D00,
  10729. STENCIL_ATTACHMENT : 0x8D20,
  10730. DEPTH_STENCIL_ATTACHMENT : 0x821A,
  10731. NONE : 0,
  10732. FRAMEBUFFER_COMPLETE : 0x8CD5,
  10733. FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
  10734. FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
  10735. FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
  10736. FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
  10737. FRAMEBUFFER_BINDING : 0x8CA6,
  10738. RENDERBUFFER_BINDING : 0x8CA7,
  10739. MAX_RENDERBUFFER_SIZE : 0x84E8,
  10740. INVALID_FRAMEBUFFER_OPERATION : 0x0506,
  10741. UNPACK_FLIP_Y_WEBGL : 0x9240,
  10742. UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
  10743. CONTEXT_LOST_WEBGL : 0x9242,
  10744. UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
  10745. BROWSER_DEFAULT_WEBGL : 0x9244,
  10746. // Desktop OpenGL
  10747. DOUBLE : 0x140A,
  10748. // WebGL 2
  10749. READ_BUFFER : 0x0C02,
  10750. UNPACK_ROW_LENGTH : 0x0CF2,
  10751. UNPACK_SKIP_ROWS : 0x0CF3,
  10752. UNPACK_SKIP_PIXELS : 0x0CF4,
  10753. PACK_ROW_LENGTH : 0x0D02,
  10754. PACK_SKIP_ROWS : 0x0D03,
  10755. PACK_SKIP_PIXELS : 0x0D04,
  10756. COLOR : 0x1800,
  10757. DEPTH : 0x1801,
  10758. STENCIL : 0x1802,
  10759. RED : 0x1903,
  10760. RGB8 : 0x8051,
  10761. RGBA8 : 0x8058,
  10762. RGB10_A2 : 0x8059,
  10763. TEXTURE_BINDING_3D : 0x806A,
  10764. UNPACK_SKIP_IMAGES : 0x806D,
  10765. UNPACK_IMAGE_HEIGHT : 0x806E,
  10766. TEXTURE_3D : 0x806F,
  10767. TEXTURE_WRAP_R : 0x8072,
  10768. MAX_3D_TEXTURE_SIZE : 0x8073,
  10769. UNSIGNED_INT_2_10_10_10_REV : 0x8368,
  10770. MAX_ELEMENTS_VERTICES : 0x80E8,
  10771. MAX_ELEMENTS_INDICES : 0x80E9,
  10772. TEXTURE_MIN_LOD : 0x813A,
  10773. TEXTURE_MAX_LOD : 0x813B,
  10774. TEXTURE_BASE_LEVEL : 0x813C,
  10775. TEXTURE_MAX_LEVEL : 0x813D,
  10776. MIN : 0x8007,
  10777. MAX : 0x8008,
  10778. DEPTH_COMPONENT24 : 0x81A6,
  10779. MAX_TEXTURE_LOD_BIAS : 0x84FD,
  10780. TEXTURE_COMPARE_MODE : 0x884C,
  10781. TEXTURE_COMPARE_FUNC : 0x884D,
  10782. CURRENT_QUERY : 0x8865,
  10783. QUERY_RESULT : 0x8866,
  10784. QUERY_RESULT_AVAILABLE : 0x8867,
  10785. STREAM_READ : 0x88E1,
  10786. STREAM_COPY : 0x88E2,
  10787. STATIC_READ : 0x88E5,
  10788. STATIC_COPY : 0x88E6,
  10789. DYNAMIC_READ : 0x88E9,
  10790. DYNAMIC_COPY : 0x88EA,
  10791. MAX_DRAW_BUFFERS : 0x8824,
  10792. DRAW_BUFFER0 : 0x8825,
  10793. DRAW_BUFFER1 : 0x8826,
  10794. DRAW_BUFFER2 : 0x8827,
  10795. DRAW_BUFFER3 : 0x8828,
  10796. DRAW_BUFFER4 : 0x8829,
  10797. DRAW_BUFFER5 : 0x882A,
  10798. DRAW_BUFFER6 : 0x882B,
  10799. DRAW_BUFFER7 : 0x882C,
  10800. DRAW_BUFFER8 : 0x882D,
  10801. DRAW_BUFFER9 : 0x882E,
  10802. DRAW_BUFFER10 : 0x882F,
  10803. DRAW_BUFFER11 : 0x8830,
  10804. DRAW_BUFFER12 : 0x8831,
  10805. DRAW_BUFFER13 : 0x8832,
  10806. DRAW_BUFFER14 : 0x8833,
  10807. DRAW_BUFFER15 : 0x8834,
  10808. MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
  10809. MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
  10810. SAMPLER_3D : 0x8B5F,
  10811. SAMPLER_2D_SHADOW : 0x8B62,
  10812. FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
  10813. PIXEL_PACK_BUFFER : 0x88EB,
  10814. PIXEL_UNPACK_BUFFER : 0x88EC,
  10815. PIXEL_PACK_BUFFER_BINDING : 0x88ED,
  10816. PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
  10817. FLOAT_MAT2x3 : 0x8B65,
  10818. FLOAT_MAT2x4 : 0x8B66,
  10819. FLOAT_MAT3x2 : 0x8B67,
  10820. FLOAT_MAT3x4 : 0x8B68,
  10821. FLOAT_MAT4x2 : 0x8B69,
  10822. FLOAT_MAT4x3 : 0x8B6A,
  10823. SRGB : 0x8C40,
  10824. SRGB8 : 0x8C41,
  10825. SRGB8_ALPHA8 : 0x8C43,
  10826. COMPARE_REF_TO_TEXTURE : 0x884E,
  10827. RGBA32F : 0x8814,
  10828. RGB32F : 0x8815,
  10829. RGBA16F : 0x881A,
  10830. RGB16F : 0x881B,
  10831. VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
  10832. MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
  10833. MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
  10834. MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
  10835. MAX_VARYING_COMPONENTS : 0x8B4B,
  10836. TEXTURE_2D_ARRAY : 0x8C1A,
  10837. TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
  10838. R11F_G11F_B10F : 0x8C3A,
  10839. UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
  10840. RGB9_E5 : 0x8C3D,
  10841. UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
  10842. TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
  10843. MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
  10844. TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
  10845. TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
  10846. TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
  10847. TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
  10848. RASTERIZER_DISCARD : 0x8C89,
  10849. MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
  10850. MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
  10851. INTERLEAVED_ATTRIBS : 0x8C8C,
  10852. SEPARATE_ATTRIBS : 0x8C8D,
  10853. TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
  10854. TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
  10855. RGBA32UI : 0x8D70,
  10856. RGB32UI : 0x8D71,
  10857. RGBA16UI : 0x8D76,
  10858. RGB16UI : 0x8D77,
  10859. RGBA8UI : 0x8D7C,
  10860. RGB8UI : 0x8D7D,
  10861. RGBA32I : 0x8D82,
  10862. RGB32I : 0x8D83,
  10863. RGBA16I : 0x8D88,
  10864. RGB16I : 0x8D89,
  10865. RGBA8I : 0x8D8E,
  10866. RGB8I : 0x8D8F,
  10867. RED_INTEGER : 0x8D94,
  10868. RGB_INTEGER : 0x8D98,
  10869. RGBA_INTEGER : 0x8D99,
  10870. SAMPLER_2D_ARRAY : 0x8DC1,
  10871. SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
  10872. SAMPLER_CUBE_SHADOW : 0x8DC5,
  10873. UNSIGNED_INT_VEC2 : 0x8DC6,
  10874. UNSIGNED_INT_VEC3 : 0x8DC7,
  10875. UNSIGNED_INT_VEC4 : 0x8DC8,
  10876. INT_SAMPLER_2D : 0x8DCA,
  10877. INT_SAMPLER_3D : 0x8DCB,
  10878. INT_SAMPLER_CUBE : 0x8DCC,
  10879. INT_SAMPLER_2D_ARRAY : 0x8DCF,
  10880. UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
  10881. UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
  10882. UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
  10883. UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
  10884. DEPTH_COMPONENT32F : 0x8CAC,
  10885. DEPTH32F_STENCIL8 : 0x8CAD,
  10886. FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
  10887. FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
  10888. FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
  10889. FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
  10890. FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
  10891. FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
  10892. FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
  10893. FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
  10894. FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
  10895. FRAMEBUFFER_DEFAULT : 0x8218,
  10896. UNSIGNED_INT_24_8 : 0x84FA,
  10897. DEPTH24_STENCIL8 : 0x88F0,
  10898. UNSIGNED_NORMALIZED : 0x8C17,
  10899. DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
  10900. READ_FRAMEBUFFER : 0x8CA8,
  10901. DRAW_FRAMEBUFFER : 0x8CA9,
  10902. READ_FRAMEBUFFER_BINDING : 0x8CAA,
  10903. RENDERBUFFER_SAMPLES : 0x8CAB,
  10904. FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
  10905. MAX_COLOR_ATTACHMENTS : 0x8CDF,
  10906. COLOR_ATTACHMENT1 : 0x8CE1,
  10907. COLOR_ATTACHMENT2 : 0x8CE2,
  10908. COLOR_ATTACHMENT3 : 0x8CE3,
  10909. COLOR_ATTACHMENT4 : 0x8CE4,
  10910. COLOR_ATTACHMENT5 : 0x8CE5,
  10911. COLOR_ATTACHMENT6 : 0x8CE6,
  10912. COLOR_ATTACHMENT7 : 0x8CE7,
  10913. COLOR_ATTACHMENT8 : 0x8CE8,
  10914. COLOR_ATTACHMENT9 : 0x8CE9,
  10915. COLOR_ATTACHMENT10 : 0x8CEA,
  10916. COLOR_ATTACHMENT11 : 0x8CEB,
  10917. COLOR_ATTACHMENT12 : 0x8CEC,
  10918. COLOR_ATTACHMENT13 : 0x8CED,
  10919. COLOR_ATTACHMENT14 : 0x8CEE,
  10920. COLOR_ATTACHMENT15 : 0x8CEF,
  10921. FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
  10922. MAX_SAMPLES : 0x8D57,
  10923. HALF_FLOAT : 0x140B,
  10924. RG : 0x8227,
  10925. RG_INTEGER : 0x8228,
  10926. R8 : 0x8229,
  10927. RG8 : 0x822B,
  10928. R16F : 0x822D,
  10929. R32F : 0x822E,
  10930. RG16F : 0x822F,
  10931. RG32F : 0x8230,
  10932. R8I : 0x8231,
  10933. R8UI : 0x8232,
  10934. R16I : 0x8233,
  10935. R16UI : 0x8234,
  10936. R32I : 0x8235,
  10937. R32UI : 0x8236,
  10938. RG8I : 0x8237,
  10939. RG8UI : 0x8238,
  10940. RG16I : 0x8239,
  10941. RG16UI : 0x823A,
  10942. RG32I : 0x823B,
  10943. RG32UI : 0x823C,
  10944. VERTEX_ARRAY_BINDING : 0x85B5,
  10945. R8_SNORM : 0x8F94,
  10946. RG8_SNORM : 0x8F95,
  10947. RGB8_SNORM : 0x8F96,
  10948. RGBA8_SNORM : 0x8F97,
  10949. SIGNED_NORMALIZED : 0x8F9C,
  10950. COPY_READ_BUFFER : 0x8F36,
  10951. COPY_WRITE_BUFFER : 0x8F37,
  10952. COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
  10953. COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
  10954. UNIFORM_BUFFER : 0x8A11,
  10955. UNIFORM_BUFFER_BINDING : 0x8A28,
  10956. UNIFORM_BUFFER_START : 0x8A29,
  10957. UNIFORM_BUFFER_SIZE : 0x8A2A,
  10958. MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
  10959. MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
  10960. MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
  10961. MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
  10962. MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
  10963. MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
  10964. MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
  10965. UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
  10966. ACTIVE_UNIFORM_BLOCKS : 0x8A36,
  10967. UNIFORM_TYPE : 0x8A37,
  10968. UNIFORM_SIZE : 0x8A38,
  10969. UNIFORM_BLOCK_INDEX : 0x8A3A,
  10970. UNIFORM_OFFSET : 0x8A3B,
  10971. UNIFORM_ARRAY_STRIDE : 0x8A3C,
  10972. UNIFORM_MATRIX_STRIDE : 0x8A3D,
  10973. UNIFORM_IS_ROW_MAJOR : 0x8A3E,
  10974. UNIFORM_BLOCK_BINDING : 0x8A3F,
  10975. UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
  10976. UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
  10977. UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
  10978. UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
  10979. UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
  10980. INVALID_INDEX : 0xFFFFFFFF,
  10981. MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
  10982. MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
  10983. MAX_SERVER_WAIT_TIMEOUT : 0x9111,
  10984. OBJECT_TYPE : 0x9112,
  10985. SYNC_CONDITION : 0x9113,
  10986. SYNC_STATUS : 0x9114,
  10987. SYNC_FLAGS : 0x9115,
  10988. SYNC_FENCE : 0x9116,
  10989. SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
  10990. UNSIGNALED : 0x9118,
  10991. SIGNALED : 0x9119,
  10992. ALREADY_SIGNALED : 0x911A,
  10993. TIMEOUT_EXPIRED : 0x911B,
  10994. CONDITION_SATISFIED : 0x911C,
  10995. WAIT_FAILED : 0x911D,
  10996. SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
  10997. VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
  10998. ANY_SAMPLES_PASSED : 0x8C2F,
  10999. ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
  11000. SAMPLER_BINDING : 0x8919,
  11001. RGB10_A2UI : 0x906F,
  11002. INT_2_10_10_10_REV : 0x8D9F,
  11003. TRANSFORM_FEEDBACK : 0x8E22,
  11004. TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
  11005. TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
  11006. TRANSFORM_FEEDBACK_BINDING : 0x8E25,
  11007. COMPRESSED_R11_EAC : 0x9270,
  11008. COMPRESSED_SIGNED_R11_EAC : 0x9271,
  11009. COMPRESSED_RG11_EAC : 0x9272,
  11010. COMPRESSED_SIGNED_RG11_EAC : 0x9273,
  11011. COMPRESSED_RGB8_ETC2 : 0x9274,
  11012. COMPRESSED_SRGB8_ETC2 : 0x9275,
  11013. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
  11014. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
  11015. COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
  11016. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
  11017. TEXTURE_IMMUTABLE_FORMAT : 0x912F,
  11018. MAX_ELEMENT_INDEX : 0x8D6B,
  11019. TEXTURE_IMMUTABLE_LEVELS : 0x82DF
  11020. };
  11021. return freezeObject(WebGLConstants);
  11022. });
  11023. /*global define*/
  11024. define('Core/ComponentDatatype',[
  11025. './defaultValue',
  11026. './defined',
  11027. './DeveloperError',
  11028. './FeatureDetection',
  11029. './freezeObject',
  11030. './WebGLConstants'
  11031. ], function(
  11032. defaultValue,
  11033. defined,
  11034. DeveloperError,
  11035. FeatureDetection,
  11036. freezeObject,
  11037. WebGLConstants) {
  11038. 'use strict';
  11039. // Bail out if the browser doesn't support typed arrays, to prevent the setup function
  11040. // from failing, since we won't be able to create a WebGL context anyway.
  11041. if (!FeatureDetection.supportsTypedArrays()) {
  11042. return {};
  11043. }
  11044. /**
  11045. * WebGL component datatypes. Components are intrinsics,
  11046. * which form attributes, which form vertices.
  11047. *
  11048. * @exports ComponentDatatype
  11049. */
  11050. var ComponentDatatype = {
  11051. /**
  11052. * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
  11053. * of an element in <code>Int8Array</code>.
  11054. *
  11055. * @type {Number}
  11056. * @constant
  11057. */
  11058. BYTE : WebGLConstants.BYTE,
  11059. /**
  11060. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  11061. * of an element in <code>Uint8Array</code>.
  11062. *
  11063. * @type {Number}
  11064. * @constant
  11065. */
  11066. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  11067. /**
  11068. * 16-bit signed short corresponding to <code>SHORT</code> and the type
  11069. * of an element in <code>Int16Array</code>.
  11070. *
  11071. * @type {Number}
  11072. * @constant
  11073. */
  11074. SHORT : WebGLConstants.SHORT,
  11075. /**
  11076. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  11077. * of an element in <code>Uint16Array</code>.
  11078. *
  11079. * @type {Number}
  11080. * @constant
  11081. */
  11082. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  11083. /**
  11084. * 32-bit signed int corresponding to <code>INT</code> and the type
  11085. * of an element in <code>Int32Array</code>.
  11086. *
  11087. * @memberOf ComponentDatatype
  11088. *
  11089. * @type {Number}
  11090. * @constant
  11091. */
  11092. INT : WebGLConstants.INT,
  11093. /**
  11094. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  11095. * of an element in <code>Uint32Array</code>.
  11096. *
  11097. * @memberOf ComponentDatatype
  11098. *
  11099. * @type {Number}
  11100. * @constant
  11101. */
  11102. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
  11103. /**
  11104. * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
  11105. * of an element in <code>Float32Array</code>.
  11106. *
  11107. * @type {Number}
  11108. * @constant
  11109. */
  11110. FLOAT : WebGLConstants.FLOAT,
  11111. /**
  11112. * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
  11113. * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
  11114. * and the type of an element in <code>Float64Array</code>.
  11115. *
  11116. * @memberOf ComponentDatatype
  11117. *
  11118. * @type {Number}
  11119. * @constant
  11120. * @default 0x140A
  11121. */
  11122. DOUBLE : WebGLConstants.DOUBLE
  11123. };
  11124. /**
  11125. * Returns the size, in bytes, of the corresponding datatype.
  11126. *
  11127. * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
  11128. * @returns {Number} The size in bytes.
  11129. *
  11130. * @exception {DeveloperError} componentDatatype is not a valid value.
  11131. *
  11132. * @example
  11133. * // Returns Int8Array.BYTES_PER_ELEMENT
  11134. * var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
  11135. */
  11136. ComponentDatatype.getSizeInBytes = function(componentDatatype){
  11137. if (!defined(componentDatatype)) {
  11138. throw new DeveloperError('value is required.');
  11139. }
  11140. switch (componentDatatype) {
  11141. case ComponentDatatype.BYTE:
  11142. return Int8Array.BYTES_PER_ELEMENT;
  11143. case ComponentDatatype.UNSIGNED_BYTE:
  11144. return Uint8Array.BYTES_PER_ELEMENT;
  11145. case ComponentDatatype.SHORT:
  11146. return Int16Array.BYTES_PER_ELEMENT;
  11147. case ComponentDatatype.UNSIGNED_SHORT:
  11148. return Uint16Array.BYTES_PER_ELEMENT;
  11149. case ComponentDatatype.INT:
  11150. return Int32Array.BYTES_PER_ELEMENT;
  11151. case ComponentDatatype.UNSIGNED_INT:
  11152. return Uint32Array.BYTES_PER_ELEMENT;
  11153. case ComponentDatatype.FLOAT:
  11154. return Float32Array.BYTES_PER_ELEMENT;
  11155. case ComponentDatatype.DOUBLE:
  11156. return Float64Array.BYTES_PER_ELEMENT;
  11157. default:
  11158. throw new DeveloperError('componentDatatype is not a valid value.');
  11159. }
  11160. };
  11161. /**
  11162. * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
  11163. *
  11164. * @param {TypedArray} array The typed array.
  11165. * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
  11166. */
  11167. ComponentDatatype.fromTypedArray = function(array) {
  11168. if (array instanceof Int8Array) {
  11169. return ComponentDatatype.BYTE;
  11170. }
  11171. if (array instanceof Uint8Array) {
  11172. return ComponentDatatype.UNSIGNED_BYTE;
  11173. }
  11174. if (array instanceof Int16Array) {
  11175. return ComponentDatatype.SHORT;
  11176. }
  11177. if (array instanceof Uint16Array) {
  11178. return ComponentDatatype.UNSIGNED_SHORT;
  11179. }
  11180. if (array instanceof Int32Array) {
  11181. return ComponentDatatype.INT;
  11182. }
  11183. if (array instanceof Uint32Array) {
  11184. return ComponentDatatype.UNSIGNED_INT;
  11185. }
  11186. if (array instanceof Float32Array) {
  11187. return ComponentDatatype.FLOAT;
  11188. }
  11189. if (array instanceof Float64Array) {
  11190. return ComponentDatatype.DOUBLE;
  11191. }
  11192. };
  11193. /**
  11194. * Validates that the provided component datatype is a valid {@link ComponentDatatype}
  11195. *
  11196. * @param {ComponentDatatype} componentDatatype The component datatype to validate.
  11197. * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
  11198. *
  11199. * @example
  11200. * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
  11201. * throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
  11202. * }
  11203. */
  11204. ComponentDatatype.validate = function(componentDatatype) {
  11205. return defined(componentDatatype) &&
  11206. (componentDatatype === ComponentDatatype.BYTE ||
  11207. componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
  11208. componentDatatype === ComponentDatatype.SHORT ||
  11209. componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
  11210. componentDatatype === ComponentDatatype.INT ||
  11211. componentDatatype === ComponentDatatype.UNSIGNED_INT ||
  11212. componentDatatype === ComponentDatatype.FLOAT ||
  11213. componentDatatype === ComponentDatatype.DOUBLE);
  11214. };
  11215. /**
  11216. * Creates a typed array corresponding to component data type.
  11217. *
  11218. * @param {ComponentDatatype} componentDatatype The component data type.
  11219. * @param {Number|Array} valuesOrLength The length of the array to create or an array.
  11220. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
  11221. *
  11222. * @exception {DeveloperError} componentDatatype is not a valid value.
  11223. *
  11224. * @example
  11225. * // creates a Float32Array with length of 100
  11226. * var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
  11227. */
  11228. ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
  11229. if (!defined(componentDatatype)) {
  11230. throw new DeveloperError('componentDatatype is required.');
  11231. }
  11232. if (!defined(valuesOrLength)) {
  11233. throw new DeveloperError('valuesOrLength is required.');
  11234. }
  11235. switch (componentDatatype) {
  11236. case ComponentDatatype.BYTE:
  11237. return new Int8Array(valuesOrLength);
  11238. case ComponentDatatype.UNSIGNED_BYTE:
  11239. return new Uint8Array(valuesOrLength);
  11240. case ComponentDatatype.SHORT:
  11241. return new Int16Array(valuesOrLength);
  11242. case ComponentDatatype.UNSIGNED_SHORT:
  11243. return new Uint16Array(valuesOrLength);
  11244. case ComponentDatatype.INT:
  11245. return new Int32Array(valuesOrLength);
  11246. case ComponentDatatype.UNSIGNED_INT:
  11247. return new Uint32Array(valuesOrLength);
  11248. case ComponentDatatype.FLOAT:
  11249. return new Float32Array(valuesOrLength);
  11250. case ComponentDatatype.DOUBLE:
  11251. return new Float64Array(valuesOrLength);
  11252. default:
  11253. throw new DeveloperError('componentDatatype is not a valid value.');
  11254. }
  11255. };
  11256. /**
  11257. * Creates a typed view of an array of bytes.
  11258. *
  11259. * @param {ComponentDatatype} componentDatatype The type of the view to create.
  11260. * @param {ArrayBuffer} buffer The buffer storage to use for the view.
  11261. * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
  11262. * @param {Number} [length] The number of elements in the view.
  11263. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
  11264. *
  11265. * @exception {DeveloperError} componentDatatype is not a valid value.
  11266. */
  11267. ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
  11268. if (!defined(componentDatatype)) {
  11269. throw new DeveloperError('componentDatatype is required.');
  11270. }
  11271. if (!defined(buffer)) {
  11272. throw new DeveloperError('buffer is required.');
  11273. }
  11274. byteOffset = defaultValue(byteOffset, 0);
  11275. length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
  11276. switch (componentDatatype) {
  11277. case ComponentDatatype.BYTE:
  11278. return new Int8Array(buffer, byteOffset, length);
  11279. case ComponentDatatype.UNSIGNED_BYTE:
  11280. return new Uint8Array(buffer, byteOffset, length);
  11281. case ComponentDatatype.SHORT:
  11282. return new Int16Array(buffer, byteOffset, length);
  11283. case ComponentDatatype.UNSIGNED_SHORT:
  11284. return new Uint16Array(buffer, byteOffset, length);
  11285. case ComponentDatatype.INT:
  11286. return new Int32Array(buffer, byteOffset, length);
  11287. case ComponentDatatype.UNSIGNED_INT:
  11288. return new Uint32Array(buffer, byteOffset, length);
  11289. case ComponentDatatype.FLOAT:
  11290. return new Float32Array(buffer, byteOffset, length);
  11291. case ComponentDatatype.DOUBLE:
  11292. return new Float64Array(buffer, byteOffset, length);
  11293. default:
  11294. throw new DeveloperError('componentDatatype is not a valid value.');
  11295. }
  11296. };
  11297. /**
  11298. * Get the ComponentDatatype from its name.
  11299. *
  11300. * @param {String} name The name of the ComponentDatatype.
  11301. * @returns {ComponentDatatype} The ComponentDatatype.
  11302. *
  11303. * @exception {DeveloperError} name is not a valid value.
  11304. */
  11305. ComponentDatatype.fromName = function(name) {
  11306. switch (name) {
  11307. case 'BYTE':
  11308. return ComponentDatatype.BYTE;
  11309. case 'UNSIGNED_BYTE':
  11310. return ComponentDatatype.UNSIGNED_BYTE;
  11311. case 'SHORT':
  11312. return ComponentDatatype.SHORT;
  11313. case 'UNSIGNED_SHORT':
  11314. return ComponentDatatype.UNSIGNED_SHORT;
  11315. case 'INT':
  11316. return ComponentDatatype.INT;
  11317. case 'UNSIGNED_INT':
  11318. return ComponentDatatype.UNSIGNED_INT;
  11319. case 'FLOAT':
  11320. return ComponentDatatype.FLOAT;
  11321. case 'DOUBLE':
  11322. return ComponentDatatype.DOUBLE;
  11323. default:
  11324. throw new DeveloperError('name is not a valid value.');
  11325. }
  11326. };
  11327. return freezeObject(ComponentDatatype);
  11328. });
  11329. /*global define*/
  11330. define('Core/AxisAlignedBoundingBox',[
  11331. './Cartesian3',
  11332. './defaultValue',
  11333. './defined',
  11334. './DeveloperError',
  11335. './Intersect'
  11336. ], function(
  11337. Cartesian3,
  11338. defaultValue,
  11339. defined,
  11340. DeveloperError,
  11341. Intersect) {
  11342. 'use strict';
  11343. /**
  11344. * Creates an instance of an AxisAlignedBoundingBox from the minimum and maximum points along the x, y, and z axes.
  11345. * @alias AxisAlignedBoundingBox
  11346. * @constructor
  11347. *
  11348. * @param {Cartesian3} [minimum=Cartesian3.ZERO] The minimum point along the x, y, and z axes.
  11349. * @param {Cartesian3} [maximum=Cartesian3.ZERO] The maximum point along the x, y, and z axes.
  11350. * @param {Cartesian3} [center] The center of the box; automatically computed if not supplied.
  11351. *
  11352. * @see BoundingSphere
  11353. * @see BoundingRectangle
  11354. */
  11355. function AxisAlignedBoundingBox(minimum, maximum, center) {
  11356. /**
  11357. * The minimum point defining the bounding box.
  11358. * @type {Cartesian3}
  11359. * @default {@link Cartesian3.ZERO}
  11360. */
  11361. this.minimum = Cartesian3.clone(defaultValue(minimum, Cartesian3.ZERO));
  11362. /**
  11363. * The maximum point defining the bounding box.
  11364. * @type {Cartesian3}
  11365. * @default {@link Cartesian3.ZERO}
  11366. */
  11367. this.maximum = Cartesian3.clone(defaultValue(maximum, Cartesian3.ZERO));
  11368. //If center was not defined, compute it.
  11369. if (!defined(center)) {
  11370. center = Cartesian3.add(this.minimum, this.maximum, new Cartesian3());
  11371. Cartesian3.multiplyByScalar(center, 0.5, center);
  11372. } else {
  11373. center = Cartesian3.clone(center);
  11374. }
  11375. /**
  11376. * The center point of the bounding box.
  11377. * @type {Cartesian3}
  11378. */
  11379. this.center = center;
  11380. }
  11381. /**
  11382. * Computes an instance of an AxisAlignedBoundingBox. The box is determined by
  11383. * finding the points spaced the farthest apart on the x, y, and z axes.
  11384. *
  11385. * @param {Cartesian3[]} positions List of points that the bounding box will enclose. Each point must have a <code>x</code>, <code>y</code>, and <code>z</code> properties.
  11386. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  11387. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  11388. *
  11389. * @example
  11390. * // Compute an axis aligned bounding box enclosing two points.
  11391. * var box = Cesium.AxisAlignedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  11392. */
  11393. AxisAlignedBoundingBox.fromPoints = function(positions, result) {
  11394. if (!defined(result)) {
  11395. result = new AxisAlignedBoundingBox();
  11396. }
  11397. if (!defined(positions) || positions.length === 0) {
  11398. result.minimum = Cartesian3.clone(Cartesian3.ZERO, result.minimum);
  11399. result.maximum = Cartesian3.clone(Cartesian3.ZERO, result.maximum);
  11400. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  11401. return result;
  11402. }
  11403. var minimumX = positions[0].x;
  11404. var minimumY = positions[0].y;
  11405. var minimumZ = positions[0].z;
  11406. var maximumX = positions[0].x;
  11407. var maximumY = positions[0].y;
  11408. var maximumZ = positions[0].z;
  11409. var length = positions.length;
  11410. for ( var i = 1; i < length; i++) {
  11411. var p = positions[i];
  11412. var x = p.x;
  11413. var y = p.y;
  11414. var z = p.z;
  11415. minimumX = Math.min(x, minimumX);
  11416. maximumX = Math.max(x, maximumX);
  11417. minimumY = Math.min(y, minimumY);
  11418. maximumY = Math.max(y, maximumY);
  11419. minimumZ = Math.min(z, minimumZ);
  11420. maximumZ = Math.max(z, maximumZ);
  11421. }
  11422. var minimum = result.minimum;
  11423. minimum.x = minimumX;
  11424. minimum.y = minimumY;
  11425. minimum.z = minimumZ;
  11426. var maximum = result.maximum;
  11427. maximum.x = maximumX;
  11428. maximum.y = maximumY;
  11429. maximum.z = maximumZ;
  11430. var center = Cartesian3.add(minimum, maximum, result.center);
  11431. Cartesian3.multiplyByScalar(center, 0.5, center);
  11432. return result;
  11433. };
  11434. /**
  11435. * Duplicates a AxisAlignedBoundingBox instance.
  11436. *
  11437. * @param {AxisAlignedBoundingBox} box The bounding box to duplicate.
  11438. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  11439. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  11440. */
  11441. AxisAlignedBoundingBox.clone = function(box, result) {
  11442. if (!defined(box)) {
  11443. return undefined;
  11444. }
  11445. if (!defined(result)) {
  11446. return new AxisAlignedBoundingBox(box.minimum, box.maximum);
  11447. }
  11448. result.minimum = Cartesian3.clone(box.minimum, result.minimum);
  11449. result.maximum = Cartesian3.clone(box.maximum, result.maximum);
  11450. result.center = Cartesian3.clone(box.center, result.center);
  11451. return result;
  11452. };
  11453. /**
  11454. * Compares the provided AxisAlignedBoundingBox componentwise and returns
  11455. * <code>true</code> if they are equal, <code>false</code> otherwise.
  11456. *
  11457. * @param {AxisAlignedBoundingBox} [left] The first AxisAlignedBoundingBox.
  11458. * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox.
  11459. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  11460. */
  11461. AxisAlignedBoundingBox.equals = function(left, right) {
  11462. return (left === right) ||
  11463. ((defined(left)) &&
  11464. (defined(right)) &&
  11465. Cartesian3.equals(left.center, right.center) &&
  11466. Cartesian3.equals(left.minimum, right.minimum) &&
  11467. Cartesian3.equals(left.maximum, right.maximum));
  11468. };
  11469. var intersectScratch = new Cartesian3();
  11470. /**
  11471. * Determines which side of a plane a box is located.
  11472. *
  11473. * @param {AxisAlignedBoundingBox} box The bounding box to test.
  11474. * @param {Plane} plane The plane to test against.
  11475. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  11476. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  11477. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  11478. * intersects the plane.
  11479. */
  11480. AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
  11481. if (!defined(box)) {
  11482. throw new DeveloperError('box is required.');
  11483. }
  11484. if (!defined(plane)) {
  11485. throw new DeveloperError('plane is required.');
  11486. }
  11487. intersectScratch = Cartesian3.subtract(box.maximum, box.minimum, intersectScratch);
  11488. var h = Cartesian3.multiplyByScalar(intersectScratch, 0.5, intersectScratch); //The positive half diagonal
  11489. var normal = plane.normal;
  11490. var e = h.x * Math.abs(normal.x) + h.y * Math.abs(normal.y) + h.z * Math.abs(normal.z);
  11491. var s = Cartesian3.dot(box.center, normal) + plane.distance; //signed distance from center
  11492. if (s - e > 0) {
  11493. return Intersect.INSIDE;
  11494. }
  11495. if (s + e < 0) {
  11496. //Not in front because normals point inward
  11497. return Intersect.OUTSIDE;
  11498. }
  11499. return Intersect.INTERSECTING;
  11500. };
  11501. /**
  11502. * Duplicates this AxisAlignedBoundingBox instance.
  11503. *
  11504. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  11505. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  11506. */
  11507. AxisAlignedBoundingBox.prototype.clone = function(result) {
  11508. return AxisAlignedBoundingBox.clone(this, result);
  11509. };
  11510. /**
  11511. * Determines which side of a plane this box is located.
  11512. *
  11513. * @param {Plane} plane The plane to test against.
  11514. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  11515. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  11516. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  11517. * intersects the plane.
  11518. */
  11519. AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
  11520. return AxisAlignedBoundingBox.intersectPlane(this, plane);
  11521. };
  11522. /**
  11523. * Compares this AxisAlignedBoundingBox against the provided AxisAlignedBoundingBox componentwise and returns
  11524. * <code>true</code> if they are equal, <code>false</code> otherwise.
  11525. *
  11526. * @param {AxisAlignedBoundingBox} [right] The right hand side AxisAlignedBoundingBox.
  11527. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  11528. */
  11529. AxisAlignedBoundingBox.prototype.equals = function(right) {
  11530. return AxisAlignedBoundingBox.equals(this, right);
  11531. };
  11532. return AxisAlignedBoundingBox;
  11533. });
  11534. /*global define*/
  11535. define('Core/Cartesian2',[
  11536. './defaultValue',
  11537. './defined',
  11538. './DeveloperError',
  11539. './freezeObject',
  11540. './Math'
  11541. ], function(
  11542. defaultValue,
  11543. defined,
  11544. DeveloperError,
  11545. freezeObject,
  11546. CesiumMath) {
  11547. 'use strict';
  11548. /**
  11549. * A 2D Cartesian point.
  11550. * @alias Cartesian2
  11551. * @constructor
  11552. *
  11553. * @param {Number} [x=0.0] The X component.
  11554. * @param {Number} [y=0.0] The Y component.
  11555. *
  11556. * @see Cartesian3
  11557. * @see Cartesian4
  11558. * @see Packable
  11559. */
  11560. function Cartesian2(x, y) {
  11561. /**
  11562. * The X component.
  11563. * @type {Number}
  11564. * @default 0.0
  11565. */
  11566. this.x = defaultValue(x, 0.0);
  11567. /**
  11568. * The Y component.
  11569. * @type {Number}
  11570. * @default 0.0
  11571. */
  11572. this.y = defaultValue(y, 0.0);
  11573. }
  11574. /**
  11575. * Creates a Cartesian2 instance from x and y coordinates.
  11576. *
  11577. * @param {Number} x The x coordinate.
  11578. * @param {Number} y The y coordinate.
  11579. * @param {Cartesian2} [result] The object onto which to store the result.
  11580. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  11581. */
  11582. Cartesian2.fromElements = function(x, y, result) {
  11583. if (!defined(result)) {
  11584. return new Cartesian2(x, y);
  11585. }
  11586. result.x = x;
  11587. result.y = y;
  11588. return result;
  11589. };
  11590. /**
  11591. * Duplicates a Cartesian2 instance.
  11592. *
  11593. * @param {Cartesian2} cartesian The Cartesian to duplicate.
  11594. * @param {Cartesian2} [result] The object onto which to store the result.
  11595. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
  11596. */
  11597. Cartesian2.clone = function(cartesian, result) {
  11598. if (!defined(cartesian)) {
  11599. return undefined;
  11600. }
  11601. if (!defined(result)) {
  11602. return new Cartesian2(cartesian.x, cartesian.y);
  11603. }
  11604. result.x = cartesian.x;
  11605. result.y = cartesian.y;
  11606. return result;
  11607. };
  11608. /**
  11609. * Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
  11610. * x and y properties of the Cartesian3 and drops z.
  11611. * @function
  11612. *
  11613. * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
  11614. * @param {Cartesian2} [result] The object onto which to store the result.
  11615. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  11616. */
  11617. Cartesian2.fromCartesian3 = Cartesian2.clone;
  11618. /**
  11619. * Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
  11620. * x and y properties of the Cartesian4 and drops z and w.
  11621. * @function
  11622. *
  11623. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
  11624. * @param {Cartesian2} [result] The object onto which to store the result.
  11625. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  11626. */
  11627. Cartesian2.fromCartesian4 = Cartesian2.clone;
  11628. /**
  11629. * The number of elements used to pack the object into an array.
  11630. * @type {Number}
  11631. */
  11632. Cartesian2.packedLength = 2;
  11633. /**
  11634. * Stores the provided instance into the provided array.
  11635. *
  11636. * @param {Cartesian2} value The value to pack.
  11637. * @param {Number[]} array The array to pack into.
  11638. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  11639. *
  11640. * @returns {Number[]} The array that was packed into
  11641. */
  11642. Cartesian2.pack = function(value, array, startingIndex) {
  11643. if (!defined(value)) {
  11644. throw new DeveloperError('value is required');
  11645. }
  11646. if (!defined(array)) {
  11647. throw new DeveloperError('array is required');
  11648. }
  11649. startingIndex = defaultValue(startingIndex, 0);
  11650. array[startingIndex++] = value.x;
  11651. array[startingIndex] = value.y;
  11652. return array;
  11653. };
  11654. /**
  11655. * Retrieves an instance from a packed array.
  11656. *
  11657. * @param {Number[]} array The packed array.
  11658. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  11659. * @param {Cartesian2} [result] The object into which to store the result.
  11660. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  11661. */
  11662. Cartesian2.unpack = function(array, startingIndex, result) {
  11663. if (!defined(array)) {
  11664. throw new DeveloperError('array is required');
  11665. }
  11666. startingIndex = defaultValue(startingIndex, 0);
  11667. if (!defined(result)) {
  11668. result = new Cartesian2();
  11669. }
  11670. result.x = array[startingIndex++];
  11671. result.y = array[startingIndex];
  11672. return result;
  11673. };
  11674. /**
  11675. * Flattens an array of Cartesian2s into and array of components.
  11676. *
  11677. * @param {Cartesian2[]} array The array of cartesians to pack.
  11678. * @param {Number[]} result The array onto which to store the result.
  11679. * @returns {Number[]} The packed array.
  11680. */
  11681. Cartesian2.packArray = function(array, result) {
  11682. if (!defined(array)) {
  11683. throw new DeveloperError('array is required');
  11684. }
  11685. var length = array.length;
  11686. if (!defined(result)) {
  11687. result = new Array(length * 2);
  11688. } else {
  11689. result.length = length * 2;
  11690. }
  11691. for (var i = 0; i < length; ++i) {
  11692. Cartesian2.pack(array[i], result, i * 2);
  11693. }
  11694. return result;
  11695. };
  11696. /**
  11697. * Unpacks an array of cartesian components into and array of Cartesian2s.
  11698. *
  11699. * @param {Number[]} array The array of components to unpack.
  11700. * @param {Cartesian2[]} result The array onto which to store the result.
  11701. * @returns {Cartesian2[]} The unpacked array.
  11702. */
  11703. Cartesian2.unpackArray = function(array, result) {
  11704. if (!defined(array)) {
  11705. throw new DeveloperError('array is required');
  11706. }
  11707. var length = array.length;
  11708. if (!defined(result)) {
  11709. result = new Array(length / 2);
  11710. } else {
  11711. result.length = length / 2;
  11712. }
  11713. for (var i = 0; i < length; i += 2) {
  11714. var index = i / 2;
  11715. result[index] = Cartesian2.unpack(array, i, result[index]);
  11716. }
  11717. return result;
  11718. };
  11719. /**
  11720. * Creates a Cartesian2 from two consecutive elements in an array.
  11721. * @function
  11722. *
  11723. * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
  11724. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  11725. * @param {Cartesian2} [result] The object onto which to store the result.
  11726. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  11727. *
  11728. * @example
  11729. * // Create a Cartesian2 with (1.0, 2.0)
  11730. * var v = [1.0, 2.0];
  11731. * var p = Cesium.Cartesian2.fromArray(v);
  11732. *
  11733. * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
  11734. * var v2 = [0.0, 0.0, 1.0, 2.0];
  11735. * var p2 = Cesium.Cartesian2.fromArray(v2, 2);
  11736. */
  11737. Cartesian2.fromArray = Cartesian2.unpack;
  11738. /**
  11739. * Computes the value of the maximum component for the supplied Cartesian.
  11740. *
  11741. * @param {Cartesian2} cartesian The cartesian to use.
  11742. * @returns {Number} The value of the maximum component.
  11743. */
  11744. Cartesian2.maximumComponent = function(cartesian) {
  11745. if (!defined(cartesian)) {
  11746. throw new DeveloperError('cartesian is required');
  11747. }
  11748. return Math.max(cartesian.x, cartesian.y);
  11749. };
  11750. /**
  11751. * Computes the value of the minimum component for the supplied Cartesian.
  11752. *
  11753. * @param {Cartesian2} cartesian The cartesian to use.
  11754. * @returns {Number} The value of the minimum component.
  11755. */
  11756. Cartesian2.minimumComponent = function(cartesian) {
  11757. if (!defined(cartesian)) {
  11758. throw new DeveloperError('cartesian is required');
  11759. }
  11760. return Math.min(cartesian.x, cartesian.y);
  11761. };
  11762. /**
  11763. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  11764. *
  11765. * @param {Cartesian2} first A cartesian to compare.
  11766. * @param {Cartesian2} second A cartesian to compare.
  11767. * @param {Cartesian2} result The object into which to store the result.
  11768. * @returns {Cartesian2} A cartesian with the minimum components.
  11769. */
  11770. Cartesian2.minimumByComponent = function(first, second, result) {
  11771. if (!defined(first)) {
  11772. throw new DeveloperError('first is required.');
  11773. }
  11774. if (!defined(second)) {
  11775. throw new DeveloperError('second is required.');
  11776. }
  11777. if (!defined(result)) {
  11778. throw new DeveloperError('result is required.');
  11779. }
  11780. result.x = Math.min(first.x, second.x);
  11781. result.y = Math.min(first.y, second.y);
  11782. return result;
  11783. };
  11784. /**
  11785. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  11786. *
  11787. * @param {Cartesian2} first A cartesian to compare.
  11788. * @param {Cartesian2} second A cartesian to compare.
  11789. * @param {Cartesian2} result The object into which to store the result.
  11790. * @returns {Cartesian2} A cartesian with the maximum components.
  11791. */
  11792. Cartesian2.maximumByComponent = function(first, second, result) {
  11793. if (!defined(first)) {
  11794. throw new DeveloperError('first is required.');
  11795. }
  11796. if (!defined(second)) {
  11797. throw new DeveloperError('second is required.');
  11798. }
  11799. if (!defined(result)) {
  11800. throw new DeveloperError('result is required.');
  11801. }
  11802. result.x = Math.max(first.x, second.x);
  11803. result.y = Math.max(first.y, second.y);
  11804. return result;
  11805. };
  11806. /**
  11807. * Computes the provided Cartesian's squared magnitude.
  11808. *
  11809. * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
  11810. * @returns {Number} The squared magnitude.
  11811. */
  11812. Cartesian2.magnitudeSquared = function(cartesian) {
  11813. if (!defined(cartesian)) {
  11814. throw new DeveloperError('cartesian is required');
  11815. }
  11816. return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  11817. };
  11818. /**
  11819. * Computes the Cartesian's magnitude (length).
  11820. *
  11821. * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
  11822. * @returns {Number} The magnitude.
  11823. */
  11824. Cartesian2.magnitude = function(cartesian) {
  11825. return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  11826. };
  11827. var distanceScratch = new Cartesian2();
  11828. /**
  11829. * Computes the distance between two points.
  11830. *
  11831. * @param {Cartesian2} left The first point to compute the distance from.
  11832. * @param {Cartesian2} right The second point to compute the distance to.
  11833. * @returns {Number} The distance between two points.
  11834. *
  11835. * @example
  11836. * // Returns 1.0
  11837. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
  11838. */
  11839. Cartesian2.distance = function(left, right) {
  11840. if (!defined(left) || !defined(right)) {
  11841. throw new DeveloperError('left and right are required.');
  11842. }
  11843. Cartesian2.subtract(left, right, distanceScratch);
  11844. return Cartesian2.magnitude(distanceScratch);
  11845. };
  11846. /**
  11847. * Computes the squared distance between two points. Comparing squared distances
  11848. * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
  11849. *
  11850. * @param {Cartesian2} left The first point to compute the distance from.
  11851. * @param {Cartesian2} right The second point to compute the distance to.
  11852. * @returns {Number} The distance between two points.
  11853. *
  11854. * @example
  11855. * // Returns 4.0, not 2.0
  11856. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
  11857. */
  11858. Cartesian2.distanceSquared = function(left, right) {
  11859. if (!defined(left) || !defined(right)) {
  11860. throw new DeveloperError('left and right are required.');
  11861. }
  11862. Cartesian2.subtract(left, right, distanceScratch);
  11863. return Cartesian2.magnitudeSquared(distanceScratch);
  11864. };
  11865. /**
  11866. * Computes the normalized form of the supplied Cartesian.
  11867. *
  11868. * @param {Cartesian2} cartesian The Cartesian to be normalized.
  11869. * @param {Cartesian2} result The object onto which to store the result.
  11870. * @returns {Cartesian2} The modified result parameter.
  11871. */
  11872. Cartesian2.normalize = function(cartesian, result) {
  11873. if (!defined(cartesian)) {
  11874. throw new DeveloperError('cartesian is required');
  11875. }
  11876. if (!defined(result)) {
  11877. throw new DeveloperError('result is required');
  11878. }
  11879. var magnitude = Cartesian2.magnitude(cartesian);
  11880. result.x = cartesian.x / magnitude;
  11881. result.y = cartesian.y / magnitude;
  11882. if (isNaN(result.x) || isNaN(result.y)) {
  11883. throw new DeveloperError('normalized result is not a number');
  11884. }
  11885. return result;
  11886. };
  11887. /**
  11888. * Computes the dot (scalar) product of two Cartesians.
  11889. *
  11890. * @param {Cartesian2} left The first Cartesian.
  11891. * @param {Cartesian2} right The second Cartesian.
  11892. * @returns {Number} The dot product.
  11893. */
  11894. Cartesian2.dot = function(left, right) {
  11895. if (!defined(left)) {
  11896. throw new DeveloperError('left is required');
  11897. }
  11898. if (!defined(right)) {
  11899. throw new DeveloperError('right is required');
  11900. }
  11901. return left.x * right.x + left.y * right.y;
  11902. };
  11903. /**
  11904. * Computes the componentwise product of two Cartesians.
  11905. *
  11906. * @param {Cartesian2} left The first Cartesian.
  11907. * @param {Cartesian2} right The second Cartesian.
  11908. * @param {Cartesian2} result The object onto which to store the result.
  11909. * @returns {Cartesian2} The modified result parameter.
  11910. */
  11911. Cartesian2.multiplyComponents = function(left, right, result) {
  11912. if (!defined(left)) {
  11913. throw new DeveloperError('left is required');
  11914. }
  11915. if (!defined(right)) {
  11916. throw new DeveloperError('right is required');
  11917. }
  11918. if (!defined(result)) {
  11919. throw new DeveloperError('result is required');
  11920. }
  11921. result.x = left.x * right.x;
  11922. result.y = left.y * right.y;
  11923. return result;
  11924. };
  11925. /**
  11926. * Computes the componentwise quotient of two Cartesians.
  11927. *
  11928. * @param {Cartesian2} left The first Cartesian.
  11929. * @param {Cartesian2} right The second Cartesian.
  11930. * @param {Cartesian2} result The object onto which to store the result.
  11931. * @returns {Cartesian2} The modified result parameter.
  11932. */
  11933. Cartesian2.divideComponents = function(left, right, result) {
  11934. if (!defined(left)) {
  11935. throw new DeveloperError('left is required');
  11936. }
  11937. if (!defined(right)) {
  11938. throw new DeveloperError('right is required');
  11939. }
  11940. if (!defined(result)) {
  11941. throw new DeveloperError('result is required');
  11942. }
  11943. result.x = left.x / right.x;
  11944. result.y = left.y / right.y;
  11945. return result;
  11946. };
  11947. /**
  11948. * Computes the componentwise sum of two Cartesians.
  11949. *
  11950. * @param {Cartesian2} left The first Cartesian.
  11951. * @param {Cartesian2} right The second Cartesian.
  11952. * @param {Cartesian2} result The object onto which to store the result.
  11953. * @returns {Cartesian2} The modified result parameter.
  11954. */
  11955. Cartesian2.add = function(left, right, result) {
  11956. if (!defined(left)) {
  11957. throw new DeveloperError('left is required');
  11958. }
  11959. if (!defined(right)) {
  11960. throw new DeveloperError('right is required');
  11961. }
  11962. if (!defined(result)) {
  11963. throw new DeveloperError('result is required');
  11964. }
  11965. result.x = left.x + right.x;
  11966. result.y = left.y + right.y;
  11967. return result;
  11968. };
  11969. /**
  11970. * Computes the componentwise difference of two Cartesians.
  11971. *
  11972. * @param {Cartesian2} left The first Cartesian.
  11973. * @param {Cartesian2} right The second Cartesian.
  11974. * @param {Cartesian2} result The object onto which to store the result.
  11975. * @returns {Cartesian2} The modified result parameter.
  11976. */
  11977. Cartesian2.subtract = function(left, right, result) {
  11978. if (!defined(left)) {
  11979. throw new DeveloperError('left is required');
  11980. }
  11981. if (!defined(right)) {
  11982. throw new DeveloperError('right is required');
  11983. }
  11984. if (!defined(result)) {
  11985. throw new DeveloperError('result is required');
  11986. }
  11987. result.x = left.x - right.x;
  11988. result.y = left.y - right.y;
  11989. return result;
  11990. };
  11991. /**
  11992. * Multiplies the provided Cartesian componentwise by the provided scalar.
  11993. *
  11994. * @param {Cartesian2} cartesian The Cartesian to be scaled.
  11995. * @param {Number} scalar The scalar to multiply with.
  11996. * @param {Cartesian2} result The object onto which to store the result.
  11997. * @returns {Cartesian2} The modified result parameter.
  11998. */
  11999. Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
  12000. if (!defined(cartesian)) {
  12001. throw new DeveloperError('cartesian is required');
  12002. }
  12003. if (typeof scalar !== 'number') {
  12004. throw new DeveloperError('scalar is required and must be a number.');
  12005. }
  12006. if (!defined(result)) {
  12007. throw new DeveloperError('result is required');
  12008. }
  12009. result.x = cartesian.x * scalar;
  12010. result.y = cartesian.y * scalar;
  12011. return result;
  12012. };
  12013. /**
  12014. * Divides the provided Cartesian componentwise by the provided scalar.
  12015. *
  12016. * @param {Cartesian2} cartesian The Cartesian to be divided.
  12017. * @param {Number} scalar The scalar to divide by.
  12018. * @param {Cartesian2} result The object onto which to store the result.
  12019. * @returns {Cartesian2} The modified result parameter.
  12020. */
  12021. Cartesian2.divideByScalar = function(cartesian, scalar, result) {
  12022. if (!defined(cartesian)) {
  12023. throw new DeveloperError('cartesian is required');
  12024. }
  12025. if (typeof scalar !== 'number') {
  12026. throw new DeveloperError('scalar is required and must be a number.');
  12027. }
  12028. if (!defined(result)) {
  12029. throw new DeveloperError('result is required');
  12030. }
  12031. result.x = cartesian.x / scalar;
  12032. result.y = cartesian.y / scalar;
  12033. return result;
  12034. };
  12035. /**
  12036. * Negates the provided Cartesian.
  12037. *
  12038. * @param {Cartesian2} cartesian The Cartesian to be negated.
  12039. * @param {Cartesian2} result The object onto which to store the result.
  12040. * @returns {Cartesian2} The modified result parameter.
  12041. */
  12042. Cartesian2.negate = function(cartesian, result) {
  12043. if (!defined(cartesian)) {
  12044. throw new DeveloperError('cartesian is required');
  12045. }
  12046. if (!defined(result)) {
  12047. throw new DeveloperError('result is required');
  12048. }
  12049. result.x = -cartesian.x;
  12050. result.y = -cartesian.y;
  12051. return result;
  12052. };
  12053. /**
  12054. * Computes the absolute value of the provided Cartesian.
  12055. *
  12056. * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
  12057. * @param {Cartesian2} result The object onto which to store the result.
  12058. * @returns {Cartesian2} The modified result parameter.
  12059. */
  12060. Cartesian2.abs = function(cartesian, result) {
  12061. if (!defined(cartesian)) {
  12062. throw new DeveloperError('cartesian is required');
  12063. }
  12064. if (!defined(result)) {
  12065. throw new DeveloperError('result is required');
  12066. }
  12067. result.x = Math.abs(cartesian.x);
  12068. result.y = Math.abs(cartesian.y);
  12069. return result;
  12070. };
  12071. var lerpScratch = new Cartesian2();
  12072. /**
  12073. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  12074. *
  12075. * @param {Cartesian2} start The value corresponding to t at 0.0.
  12076. * @param {Cartesian2} end The value corresponding to t at 1.0.
  12077. * @param {Number} t The point along t at which to interpolate.
  12078. * @param {Cartesian2} result The object onto which to store the result.
  12079. * @returns {Cartesian2} The modified result parameter.
  12080. */
  12081. Cartesian2.lerp = function(start, end, t, result) {
  12082. if (!defined(start)) {
  12083. throw new DeveloperError('start is required.');
  12084. }
  12085. if (!defined(end)) {
  12086. throw new DeveloperError('end is required.');
  12087. }
  12088. if (typeof t !== 'number') {
  12089. throw new DeveloperError('t is required and must be a number.');
  12090. }
  12091. if (!defined(result)) {
  12092. throw new DeveloperError('result is required.');
  12093. }
  12094. Cartesian2.multiplyByScalar(end, t, lerpScratch);
  12095. result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
  12096. return Cartesian2.add(lerpScratch, result, result);
  12097. };
  12098. var angleBetweenScratch = new Cartesian2();
  12099. var angleBetweenScratch2 = new Cartesian2();
  12100. /**
  12101. * Returns the angle, in radians, between the provided Cartesians.
  12102. *
  12103. * @param {Cartesian2} left The first Cartesian.
  12104. * @param {Cartesian2} right The second Cartesian.
  12105. * @returns {Number} The angle between the Cartesians.
  12106. */
  12107. Cartesian2.angleBetween = function(left, right) {
  12108. if (!defined(left)) {
  12109. throw new DeveloperError('left is required');
  12110. }
  12111. if (!defined(right)) {
  12112. throw new DeveloperError('right is required');
  12113. }
  12114. Cartesian2.normalize(left, angleBetweenScratch);
  12115. Cartesian2.normalize(right, angleBetweenScratch2);
  12116. return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
  12117. };
  12118. var mostOrthogonalAxisScratch = new Cartesian2();
  12119. /**
  12120. * Returns the axis that is most orthogonal to the provided Cartesian.
  12121. *
  12122. * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
  12123. * @param {Cartesian2} result The object onto which to store the result.
  12124. * @returns {Cartesian2} The most orthogonal axis.
  12125. */
  12126. Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
  12127. if (!defined(cartesian)) {
  12128. throw new DeveloperError('cartesian is required.');
  12129. }
  12130. if (!defined(result)) {
  12131. throw new DeveloperError('result is required.');
  12132. }
  12133. var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
  12134. Cartesian2.abs(f, f);
  12135. if (f.x <= f.y) {
  12136. result = Cartesian2.clone(Cartesian2.UNIT_X, result);
  12137. } else {
  12138. result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
  12139. }
  12140. return result;
  12141. };
  12142. /**
  12143. * Compares the provided Cartesians componentwise and returns
  12144. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12145. *
  12146. * @param {Cartesian2} [left] The first Cartesian.
  12147. * @param {Cartesian2} [right] The second Cartesian.
  12148. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  12149. */
  12150. Cartesian2.equals = function(left, right) {
  12151. return (left === right) ||
  12152. ((defined(left)) &&
  12153. (defined(right)) &&
  12154. (left.x === right.x) &&
  12155. (left.y === right.y));
  12156. };
  12157. /**
  12158. * @private
  12159. */
  12160. Cartesian2.equalsArray = function(cartesian, array, offset) {
  12161. return cartesian.x === array[offset] &&
  12162. cartesian.y === array[offset + 1];
  12163. };
  12164. /**
  12165. * Compares the provided Cartesians componentwise and returns
  12166. * <code>true</code> if they pass an absolute or relative tolerance test,
  12167. * <code>false</code> otherwise.
  12168. *
  12169. * @param {Cartesian2} [left] The first Cartesian.
  12170. * @param {Cartesian2} [right] The second Cartesian.
  12171. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  12172. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  12173. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  12174. */
  12175. Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  12176. return (left === right) ||
  12177. (defined(left) &&
  12178. defined(right) &&
  12179. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  12180. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
  12181. };
  12182. /**
  12183. * An immutable Cartesian2 instance initialized to (0.0, 0.0).
  12184. *
  12185. * @type {Cartesian2}
  12186. * @constant
  12187. */
  12188. Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
  12189. /**
  12190. * An immutable Cartesian2 instance initialized to (1.0, 0.0).
  12191. *
  12192. * @type {Cartesian2}
  12193. * @constant
  12194. */
  12195. Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
  12196. /**
  12197. * An immutable Cartesian2 instance initialized to (0.0, 1.0).
  12198. *
  12199. * @type {Cartesian2}
  12200. * @constant
  12201. */
  12202. Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
  12203. /**
  12204. * Duplicates this Cartesian2 instance.
  12205. *
  12206. * @param {Cartesian2} [result] The object onto which to store the result.
  12207. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  12208. */
  12209. Cartesian2.prototype.clone = function(result) {
  12210. return Cartesian2.clone(this, result);
  12211. };
  12212. /**
  12213. * Compares this Cartesian against the provided Cartesian componentwise and returns
  12214. * <code>true</code> if they are equal, <code>false</code> otherwise.
  12215. *
  12216. * @param {Cartesian2} [right] The right hand side Cartesian.
  12217. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  12218. */
  12219. Cartesian2.prototype.equals = function(right) {
  12220. return Cartesian2.equals(this, right);
  12221. };
  12222. /**
  12223. * Compares this Cartesian against the provided Cartesian componentwise and returns
  12224. * <code>true</code> if they pass an absolute or relative tolerance test,
  12225. * <code>false</code> otherwise.
  12226. *
  12227. * @param {Cartesian2} [right] The right hand side Cartesian.
  12228. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  12229. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  12230. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  12231. */
  12232. Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  12233. return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  12234. };
  12235. /**
  12236. * Creates a string representing this Cartesian in the format '(x, y)'.
  12237. *
  12238. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  12239. */
  12240. Cartesian2.prototype.toString = function() {
  12241. return '(' + this.x + ', ' + this.y + ')';
  12242. };
  12243. return Cartesian2;
  12244. });
  12245. /*global define*/
  12246. define('Core/QuadraticRealPolynomial',[
  12247. './DeveloperError',
  12248. './Math'
  12249. ], function(
  12250. DeveloperError,
  12251. CesiumMath) {
  12252. 'use strict';
  12253. /**
  12254. * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
  12255. *
  12256. * @exports QuadraticRealPolynomial
  12257. */
  12258. var QuadraticRealPolynomial = {};
  12259. /**
  12260. * Provides the discriminant of the quadratic equation from the supplied coefficients.
  12261. *
  12262. * @param {Number} a The coefficient of the 2nd order monomial.
  12263. * @param {Number} b The coefficient of the 1st order monomial.
  12264. * @param {Number} c The coefficient of the 0th order monomial.
  12265. * @returns {Number} The value of the discriminant.
  12266. */
  12267. QuadraticRealPolynomial.computeDiscriminant = function(a, b, c) {
  12268. if (typeof a !== 'number') {
  12269. throw new DeveloperError('a is a required number.');
  12270. }
  12271. if (typeof b !== 'number') {
  12272. throw new DeveloperError('b is a required number.');
  12273. }
  12274. if (typeof c !== 'number') {
  12275. throw new DeveloperError('c is a required number.');
  12276. }
  12277. var discriminant = b * b - 4.0 * a * c;
  12278. return discriminant;
  12279. };
  12280. function addWithCancellationCheck(left, right, tolerance) {
  12281. var difference = left + right;
  12282. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  12283. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  12284. return 0.0;
  12285. }
  12286. return difference;
  12287. }
  12288. /**
  12289. * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
  12290. *
  12291. * @param {Number} a The coefficient of the 2nd order monomial.
  12292. * @param {Number} b The coefficient of the 1st order monomial.
  12293. * @param {Number} c The coefficient of the 0th order monomial.
  12294. * @returns {Number[]} The real valued roots.
  12295. */
  12296. QuadraticRealPolynomial.computeRealRoots = function(a, b, c) {
  12297. if (typeof a !== 'number') {
  12298. throw new DeveloperError('a is a required number.');
  12299. }
  12300. if (typeof b !== 'number') {
  12301. throw new DeveloperError('b is a required number.');
  12302. }
  12303. if (typeof c !== 'number') {
  12304. throw new DeveloperError('c is a required number.');
  12305. }
  12306. var ratio;
  12307. if (a === 0.0) {
  12308. if (b === 0.0) {
  12309. // Constant function: c = 0.
  12310. return [];
  12311. }
  12312. // Linear function: b * x + c = 0.
  12313. return [-c / b];
  12314. } else if (b === 0.0) {
  12315. if (c === 0.0) {
  12316. // 2nd order monomial: a * x^2 = 0.
  12317. return [0.0, 0.0];
  12318. }
  12319. var cMagnitude = Math.abs(c);
  12320. var aMagnitude = Math.abs(a);
  12321. if ((cMagnitude < aMagnitude) && (cMagnitude / aMagnitude < CesiumMath.EPSILON14)) { // c ~= 0.0.
  12322. // 2nd order monomial: a * x^2 = 0.
  12323. return [0.0, 0.0];
  12324. } else if ((cMagnitude > aMagnitude) && (aMagnitude / cMagnitude < CesiumMath.EPSILON14)) { // a ~= 0.0.
  12325. // Constant function: c = 0.
  12326. return [];
  12327. }
  12328. // a * x^2 + c = 0
  12329. ratio = -c / a;
  12330. if (ratio < 0.0) {
  12331. // Both roots are complex.
  12332. return [];
  12333. }
  12334. // Both roots are real.
  12335. var root = Math.sqrt(ratio);
  12336. return [-root, root];
  12337. } else if (c === 0.0) {
  12338. // a * x^2 + b * x = 0
  12339. ratio = -b / a;
  12340. if (ratio < 0.0) {
  12341. return [ratio, 0.0];
  12342. }
  12343. return [0.0, ratio];
  12344. }
  12345. // a * x^2 + b * x + c = 0
  12346. var b2 = b * b;
  12347. var four_ac = 4.0 * a * c;
  12348. var radicand = addWithCancellationCheck(b2, -four_ac, CesiumMath.EPSILON14);
  12349. if (radicand < 0.0) {
  12350. // Both roots are complex.
  12351. return [];
  12352. }
  12353. var q = -0.5 * addWithCancellationCheck(b, CesiumMath.sign(b) * Math.sqrt(radicand), CesiumMath.EPSILON14);
  12354. if (b > 0.0) {
  12355. return [q / a, c / q];
  12356. }
  12357. return [c / q, q / a];
  12358. };
  12359. return QuadraticRealPolynomial;
  12360. });
  12361. /*global define*/
  12362. define('Core/CubicRealPolynomial',[
  12363. './DeveloperError',
  12364. './QuadraticRealPolynomial'
  12365. ], function(
  12366. DeveloperError,
  12367. QuadraticRealPolynomial) {
  12368. 'use strict';
  12369. /**
  12370. * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
  12371. *
  12372. * @exports CubicRealPolynomial
  12373. */
  12374. var CubicRealPolynomial = {};
  12375. /**
  12376. * Provides the discriminant of the cubic equation from the supplied coefficients.
  12377. *
  12378. * @param {Number} a The coefficient of the 3rd order monomial.
  12379. * @param {Number} b The coefficient of the 2nd order monomial.
  12380. * @param {Number} c The coefficient of the 1st order monomial.
  12381. * @param {Number} d The coefficient of the 0th order monomial.
  12382. * @returns {Number} The value of the discriminant.
  12383. */
  12384. CubicRealPolynomial.computeDiscriminant = function(a, b, c, d) {
  12385. if (typeof a !== 'number') {
  12386. throw new DeveloperError('a is a required number.');
  12387. }
  12388. if (typeof b !== 'number') {
  12389. throw new DeveloperError('b is a required number.');
  12390. }
  12391. if (typeof c !== 'number') {
  12392. throw new DeveloperError('c is a required number.');
  12393. }
  12394. if (typeof d !== 'number') {
  12395. throw new DeveloperError('d is a required number.');
  12396. }
  12397. var a2 = a * a;
  12398. var b2 = b * b;
  12399. var c2 = c * c;
  12400. var d2 = d * d;
  12401. var discriminant = 18.0 * a * b * c * d + b2 * c2 - 27.0 * a2 * d2 - 4.0 * (a * c2 * c + b2 * b * d);
  12402. return discriminant;
  12403. };
  12404. function computeRealRoots(a, b, c, d) {
  12405. var A = a;
  12406. var B = b / 3.0;
  12407. var C = c / 3.0;
  12408. var D = d;
  12409. var AC = A * C;
  12410. var BD = B * D;
  12411. var B2 = B * B;
  12412. var C2 = C * C;
  12413. var delta1 = A * C - B2;
  12414. var delta2 = A * D - B * C;
  12415. var delta3 = B * D - C2;
  12416. var discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
  12417. var temp;
  12418. var temp1;
  12419. if (discriminant < 0.0) {
  12420. var ABar;
  12421. var CBar;
  12422. var DBar;
  12423. if (B2 * BD >= AC * C2) {
  12424. ABar = A;
  12425. CBar = delta1;
  12426. DBar = -2.0 * B * delta1 + A * delta2;
  12427. } else {
  12428. ABar = D;
  12429. CBar = delta3;
  12430. DBar = -D * delta2 + 2.0 * C * delta3;
  12431. }
  12432. var s = (DBar < 0.0) ? -1.0 : 1.0; // This is not Math.Sign()!
  12433. var temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
  12434. temp1 = -DBar + temp0;
  12435. var x = temp1 / 2.0;
  12436. var p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
  12437. var q = (temp1 === temp0) ? -p : -CBar / p;
  12438. temp = (CBar <= 0.0) ? p + q : -DBar / (p * p + q * q + CBar);
  12439. if (B2 * BD >= AC * C2) {
  12440. return [(temp - B) / A];
  12441. }
  12442. return [-D / (temp + C)];
  12443. }
  12444. var CBarA = delta1;
  12445. var DBarA = -2.0 * B * delta1 + A * delta2;
  12446. var CBarD = delta3;
  12447. var DBarD = -D * delta2 + 2.0 * C * delta3;
  12448. var squareRootOfDiscriminant = Math.sqrt(discriminant);
  12449. var halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;
  12450. var theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
  12451. temp = 2.0 * Math.sqrt(-CBarA);
  12452. var cosine = Math.cos(theta);
  12453. temp1 = temp * cosine;
  12454. var temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  12455. var numeratorLarge = (temp1 + temp3 > 2.0 * B) ? temp1 - B : temp3 - B;
  12456. var denominatorLarge = A;
  12457. var root1 = numeratorLarge / denominatorLarge;
  12458. theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
  12459. temp = 2.0 * Math.sqrt(-CBarD);
  12460. cosine = Math.cos(theta);
  12461. temp1 = temp * cosine;
  12462. temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  12463. var numeratorSmall = -D;
  12464. var denominatorSmall = (temp1 + temp3 < 2.0 * C) ? temp1 + C : temp3 + C;
  12465. var root3 = numeratorSmall / denominatorSmall;
  12466. var E = denominatorLarge * denominatorSmall;
  12467. var F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
  12468. var G = numeratorLarge * numeratorSmall;
  12469. var root2 = (C * F - B * G) / (-B * F + C * E);
  12470. if (root1 <= root2) {
  12471. if (root1 <= root3) {
  12472. if (root2 <= root3) {
  12473. return [root1, root2, root3];
  12474. }
  12475. return [root1, root3, root2];
  12476. }
  12477. return [root3, root1, root2];
  12478. }
  12479. if (root1 <= root3) {
  12480. return [root2, root1, root3];
  12481. }
  12482. if (root2 <= root3) {
  12483. return [root2, root3, root1];
  12484. }
  12485. return [root3, root2, root1];
  12486. }
  12487. /**
  12488. * Provides the real valued roots of the cubic polynomial with the provided coefficients.
  12489. *
  12490. * @param {Number} a The coefficient of the 3rd order monomial.
  12491. * @param {Number} b The coefficient of the 2nd order monomial.
  12492. * @param {Number} c The coefficient of the 1st order monomial.
  12493. * @param {Number} d The coefficient of the 0th order monomial.
  12494. * @returns {Number[]} The real valued roots.
  12495. */
  12496. CubicRealPolynomial.computeRealRoots = function(a, b, c, d) {
  12497. if (typeof a !== 'number') {
  12498. throw new DeveloperError('a is a required number.');
  12499. }
  12500. if (typeof b !== 'number') {
  12501. throw new DeveloperError('b is a required number.');
  12502. }
  12503. if (typeof c !== 'number') {
  12504. throw new DeveloperError('c is a required number.');
  12505. }
  12506. if (typeof d !== 'number') {
  12507. throw new DeveloperError('d is a required number.');
  12508. }
  12509. var roots;
  12510. var ratio;
  12511. if (a === 0.0) {
  12512. // Quadratic function: b * x^2 + c * x + d = 0.
  12513. return QuadraticRealPolynomial.computeRealRoots(b, c, d);
  12514. } else if (b === 0.0) {
  12515. if (c === 0.0) {
  12516. if (d === 0.0) {
  12517. // 3rd order monomial: a * x^3 = 0.
  12518. return [0.0, 0.0, 0.0];
  12519. }
  12520. // a * x^3 + d = 0
  12521. ratio = -d / a;
  12522. var root = (ratio < 0.0) ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
  12523. return [root, root, root];
  12524. } else if (d === 0.0) {
  12525. // x * (a * x^2 + c) = 0.
  12526. roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);
  12527. // Return the roots in ascending order.
  12528. if (roots.Length === 0) {
  12529. return [0.0];
  12530. }
  12531. return [roots[0], 0.0, roots[1]];
  12532. }
  12533. // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
  12534. return computeRealRoots(a, 0, c, d);
  12535. } else if (c === 0.0) {
  12536. if (d === 0.0) {
  12537. // x^2 * (a * x + b) = 0.
  12538. ratio = -b / a;
  12539. if (ratio < 0.0) {
  12540. return [ratio, 0.0, 0.0];
  12541. }
  12542. return [0.0, 0.0, ratio];
  12543. }
  12544. // a * x^3 + b * x^2 + d = 0.
  12545. return computeRealRoots(a, b, 0, d);
  12546. } else if (d === 0.0) {
  12547. // x * (a * x^2 + b * x + c) = 0
  12548. roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);
  12549. // Return the roots in ascending order.
  12550. if (roots.length === 0) {
  12551. return [0.0];
  12552. } else if (roots[1] <= 0.0) {
  12553. return [roots[0], roots[1], 0.0];
  12554. } else if (roots[0] >= 0.0) {
  12555. return [0.0, roots[0], roots[1]];
  12556. }
  12557. return [roots[0], 0.0, roots[1]];
  12558. }
  12559. return computeRealRoots(a, b, c, d);
  12560. };
  12561. return CubicRealPolynomial;
  12562. });
  12563. /*global define*/
  12564. define('Core/QuarticRealPolynomial',[
  12565. './CubicRealPolynomial',
  12566. './DeveloperError',
  12567. './Math',
  12568. './QuadraticRealPolynomial'
  12569. ], function(
  12570. CubicRealPolynomial,
  12571. DeveloperError,
  12572. CesiumMath,
  12573. QuadraticRealPolynomial) {
  12574. 'use strict';
  12575. /**
  12576. * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
  12577. *
  12578. * @exports QuarticRealPolynomial
  12579. */
  12580. var QuarticRealPolynomial = {};
  12581. /**
  12582. * Provides the discriminant of the quartic equation from the supplied coefficients.
  12583. *
  12584. * @param {Number} a The coefficient of the 4th order monomial.
  12585. * @param {Number} b The coefficient of the 3rd order monomial.
  12586. * @param {Number} c The coefficient of the 2nd order monomial.
  12587. * @param {Number} d The coefficient of the 1st order monomial.
  12588. * @param {Number} e The coefficient of the 0th order monomial.
  12589. * @returns {Number} The value of the discriminant.
  12590. */
  12591. QuarticRealPolynomial.computeDiscriminant = function(a, b, c, d, e) {
  12592. if (typeof a !== 'number') {
  12593. throw new DeveloperError('a is a required number.');
  12594. }
  12595. if (typeof b !== 'number') {
  12596. throw new DeveloperError('b is a required number.');
  12597. }
  12598. if (typeof c !== 'number') {
  12599. throw new DeveloperError('c is a required number.');
  12600. }
  12601. if (typeof d !== 'number') {
  12602. throw new DeveloperError('d is a required number.');
  12603. }
  12604. if (typeof e !== 'number') {
  12605. throw new DeveloperError('e is a required number.');
  12606. }
  12607. var a2 = a * a;
  12608. var a3 = a2 * a;
  12609. var b2 = b * b;
  12610. var b3 = b2 * b;
  12611. var c2 = c * c;
  12612. var c3 = c2 * c;
  12613. var d2 = d * d;
  12614. var d3 = d2 * d;
  12615. var e2 = e * e;
  12616. var e3 = e2 * e;
  12617. var discriminant = (b2 * c2 * d2 - 4.0 * b3 * d3 - 4.0 * a * c3 * d2 + 18 * a * b * c * d3 - 27.0 * a2 * d2 * d2 + 256.0 * a3 * e3) +
  12618. e * (18.0 * b3 * c * d - 4.0 * b2 * c3 + 16.0 * a * c2 * c2 - 80.0 * a * b * c2 * d - 6.0 * a * b2 * d2 + 144.0 * a2 * c * d2) +
  12619. e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d);
  12620. return discriminant;
  12621. };
  12622. function original(a3, a2, a1, a0) {
  12623. var a3Squared = a3 * a3;
  12624. var p = a2 - 3.0 * a3Squared / 8.0;
  12625. var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0;
  12626. var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0;
  12627. // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
  12628. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q);
  12629. if (cubicRoots.length > 0) {
  12630. var temp = -a3 / 4.0;
  12631. // Use the largest positive root.
  12632. var hSquared = cubicRoots[cubicRoots.length - 1];
  12633. if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
  12634. // y^4 + p y^2 + r = 0.
  12635. var roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);
  12636. if (roots.length === 2) {
  12637. var root0 = roots[0];
  12638. var root1 = roots[1];
  12639. var y;
  12640. if (root0 >= 0.0 && root1 >= 0.0) {
  12641. var y0 = Math.sqrt(root0);
  12642. var y1 = Math.sqrt(root1);
  12643. return [temp - y1, temp - y0, temp + y0, temp + y1];
  12644. } else if (root0 >= 0.0 && root1 < 0.0) {
  12645. y = Math.sqrt(root0);
  12646. return [temp - y, temp + y];
  12647. } else if (root0 < 0.0 && root1 >= 0.0) {
  12648. y = Math.sqrt(root1);
  12649. return [temp - y, temp + y];
  12650. }
  12651. }
  12652. return [];
  12653. } else if (hSquared > 0.0) {
  12654. var h = Math.sqrt(hSquared);
  12655. var m = (p + hSquared - q / h) / 2.0;
  12656. var n = (p + hSquared + q / h) / 2.0;
  12657. // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n);
  12658. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
  12659. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);
  12660. if (roots1.length !== 0) {
  12661. roots1[0] += temp;
  12662. roots1[1] += temp;
  12663. if (roots2.length !== 0) {
  12664. roots2[0] += temp;
  12665. roots2[1] += temp;
  12666. if (roots1[1] <= roots2[0]) {
  12667. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  12668. } else if (roots2[1] <= roots1[0]) {
  12669. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  12670. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  12671. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  12672. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  12673. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  12674. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  12675. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  12676. }
  12677. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  12678. }
  12679. return roots1;
  12680. }
  12681. if (roots2.length !== 0) {
  12682. roots2[0] += temp;
  12683. roots2[1] += temp;
  12684. return roots2;
  12685. }
  12686. return [];
  12687. }
  12688. }
  12689. return [];
  12690. }
  12691. function neumark(a3, a2, a1, a0) {
  12692. var a1Squared = a1 * a1;
  12693. var a2Squared = a2 * a2;
  12694. var a3Squared = a3 * a3;
  12695. var p = -2.0 * a2;
  12696. var q = a1 * a3 + a2Squared - 4.0 * a0;
  12697. var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;
  12698. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);
  12699. if (cubicRoots.length > 0) {
  12700. // Use the most positive root
  12701. var y = cubicRoots[0];
  12702. var temp = (a2 - y);
  12703. var tempSquared = temp * temp;
  12704. var g1 = a3 / 2.0;
  12705. var h1 = temp / 2.0;
  12706. var m = tempSquared - 4.0 * a0;
  12707. var mError = tempSquared + 4.0 * Math.abs(a0);
  12708. var n = a3Squared - 4.0 * y;
  12709. var nError = a3Squared + 4.0 * Math.abs(y);
  12710. var g2;
  12711. var h2;
  12712. if (y < 0.0 || (m * nError < n * mError)) {
  12713. var squareRootOfN = Math.sqrt(n);
  12714. g2 = squareRootOfN / 2.0;
  12715. h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
  12716. } else {
  12717. var squareRootOfM = Math.sqrt(m);
  12718. g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
  12719. h2 = squareRootOfM / 2.0;
  12720. }
  12721. var G;
  12722. var g;
  12723. if (g1 === 0.0 && g2 === 0.0) {
  12724. G = 0.0;
  12725. g = 0.0;
  12726. } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
  12727. G = g1 + g2;
  12728. g = y / G;
  12729. } else {
  12730. g = g1 - g2;
  12731. G = y / g;
  12732. }
  12733. var H;
  12734. var h;
  12735. if (h1 === 0.0 && h2 === 0.0) {
  12736. H = 0.0;
  12737. h = 0.0;
  12738. } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
  12739. H = h1 + h2;
  12740. h = a0 / H;
  12741. } else {
  12742. h = h1 - h2;
  12743. H = a0 / h;
  12744. }
  12745. // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h);
  12746. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
  12747. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);
  12748. if (roots1.length !== 0) {
  12749. if (roots2.length !== 0) {
  12750. if (roots1[1] <= roots2[0]) {
  12751. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  12752. } else if (roots2[1] <= roots1[0]) {
  12753. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  12754. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  12755. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  12756. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  12757. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  12758. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  12759. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  12760. } else {
  12761. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  12762. }
  12763. }
  12764. return roots1;
  12765. }
  12766. if (roots2.length !== 0) {
  12767. return roots2;
  12768. }
  12769. }
  12770. return [];
  12771. }
  12772. /**
  12773. * Provides the real valued roots of the quartic polynomial with the provided coefficients.
  12774. *
  12775. * @param {Number} a The coefficient of the 4th order monomial.
  12776. * @param {Number} b The coefficient of the 3rd order monomial.
  12777. * @param {Number} c The coefficient of the 2nd order monomial.
  12778. * @param {Number} d The coefficient of the 1st order monomial.
  12779. * @param {Number} e The coefficient of the 0th order monomial.
  12780. * @returns {Number[]} The real valued roots.
  12781. */
  12782. QuarticRealPolynomial.computeRealRoots = function(a, b, c, d, e) {
  12783. if (typeof a !== 'number') {
  12784. throw new DeveloperError('a is a required number.');
  12785. }
  12786. if (typeof b !== 'number') {
  12787. throw new DeveloperError('b is a required number.');
  12788. }
  12789. if (typeof c !== 'number') {
  12790. throw new DeveloperError('c is a required number.');
  12791. }
  12792. if (typeof d !== 'number') {
  12793. throw new DeveloperError('d is a required number.');
  12794. }
  12795. if (typeof e !== 'number') {
  12796. throw new DeveloperError('e is a required number.');
  12797. }
  12798. if (Math.abs(a) < CesiumMath.EPSILON15) {
  12799. return CubicRealPolynomial.computeRealRoots(b, c, d, e);
  12800. }
  12801. var a3 = b / a;
  12802. var a2 = c / a;
  12803. var a1 = d / a;
  12804. var a0 = e / a;
  12805. var k = (a3 < 0.0) ? 1 : 0;
  12806. k += (a2 < 0.0) ? k + 1 : k;
  12807. k += (a1 < 0.0) ? k + 1 : k;
  12808. k += (a0 < 0.0) ? k + 1 : k;
  12809. switch (k) {
  12810. case 0:
  12811. return original(a3, a2, a1, a0);
  12812. case 1:
  12813. return neumark(a3, a2, a1, a0);
  12814. case 2:
  12815. return neumark(a3, a2, a1, a0);
  12816. case 3:
  12817. return original(a3, a2, a1, a0);
  12818. case 4:
  12819. return original(a3, a2, a1, a0);
  12820. case 5:
  12821. return neumark(a3, a2, a1, a0);
  12822. case 6:
  12823. return original(a3, a2, a1, a0);
  12824. case 7:
  12825. return original(a3, a2, a1, a0);
  12826. case 8:
  12827. return neumark(a3, a2, a1, a0);
  12828. case 9:
  12829. return original(a3, a2, a1, a0);
  12830. case 10:
  12831. return original(a3, a2, a1, a0);
  12832. case 11:
  12833. return neumark(a3, a2, a1, a0);
  12834. case 12:
  12835. return original(a3, a2, a1, a0);
  12836. case 13:
  12837. return original(a3, a2, a1, a0);
  12838. case 14:
  12839. return original(a3, a2, a1, a0);
  12840. case 15:
  12841. return original(a3, a2, a1, a0);
  12842. default:
  12843. return undefined;
  12844. }
  12845. };
  12846. return QuarticRealPolynomial;
  12847. });
  12848. /*global define*/
  12849. define('Core/Ray',[
  12850. './Cartesian3',
  12851. './defaultValue',
  12852. './defined',
  12853. './DeveloperError'
  12854. ], function(
  12855. Cartesian3,
  12856. defaultValue,
  12857. defined,
  12858. DeveloperError) {
  12859. 'use strict';
  12860. /**
  12861. * Represents a ray that extends infinitely from the provided origin in the provided direction.
  12862. * @alias Ray
  12863. * @constructor
  12864. *
  12865. * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
  12866. * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
  12867. */
  12868. function Ray(origin, direction) {
  12869. direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
  12870. if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
  12871. Cartesian3.normalize(direction, direction);
  12872. }
  12873. /**
  12874. * The origin of the ray.
  12875. * @type {Cartesian3}
  12876. * @default {@link Cartesian3.ZERO}
  12877. */
  12878. this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));
  12879. /**
  12880. * The direction of the ray.
  12881. * @type {Cartesian3}
  12882. */
  12883. this.direction = direction;
  12884. }
  12885. /**
  12886. * Computes the point along the ray given by r(t) = o + t*d,
  12887. * where o is the origin of the ray and d is the direction.
  12888. *
  12889. * @param {Ray} ray The ray.
  12890. * @param {Number} t A scalar value.
  12891. * @param {Cartesian3} [result] The object in which the result will be stored.
  12892. * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
  12893. *
  12894. * @example
  12895. * //Get the first intersection point of a ray and an ellipsoid.
  12896. * var intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
  12897. * var point = Cesium.Ray.getPoint(ray, intersection.start);
  12898. */
  12899. Ray.getPoint = function(ray, t, result) {
  12900. if (!defined(ray)){
  12901. throw new DeveloperError('ray is requred');
  12902. }
  12903. if (typeof t !== 'number') {
  12904. throw new DeveloperError('t is a required number');
  12905. }
  12906. if (!defined(result)) {
  12907. result = new Cartesian3();
  12908. }
  12909. result = Cartesian3.multiplyByScalar(ray.direction, t, result);
  12910. return Cartesian3.add(ray.origin, result, result);
  12911. };
  12912. return Ray;
  12913. });
  12914. /*global define*/
  12915. define('Core/IntersectionTests',[
  12916. './Cartesian3',
  12917. './Cartographic',
  12918. './defaultValue',
  12919. './defined',
  12920. './DeveloperError',
  12921. './Math',
  12922. './Matrix3',
  12923. './QuadraticRealPolynomial',
  12924. './QuarticRealPolynomial',
  12925. './Ray'
  12926. ], function(
  12927. Cartesian3,
  12928. Cartographic,
  12929. defaultValue,
  12930. defined,
  12931. DeveloperError,
  12932. CesiumMath,
  12933. Matrix3,
  12934. QuadraticRealPolynomial,
  12935. QuarticRealPolynomial,
  12936. Ray) {
  12937. 'use strict';
  12938. /**
  12939. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  12940. *
  12941. * @exports IntersectionTests
  12942. */
  12943. var IntersectionTests = {};
  12944. /**
  12945. * Computes the intersection of a ray and a plane.
  12946. *
  12947. * @param {Ray} ray The ray.
  12948. * @param {Plane} plane The plane.
  12949. * @param {Cartesian3} [result] The object onto which to store the result.
  12950. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  12951. */
  12952. IntersectionTests.rayPlane = function(ray, plane, result) {
  12953. if (!defined(ray)) {
  12954. throw new DeveloperError('ray is required.');
  12955. }
  12956. if (!defined(plane)) {
  12957. throw new DeveloperError('plane is required.');
  12958. }
  12959. if (!defined(result)) {
  12960. result = new Cartesian3();
  12961. }
  12962. var origin = ray.origin;
  12963. var direction = ray.direction;
  12964. var normal = plane.normal;
  12965. var denominator = Cartesian3.dot(normal, direction);
  12966. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  12967. // Ray is parallel to plane. The ray may be in the polygon's plane.
  12968. return undefined;
  12969. }
  12970. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  12971. if (t < 0) {
  12972. return undefined;
  12973. }
  12974. result = Cartesian3.multiplyByScalar(direction, t, result);
  12975. return Cartesian3.add(origin, result, result);
  12976. };
  12977. var scratchEdge0 = new Cartesian3();
  12978. var scratchEdge1 = new Cartesian3();
  12979. var scratchPVec = new Cartesian3();
  12980. var scratchTVec = new Cartesian3();
  12981. var scratchQVec = new Cartesian3();
  12982. /**
  12983. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  12984. *
  12985. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  12986. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  12987. *
  12988. * @memberof IntersectionTests
  12989. *
  12990. * @param {Ray} ray The ray.
  12991. * @param {Cartesian3} p0 The first vertex of the triangle.
  12992. * @param {Cartesian3} p1 The second vertex of the triangle.
  12993. * @param {Cartesian3} p2 The third vertex of the triangle.
  12994. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  12995. * and return undefined for intersections with the back face.
  12996. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  12997. */
  12998. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  12999. if (!defined(ray)) {
  13000. throw new DeveloperError('ray is required.');
  13001. }
  13002. if (!defined(p0)) {
  13003. throw new DeveloperError('p0 is required.');
  13004. }
  13005. if (!defined(p1)) {
  13006. throw new DeveloperError('p1 is required.');
  13007. }
  13008. if (!defined(p2)) {
  13009. throw new DeveloperError('p2 is required.');
  13010. }
  13011. cullBackFaces = defaultValue(cullBackFaces, false);
  13012. var origin = ray.origin;
  13013. var direction = ray.direction;
  13014. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  13015. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  13016. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  13017. var det = Cartesian3.dot(edge0, p);
  13018. var tvec;
  13019. var q;
  13020. var u;
  13021. var v;
  13022. var t;
  13023. if (cullBackFaces) {
  13024. if (det < CesiumMath.EPSILON6) {
  13025. return undefined;
  13026. }
  13027. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  13028. u = Cartesian3.dot(tvec, p);
  13029. if (u < 0.0 || u > det) {
  13030. return undefined;
  13031. }
  13032. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  13033. v = Cartesian3.dot(direction, q);
  13034. if (v < 0.0 || u + v > det) {
  13035. return undefined;
  13036. }
  13037. t = Cartesian3.dot(edge1, q) / det;
  13038. } else {
  13039. if (Math.abs(det) < CesiumMath.EPSILON6) {
  13040. return undefined;
  13041. }
  13042. var invDet = 1.0 / det;
  13043. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  13044. u = Cartesian3.dot(tvec, p) * invDet;
  13045. if (u < 0.0 || u > 1.0) {
  13046. return undefined;
  13047. }
  13048. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  13049. v = Cartesian3.dot(direction, q) * invDet;
  13050. if (v < 0.0 || u + v > 1.0) {
  13051. return undefined;
  13052. }
  13053. t = Cartesian3.dot(edge1, q) * invDet;
  13054. }
  13055. return t;
  13056. };
  13057. /**
  13058. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  13059. *
  13060. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  13061. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  13062. *
  13063. * @memberof IntersectionTests
  13064. *
  13065. * @param {Ray} ray The ray.
  13066. * @param {Cartesian3} p0 The first vertex of the triangle.
  13067. * @param {Cartesian3} p1 The second vertex of the triangle.
  13068. * @param {Cartesian3} p2 The third vertex of the triangle.
  13069. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  13070. * and return undefined for intersections with the back face.
  13071. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  13072. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  13073. */
  13074. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  13075. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  13076. if (!defined(t) || t < 0.0) {
  13077. return undefined;
  13078. }
  13079. if (!defined(result)) {
  13080. result = new Cartesian3();
  13081. }
  13082. Cartesian3.multiplyByScalar(ray.direction, t, result);
  13083. return Cartesian3.add(ray.origin, result, result);
  13084. };
  13085. var scratchLineSegmentTriangleRay = new Ray();
  13086. /**
  13087. * Computes the intersection of a line segment and a triangle.
  13088. * @memberof IntersectionTests
  13089. *
  13090. * @param {Cartesian3} v0 The an end point of the line segment.
  13091. * @param {Cartesian3} v1 The other end point of the line segment.
  13092. * @param {Cartesian3} p0 The first vertex of the triangle.
  13093. * @param {Cartesian3} p1 The second vertex of the triangle.
  13094. * @param {Cartesian3} p2 The third vertex of the triangle.
  13095. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  13096. * and return undefined for intersections with the back face.
  13097. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  13098. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  13099. */
  13100. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  13101. if (!defined(v0)) {
  13102. throw new DeveloperError('v0 is required.');
  13103. }
  13104. if (!defined(v1)) {
  13105. throw new DeveloperError('v1 is required.');
  13106. }
  13107. if (!defined(p0)) {
  13108. throw new DeveloperError('p0 is required.');
  13109. }
  13110. if (!defined(p1)) {
  13111. throw new DeveloperError('p1 is required.');
  13112. }
  13113. if (!defined(p2)) {
  13114. throw new DeveloperError('p2 is required.');
  13115. }
  13116. var ray = scratchLineSegmentTriangleRay;
  13117. Cartesian3.clone(v0, ray.origin);
  13118. Cartesian3.subtract(v1, v0, ray.direction);
  13119. Cartesian3.normalize(ray.direction, ray.direction);
  13120. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  13121. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  13122. return undefined;
  13123. }
  13124. if (!defined(result)) {
  13125. result = new Cartesian3();
  13126. }
  13127. Cartesian3.multiplyByScalar(ray.direction, t, result);
  13128. return Cartesian3.add(ray.origin, result, result);
  13129. };
  13130. function solveQuadratic(a, b, c, result) {
  13131. var det = b * b - 4.0 * a * c;
  13132. if (det < 0.0) {
  13133. return undefined;
  13134. } else if (det > 0.0) {
  13135. var denom = 1.0 / (2.0 * a);
  13136. var disc = Math.sqrt(det);
  13137. var root0 = (-b + disc) * denom;
  13138. var root1 = (-b - disc) * denom;
  13139. if (root0 < root1) {
  13140. result.root0 = root0;
  13141. result.root1 = root1;
  13142. } else {
  13143. result.root0 = root1;
  13144. result.root1 = root0;
  13145. }
  13146. return result;
  13147. }
  13148. var root = -b / (2.0 * a);
  13149. if (root === 0.0) {
  13150. return undefined;
  13151. }
  13152. result.root0 = result.root1 = root;
  13153. return result;
  13154. }
  13155. var raySphereRoots = {
  13156. root0 : 0.0,
  13157. root1 : 0.0
  13158. };
  13159. function raySphere(ray, sphere, result) {
  13160. if (!defined(result)) {
  13161. result = {};
  13162. }
  13163. var origin = ray.origin;
  13164. var direction = ray.direction;
  13165. var center = sphere.center;
  13166. var radiusSquared = sphere.radius * sphere.radius;
  13167. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  13168. var a = Cartesian3.dot(direction, direction);
  13169. var b = 2.0 * Cartesian3.dot(direction, diff);
  13170. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  13171. var roots = solveQuadratic(a, b, c, raySphereRoots);
  13172. if (!defined(roots)) {
  13173. return undefined;
  13174. }
  13175. result.start = roots.root0;
  13176. result.stop = roots.root1;
  13177. return result;
  13178. }
  13179. /**
  13180. * Computes the intersection points of a ray with a sphere.
  13181. * @memberof IntersectionTests
  13182. *
  13183. * @param {Ray} ray The ray.
  13184. * @param {BoundingSphere} sphere The sphere.
  13185. * @param {Object} [result] The result onto which to store the result.
  13186. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the ray or undefined if there are no intersections.
  13187. */
  13188. IntersectionTests.raySphere = function(ray, sphere, result) {
  13189. if (!defined(ray)) {
  13190. throw new DeveloperError('ray is required.');
  13191. }
  13192. if (!defined(sphere)) {
  13193. throw new DeveloperError('sphere is required.');
  13194. }
  13195. result = raySphere(ray, sphere, result);
  13196. if (!defined(result) || result.stop < 0.0) {
  13197. return undefined;
  13198. }
  13199. result.start = Math.max(result.start, 0.0);
  13200. return result;
  13201. };
  13202. var scratchLineSegmentRay = new Ray();
  13203. /**
  13204. * Computes the intersection points of a line segment with a sphere.
  13205. * @memberof IntersectionTests
  13206. *
  13207. * @param {Cartesian3} p0 An end point of the line segment.
  13208. * @param {Cartesian3} p1 The other end point of the line segment.
  13209. * @param {BoundingSphere} sphere The sphere.
  13210. * @param {Object} [result] The result onto which to store the result.
  13211. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the line segment or undefined if there are no intersections.
  13212. */
  13213. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  13214. if (!defined(p0)) {
  13215. throw new DeveloperError('p0 is required.');
  13216. }
  13217. if (!defined(p1)) {
  13218. throw new DeveloperError('p1 is required.');
  13219. }
  13220. if (!defined(sphere)) {
  13221. throw new DeveloperError('sphere is required.');
  13222. }
  13223. var ray = scratchLineSegmentRay;
  13224. Cartesian3.clone(p0, ray.origin);
  13225. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  13226. var maxT = Cartesian3.magnitude(direction);
  13227. Cartesian3.normalize(direction, direction);
  13228. result = raySphere(ray, sphere, result);
  13229. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  13230. return undefined;
  13231. }
  13232. result.start = Math.max(result.start, 0.0);
  13233. result.stop = Math.min(result.stop, maxT);
  13234. return result;
  13235. };
  13236. var scratchQ = new Cartesian3();
  13237. var scratchW = new Cartesian3();
  13238. /**
  13239. * Computes the intersection points of a ray with an ellipsoid.
  13240. *
  13241. * @param {Ray} ray The ray.
  13242. * @param {Ellipsoid} ellipsoid The ellipsoid.
  13243. * @returns {Object} An object with the first (<code>start</code>) and the second (<code>stop</code>) intersection scalars for points along the ray or undefined if there are no intersections.
  13244. */
  13245. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  13246. if (!defined(ray)) {
  13247. throw new DeveloperError('ray is required.');
  13248. }
  13249. if (!defined(ellipsoid)) {
  13250. throw new DeveloperError('ellipsoid is required.');
  13251. }
  13252. var inverseRadii = ellipsoid.oneOverRadii;
  13253. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  13254. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  13255. var q2 = Cartesian3.magnitudeSquared(q);
  13256. var qw = Cartesian3.dot(q, w);
  13257. var difference, w2, product, discriminant, temp;
  13258. if (q2 > 1.0) {
  13259. // Outside ellipsoid.
  13260. if (qw >= 0.0) {
  13261. // Looking outward or tangent (0 intersections).
  13262. return undefined;
  13263. }
  13264. // qw < 0.0.
  13265. var qw2 = qw * qw;
  13266. difference = q2 - 1.0; // Positively valued.
  13267. w2 = Cartesian3.magnitudeSquared(w);
  13268. product = w2 * difference;
  13269. if (qw2 < product) {
  13270. // Imaginary roots (0 intersections).
  13271. return undefined;
  13272. } else if (qw2 > product) {
  13273. // Distinct roots (2 intersections).
  13274. discriminant = qw * qw - product;
  13275. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  13276. var root0 = temp / w2;
  13277. var root1 = difference / temp;
  13278. if (root0 < root1) {
  13279. return {
  13280. start : root0,
  13281. stop : root1
  13282. };
  13283. }
  13284. return {
  13285. start : root1,
  13286. stop : root0
  13287. };
  13288. } else {
  13289. // qw2 == product. Repeated roots (2 intersections).
  13290. var root = Math.sqrt(difference / w2);
  13291. return {
  13292. start : root,
  13293. stop : root
  13294. };
  13295. }
  13296. } else if (q2 < 1.0) {
  13297. // Inside ellipsoid (2 intersections).
  13298. difference = q2 - 1.0; // Negatively valued.
  13299. w2 = Cartesian3.magnitudeSquared(w);
  13300. product = w2 * difference; // Negatively valued.
  13301. discriminant = qw * qw - product;
  13302. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  13303. return {
  13304. start : 0.0,
  13305. stop : temp / w2
  13306. };
  13307. } else {
  13308. // q2 == 1.0. On ellipsoid.
  13309. if (qw < 0.0) {
  13310. // Looking inward.
  13311. w2 = Cartesian3.magnitudeSquared(w);
  13312. return {
  13313. start : 0.0,
  13314. stop : -qw / w2
  13315. };
  13316. }
  13317. // qw >= 0.0. Looking outward or tangent.
  13318. return undefined;
  13319. }
  13320. };
  13321. function addWithCancellationCheck(left, right, tolerance) {
  13322. var difference = left + right;
  13323. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  13324. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  13325. return 0.0;
  13326. }
  13327. return difference;
  13328. }
  13329. function quadraticVectorExpression(A, b, c, x, w) {
  13330. var xSquared = x * x;
  13331. var wSquared = w * w;
  13332. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  13333. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  13334. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  13335. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  13336. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  13337. var cosines;
  13338. var solutions = [];
  13339. if (r0 === 0.0 && r1 === 0.0) {
  13340. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  13341. if (cosines.length === 0) {
  13342. return solutions;
  13343. }
  13344. var cosine0 = cosines[0];
  13345. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  13346. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  13347. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  13348. if (cosines.length === 2) {
  13349. var cosine1 = cosines[1];
  13350. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  13351. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  13352. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  13353. }
  13354. return solutions;
  13355. }
  13356. var r0Squared = r0 * r0;
  13357. var r1Squared = r1 * r1;
  13358. var l2Squared = l2 * l2;
  13359. var r0r1 = r0 * r1;
  13360. var c4 = l2Squared + r1Squared;
  13361. var c3 = 2.0 * (l1 * l2 + r0r1);
  13362. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  13363. var c1 = 2.0 * (l0 * l1 - r0r1);
  13364. var c0 = l0 * l0 - r0Squared;
  13365. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  13366. return solutions;
  13367. }
  13368. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  13369. var length = cosines.length;
  13370. if (length === 0) {
  13371. return solutions;
  13372. }
  13373. for ( var i = 0; i < length; ++i) {
  13374. var cosine = cosines[i];
  13375. var cosineSquared = cosine * cosine;
  13376. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  13377. var sine = Math.sqrt(sineSquared);
  13378. //var left = l2 * cosineSquared + l1 * cosine + l0;
  13379. var left;
  13380. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  13381. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  13382. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  13383. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  13384. } else {
  13385. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  13386. }
  13387. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  13388. var product = left * right;
  13389. if (product < 0.0) {
  13390. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  13391. } else if (product > 0.0) {
  13392. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  13393. } else if (sine !== 0.0) {
  13394. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  13395. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  13396. ++i;
  13397. } else {
  13398. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  13399. }
  13400. }
  13401. return solutions;
  13402. }
  13403. var firstAxisScratch = new Cartesian3();
  13404. var secondAxisScratch = new Cartesian3();
  13405. var thirdAxisScratch = new Cartesian3();
  13406. var referenceScratch = new Cartesian3();
  13407. var bCart = new Cartesian3();
  13408. var bScratch = new Matrix3();
  13409. var btScratch = new Matrix3();
  13410. var diScratch = new Matrix3();
  13411. var dScratch = new Matrix3();
  13412. var cScratch = new Matrix3();
  13413. var tempMatrix = new Matrix3();
  13414. var aScratch = new Matrix3();
  13415. var sScratch = new Cartesian3();
  13416. var closestScratch = new Cartesian3();
  13417. var surfPointScratch = new Cartographic();
  13418. /**
  13419. * Provides the point along the ray which is nearest to the ellipsoid.
  13420. *
  13421. * @param {Ray} ray The ray.
  13422. * @param {Ellipsoid} ellipsoid The ellipsoid.
  13423. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  13424. */
  13425. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  13426. if (!defined(ray)) {
  13427. throw new DeveloperError('ray is required.');
  13428. }
  13429. if (!defined(ellipsoid)) {
  13430. throw new DeveloperError('ellipsoid is required.');
  13431. }
  13432. var position = ray.origin;
  13433. var direction = ray.direction;
  13434. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  13435. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  13436. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  13437. return position;
  13438. }
  13439. }
  13440. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  13441. // Compute the scaled direction vector.
  13442. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  13443. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  13444. var firstAxis = Cartesian3.normalize(f, f);
  13445. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  13446. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  13447. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  13448. var B = bScratch;
  13449. B[0] = firstAxis.x;
  13450. B[1] = firstAxis.y;
  13451. B[2] = firstAxis.z;
  13452. B[3] = secondAxis.x;
  13453. B[4] = secondAxis.y;
  13454. B[5] = secondAxis.z;
  13455. B[6] = thirdAxis.x;
  13456. B[7] = thirdAxis.y;
  13457. B[8] = thirdAxis.z;
  13458. var B_T = Matrix3.transpose(B, btScratch);
  13459. // Get the scaling matrix and its inverse.
  13460. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  13461. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  13462. var C = cScratch;
  13463. C[0] = 0.0;
  13464. C[1] = -direction.z;
  13465. C[2] = direction.y;
  13466. C[3] = direction.z;
  13467. C[4] = 0.0;
  13468. C[5] = -direction.x;
  13469. C[6] = -direction.y;
  13470. C[7] = direction.x;
  13471. C[8] = 0.0;
  13472. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  13473. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  13474. var b = Matrix3.multiplyByVector(temp, position, bCart);
  13475. // Solve for the solutions to the expression in standard form:
  13476. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  13477. var s;
  13478. var altitude;
  13479. var length = solutions.length;
  13480. if (length > 0) {
  13481. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  13482. var maximumValue = Number.NEGATIVE_INFINITY;
  13483. for ( var i = 0; i < length; ++i) {
  13484. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  13485. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  13486. var dotProduct = Cartesian3.dot(v, direction);
  13487. if (dotProduct > maximumValue) {
  13488. maximumValue = dotProduct;
  13489. closest = Cartesian3.clone(s, closest);
  13490. }
  13491. }
  13492. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  13493. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  13494. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  13495. altitude = intersects ? -altitude : altitude;
  13496. surfacePoint.height = altitude;
  13497. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  13498. }
  13499. return undefined;
  13500. };
  13501. var lineSegmentPlaneDifference = new Cartesian3();
  13502. /**
  13503. * Computes the intersection of a line segment and a plane.
  13504. *
  13505. * @param {Cartesian3} endPoint0 An end point of the line segment.
  13506. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  13507. * @param {Plane} plane The plane.
  13508. * @param {Cartesian3} [result] The object onto which to store the result.
  13509. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  13510. *
  13511. * @example
  13512. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  13513. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  13514. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  13515. *
  13516. * var p0 = new Cesium.Cartesian3(...);
  13517. * var p1 = new Cesium.Cartesian3(...);
  13518. *
  13519. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  13520. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  13521. */
  13522. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  13523. if (!defined(endPoint0)) {
  13524. throw new DeveloperError('endPoint0 is required.');
  13525. }
  13526. if (!defined(endPoint1)) {
  13527. throw new DeveloperError('endPoint1 is required.');
  13528. }
  13529. if (!defined(plane)) {
  13530. throw new DeveloperError('plane is required.');
  13531. }
  13532. if (!defined(result)) {
  13533. result = new Cartesian3();
  13534. }
  13535. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  13536. var normal = plane.normal;
  13537. var nDotDiff = Cartesian3.dot(normal, difference);
  13538. // check if the segment and plane are parallel
  13539. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  13540. return undefined;
  13541. }
  13542. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  13543. var t = -(plane.distance + nDotP0) / nDotDiff;
  13544. // intersection only if t is in [0, 1]
  13545. if (t < 0.0 || t > 1.0) {
  13546. return undefined;
  13547. }
  13548. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  13549. Cartesian3.multiplyByScalar(difference, t, result);
  13550. Cartesian3.add(endPoint0, result, result);
  13551. return result;
  13552. };
  13553. /**
  13554. * Computes the intersection of a triangle and a plane
  13555. *
  13556. * @param {Cartesian3} p0 First point of the triangle
  13557. * @param {Cartesian3} p1 Second point of the triangle
  13558. * @param {Cartesian3} p2 Third point of the triangle
  13559. * @param {Plane} plane Intersection plane
  13560. * @returns {Object} An object with properties <code>positions</code> and <code>indices</code>, which are arrays that represent three triangles that do not cross the plane. (Undefined if no intersection exists)
  13561. *
  13562. * @example
  13563. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  13564. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  13565. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  13566. *
  13567. * var p0 = new Cesium.Cartesian3(...);
  13568. * var p1 = new Cesium.Cartesian3(...);
  13569. * var p2 = new Cesium.Cartesian3(...);
  13570. *
  13571. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  13572. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  13573. */
  13574. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  13575. if ((!defined(p0)) ||
  13576. (!defined(p1)) ||
  13577. (!defined(p2)) ||
  13578. (!defined(plane))) {
  13579. throw new DeveloperError('p0, p1, p2, and plane are required.');
  13580. }
  13581. var planeNormal = plane.normal;
  13582. var planeD = plane.distance;
  13583. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  13584. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  13585. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  13586. // Given these dots products, the calls to lineSegmentPlaneIntersection
  13587. // always have defined results.
  13588. var numBehind = 0;
  13589. numBehind += p0Behind ? 1 : 0;
  13590. numBehind += p1Behind ? 1 : 0;
  13591. numBehind += p2Behind ? 1 : 0;
  13592. var u1, u2;
  13593. if (numBehind === 1 || numBehind === 2) {
  13594. u1 = new Cartesian3();
  13595. u2 = new Cartesian3();
  13596. }
  13597. if (numBehind === 1) {
  13598. if (p0Behind) {
  13599. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  13600. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  13601. return {
  13602. positions : [p0, p1, p2, u1, u2 ],
  13603. indices : [
  13604. // Behind
  13605. 0, 3, 4,
  13606. // In front
  13607. 1, 2, 4,
  13608. 1, 4, 3
  13609. ]
  13610. };
  13611. } else if (p1Behind) {
  13612. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  13613. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  13614. return {
  13615. positions : [p0, p1, p2, u1, u2 ],
  13616. indices : [
  13617. // Behind
  13618. 1, 3, 4,
  13619. // In front
  13620. 2, 0, 4,
  13621. 2, 4, 3
  13622. ]
  13623. };
  13624. } else if (p2Behind) {
  13625. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  13626. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  13627. return {
  13628. positions : [p0, p1, p2, u1, u2 ],
  13629. indices : [
  13630. // Behind
  13631. 2, 3, 4,
  13632. // In front
  13633. 0, 1, 4,
  13634. 0, 4, 3
  13635. ]
  13636. };
  13637. }
  13638. } else if (numBehind === 2) {
  13639. if (!p0Behind) {
  13640. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  13641. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  13642. return {
  13643. positions : [p0, p1, p2, u1, u2 ],
  13644. indices : [
  13645. // Behind
  13646. 1, 2, 4,
  13647. 1, 4, 3,
  13648. // In front
  13649. 0, 3, 4
  13650. ]
  13651. };
  13652. } else if (!p1Behind) {
  13653. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  13654. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  13655. return {
  13656. positions : [p0, p1, p2, u1, u2 ],
  13657. indices : [
  13658. // Behind
  13659. 2, 0, 4,
  13660. 2, 4, 3,
  13661. // In front
  13662. 1, 3, 4
  13663. ]
  13664. };
  13665. } else if (!p2Behind) {
  13666. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  13667. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  13668. return {
  13669. positions : [p0, p1, p2, u1, u2 ],
  13670. indices : [
  13671. // Behind
  13672. 0, 1, 4,
  13673. 0, 4, 3,
  13674. // In front
  13675. 2, 3, 4
  13676. ]
  13677. };
  13678. }
  13679. }
  13680. // if numBehind is 3, the triangle is completely behind the plane;
  13681. // otherwise, it is completely in front (numBehind is 0).
  13682. return undefined;
  13683. };
  13684. return IntersectionTests;
  13685. });
  13686. /*global define*/
  13687. define('Core/Plane',[
  13688. './Cartesian3',
  13689. './defined',
  13690. './DeveloperError',
  13691. './freezeObject'
  13692. ], function(
  13693. Cartesian3,
  13694. defined,
  13695. DeveloperError,
  13696. freezeObject) {
  13697. 'use strict';
  13698. /**
  13699. * A plane in Hessian Normal Form defined by
  13700. * <pre>
  13701. * ax + by + cz + d = 0
  13702. * </pre>
  13703. * where (a, b, c) is the plane's <code>normal</code>, d is the signed
  13704. * <code>distance</code> to the plane, and (x, y, z) is any point on
  13705. * the plane.
  13706. *
  13707. * @alias Plane
  13708. * @constructor
  13709. *
  13710. * @param {Cartesian3} normal The plane's normal (normalized).
  13711. * @param {Number} distance The shortest distance from the origin to the plane. The sign of
  13712. * <code>distance</code> determines which side of the plane the origin
  13713. * is on. If <code>distance</code> is positive, the origin is in the half-space
  13714. * in the direction of the normal; if negative, the origin is in the half-space
  13715. * opposite to the normal; if zero, the plane passes through the origin.
  13716. *
  13717. * @example
  13718. * // The plane x=0
  13719. * var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
  13720. */
  13721. function Plane(normal, distance) {
  13722. if (!defined(normal)) {
  13723. throw new DeveloperError('normal is required.');
  13724. }
  13725. if (!defined(distance)) {
  13726. throw new DeveloperError('distance is required.');
  13727. }
  13728. /**
  13729. * The plane's normal.
  13730. *
  13731. * @type {Cartesian3}
  13732. */
  13733. this.normal = Cartesian3.clone(normal);
  13734. /**
  13735. * The shortest distance from the origin to the plane. The sign of
  13736. * <code>distance</code> determines which side of the plane the origin
  13737. * is on. If <code>distance</code> is positive, the origin is in the half-space
  13738. * in the direction of the normal; if negative, the origin is in the half-space
  13739. * opposite to the normal; if zero, the plane passes through the origin.
  13740. *
  13741. * @type {Number}
  13742. */
  13743. this.distance = distance;
  13744. }
  13745. /**
  13746. * Creates a plane from a normal and a point on the plane.
  13747. *
  13748. * @param {Cartesian3} point The point on the plane.
  13749. * @param {Cartesian3} normal The plane's normal (normalized).
  13750. * @param {Plane} [result] The object onto which to store the result.
  13751. * @returns {Plane} A new plane instance or the modified result parameter.
  13752. *
  13753. * @example
  13754. * var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  13755. * var normal = ellipsoid.geodeticSurfaceNormal(point);
  13756. * var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
  13757. */
  13758. Plane.fromPointNormal = function(point, normal, result) {
  13759. if (!defined(point)) {
  13760. throw new DeveloperError('point is required.');
  13761. }
  13762. if (!defined(normal)) {
  13763. throw new DeveloperError('normal is required.');
  13764. }
  13765. var distance = -Cartesian3.dot(normal, point);
  13766. if (!defined(result)) {
  13767. return new Plane(normal, distance);
  13768. }
  13769. Cartesian3.clone(normal, result.normal);
  13770. result.distance = distance;
  13771. return result;
  13772. };
  13773. var scratchNormal = new Cartesian3();
  13774. /**
  13775. * Creates a plane from the general equation
  13776. *
  13777. * @param {Cartesian4} coefficients The plane's normal (normalized).
  13778. * @param {Plane} [result] The object onto which to store the result.
  13779. * @returns {Plane} A new plane instance or the modified result parameter.
  13780. */
  13781. Plane.fromCartesian4 = function(coefficients, result) {
  13782. if (!defined(coefficients)) {
  13783. throw new DeveloperError('coefficients is required.');
  13784. }
  13785. var normal = Cartesian3.fromCartesian4(coefficients, scratchNormal);
  13786. var distance = coefficients.w;
  13787. if (!defined(result)) {
  13788. return new Plane(normal, distance);
  13789. } else {
  13790. Cartesian3.clone(normal, result.normal);
  13791. result.distance = distance;
  13792. return result;
  13793. }
  13794. };
  13795. /**
  13796. * Computes the signed shortest distance of a point to a plane.
  13797. * The sign of the distance determines which side of the plane the point
  13798. * is on. If the distance is positive, the point is in the half-space
  13799. * in the direction of the normal; if negative, the point is in the half-space
  13800. * opposite to the normal; if zero, the plane passes through the point.
  13801. *
  13802. * @param {Plane} plane The plane.
  13803. * @param {Cartesian3} point The point.
  13804. * @returns {Number} The signed shortest distance of the point to the plane.
  13805. */
  13806. Plane.getPointDistance = function(plane, point) {
  13807. if (!defined(plane)) {
  13808. throw new DeveloperError('plane is required.');
  13809. }
  13810. if (!defined(point)) {
  13811. throw new DeveloperError('point is required.');
  13812. }
  13813. return Cartesian3.dot(plane.normal, point) + plane.distance;
  13814. };
  13815. /**
  13816. * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
  13817. *
  13818. * @type {Plane}
  13819. * @constant
  13820. */
  13821. Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
  13822. /**
  13823. * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
  13824. *
  13825. * @type {Plane}
  13826. * @constant
  13827. */
  13828. Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
  13829. /**
  13830. * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
  13831. *
  13832. * @type {Plane}
  13833. * @constant
  13834. */
  13835. Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));
  13836. return Plane;
  13837. });
  13838. /**
  13839. @license
  13840. when.js - https://github.com/cujojs/when
  13841. MIT License (c) copyright B Cavalier & J Hann
  13842. * A lightweight CommonJS Promises/A and when() implementation
  13843. * when is part of the cujo.js family of libraries (http://cujojs.com/)
  13844. *
  13845. * Licensed under the MIT License at:
  13846. * http://www.opensource.org/licenses/mit-license.php
  13847. *
  13848. * @version 1.7.1
  13849. */
  13850. (function(define) { 'use strict';
  13851. define('ThirdParty/when',[],function () {
  13852. var reduceArray, slice, undef;
  13853. //
  13854. // Public API
  13855. //
  13856. when.defer = defer; // Create a deferred
  13857. when.resolve = resolve; // Create a resolved promise
  13858. when.reject = reject; // Create a rejected promise
  13859. when.join = join; // Join 2 or more promises
  13860. when.all = all; // Resolve a list of promises
  13861. when.map = map; // Array.map() for promises
  13862. when.reduce = reduce; // Array.reduce() for promises
  13863. when.any = any; // One-winner race
  13864. when.some = some; // Multi-winner race
  13865. when.chain = chain; // Make a promise trigger another resolver
  13866. when.isPromise = isPromise; // Determine if a thing is a promise
  13867. /**
  13868. * Register an observer for a promise or immediate value.
  13869. *
  13870. * @param {*} promiseOrValue
  13871. * @param {function?} [onFulfilled] callback to be called when promiseOrValue is
  13872. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  13873. * will be invoked immediately.
  13874. * @param {function?} [onRejected] callback to be called when promiseOrValue is
  13875. * rejected.
  13876. * @param {function?} [onProgress] callback to be called when progress updates
  13877. * are issued for promiseOrValue.
  13878. * @returns {Promise} a new {@link Promise} that will complete with the return
  13879. * value of callback or errback or the completion value of promiseOrValue if
  13880. * callback and/or errback is not supplied.
  13881. */
  13882. function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
  13883. // Get a trusted promise for the input promiseOrValue, and then
  13884. // register promise handlers
  13885. return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
  13886. }
  13887. /**
  13888. * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
  13889. * promiseOrValue is a foreign promise, or a new, already-fulfilled {@link Promise}
  13890. * whose value is promiseOrValue if promiseOrValue is an immediate value.
  13891. *
  13892. * @param {*} promiseOrValue
  13893. * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
  13894. * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
  13895. * whose resolution value is:
  13896. * * the resolution value of promiseOrValue if it's a foreign promise, or
  13897. * * promiseOrValue if it's a value
  13898. */
  13899. function resolve(promiseOrValue) {
  13900. var promise, deferred;
  13901. if(promiseOrValue instanceof Promise) {
  13902. // It's a when.js promise, so we trust it
  13903. promise = promiseOrValue;
  13904. } else {
  13905. // It's not a when.js promise. See if it's a foreign promise or a value.
  13906. if(isPromise(promiseOrValue)) {
  13907. // It's a thenable, but we don't know where it came from, so don't trust
  13908. // its implementation entirely. Introduce a trusted middleman when.js promise
  13909. deferred = defer();
  13910. // IMPORTANT: This is the only place when.js should ever call .then() on an
  13911. // untrusted promise. Don't expose the return value to the untrusted promise
  13912. promiseOrValue.then(
  13913. function(value) { deferred.resolve(value); },
  13914. function(reason) { deferred.reject(reason); },
  13915. function(update) { deferred.progress(update); }
  13916. );
  13917. promise = deferred.promise;
  13918. } else {
  13919. // It's a value, not a promise. Create a resolved promise for it.
  13920. promise = fulfilled(promiseOrValue);
  13921. }
  13922. }
  13923. return promise;
  13924. }
  13925. /**
  13926. * Returns a rejected promise for the supplied promiseOrValue. The returned
  13927. * promise will be rejected with:
  13928. * - promiseOrValue, if it is a value, or
  13929. * - if promiseOrValue is a promise
  13930. * - promiseOrValue's value after it is fulfilled
  13931. * - promiseOrValue's reason after it is rejected
  13932. * @param {*} promiseOrValue the rejected value of the returned {@link Promise}
  13933. * @returns {Promise} rejected {@link Promise}
  13934. */
  13935. function reject(promiseOrValue) {
  13936. return when(promiseOrValue, rejected);
  13937. }
  13938. /**
  13939. * Trusted Promise constructor. A Promise created from this constructor is
  13940. * a trusted when.js promise. Any other duck-typed promise is considered
  13941. * untrusted.
  13942. * @constructor
  13943. * @name Promise
  13944. */
  13945. function Promise(then) {
  13946. this.then = then;
  13947. }
  13948. Promise.prototype = {
  13949. /**
  13950. * Register a callback that will be called when a promise is
  13951. * fulfilled or rejected. Optionally also register a progress handler.
  13952. * Shortcut for .then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress)
  13953. * @param {function?} [onFulfilledOrRejected]
  13954. * @param {function?} [onProgress]
  13955. * @returns {Promise}
  13956. */
  13957. always: function(onFulfilledOrRejected, onProgress) {
  13958. return this.then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress);
  13959. },
  13960. /**
  13961. * Register a rejection handler. Shortcut for .then(undefined, onRejected)
  13962. * @param {function?} onRejected
  13963. * @returns {Promise}
  13964. */
  13965. otherwise: function(onRejected) {
  13966. return this.then(undef, onRejected);
  13967. },
  13968. /**
  13969. * Shortcut for .then(function() { return value; })
  13970. * @param {*} value
  13971. * @returns {Promise} a promise that:
  13972. * - is fulfilled if value is not a promise, or
  13973. * - if value is a promise, will fulfill with its value, or reject
  13974. * with its reason.
  13975. */
  13976. yield: function(value) {
  13977. return this.then(function() {
  13978. return value;
  13979. });
  13980. },
  13981. /**
  13982. * Assumes that this promise will fulfill with an array, and arranges
  13983. * for the onFulfilled to be called with the array as its argument list
  13984. * i.e. onFulfilled.spread(undefined, array).
  13985. * @param {function} onFulfilled function to receive spread arguments
  13986. * @returns {Promise}
  13987. */
  13988. spread: function(onFulfilled) {
  13989. return this.then(function(array) {
  13990. // array may contain promises, so resolve its contents.
  13991. return all(array, function(array) {
  13992. return onFulfilled.apply(undef, array);
  13993. });
  13994. });
  13995. }
  13996. };
  13997. /**
  13998. * Create an already-resolved promise for the supplied value
  13999. * @private
  14000. *
  14001. * @param {*} value
  14002. * @returns {Promise} fulfilled promise
  14003. */
  14004. function fulfilled(value) {
  14005. var p = new Promise(function(onFulfilled) {
  14006. // TODO: Promises/A+ check typeof onFulfilled
  14007. try {
  14008. return resolve(onFulfilled ? onFulfilled(value) : value);
  14009. } catch(e) {
  14010. return rejected(e);
  14011. }
  14012. });
  14013. return p;
  14014. }
  14015. /**
  14016. * Create an already-rejected {@link Promise} with the supplied
  14017. * rejection reason.
  14018. * @private
  14019. *
  14020. * @param {*} reason
  14021. * @returns {Promise} rejected promise
  14022. */
  14023. function rejected(reason) {
  14024. var p = new Promise(function(_, onRejected) {
  14025. // TODO: Promises/A+ check typeof onRejected
  14026. try {
  14027. return onRejected ? resolve(onRejected(reason)) : rejected(reason);
  14028. } catch(e) {
  14029. return rejected(e);
  14030. }
  14031. });
  14032. return p;
  14033. }
  14034. /**
  14035. * Creates a new, Deferred with fully isolated resolver and promise parts,
  14036. * either or both of which may be given out safely to consumers.
  14037. * The Deferred itself has the full API: resolve, reject, progress, and
  14038. * then. The resolver has resolve, reject, and progress. The promise
  14039. * only has then.
  14040. *
  14041. * @returns {Deferred}
  14042. */
  14043. function defer() {
  14044. var deferred, promise, handlers, progressHandlers,
  14045. _then, _progress, _resolve;
  14046. /**
  14047. * The promise for the new deferred
  14048. * @type {Promise}
  14049. */
  14050. promise = new Promise(then);
  14051. /**
  14052. * The full Deferred object, with {@link Promise} and {@link Resolver} parts
  14053. * @class Deferred
  14054. * @name Deferred
  14055. */
  14056. deferred = {
  14057. then: then, // DEPRECATED: use deferred.promise.then
  14058. resolve: promiseResolve,
  14059. reject: promiseReject,
  14060. // TODO: Consider renaming progress() to notify()
  14061. progress: promiseProgress,
  14062. promise: promise,
  14063. resolver: {
  14064. resolve: promiseResolve,
  14065. reject: promiseReject,
  14066. progress: promiseProgress
  14067. }
  14068. };
  14069. handlers = [];
  14070. progressHandlers = [];
  14071. /**
  14072. * Pre-resolution then() that adds the supplied callback, errback, and progback
  14073. * functions to the registered listeners
  14074. * @private
  14075. *
  14076. * @param {function?} [onFulfilled] resolution handler
  14077. * @param {function?} [onRejected] rejection handler
  14078. * @param {function?} [onProgress] progress handler
  14079. */
  14080. _then = function(onFulfilled, onRejected, onProgress) {
  14081. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  14082. var deferred, progressHandler;
  14083. deferred = defer();
  14084. progressHandler = typeof onProgress === 'function'
  14085. ? function(update) {
  14086. try {
  14087. // Allow progress handler to transform progress event
  14088. deferred.progress(onProgress(update));
  14089. } catch(e) {
  14090. // Use caught value as progress
  14091. deferred.progress(e);
  14092. }
  14093. }
  14094. : function(update) { deferred.progress(update); };
  14095. handlers.push(function(promise) {
  14096. promise.then(onFulfilled, onRejected)
  14097. .then(deferred.resolve, deferred.reject, progressHandler);
  14098. });
  14099. progressHandlers.push(progressHandler);
  14100. return deferred.promise;
  14101. };
  14102. /**
  14103. * Issue a progress event, notifying all progress listeners
  14104. * @private
  14105. * @param {*} update progress event payload to pass to all listeners
  14106. */
  14107. _progress = function(update) {
  14108. processQueue(progressHandlers, update);
  14109. return update;
  14110. };
  14111. /**
  14112. * Transition from pre-resolution state to post-resolution state, notifying
  14113. * all listeners of the resolution or rejection
  14114. * @private
  14115. * @param {*} value the value of this deferred
  14116. */
  14117. _resolve = function(value) {
  14118. value = resolve(value);
  14119. // Replace _then with one that directly notifies with the result.
  14120. _then = value.then;
  14121. // Replace _resolve so that this Deferred can only be resolved once
  14122. _resolve = resolve;
  14123. // Make _progress a noop, to disallow progress for the resolved promise.
  14124. _progress = noop;
  14125. // Notify handlers
  14126. processQueue(handlers, value);
  14127. // Free progressHandlers array since we'll never issue progress events
  14128. progressHandlers = handlers = undef;
  14129. return value;
  14130. };
  14131. return deferred;
  14132. /**
  14133. * Wrapper to allow _then to be replaced safely
  14134. * @param {function?} [onFulfilled] resolution handler
  14135. * @param {function?} [onRejected] rejection handler
  14136. * @param {function?} [onProgress] progress handler
  14137. * @returns {Promise} new promise
  14138. */
  14139. function then(onFulfilled, onRejected, onProgress) {
  14140. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  14141. return _then(onFulfilled, onRejected, onProgress);
  14142. }
  14143. /**
  14144. * Wrapper to allow _resolve to be replaced
  14145. */
  14146. function promiseResolve(val) {
  14147. return _resolve(val);
  14148. }
  14149. /**
  14150. * Wrapper to allow _reject to be replaced
  14151. */
  14152. function promiseReject(err) {
  14153. return _resolve(rejected(err));
  14154. }
  14155. /**
  14156. * Wrapper to allow _progress to be replaced
  14157. */
  14158. function promiseProgress(update) {
  14159. return _progress(update);
  14160. }
  14161. }
  14162. /**
  14163. * Determines if promiseOrValue is a promise or not. Uses the feature
  14164. * test from http://wiki.commonjs.org/wiki/Promises/A to determine if
  14165. * promiseOrValue is a promise.
  14166. *
  14167. * @param {*} promiseOrValue anything
  14168. * @returns {boolean} true if promiseOrValue is a {@link Promise}
  14169. */
  14170. function isPromise(promiseOrValue) {
  14171. return promiseOrValue && typeof promiseOrValue.then === 'function';
  14172. }
  14173. /**
  14174. * Initiates a competitive race, returning a promise that will resolve when
  14175. * howMany of the supplied promisesOrValues have resolved, or will reject when
  14176. * it becomes impossible for howMany to resolve, for example, when
  14177. * (promisesOrValues.length - howMany) + 1 input promises reject.
  14178. *
  14179. * @param {Array} promisesOrValues array of anything, may contain a mix
  14180. * of promises and values
  14181. * @param howMany {number} number of promisesOrValues to resolve
  14182. * @param {function?} [onFulfilled] resolution handler
  14183. * @param {function?} [onRejected] rejection handler
  14184. * @param {function?} [onProgress] progress handler
  14185. * @returns {Promise} promise that will resolve to an array of howMany values that
  14186. * resolved first, or will reject with an array of (promisesOrValues.length - howMany) + 1
  14187. * rejection reasons.
  14188. */
  14189. function some(promisesOrValues, howMany, onFulfilled, onRejected, onProgress) {
  14190. checkCallbacks(2, arguments);
  14191. return when(promisesOrValues, function(promisesOrValues) {
  14192. var toResolve, toReject, values, reasons, deferred, fulfillOne, rejectOne, progress, len, i;
  14193. len = promisesOrValues.length >>> 0;
  14194. toResolve = Math.max(0, Math.min(howMany, len));
  14195. values = [];
  14196. toReject = (len - toResolve) + 1;
  14197. reasons = [];
  14198. deferred = defer();
  14199. // No items in the input, resolve immediately
  14200. if (!toResolve) {
  14201. deferred.resolve(values);
  14202. } else {
  14203. progress = deferred.progress;
  14204. rejectOne = function(reason) {
  14205. reasons.push(reason);
  14206. if(!--toReject) {
  14207. fulfillOne = rejectOne = noop;
  14208. deferred.reject(reasons);
  14209. }
  14210. };
  14211. fulfillOne = function(val) {
  14212. // This orders the values based on promise resolution order
  14213. // Another strategy would be to use the original position of
  14214. // the corresponding promise.
  14215. values.push(val);
  14216. if (!--toResolve) {
  14217. fulfillOne = rejectOne = noop;
  14218. deferred.resolve(values);
  14219. }
  14220. };
  14221. for(i = 0; i < len; ++i) {
  14222. if(i in promisesOrValues) {
  14223. when(promisesOrValues[i], fulfiller, rejecter, progress);
  14224. }
  14225. }
  14226. }
  14227. return deferred.then(onFulfilled, onRejected, onProgress);
  14228. function rejecter(reason) {
  14229. rejectOne(reason);
  14230. }
  14231. function fulfiller(val) {
  14232. fulfillOne(val);
  14233. }
  14234. });
  14235. }
  14236. /**
  14237. * Initiates a competitive race, returning a promise that will resolve when
  14238. * any one of the supplied promisesOrValues has resolved or will reject when
  14239. * *all* promisesOrValues have rejected.
  14240. *
  14241. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  14242. * of {@link Promise}s and values
  14243. * @param {function?} [onFulfilled] resolution handler
  14244. * @param {function?} [onRejected] rejection handler
  14245. * @param {function?} [onProgress] progress handler
  14246. * @returns {Promise} promise that will resolve to the value that resolved first, or
  14247. * will reject with an array of all rejected inputs.
  14248. */
  14249. function any(promisesOrValues, onFulfilled, onRejected, onProgress) {
  14250. function unwrapSingleResult(val) {
  14251. return onFulfilled ? onFulfilled(val[0]) : val[0];
  14252. }
  14253. return some(promisesOrValues, 1, unwrapSingleResult, onRejected, onProgress);
  14254. }
  14255. /**
  14256. * Return a promise that will resolve only once all the supplied promisesOrValues
  14257. * have resolved. The resolution value of the returned promise will be an array
  14258. * containing the resolution values of each of the promisesOrValues.
  14259. * @memberOf when
  14260. *
  14261. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  14262. * of {@link Promise}s and values
  14263. * @param {function?} [onFulfilled] resolution handler
  14264. * @param {function?} [onRejected] rejection handler
  14265. * @param {function?} [onProgress] progress handler
  14266. * @returns {Promise}
  14267. */
  14268. function all(promisesOrValues, onFulfilled, onRejected, onProgress) {
  14269. checkCallbacks(1, arguments);
  14270. return map(promisesOrValues, identity).then(onFulfilled, onRejected, onProgress);
  14271. }
  14272. /**
  14273. * Joins multiple promises into a single returned promise.
  14274. * @returns {Promise} a promise that will fulfill when *all* the input promises
  14275. * have fulfilled, or will reject when *any one* of the input promises rejects.
  14276. */
  14277. function join(/* ...promises */) {
  14278. return map(arguments, identity);
  14279. }
  14280. /**
  14281. * Traditional map function, similar to `Array.prototype.map()`, but allows
  14282. * input to contain {@link Promise}s and/or values, and mapFunc may return
  14283. * either a value or a {@link Promise}
  14284. *
  14285. * @param {Array|Promise} promise array of anything, may contain a mix
  14286. * of {@link Promise}s and values
  14287. * @param {function} mapFunc mapping function mapFunc(value) which may return
  14288. * either a {@link Promise} or value
  14289. * @returns {Promise} a {@link Promise} that will resolve to an array containing
  14290. * the mapped output values.
  14291. */
  14292. function map(promise, mapFunc) {
  14293. return when(promise, function(array) {
  14294. var results, len, toResolve, resolve, i, d;
  14295. // Since we know the resulting length, we can preallocate the results
  14296. // array to avoid array expansions.
  14297. toResolve = len = array.length >>> 0;
  14298. results = [];
  14299. d = defer();
  14300. if(!toResolve) {
  14301. d.resolve(results);
  14302. } else {
  14303. resolve = function resolveOne(item, i) {
  14304. when(item, mapFunc).then(function(mapped) {
  14305. results[i] = mapped;
  14306. if(!--toResolve) {
  14307. d.resolve(results);
  14308. }
  14309. }, d.reject);
  14310. };
  14311. // Since mapFunc may be async, get all invocations of it into flight
  14312. for(i = 0; i < len; i++) {
  14313. if(i in array) {
  14314. resolve(array[i], i);
  14315. } else {
  14316. --toResolve;
  14317. }
  14318. }
  14319. }
  14320. return d.promise;
  14321. });
  14322. }
  14323. /**
  14324. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  14325. * input may contain promises and/or values, and reduceFunc
  14326. * may return either a value or a promise, *and* initialValue may
  14327. * be a promise for the starting value.
  14328. *
  14329. * @param {Array|Promise} promise array or promise for an array of anything,
  14330. * may contain a mix of promises and values.
  14331. * @param {function} reduceFunc reduce function reduce(currentValue, nextValue, index, total),
  14332. * where total is the total number of items being reduced, and will be the same
  14333. * in each call to reduceFunc.
  14334. * @returns {Promise} that will resolve to the final reduced value
  14335. */
  14336. function reduce(promise, reduceFunc /*, initialValue */) {
  14337. var args = slice.call(arguments, 1);
  14338. return when(promise, function(array) {
  14339. var total;
  14340. total = array.length;
  14341. // Wrap the supplied reduceFunc with one that handles promises and then
  14342. // delegates to the supplied.
  14343. args[0] = function (current, val, i) {
  14344. return when(current, function (c) {
  14345. return when(val, function (value) {
  14346. return reduceFunc(c, value, i, total);
  14347. });
  14348. });
  14349. };
  14350. return reduceArray.apply(array, args);
  14351. });
  14352. }
  14353. /**
  14354. * Ensure that resolution of promiseOrValue will trigger resolver with the
  14355. * value or reason of promiseOrValue, or instead with resolveValue if it is provided.
  14356. *
  14357. * @param promiseOrValue
  14358. * @param {Object} resolver
  14359. * @param {function} resolver.resolve
  14360. * @param {function} resolver.reject
  14361. * @param {*} [resolveValue]
  14362. * @returns {Promise}
  14363. */
  14364. function chain(promiseOrValue, resolver, resolveValue) {
  14365. var useResolveValue = arguments.length > 2;
  14366. return when(promiseOrValue,
  14367. function(val) {
  14368. val = useResolveValue ? resolveValue : val;
  14369. resolver.resolve(val);
  14370. return val;
  14371. },
  14372. function(reason) {
  14373. resolver.reject(reason);
  14374. return rejected(reason);
  14375. },
  14376. resolver.progress
  14377. );
  14378. }
  14379. //
  14380. // Utility functions
  14381. //
  14382. /**
  14383. * Apply all functions in queue to value
  14384. * @param {Array} queue array of functions to execute
  14385. * @param {*} value argument passed to each function
  14386. */
  14387. function processQueue(queue, value) {
  14388. var handler, i = 0;
  14389. while (handler = queue[i++]) {
  14390. handler(value);
  14391. }
  14392. }
  14393. /**
  14394. * Helper that checks arrayOfCallbacks to ensure that each element is either
  14395. * a function, or null or undefined.
  14396. * @private
  14397. * @param {number} start index at which to start checking items in arrayOfCallbacks
  14398. * @param {Array} arrayOfCallbacks array to check
  14399. * @throws {Error} if any element of arrayOfCallbacks is something other than
  14400. * a functions, null, or undefined.
  14401. */
  14402. function checkCallbacks(start, arrayOfCallbacks) {
  14403. // TODO: Promises/A+ update type checking and docs
  14404. var arg, i = arrayOfCallbacks.length;
  14405. while(i > start) {
  14406. arg = arrayOfCallbacks[--i];
  14407. if (arg != null && typeof arg != 'function') {
  14408. throw new Error('arg '+i+' must be a function');
  14409. }
  14410. }
  14411. }
  14412. /**
  14413. * No-Op function used in method replacement
  14414. * @private
  14415. */
  14416. function noop() {}
  14417. slice = [].slice;
  14418. // ES5 reduce implementation if native not available
  14419. // See: http://es5.github.com/#x15.4.4.21 as there are many
  14420. // specifics and edge cases.
  14421. reduceArray = [].reduce ||
  14422. function(reduceFunc /*, initialValue */) {
  14423. /*jshint maxcomplexity: 7*/
  14424. // ES5 dictates that reduce.length === 1
  14425. // This implementation deviates from ES5 spec in the following ways:
  14426. // 1. It does not check if reduceFunc is a Callable
  14427. var arr, args, reduced, len, i;
  14428. i = 0;
  14429. // This generates a jshint warning, despite being valid
  14430. // "Missing 'new' prefix when invoking a constructor."
  14431. // See https://github.com/jshint/jshint/issues/392
  14432. arr = Object(this);
  14433. len = arr.length >>> 0;
  14434. args = arguments;
  14435. // If no initialValue, use first item of array (we know length !== 0 here)
  14436. // and adjust i to start at second item
  14437. if(args.length <= 1) {
  14438. // Skip to the first real element in the array
  14439. for(;;) {
  14440. if(i in arr) {
  14441. reduced = arr[i++];
  14442. break;
  14443. }
  14444. // If we reached the end of the array without finding any real
  14445. // elements, it's a TypeError
  14446. if(++i >= len) {
  14447. throw new TypeError();
  14448. }
  14449. }
  14450. } else {
  14451. // If initialValue provided, use it
  14452. reduced = args[1];
  14453. }
  14454. // Do the actual reduce
  14455. for(;i < len; ++i) {
  14456. // Skip holes
  14457. if(i in arr) {
  14458. reduced = reduceFunc(reduced, arr[i], i, arr);
  14459. }
  14460. }
  14461. return reduced;
  14462. };
  14463. function identity(x) {
  14464. return x;
  14465. }
  14466. return when;
  14467. });
  14468. })(typeof define == 'function' && define.amd
  14469. ? define
  14470. : function (factory) { typeof exports === 'object'
  14471. ? (module.exports = factory())
  14472. : (this.when = factory());
  14473. }
  14474. // Boilerplate for AMD, Node, and browser global
  14475. );
  14476. /*global define*/
  14477. define('Core/oneTimeWarning',[
  14478. './defaultValue',
  14479. './defined',
  14480. './DeveloperError'
  14481. ], function(
  14482. defaultValue,
  14483. defined,
  14484. DeveloperError) {
  14485. "use strict";
  14486. var warnings = {};
  14487. /**
  14488. * Logs a one time message to the console. Use this function instead of
  14489. * <code>console.log</code> directly since this does not log duplicate messages
  14490. * unless it is called from multiple workers.
  14491. *
  14492. * @exports oneTimeWarning
  14493. *
  14494. * @param {String} identifier The unique identifier for this warning.
  14495. * @param {String} [message=identifier] The message to log to the console.
  14496. *
  14497. * @example
  14498. * for(var i=0;i<foo.length;++i) {
  14499. * if (!defined(foo[i].bar)) {
  14500. * // Something that can be recovered from but may happen a lot
  14501. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  14502. * foo[i].bar = 0;
  14503. * // ...
  14504. * }
  14505. * }
  14506. *
  14507. * @private
  14508. */
  14509. function oneTimeWarning(identifier, message) {
  14510. if (!defined(identifier)) {
  14511. throw new DeveloperError('identifier is required.');
  14512. }
  14513. if (!defined(warnings[identifier])) {
  14514. warnings[identifier] = true;
  14515. console.log(defaultValue(message, identifier));
  14516. }
  14517. }
  14518. oneTimeWarning.geometryOutlines = 'Entity geometry outlines are unsupported on terrain. Outlines will be disabled. To enable outlines, disable geometry terrain clamping by explicitly setting height to 0.';
  14519. return oneTimeWarning;
  14520. });
  14521. /*global define*/
  14522. define('Core/deprecationWarning',[
  14523. './defined',
  14524. './DeveloperError',
  14525. './oneTimeWarning'
  14526. ], function(
  14527. defined,
  14528. DeveloperError,
  14529. oneTimeWarning) {
  14530. 'use strict';
  14531. /**
  14532. * Logs a deprecation message to the console. Use this function instead of
  14533. * <code>console.log</code> directly since this does not log duplicate messages
  14534. * unless it is called from multiple workers.
  14535. *
  14536. * @exports deprecationWarning
  14537. *
  14538. * @param {String} identifier The unique identifier for this deprecated API.
  14539. * @param {String} message The message to log to the console.
  14540. *
  14541. * @example
  14542. * // Deprecated function or class
  14543. * function Foo() {
  14544. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  14545. * // ...
  14546. * }
  14547. *
  14548. * // Deprecated function
  14549. * Bar.prototype.func = function() {
  14550. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  14551. * // ...
  14552. * };
  14553. *
  14554. * // Deprecated property
  14555. * defineProperties(Bar.prototype, {
  14556. * prop : {
  14557. * get : function() {
  14558. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  14559. * // ...
  14560. * },
  14561. * set : function(value) {
  14562. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  14563. * // ...
  14564. * }
  14565. * }
  14566. * });
  14567. *
  14568. * @private
  14569. */
  14570. function deprecationWarning(identifier, message) {
  14571. if (!defined(identifier) || !defined(message)) {
  14572. throw new DeveloperError('identifier and message are required.');
  14573. }
  14574. oneTimeWarning(identifier, message);
  14575. }
  14576. return deprecationWarning;
  14577. });
  14578. /*global define*/
  14579. define('Core/binarySearch',[
  14580. './defined',
  14581. './DeveloperError'
  14582. ], function(
  14583. defined,
  14584. DeveloperError) {
  14585. 'use strict';
  14586. /**
  14587. * Finds an item in a sorted array.
  14588. *
  14589. * @exports binarySearch
  14590. *
  14591. * @param {Array} array The sorted array to search.
  14592. * @param {Object} itemToFind The item to find in the array.
  14593. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  14594. * elements in the array.
  14595. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  14596. * does not exist, the return value is a negative number which is the bitwise complement (~)
  14597. * of the index before which the itemToFind should be inserted in order to maintain the
  14598. * sorted order of the array.
  14599. *
  14600. * @example
  14601. * // Create a comparator function to search through an array of numbers.
  14602. * function comparator(a, b) {
  14603. * return a - b;
  14604. * };
  14605. * var numbers = [0, 2, 4, 6, 8];
  14606. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  14607. */
  14608. function binarySearch(array, itemToFind, comparator) {
  14609. if (!defined(array)) {
  14610. throw new DeveloperError('array is required.');
  14611. }
  14612. if (!defined(itemToFind)) {
  14613. throw new DeveloperError('itemToFind is required.');
  14614. }
  14615. if (!defined(comparator)) {
  14616. throw new DeveloperError('comparator is required.');
  14617. }
  14618. var low = 0;
  14619. var high = array.length - 1;
  14620. var i;
  14621. var comparison;
  14622. while (low <= high) {
  14623. i = ~~((low + high) / 2);
  14624. comparison = comparator(array[i], itemToFind);
  14625. if (comparison < 0) {
  14626. low = i + 1;
  14627. continue;
  14628. }
  14629. if (comparison > 0) {
  14630. high = i - 1;
  14631. continue;
  14632. }
  14633. return i;
  14634. }
  14635. return ~(high + 1);
  14636. }
  14637. /**
  14638. * A function used to compare two items while performing a binary search.
  14639. * @callback binarySearch~Comparator
  14640. *
  14641. * @param {Object} a An item in the array.
  14642. * @param {Object} b The item being searched for.
  14643. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  14644. * a positive value if <code>a</code> is greater than <code>b</code>, or
  14645. * 0 if <code>a</code> is equal to <code>b</code>.
  14646. *
  14647. * @example
  14648. * function compareNumbers(a, b) {
  14649. * return a - b;
  14650. * }
  14651. */
  14652. return binarySearch;
  14653. });
  14654. /*global define*/
  14655. define('Core/EarthOrientationParametersSample',[],function() {
  14656. 'use strict';
  14657. /**
  14658. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  14659. *
  14660. * @alias EarthOrientationParametersSample
  14661. * @constructor
  14662. *
  14663. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  14664. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  14665. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  14666. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  14667. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  14668. *
  14669. * @private
  14670. */
  14671. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  14672. /**
  14673. * The pole wander about the X axis, in radians.
  14674. * @type {Number}
  14675. */
  14676. this.xPoleWander = xPoleWander;
  14677. /**
  14678. * The pole wander about the Y axis, in radians.
  14679. * @type {Number}
  14680. */
  14681. this.yPoleWander = yPoleWander;
  14682. /**
  14683. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  14684. * @type {Number}
  14685. */
  14686. this.xPoleOffset = xPoleOffset;
  14687. /**
  14688. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  14689. * @type {Number}
  14690. */
  14691. this.yPoleOffset = yPoleOffset;
  14692. /**
  14693. * The difference in time standards, UT1 - UTC, in seconds.
  14694. * @type {Number}
  14695. */
  14696. this.ut1MinusUtc = ut1MinusUtc;
  14697. }
  14698. return EarthOrientationParametersSample;
  14699. });
  14700. /**
  14701. @license
  14702. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  14703. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  14704. php.js is copyright 2012 Kevin van Zonneveld.
  14705. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  14706. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  14707. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  14708. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  14709. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  14710. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  14711. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  14712. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  14713. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  14714. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  14715. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  14716. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  14717. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  14718. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  14719. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  14720. (http://geekfg.blogspot.com), Andrea Giammarchi
  14721. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  14722. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  14723. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  14724. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  14725. Marc Palau, Martin
  14726. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  14727. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  14728. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  14729. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  14730. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  14731. Ariede (http://caioariede.com), Robin, Kankrelune
  14732. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  14733. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  14734. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  14735. David, Aman Gupta, Michael White, Public Domain
  14736. (http://www.json.org/json2.js), Steven Levithan
  14737. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  14738. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  14739. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  14740. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  14741. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  14742. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  14743. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  14744. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  14745. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  14746. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  14747. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  14748. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  14749. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  14750. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  14751. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  14752. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  14753. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  14754. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  14755. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  14756. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  14757. (http://yass.meetcweb.com), Peter-Paul Koch
  14758. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  14759. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  14760. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  14761. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  14762. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  14763. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  14764. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  14765. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  14766. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  14767. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  14768. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  14769. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  14770. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  14771. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  14772. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  14773. (http://www.premasolutions.com/), Philippe Jausions
  14774. (http://pear.php.net/user/jausions), Aidan Lister
  14775. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  14776. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  14777. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  14778. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  14779. (http://www.pedrotainha.com), James, Arnout Kazemier
  14780. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  14781. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  14782. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  14783. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  14784. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  14785. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  14786. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  14787. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  14788. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  14789. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  14790. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  14791. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  14792. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  14793. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  14794. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  14795. (http://benblume.co.uk/), DtTvB
  14796. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  14797. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  14798. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  14799. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  14800. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  14801. Bryan
  14802. Licensed under the MIT (MIT-LICENSE.txt) license.
  14803. Permission is hereby granted, free of charge, to any person obtaining a
  14804. copy of this software and associated documentation files (the
  14805. "Software"), to deal in the Software without restriction, including
  14806. without limitation the rights to use, copy, modify, merge, publish,
  14807. distribute, sublicense, and/or sell copies of the Software, and to
  14808. permit persons to whom the Software is furnished to do so, subject to
  14809. the following conditions:
  14810. The above copyright notice and this permission notice shall be included
  14811. in all copies or substantial portions of the Software.
  14812. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14813. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14814. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  14815. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  14816. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  14817. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  14818. OTHER DEALINGS IN THE SOFTWARE.
  14819. */
  14820. /*global define*/
  14821. define('ThirdParty/sprintf',[],function() {
  14822. function sprintf () {
  14823. // http://kevin.vanzonneveld.net
  14824. // + original by: Ash Searle (http://hexmen.com/blog/)
  14825. // + namespaced by: Michael White (http://getsprink.com)
  14826. // + tweaked by: Jack
  14827. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14828. // + input by: Paulo Freitas
  14829. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14830. // + input by: Brett Zamir (http://brett-zamir.me)
  14831. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  14832. // + improved by: Dj
  14833. // + improved by: Allidylls
  14834. // * example 1: sprintf("%01.2f", 123.1);
  14835. // * returns 1: 123.10
  14836. // * example 2: sprintf("[%10s]", 'monkey');
  14837. // * returns 2: '[ monkey]'
  14838. // * example 3: sprintf("[%'#10s]", 'monkey');
  14839. // * returns 3: '[####monkey]'
  14840. // * example 4: sprintf("%d", 123456789012345);
  14841. // * returns 4: '123456789012345'
  14842. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  14843. var a = arguments,
  14844. i = 0,
  14845. format = a[i++];
  14846. // pad()
  14847. var pad = function (str, len, chr, leftJustify) {
  14848. if (!chr) {
  14849. chr = ' ';
  14850. }
  14851. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  14852. return leftJustify ? str + padding : padding + str;
  14853. };
  14854. // justify()
  14855. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  14856. var diff = minWidth - value.length;
  14857. if (diff > 0) {
  14858. if (leftJustify || !zeroPad) {
  14859. value = pad(value, minWidth, customPadChar, leftJustify);
  14860. } else {
  14861. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  14862. }
  14863. }
  14864. return value;
  14865. };
  14866. // formatBaseX()
  14867. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  14868. // Note: casts negative numbers to positive ones
  14869. var number = value >>> 0;
  14870. prefix = prefix && number && {
  14871. '2': '0b',
  14872. '8': '0',
  14873. '16': '0x'
  14874. }[base] || '';
  14875. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  14876. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  14877. };
  14878. // formatString()
  14879. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  14880. if (precision != null) {
  14881. value = value.slice(0, precision);
  14882. }
  14883. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  14884. };
  14885. // doFormat()
  14886. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  14887. var number;
  14888. var prefix;
  14889. var method;
  14890. var textTransform;
  14891. var value;
  14892. if (substring == '%%') {
  14893. return '%';
  14894. }
  14895. // parse flags
  14896. var leftJustify = false,
  14897. positivePrefix = '',
  14898. zeroPad = false,
  14899. prefixBaseX = false,
  14900. customPadChar = ' ';
  14901. var flagsl = flags.length;
  14902. for (var j = 0; flags && j < flagsl; j++) {
  14903. switch (flags.charAt(j)) {
  14904. case ' ':
  14905. positivePrefix = ' ';
  14906. break;
  14907. case '+':
  14908. positivePrefix = '+';
  14909. break;
  14910. case '-':
  14911. leftJustify = true;
  14912. break;
  14913. case "'":
  14914. customPadChar = flags.charAt(j + 1);
  14915. break;
  14916. case '0':
  14917. zeroPad = true;
  14918. break;
  14919. case '#':
  14920. prefixBaseX = true;
  14921. break;
  14922. }
  14923. }
  14924. // parameters may be null, undefined, empty-string or real valued
  14925. // we want to ignore null, undefined and empty-string values
  14926. if (!minWidth) {
  14927. minWidth = 0;
  14928. } else if (minWidth == '*') {
  14929. minWidth = +a[i++];
  14930. } else if (minWidth.charAt(0) == '*') {
  14931. minWidth = +a[minWidth.slice(1, -1)];
  14932. } else {
  14933. minWidth = +minWidth;
  14934. }
  14935. // Note: undocumented perl feature:
  14936. if (minWidth < 0) {
  14937. minWidth = -minWidth;
  14938. leftJustify = true;
  14939. }
  14940. if (!isFinite(minWidth)) {
  14941. throw new Error('sprintf: (minimum-)width must be finite');
  14942. }
  14943. if (!precision) {
  14944. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  14945. } else if (precision == '*') {
  14946. precision = +a[i++];
  14947. } else if (precision.charAt(0) == '*') {
  14948. precision = +a[precision.slice(1, -1)];
  14949. } else {
  14950. precision = +precision;
  14951. }
  14952. // grab value using valueIndex if required?
  14953. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  14954. switch (type) {
  14955. case 's':
  14956. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  14957. case 'c':
  14958. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  14959. case 'b':
  14960. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14961. case 'o':
  14962. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14963. case 'x':
  14964. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14965. case 'X':
  14966. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  14967. case 'u':
  14968. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  14969. case 'i':
  14970. case 'd':
  14971. number = +value || 0;
  14972. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  14973. prefix = number < 0 ? '-' : positivePrefix;
  14974. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  14975. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  14976. case 'e':
  14977. case 'E':
  14978. case 'f': // Should handle locales (as per setlocale)
  14979. case 'F':
  14980. case 'g':
  14981. case 'G':
  14982. number = +value;
  14983. prefix = number < 0 ? '-' : positivePrefix;
  14984. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  14985. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  14986. value = prefix + Math.abs(number)[method](precision);
  14987. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  14988. default:
  14989. return substring;
  14990. }
  14991. };
  14992. return format.replace(regex, doFormat);
  14993. }
  14994. return sprintf;
  14995. });
  14996. /*global define*/
  14997. define('Core/GregorianDate',[],function() {
  14998. 'use strict';
  14999. /**
  15000. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  15001. * In addition to submillisecond precision, this object can also represent leap seconds.
  15002. * @alias GregorianDate
  15003. * @constructor
  15004. *
  15005. * @see JulianDate#toGregorianDate
  15006. */
  15007. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  15008. /**
  15009. * Gets or sets the year as a whole number.
  15010. * @type {Number}
  15011. */
  15012. this.year = year;
  15013. /**
  15014. * Gets or sets the month as a whole number with range [1, 12].
  15015. * @type {Number}
  15016. */
  15017. this.month = month;
  15018. /**
  15019. * Gets or sets the day of the month as a whole number starting at 1.
  15020. * @type {Number}
  15021. */
  15022. this.day = day;
  15023. /**
  15024. * Gets or sets the hour as a whole number with range [0, 23].
  15025. * @type {Number}
  15026. */
  15027. this.hour = hour;
  15028. /**
  15029. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  15030. * @type {Number}
  15031. */
  15032. this.minute = minute;
  15033. /**
  15034. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  15035. * @type {Number}
  15036. */
  15037. this.second = second;
  15038. /**
  15039. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  15040. * @type {Number}
  15041. */
  15042. this.millisecond = millisecond;
  15043. /**
  15044. * Gets or sets whether this time is during a leap second.
  15045. * @type {Boolean}
  15046. */
  15047. this.isLeapSecond = isLeapSecond;
  15048. }
  15049. return GregorianDate;
  15050. });
  15051. /*global define*/
  15052. define('Core/isLeapYear',[
  15053. './DeveloperError'
  15054. ], function(
  15055. DeveloperError) {
  15056. 'use strict';
  15057. /**
  15058. * Determines if a given date is a leap year.
  15059. *
  15060. * @exports isLeapYear
  15061. *
  15062. * @param {Number} year The year to be tested.
  15063. * @returns {Boolean} True if <code>year</code> is a leap year.
  15064. *
  15065. * @example
  15066. * var leapYear = Cesium.isLeapYear(2000); // true
  15067. */
  15068. function isLeapYear(year) {
  15069. if (year === null || isNaN(year)) {
  15070. throw new DeveloperError('year is required and must be a number.');
  15071. }
  15072. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  15073. }
  15074. return isLeapYear;
  15075. });
  15076. /*global define*/
  15077. define('Core/LeapSecond',[],function() {
  15078. 'use strict';
  15079. /**
  15080. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  15081. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  15082. * @alias LeapSecond
  15083. * @constructor
  15084. *
  15085. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  15086. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  15087. */
  15088. function LeapSecond(date, offset) {
  15089. /**
  15090. * Gets or sets the date at which this leap second occurs.
  15091. * @type {JulianDate}
  15092. */
  15093. this.julianDate = date;
  15094. /**
  15095. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  15096. * of this leap second.
  15097. * @type {Number}
  15098. */
  15099. this.offset = offset;
  15100. }
  15101. return LeapSecond;
  15102. });
  15103. /*global define*/
  15104. define('Core/TimeConstants',[
  15105. './freezeObject'
  15106. ], function(
  15107. freezeObject) {
  15108. 'use strict';
  15109. /**
  15110. * Constants for time conversions like those done by {@link JulianDate}.
  15111. *
  15112. * @exports TimeConstants
  15113. *
  15114. * @see JulianDate
  15115. *
  15116. * @private
  15117. */
  15118. var TimeConstants = {
  15119. /**
  15120. * The number of seconds in one millisecond: <code>0.001</code>
  15121. * @type {Number}
  15122. * @constant
  15123. */
  15124. SECONDS_PER_MILLISECOND : 0.001,
  15125. /**
  15126. * The number of seconds in one minute: <code>60</code>.
  15127. * @type {Number}
  15128. * @constant
  15129. */
  15130. SECONDS_PER_MINUTE : 60.0,
  15131. /**
  15132. * The number of minutes in one hour: <code>60</code>.
  15133. * @type {Number}
  15134. * @constant
  15135. */
  15136. MINUTES_PER_HOUR : 60.0,
  15137. /**
  15138. * The number of hours in one day: <code>24</code>.
  15139. * @type {Number}
  15140. * @constant
  15141. */
  15142. HOURS_PER_DAY : 24.0,
  15143. /**
  15144. * The number of seconds in one hour: <code>3600</code>.
  15145. * @type {Number}
  15146. * @constant
  15147. */
  15148. SECONDS_PER_HOUR : 3600.0,
  15149. /**
  15150. * The number of minutes in one day: <code>1440</code>.
  15151. * @type {Number}
  15152. * @constant
  15153. */
  15154. MINUTES_PER_DAY : 1440.0,
  15155. /**
  15156. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  15157. * @type {Number}
  15158. * @constant
  15159. */
  15160. SECONDS_PER_DAY : 86400.0,
  15161. /**
  15162. * The number of days in one Julian century: <code>36525</code>.
  15163. * @type {Number}
  15164. * @constant
  15165. */
  15166. DAYS_PER_JULIAN_CENTURY : 36525.0,
  15167. /**
  15168. * One trillionth of a second.
  15169. * @type {Number}
  15170. * @constant
  15171. */
  15172. PICOSECOND : 0.000000001,
  15173. /**
  15174. * The number of days to subtract from a Julian date to determine the
  15175. * modified Julian date, which gives the number of days since midnight
  15176. * on November 17, 1858.
  15177. * @type {Number}
  15178. * @constant
  15179. */
  15180. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  15181. };
  15182. return freezeObject(TimeConstants);
  15183. });
  15184. /*global define*/
  15185. define('Core/TimeStandard',[
  15186. './freezeObject'
  15187. ], function(
  15188. freezeObject) {
  15189. 'use strict';
  15190. /**
  15191. * Provides the type of time standards which JulianDate can take as input.
  15192. *
  15193. * @exports TimeStandard
  15194. *
  15195. * @see JulianDate
  15196. */
  15197. var TimeStandard = {
  15198. /**
  15199. * Represents the coordinated Universal Time (UTC) time standard.
  15200. *
  15201. * UTC is related to TAI according to the relationship
  15202. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  15203. * seconds which have been introduced as of the time in TAI.
  15204. *
  15205. */
  15206. UTC : 0,
  15207. /**
  15208. * Represents the International Atomic Time (TAI) time standard.
  15209. * TAI is the principal time standard to which the other time standards are related.
  15210. */
  15211. TAI : 1
  15212. };
  15213. return freezeObject(TimeStandard);
  15214. });
  15215. /*global define*/
  15216. define('Core/JulianDate',[
  15217. '../ThirdParty/sprintf',
  15218. './binarySearch',
  15219. './defaultValue',
  15220. './defined',
  15221. './DeveloperError',
  15222. './GregorianDate',
  15223. './isLeapYear',
  15224. './LeapSecond',
  15225. './TimeConstants',
  15226. './TimeStandard'
  15227. ], function(
  15228. sprintf,
  15229. binarySearch,
  15230. defaultValue,
  15231. defined,
  15232. DeveloperError,
  15233. GregorianDate,
  15234. isLeapYear,
  15235. LeapSecond,
  15236. TimeConstants,
  15237. TimeStandard) {
  15238. 'use strict';
  15239. var gregorianDateScratch = new GregorianDate();
  15240. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  15241. var daysInLeapFeburary = 29;
  15242. function compareLeapSecondDates(leapSecond, dateToFind) {
  15243. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  15244. }
  15245. // we don't really need a leap second instance, anything with a julianDate property will do
  15246. var binarySearchScratchLeapSecond = new LeapSecond();
  15247. function convertUtcToTai(julianDate) {
  15248. //Even though julianDate is in UTC, we'll treat it as TAI and
  15249. //search the leap second table for it.
  15250. binarySearchScratchLeapSecond.julianDate = julianDate;
  15251. var leapSeconds = JulianDate.leapSeconds;
  15252. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  15253. if (index < 0) {
  15254. index = ~index;
  15255. }
  15256. if (index >= leapSeconds.length) {
  15257. index = leapSeconds.length - 1;
  15258. }
  15259. var offset = leapSeconds[index].offset;
  15260. if (index > 0) {
  15261. //Now we have the index of the closest leap second that comes on or after our UTC time.
  15262. //However, if the difference between the UTC date being converted and the TAI
  15263. //defined leap second is greater than the offset, we are off by one and need to use
  15264. //the previous leap second.
  15265. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  15266. if (difference > offset) {
  15267. index--;
  15268. offset = leapSeconds[index].offset;
  15269. }
  15270. }
  15271. JulianDate.addSeconds(julianDate, offset, julianDate);
  15272. }
  15273. function convertTaiToUtc(julianDate, result) {
  15274. binarySearchScratchLeapSecond.julianDate = julianDate;
  15275. var leapSeconds = JulianDate.leapSeconds;
  15276. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  15277. if (index < 0) {
  15278. index = ~index;
  15279. }
  15280. //All times before our first leap second get the first offset.
  15281. if (index === 0) {
  15282. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  15283. }
  15284. //All times after our leap second get the last offset.
  15285. if (index >= leapSeconds.length) {
  15286. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  15287. }
  15288. //Compute the difference between the found leap second and the time we are converting.
  15289. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  15290. if (difference === 0) {
  15291. //The date is in our leap second table.
  15292. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  15293. }
  15294. if (difference <= 1.0) {
  15295. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  15296. return undefined;
  15297. }
  15298. //The time is in between two leap seconds, index is the leap second after the date
  15299. //we're converting, so we subtract one to get the correct LeapSecond instance.
  15300. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  15301. }
  15302. function setComponents(wholeDays, secondsOfDay, julianDate) {
  15303. var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
  15304. wholeDays += extraDays;
  15305. secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
  15306. if (secondsOfDay < 0) {
  15307. wholeDays--;
  15308. secondsOfDay += TimeConstants.SECONDS_PER_DAY;
  15309. }
  15310. julianDate.dayNumber = wholeDays;
  15311. julianDate.secondsOfDay = secondsOfDay;
  15312. return julianDate;
  15313. }
  15314. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  15315. // Algorithm from page 604 of the Explanatory Supplement to the
  15316. // Astronomical Almanac (Seidelmann 1992).
  15317. var a = ((month - 14) / 12) | 0;
  15318. var b = year + 4800 + a;
  15319. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  15320. // JulianDates are noon-based
  15321. hour = hour - 12;
  15322. if (hour < 0) {
  15323. hour += 24;
  15324. }
  15325. var secondsOfDay = second + ((hour * TimeConstants.SECONDS_PER_HOUR) + (minute * TimeConstants.SECONDS_PER_MINUTE) + (millisecond * TimeConstants.SECONDS_PER_MILLISECOND));
  15326. if (secondsOfDay >= 43200.0) {
  15327. dayNumber -= 1;
  15328. }
  15329. return [dayNumber, secondsOfDay];
  15330. }
  15331. //Regular expressions used for ISO8601 date parsing.
  15332. //YYYY
  15333. var matchCalendarYear = /^(\d{4})$/;
  15334. //YYYY-MM (YYYYMM is invalid)
  15335. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  15336. //YYYY-DDD or YYYYDDD
  15337. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  15338. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  15339. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  15340. //YYYY-MM-DD or YYYYMMDD
  15341. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  15342. // Match utc offset
  15343. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  15344. // Match hours HH or HH.xxxxx
  15345. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  15346. // Match hours/minutes HH:MM HHMM.xxxxx
  15347. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  15348. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  15349. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  15350. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  15351. /**
  15352. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  15353. * For increased precision, this class stores the whole number part of the date and the seconds
  15354. * part of the date in separate components. In order to be safe for arithmetic and represent
  15355. * leap seconds, the date is always stored in the International Atomic Time standard
  15356. * {@link TimeStandard.TAI}.
  15357. * @alias JulianDate
  15358. * @constructor
  15359. *
  15360. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  15361. * @param {Number} [secondsOfDay=0.0] The number of seconds into the current Julian Day Number. Fractional seconds, negative seconds and seconds greater than a day will be handled correctly.
  15362. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  15363. */
  15364. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  15365. /**
  15366. * Gets or sets the number of whole days.
  15367. * @type {Number}
  15368. */
  15369. this.dayNumber = undefined;
  15370. /**
  15371. * Gets or sets the number of seconds into the current day.
  15372. * @type {Number}
  15373. */
  15374. this.secondsOfDay = undefined;
  15375. julianDayNumber = defaultValue(julianDayNumber, 0.0);
  15376. secondsOfDay = defaultValue(secondsOfDay, 0.0);
  15377. timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
  15378. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  15379. var wholeDays = julianDayNumber | 0;
  15380. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
  15381. setComponents(wholeDays, secondsOfDay, this);
  15382. if (timeStandard === TimeStandard.UTC) {
  15383. convertUtcToTai(this);
  15384. }
  15385. }
  15386. /**
  15387. * Creates a new instance from a JavaScript Date.
  15388. *
  15389. * @param {Date} date A JavaScript Date.
  15390. * @param {JulianDate} [result] An existing instance to use for the result.
  15391. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15392. *
  15393. * @exception {DeveloperError} date must be a valid JavaScript Date.
  15394. */
  15395. JulianDate.fromDate = function(date, result) {
  15396. if (!(date instanceof Date) || isNaN(date.getTime())) {
  15397. throw new DeveloperError('date must be a valid JavaScript Date.');
  15398. }
  15399. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  15400. if (!defined(result)) {
  15401. return new JulianDate(components[0], components[1], TimeStandard.UTC);
  15402. }
  15403. setComponents(components[0], components[1], result);
  15404. convertUtcToTai(result);
  15405. return result;
  15406. };
  15407. /**
  15408. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  15409. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  15410. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  15411. *
  15412. * @param {String} iso8601String An ISO 8601 date.
  15413. * @param {JulianDate} [result] An existing instance to use for the result.
  15414. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15415. *
  15416. * @exception {DeveloperError} Invalid ISO 8601 date.
  15417. */
  15418. JulianDate.fromIso8601 = function(iso8601String, result) {
  15419. if (typeof iso8601String !== 'string') {
  15420. throw new DeveloperError(iso8601ErrorMessage);
  15421. }
  15422. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  15423. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  15424. iso8601String = iso8601String.replace(',', '.');
  15425. //Split the string into its date and time components, denoted by a mandatory T
  15426. var tokens = iso8601String.split('T');
  15427. var year;
  15428. var month = 1;
  15429. var day = 1;
  15430. var hour = 0;
  15431. var minute = 0;
  15432. var second = 0;
  15433. var millisecond = 0;
  15434. //Lacking a time is okay, but a missing date is illegal.
  15435. var date = tokens[0];
  15436. var time = tokens[1];
  15437. var tmp;
  15438. var inLeapYear;
  15439. if (!defined(date)) {
  15440. throw new DeveloperError(iso8601ErrorMessage);
  15441. }
  15442. var dashCount;
  15443. //First match the date against possible regular expressions.
  15444. tokens = date.match(matchCalendarDate);
  15445. if (tokens !== null) {
  15446. dashCount = date.split('-').length - 1;
  15447. if (dashCount > 0 && dashCount !== 2) {
  15448. throw new DeveloperError(iso8601ErrorMessage);
  15449. }
  15450. year = +tokens[1];
  15451. month = +tokens[2];
  15452. day = +tokens[3];
  15453. } else {
  15454. tokens = date.match(matchCalendarMonth);
  15455. if (tokens !== null) {
  15456. year = +tokens[1];
  15457. month = +tokens[2];
  15458. } else {
  15459. tokens = date.match(matchCalendarYear);
  15460. if (tokens !== null) {
  15461. year = +tokens[1];
  15462. } else {
  15463. //Not a year/month/day so it must be an ordinal date.
  15464. var dayOfYear;
  15465. tokens = date.match(matchOrdinalDate);
  15466. if (tokens !== null) {
  15467. year = +tokens[1];
  15468. dayOfYear = +tokens[2];
  15469. inLeapYear = isLeapYear(year);
  15470. //This validation is only applicable for this format.
  15471. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  15472. throw new DeveloperError(iso8601ErrorMessage);
  15473. }
  15474. } else {
  15475. tokens = date.match(matchWeekDate);
  15476. if (tokens !== null) {
  15477. //ISO week date to ordinal date from
  15478. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  15479. year = +tokens[1];
  15480. var weekNumber = +tokens[2];
  15481. var dayOfWeek = +tokens[3] || 0;
  15482. dashCount = date.split('-').length - 1;
  15483. if (dashCount > 0 &&
  15484. ((!defined(tokens[3]) && dashCount !== 1) ||
  15485. (defined(tokens[3]) && dashCount !== 2))) {
  15486. throw new DeveloperError(iso8601ErrorMessage);
  15487. }
  15488. var january4 = new Date(Date.UTC(year, 0, 4));
  15489. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  15490. } else {
  15491. //None of our regular expressions succeeded in parsing the date properly.
  15492. throw new DeveloperError(iso8601ErrorMessage);
  15493. }
  15494. }
  15495. //Split an ordinal date into month/day.
  15496. tmp = new Date(Date.UTC(year, 0, 1));
  15497. tmp.setUTCDate(dayOfYear);
  15498. month = tmp.getUTCMonth() + 1;
  15499. day = tmp.getUTCDate();
  15500. }
  15501. }
  15502. }
  15503. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  15504. inLeapYear = isLeapYear(year);
  15505. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  15506. throw new DeveloperError(iso8601ErrorMessage);
  15507. }
  15508. //Not move onto the time string, which is much simpler.
  15509. var offsetIndex;
  15510. if (defined(time)) {
  15511. tokens = time.match(matchHoursMinutesSeconds);
  15512. if (tokens !== null) {
  15513. dashCount = time.split(':').length - 1;
  15514. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  15515. throw new DeveloperError(iso8601ErrorMessage);
  15516. }
  15517. hour = +tokens[1];
  15518. minute = +tokens[2];
  15519. second = +tokens[3];
  15520. millisecond = +(tokens[4] || 0) * 1000.0;
  15521. offsetIndex = 5;
  15522. } else {
  15523. tokens = time.match(matchHoursMinutes);
  15524. if (tokens !== null) {
  15525. dashCount = time.split(':').length - 1;
  15526. if (dashCount > 2) {
  15527. throw new DeveloperError(iso8601ErrorMessage);
  15528. }
  15529. hour = +tokens[1];
  15530. minute = +tokens[2];
  15531. second = +(tokens[3] || 0) * 60.0;
  15532. offsetIndex = 4;
  15533. } else {
  15534. tokens = time.match(matchHours);
  15535. if (tokens !== null) {
  15536. hour = +tokens[1];
  15537. minute = +(tokens[2] || 0) * 60.0;
  15538. offsetIndex = 3;
  15539. } else {
  15540. throw new DeveloperError(iso8601ErrorMessage);
  15541. }
  15542. }
  15543. }
  15544. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  15545. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  15546. throw new DeveloperError(iso8601ErrorMessage);
  15547. }
  15548. //Check the UTC offset value, if no value exists, use local time
  15549. //a Z indicates UTC, + or - are offsets.
  15550. var offset = tokens[offsetIndex];
  15551. var offsetHours = +(tokens[offsetIndex + 1]);
  15552. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  15553. switch (offset) {
  15554. case '+':
  15555. hour = hour - offsetHours;
  15556. minute = minute - offsetMinutes;
  15557. break;
  15558. case '-':
  15559. hour = hour + offsetHours;
  15560. minute = minute + offsetMinutes;
  15561. break;
  15562. case 'Z':
  15563. break;
  15564. default:
  15565. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  15566. break;
  15567. }
  15568. } else {
  15569. //If no time is specified, it is considered the beginning of the day, local time.
  15570. minute = minute + new Date(year, month - 1, day).getTimezoneOffset();
  15571. }
  15572. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  15573. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  15574. //Then we add it back in after converting to TAI.
  15575. var isLeapSecond = second === 60;
  15576. if (isLeapSecond) {
  15577. second--;
  15578. }
  15579. //Even if we successfully parsed the string into its components, after applying UTC offset or
  15580. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  15581. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  15582. while (minute >= 60) {
  15583. minute -= 60;
  15584. hour++;
  15585. }
  15586. while (hour >= 24) {
  15587. hour -= 24;
  15588. day++;
  15589. }
  15590. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15591. while (day > tmp) {
  15592. day -= tmp;
  15593. month++;
  15594. if (month > 12) {
  15595. month -= 12;
  15596. year++;
  15597. }
  15598. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15599. }
  15600. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  15601. while (minute < 0) {
  15602. minute += 60;
  15603. hour--;
  15604. }
  15605. while (hour < 0) {
  15606. hour += 24;
  15607. day--;
  15608. }
  15609. while (day < 1) {
  15610. month--;
  15611. if (month < 1) {
  15612. month += 12;
  15613. year--;
  15614. }
  15615. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  15616. day += tmp;
  15617. }
  15618. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  15619. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  15620. if (!defined(result)) {
  15621. result = new JulianDate(components[0], components[1], TimeStandard.UTC);
  15622. } else {
  15623. setComponents(components[0], components[1], result);
  15624. convertUtcToTai(result);
  15625. }
  15626. //If we were on a leap second, add it back.
  15627. if (isLeapSecond) {
  15628. JulianDate.addSeconds(result, 1, result);
  15629. }
  15630. return result;
  15631. };
  15632. /**
  15633. * Creates a new instance that represents the current system time.
  15634. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  15635. *
  15636. * @param {JulianDate} [result] An existing instance to use for the result.
  15637. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  15638. */
  15639. JulianDate.now = function(result) {
  15640. return JulianDate.fromDate(new Date(), result);
  15641. };
  15642. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
  15643. /**
  15644. * Creates a {@link GregorianDate} from the provided instance.
  15645. *
  15646. * @param {JulianDate} julianDate The date to be converted.
  15647. * @param {GregorianDate} [result] An existing instance to use for the result.
  15648. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  15649. */
  15650. JulianDate.toGregorianDate = function(julianDate, result) {
  15651. if (!defined(julianDate)) {
  15652. throw new DeveloperError('julianDate is required.');
  15653. }
  15654. var isLeapSecond = false;
  15655. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  15656. if (!defined(thisUtc)) {
  15657. //Conversion to UTC will fail if we are during a leap second.
  15658. //If that's the case, subtract a second and convert again.
  15659. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  15660. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  15661. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  15662. isLeapSecond = true;
  15663. }
  15664. var julianDayNumber = thisUtc.dayNumber;
  15665. var secondsOfDay = thisUtc.secondsOfDay;
  15666. if (secondsOfDay >= 43200.0) {
  15667. julianDayNumber += 1;
  15668. }
  15669. // Algorithm from page 604 of the Explanatory Supplement to the
  15670. // Astronomical Almanac (Seidelmann 1992).
  15671. var L = (julianDayNumber + 68569) | 0;
  15672. var N = (4 * L / 146097) | 0;
  15673. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  15674. var I = ((4000 * (L + 1)) / 1461001) | 0;
  15675. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  15676. var J = ((80 * L) / 2447) | 0;
  15677. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  15678. L = (J / 11) | 0;
  15679. var month = (J + 2 - 12 * L) | 0;
  15680. var year = (100 * (N - 49) + I + L) | 0;
  15681. var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
  15682. var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR);
  15683. var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
  15684. remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE);
  15685. var second = remainingSeconds | 0;
  15686. var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND);
  15687. // JulianDates are noon-based
  15688. hour += 12;
  15689. if (hour > 23) {
  15690. hour -= 24;
  15691. }
  15692. //If we were on a leap second, add it back.
  15693. if (isLeapSecond) {
  15694. second += 1;
  15695. }
  15696. if (!defined(result)) {
  15697. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  15698. }
  15699. result.year = year;
  15700. result.month = month;
  15701. result.day = day;
  15702. result.hour = hour;
  15703. result.minute = minute;
  15704. result.second = second;
  15705. result.millisecond = millisecond;
  15706. result.isLeapSecond = isLeapSecond;
  15707. return result;
  15708. };
  15709. /**
  15710. * Creates a JavaScript Date from the provided instance.
  15711. * Since JavaScript dates are only accurate to the nearest millisecond and
  15712. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  15713. * If the provided JulianDate is during a leap second, the previous second is used.
  15714. *
  15715. * @param {JulianDate} julianDate The date to be converted.
  15716. * @returns {Date} A new instance representing the provided date.
  15717. */
  15718. JulianDate.toDate = function(julianDate) {
  15719. if (!defined(julianDate)) {
  15720. throw new DeveloperError('julianDate is required.');
  15721. }
  15722. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  15723. var second = gDate.second;
  15724. if (gDate.isLeapSecond) {
  15725. second -= 1;
  15726. }
  15727. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  15728. };
  15729. /**
  15730. * Creates an ISO8601 representation of the provided date.
  15731. *
  15732. * @param {JulianDate} julianDate The date to be converted.
  15733. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  15734. * @returns {String} The ISO8601 representation of the provided date.
  15735. */
  15736. JulianDate.toIso8601 = function(julianDate, precision) {
  15737. if (!defined(julianDate)) {
  15738. throw new DeveloperError('julianDate is required.');
  15739. }
  15740. var gDate = JulianDate.toGregorianDate(julianDate, gDate);
  15741. var millisecondStr;
  15742. if (!defined(precision) && gDate.millisecond !== 0) {
  15743. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  15744. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', '');
  15745. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  15746. }
  15747. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  15748. if (!defined(precision) || precision === 0) {
  15749. return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second);
  15750. }
  15751. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  15752. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  15753. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  15754. };
  15755. /**
  15756. * Duplicates a JulianDate instance.
  15757. *
  15758. * @param {JulianDate} julianDate The date to duplicate.
  15759. * @param {JulianDate} [result] An existing instance to use for the result.
  15760. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  15761. */
  15762. JulianDate.clone = function(julianDate, result) {
  15763. if (!defined(julianDate)) {
  15764. return undefined;
  15765. }
  15766. if (!defined(result)) {
  15767. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI);
  15768. }
  15769. result.dayNumber = julianDate.dayNumber;
  15770. result.secondsOfDay = julianDate.secondsOfDay;
  15771. return result;
  15772. };
  15773. /**
  15774. * Compares two instances.
  15775. *
  15776. * @param {JulianDate} left The first instance.
  15777. * @param {JulianDate} right The second instance.
  15778. * @returns {Number} A negative value if left is less than right, a positive value if left is greater than right, or zero if left and right are equal.
  15779. */
  15780. JulianDate.compare = function(left, right) {
  15781. if (!defined(left)) {
  15782. throw new DeveloperError('left is required.');
  15783. }
  15784. if (!defined(right)) {
  15785. throw new DeveloperError('right is required.');
  15786. }
  15787. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  15788. if (julianDayNumberDifference !== 0) {
  15789. return julianDayNumberDifference;
  15790. }
  15791. return left.secondsOfDay - right.secondsOfDay;
  15792. };
  15793. /**
  15794. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  15795. *
  15796. * @param {JulianDate} [left] The first instance.
  15797. * @param {JulianDate} [right] The second instance.
  15798. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  15799. */
  15800. JulianDate.equals = function(left, right) {
  15801. return (left === right) ||
  15802. (defined(left) &&
  15803. defined(right) &&
  15804. left.dayNumber === right.dayNumber &&
  15805. left.secondsOfDay === right.secondsOfDay);
  15806. };
  15807. /**
  15808. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  15809. * each other. That is, in order for the dates to be considered equal (and for
  15810. * this function to return <code>true</code>), the absolute value of the difference between them, in
  15811. * seconds, must be less than <code>epsilon</code>.
  15812. *
  15813. * @param {JulianDate} [left] The first instance.
  15814. * @param {JulianDate} [right] The second instance.
  15815. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  15816. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  15817. */
  15818. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  15819. if (!defined(epsilon)) {
  15820. throw new DeveloperError('epsilon is required.');
  15821. }
  15822. return (left === right) ||
  15823. (defined(left) &&
  15824. defined(right) &&
  15825. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  15826. };
  15827. /**
  15828. * Computes the total number of whole and fractional days represented by the provided instance.
  15829. *
  15830. * @param {JulianDate} julianDate The date.
  15831. * @returns {Number} The Julian date as single floating point number.
  15832. */
  15833. JulianDate.totalDays = function(julianDate) {
  15834. if (!defined(julianDate)) {
  15835. throw new DeveloperError('julianDate is required.');
  15836. }
  15837. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY);
  15838. };
  15839. /**
  15840. * Computes the difference in seconds between the provided instance.
  15841. *
  15842. * @param {JulianDate} left The first instance.
  15843. * @param {JulianDate} right The second instance.
  15844. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  15845. */
  15846. JulianDate.secondsDifference = function(left, right) {
  15847. if (!defined(left)) {
  15848. throw new DeveloperError('left is required.');
  15849. }
  15850. if (!defined(right)) {
  15851. throw new DeveloperError('right is required.');
  15852. }
  15853. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
  15854. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  15855. };
  15856. /**
  15857. * Computes the difference in days between the provided instance.
  15858. *
  15859. * @param {JulianDate} left The first instance.
  15860. * @param {JulianDate} right The second instance.
  15861. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  15862. */
  15863. JulianDate.daysDifference = function(left, right) {
  15864. if (!defined(left)) {
  15865. throw new DeveloperError('left is required.');
  15866. }
  15867. if (!defined(right)) {
  15868. throw new DeveloperError('right is required.');
  15869. }
  15870. var dayDifference = (left.dayNumber - right.dayNumber);
  15871. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
  15872. return dayDifference + secondDifference;
  15873. };
  15874. /**
  15875. * Computes the number of seconds the provided instance is ahead of UTC.
  15876. *
  15877. * @param {JulianDate} julianDate The date.
  15878. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  15879. */
  15880. JulianDate.computeTaiMinusUtc = function(julianDate) {
  15881. binarySearchScratchLeapSecond.julianDate = julianDate;
  15882. var leapSeconds = JulianDate.leapSeconds;
  15883. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  15884. if (index < 0) {
  15885. index = ~index;
  15886. --index;
  15887. if (index < 0) {
  15888. index = 0;
  15889. }
  15890. }
  15891. return leapSeconds[index].offset;
  15892. };
  15893. /**
  15894. * Adds the provided number of seconds to the provided date instance.
  15895. *
  15896. * @param {JulianDate} julianDate The date.
  15897. * @param {Number} seconds The number of seconds to add or subtract.
  15898. * @param {JulianDate} result An existing instance to use for the result.
  15899. * @returns {JulianDate} The modified result parameter.
  15900. */
  15901. JulianDate.addSeconds = function(julianDate, seconds, result) {
  15902. if (!defined(julianDate)) {
  15903. throw new DeveloperError('julianDate is required.');
  15904. }
  15905. if (!defined(seconds)) {
  15906. throw new DeveloperError('seconds is required.');
  15907. }
  15908. if (!defined(result)) {
  15909. throw new DeveloperError('result is required.');
  15910. }
  15911. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  15912. };
  15913. /**
  15914. * Adds the provided number of minutes to the provided date instance.
  15915. *
  15916. * @param {JulianDate} julianDate The date.
  15917. * @param {Number} minutes The number of minutes to add or subtract.
  15918. * @param {JulianDate} result An existing instance to use for the result.
  15919. * @returns {JulianDate} The modified result parameter.
  15920. */
  15921. JulianDate.addMinutes = function(julianDate, minutes, result) {
  15922. if (!defined(julianDate)) {
  15923. throw new DeveloperError('julianDate is required.');
  15924. }
  15925. if (!defined(minutes)) {
  15926. throw new DeveloperError('minutes is required.');
  15927. }
  15928. if (!defined(result)) {
  15929. throw new DeveloperError('result is required.');
  15930. }
  15931. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE);
  15932. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  15933. };
  15934. /**
  15935. * Adds the provided number of hours to the provided date instance.
  15936. *
  15937. * @param {JulianDate} julianDate The date.
  15938. * @param {Number} hours The number of hours to add or subtract.
  15939. * @param {JulianDate} result An existing instance to use for the result.
  15940. * @returns {JulianDate} The modified result parameter.
  15941. */
  15942. JulianDate.addHours = function(julianDate, hours, result) {
  15943. if (!defined(julianDate)) {
  15944. throw new DeveloperError('julianDate is required.');
  15945. }
  15946. if (!defined(hours)) {
  15947. throw new DeveloperError('hours is required.');
  15948. }
  15949. if (!defined(result)) {
  15950. throw new DeveloperError('result is required.');
  15951. }
  15952. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR);
  15953. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  15954. };
  15955. /**
  15956. * Adds the provided number of days to the provided date instance.
  15957. *
  15958. * @param {JulianDate} julianDate The date.
  15959. * @param {Number} days The number of days to add or subtract.
  15960. * @param {JulianDate} result An existing instance to use for the result.
  15961. * @returns {JulianDate} The modified result parameter.
  15962. */
  15963. JulianDate.addDays = function(julianDate, days, result) {
  15964. if (!defined(julianDate)) {
  15965. throw new DeveloperError('julianDate is required.');
  15966. }
  15967. if (!defined(days)) {
  15968. throw new DeveloperError('days is required.');
  15969. }
  15970. if (!defined(result)) {
  15971. throw new DeveloperError('result is required.');
  15972. }
  15973. var newJulianDayNumber = julianDate.dayNumber + days;
  15974. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  15975. };
  15976. /**
  15977. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  15978. *
  15979. * @param {JulianDate} left The first instance.
  15980. * @param {JulianDate} right The second instance.
  15981. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  15982. */
  15983. JulianDate.lessThan = function(left, right) {
  15984. return JulianDate.compare(left, right) < 0;
  15985. };
  15986. /**
  15987. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  15988. *
  15989. * @param {JulianDate} left The first instance.
  15990. * @param {JulianDate} right The second instance.
  15991. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  15992. */
  15993. JulianDate.lessThanOrEquals = function(left, right) {
  15994. return JulianDate.compare(left, right) <= 0;
  15995. };
  15996. /**
  15997. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  15998. *
  15999. * @param {JulianDate} left The first instance.
  16000. * @param {JulianDate} right The second instance.
  16001. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  16002. */
  16003. JulianDate.greaterThan = function(left, right) {
  16004. return JulianDate.compare(left, right) > 0;
  16005. };
  16006. /**
  16007. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  16008. *
  16009. * @param {JulianDate} left The first instance.
  16010. * @param {JulianDate} right The second instance.
  16011. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  16012. */
  16013. JulianDate.greaterThanOrEquals = function(left, right) {
  16014. return JulianDate.compare(left, right) >= 0;
  16015. };
  16016. /**
  16017. * Duplicates this instance.
  16018. *
  16019. * @param {JulianDate} [result] An existing instance to use for the result.
  16020. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  16021. */
  16022. JulianDate.prototype.clone = function(result) {
  16023. return JulianDate.clone(this, result);
  16024. };
  16025. /**
  16026. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  16027. *
  16028. * @param {JulianDate} [right] The second instance.
  16029. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  16030. */
  16031. JulianDate.prototype.equals = function(right) {
  16032. return JulianDate.equals(this, right);
  16033. };
  16034. /**
  16035. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  16036. * each other. That is, in order for the dates to be considered equal (and for
  16037. * this function to return <code>true</code>), the absolute value of the difference between them, in
  16038. * seconds, must be less than <code>epsilon</code>.
  16039. *
  16040. * @param {JulianDate} [right] The second instance.
  16041. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  16042. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  16043. */
  16044. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  16045. return JulianDate.equalsEpsilon(this, right, epsilon);
  16046. };
  16047. /**
  16048. * Creates a string representing this date in ISO8601 format.
  16049. *
  16050. * @returns {String} A string representing this date in ISO8601 format.
  16051. */
  16052. JulianDate.prototype.toString = function() {
  16053. return JulianDate.toIso8601(this);
  16054. };
  16055. /**
  16056. * Gets or sets the list of leap seconds used throughout Cesium.
  16057. * @memberof JulianDate
  16058. * @type {LeapSecond[]}
  16059. */
  16060. JulianDate.leapSeconds = [
  16061. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard.TAI), 10), // January 1, 1972 00:00:00 UTC
  16062. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard.TAI), 11), // July 1, 1972 00:00:00 UTC
  16063. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard.TAI), 12), // January 1, 1973 00:00:00 UTC
  16064. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard.TAI), 13), // January 1, 1974 00:00:00 UTC
  16065. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard.TAI), 14), // January 1, 1975 00:00:00 UTC
  16066. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard.TAI), 15), // January 1, 1976 00:00:00 UTC
  16067. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard.TAI), 16), // January 1, 1977 00:00:00 UTC
  16068. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard.TAI), 17), // January 1, 1978 00:00:00 UTC
  16069. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard.TAI), 18), // January 1, 1979 00:00:00 UTC
  16070. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard.TAI), 19), // January 1, 1980 00:00:00 UTC
  16071. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard.TAI), 20), // July 1, 1981 00:00:00 UTC
  16072. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard.TAI), 21), // July 1, 1982 00:00:00 UTC
  16073. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard.TAI), 22), // July 1, 1983 00:00:00 UTC
  16074. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard.TAI), 23), // July 1, 1985 00:00:00 UTC
  16075. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard.TAI), 24), // January 1, 1988 00:00:00 UTC
  16076. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard.TAI), 25), // January 1, 1990 00:00:00 UTC
  16077. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard.TAI), 26), // January 1, 1991 00:00:00 UTC
  16078. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard.TAI), 27), // July 1, 1992 00:00:00 UTC
  16079. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard.TAI), 28), // July 1, 1993 00:00:00 UTC
  16080. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard.TAI), 29), // July 1, 1994 00:00:00 UTC
  16081. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard.TAI), 30), // January 1, 1996 00:00:00 UTC
  16082. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard.TAI), 31), // July 1, 1997 00:00:00 UTC
  16083. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard.TAI), 32), // January 1, 1999 00:00:00 UTC
  16084. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard.TAI), 33), // January 1, 2006 00:00:00 UTC
  16085. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard.TAI), 34), // January 1, 2009 00:00:00 UTC
  16086. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard.TAI), 35), // July 1, 2012 00:00:00 UTC
  16087. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard.TAI), 36), // July 1, 2015 00:00:00 UTC
  16088. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard.TAI), 37) // January 1, 2017 00:00:00 UTC
  16089. ];
  16090. return JulianDate;
  16091. });
  16092. /*global define*/
  16093. define('Core/clone',[
  16094. './defaultValue'
  16095. ], function(
  16096. defaultValue) {
  16097. 'use strict';
  16098. /**
  16099. * Clones an object, returning a new object containing the same properties.
  16100. *
  16101. * @exports clone
  16102. *
  16103. * @param {Object} object The object to clone.
  16104. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  16105. * @returns {Object} The cloned object.
  16106. */
  16107. function clone(object, deep) {
  16108. if (object === null || typeof object !== 'object') {
  16109. return object;
  16110. }
  16111. deep = defaultValue(deep, false);
  16112. var result = new object.constructor();
  16113. for ( var propertyName in object) {
  16114. if (object.hasOwnProperty(propertyName)) {
  16115. var value = object[propertyName];
  16116. if (deep) {
  16117. value = clone(value, deep);
  16118. }
  16119. result[propertyName] = value;
  16120. }
  16121. }
  16122. return result;
  16123. }
  16124. return clone;
  16125. });
  16126. /*global define*/
  16127. define('Core/parseResponseHeaders',[], function() {
  16128. 'use strict';
  16129. /**
  16130. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  16131. * a dictionary.
  16132. *
  16133. * @exports parseResponseHeaders
  16134. *
  16135. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  16136. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  16137. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  16138. * is that header's value.
  16139. *
  16140. * @private
  16141. */
  16142. function parseResponseHeaders(headerString) {
  16143. var headers = {};
  16144. if (!headerString) {
  16145. return headers;
  16146. }
  16147. var headerPairs = headerString.split('\u000d\u000a');
  16148. for (var i = 0; i < headerPairs.length; ++i) {
  16149. var headerPair = headerPairs[i];
  16150. // Can't use split() here because it does the wrong thing
  16151. // if the header value has the string ": " in it.
  16152. var index = headerPair.indexOf('\u003a\u0020');
  16153. if (index > 0) {
  16154. var key = headerPair.substring(0, index);
  16155. var val = headerPair.substring(index + 2);
  16156. headers[key] = val;
  16157. }
  16158. }
  16159. return headers;
  16160. }
  16161. return parseResponseHeaders;
  16162. });
  16163. /*global define*/
  16164. define('Core/RequestErrorEvent',[
  16165. './defined',
  16166. './parseResponseHeaders'
  16167. ], function(
  16168. defined,
  16169. parseResponseHeaders) {
  16170. 'use strict';
  16171. /**
  16172. * An event that is raised when a request encounters an error.
  16173. *
  16174. * @constructor
  16175. * @alias RequestErrorEvent
  16176. *
  16177. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  16178. * @param {Object} [response] The response included along with the error.
  16179. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  16180. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  16181. */
  16182. function RequestErrorEvent(statusCode, response, responseHeaders) {
  16183. /**
  16184. * The HTTP error status code, such as 404. If the error does not have a particular
  16185. * HTTP code, this property will be undefined.
  16186. *
  16187. * @type {Number}
  16188. */
  16189. this.statusCode = statusCode;
  16190. /**
  16191. * The response included along with the error. If the error does not include a response,
  16192. * this property will be undefined.
  16193. *
  16194. * @type {Object}
  16195. */
  16196. this.response = response;
  16197. /**
  16198. * The headers included in the response, represented as an object literal of key/value pairs.
  16199. * If the error does not include any headers, this property will be undefined.
  16200. *
  16201. * @type {Object}
  16202. */
  16203. this.responseHeaders = responseHeaders;
  16204. if (typeof this.responseHeaders === 'string') {
  16205. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  16206. }
  16207. }
  16208. /**
  16209. * Creates a string representing this RequestErrorEvent.
  16210. * @memberof RequestErrorEvent
  16211. *
  16212. * @returns {String} A string representing the provided RequestErrorEvent.
  16213. */
  16214. RequestErrorEvent.prototype.toString = function() {
  16215. var str = 'Request has failed.';
  16216. if (defined(this.statusCode)) {
  16217. str += ' Status Code: ' + this.statusCode;
  16218. }
  16219. return str;
  16220. };
  16221. return RequestErrorEvent;
  16222. });
  16223. /**
  16224. * @license
  16225. *
  16226. * Grauw URI utilities
  16227. *
  16228. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  16229. *
  16230. * @author Laurens Holst (http://www.grauw.nl/)
  16231. *
  16232. * Copyright 2012 Laurens Holst
  16233. *
  16234. * Licensed under the Apache License, Version 2.0 (the "License");
  16235. * you may not use this file except in compliance with the License.
  16236. * You may obtain a copy of the License at
  16237. *
  16238. * http://www.apache.org/licenses/LICENSE-2.0
  16239. *
  16240. * Unless required by applicable law or agreed to in writing, software
  16241. * distributed under the License is distributed on an "AS IS" BASIS,
  16242. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16243. * See the License for the specific language governing permissions and
  16244. * limitations under the License.
  16245. *
  16246. */
  16247. /*global define*/
  16248. define('ThirdParty/Uri',[],function() {
  16249. /**
  16250. * Constructs a URI object.
  16251. * @constructor
  16252. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  16253. * @param {string|URI} uri A string or URI object to create the object from.
  16254. */
  16255. function URI(uri) {
  16256. if (uri instanceof URI) { // copy constructor
  16257. this.scheme = uri.scheme;
  16258. this.authority = uri.authority;
  16259. this.path = uri.path;
  16260. this.query = uri.query;
  16261. this.fragment = uri.fragment;
  16262. } else if (uri) { // uri is URI string or cast to string
  16263. var c = parseRegex.exec(uri);
  16264. this.scheme = c[1];
  16265. this.authority = c[2];
  16266. this.path = c[3];
  16267. this.query = c[4];
  16268. this.fragment = c[5];
  16269. }
  16270. }
  16271. // Initial values on the prototype
  16272. URI.prototype.scheme = null;
  16273. URI.prototype.authority = null;
  16274. URI.prototype.path = '';
  16275. URI.prototype.query = null;
  16276. URI.prototype.fragment = null;
  16277. // Regular expression from RFC 3986 appendix B
  16278. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  16279. /**
  16280. * Returns the scheme part of the URI.
  16281. * In "http://example.com:80/a/b?x#y" this is "http".
  16282. */
  16283. URI.prototype.getScheme = function() {
  16284. return this.scheme;
  16285. };
  16286. /**
  16287. * Returns the authority part of the URI.
  16288. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  16289. */
  16290. URI.prototype.getAuthority = function() {
  16291. return this.authority;
  16292. };
  16293. /**
  16294. * Returns the path part of the URI.
  16295. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  16296. * In "mailto:mike@example.com" this is "mike@example.com".
  16297. */
  16298. URI.prototype.getPath = function() {
  16299. return this.path;
  16300. };
  16301. /**
  16302. * Returns the query part of the URI.
  16303. * In "http://example.com:80/a/b?x#y" this is "x".
  16304. */
  16305. URI.prototype.getQuery = function() {
  16306. return this.query;
  16307. };
  16308. /**
  16309. * Returns the fragment part of the URI.
  16310. * In "http://example.com:80/a/b?x#y" this is "y".
  16311. */
  16312. URI.prototype.getFragment = function() {
  16313. return this.fragment;
  16314. };
  16315. /**
  16316. * Tests whether the URI is an absolute URI.
  16317. * See RFC 3986 section 4.3.
  16318. */
  16319. URI.prototype.isAbsolute = function() {
  16320. return !!this.scheme && !this.fragment;
  16321. };
  16322. ///**
  16323. //* Extensive validation of the URI against the ABNF in RFC 3986
  16324. //*/
  16325. //URI.prototype.validate
  16326. /**
  16327. * Tests whether the URI is a same-document reference.
  16328. * See RFC 3986 section 4.4.
  16329. *
  16330. * To perform more thorough comparison, you can normalise the URI objects.
  16331. */
  16332. URI.prototype.isSameDocumentAs = function(uri) {
  16333. return uri.scheme == this.scheme &&
  16334. uri.authority == this.authority &&
  16335. uri.path == this.path &&
  16336. uri.query == this.query;
  16337. };
  16338. /**
  16339. * Simple String Comparison of two URIs.
  16340. * See RFC 3986 section 6.2.1.
  16341. *
  16342. * To perform more thorough comparison, you can normalise the URI objects.
  16343. */
  16344. URI.prototype.equals = function(uri) {
  16345. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  16346. };
  16347. /**
  16348. * Normalizes the URI using syntax-based normalization.
  16349. * This includes case normalization, percent-encoding normalization and path segment normalization.
  16350. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  16351. * (Although that would not be a valid URI in the first place. See validate().)
  16352. * See RFC 3986 section 6.2.2.
  16353. */
  16354. URI.prototype.normalize = function() {
  16355. this.removeDotSegments();
  16356. if (this.scheme)
  16357. this.scheme = this.scheme.toLowerCase();
  16358. if (this.authority)
  16359. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  16360. replace(caseRegex, replaceCase);
  16361. if (this.path)
  16362. this.path = this.path.replace(caseRegex, replaceCase);
  16363. if (this.query)
  16364. this.query = this.query.replace(caseRegex, replaceCase);
  16365. if (this.fragment)
  16366. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  16367. };
  16368. var caseRegex = /%[0-9a-z]{2}/gi;
  16369. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  16370. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  16371. function replaceCase(str) {
  16372. var dec = unescape(str);
  16373. return percentRegex.test(dec) ? dec : str.toUpperCase();
  16374. }
  16375. function replaceAuthority(str, p1, p2, p3) {
  16376. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  16377. }
  16378. /**
  16379. * Resolve a relative URI (this) against a base URI.
  16380. * The base URI must be an absolute URI.
  16381. * See RFC 3986 section 5.2
  16382. */
  16383. URI.prototype.resolve = function(baseURI) {
  16384. var uri = new URI();
  16385. if (this.scheme) {
  16386. uri.scheme = this.scheme;
  16387. uri.authority = this.authority;
  16388. uri.path = this.path;
  16389. uri.query = this.query;
  16390. } else {
  16391. uri.scheme = baseURI.scheme;
  16392. if (this.authority) {
  16393. uri.authority = this.authority;
  16394. uri.path = this.path;
  16395. uri.query = this.query;
  16396. } else {
  16397. uri.authority = baseURI.authority;
  16398. if (this.path == '') {
  16399. uri.path = baseURI.path;
  16400. uri.query = this.query || baseURI.query;
  16401. } else {
  16402. if (this.path.charAt(0) == '/') {
  16403. uri.path = this.path;
  16404. uri.removeDotSegments();
  16405. } else {
  16406. if (baseURI.authority && baseURI.path == '') {
  16407. uri.path = '/' + this.path;
  16408. } else {
  16409. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  16410. }
  16411. uri.removeDotSegments();
  16412. }
  16413. uri.query = this.query;
  16414. }
  16415. }
  16416. }
  16417. uri.fragment = this.fragment;
  16418. return uri;
  16419. };
  16420. /**
  16421. * Remove dot segments from path.
  16422. * See RFC 3986 section 5.2.4
  16423. * @private
  16424. */
  16425. URI.prototype.removeDotSegments = function() {
  16426. var input = this.path.split('/'),
  16427. output = [],
  16428. segment,
  16429. absPath = input[0] == '';
  16430. if (absPath)
  16431. input.shift();
  16432. var sFirst = input[0] == '' ? input.shift() : null;
  16433. while (input.length) {
  16434. segment = input.shift();
  16435. if (segment == '..') {
  16436. output.pop();
  16437. } else if (segment != '.') {
  16438. output.push(segment);
  16439. }
  16440. }
  16441. if (segment == '.' || segment == '..')
  16442. output.push('');
  16443. if (absPath)
  16444. output.unshift('');
  16445. this.path = output.join('/');
  16446. };
  16447. // We don't like this function because it builds up a cache that is never cleared.
  16448. // /**
  16449. // * Resolves a relative URI against an absolute base URI.
  16450. // * Convenience method.
  16451. // * @param {String} uri the relative URI to resolve
  16452. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  16453. // */
  16454. // URI.resolve = function(sURI, sBaseURI) {
  16455. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  16456. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  16457. // return uri.resolve(baseURI).toString();
  16458. // };
  16459. // var cache = {};
  16460. /**
  16461. * Serialises the URI to a string.
  16462. */
  16463. URI.prototype.toString = function() {
  16464. var result = '';
  16465. if (this.scheme)
  16466. result += this.scheme + ':';
  16467. if (this.authority)
  16468. result += '//' + this.authority;
  16469. result += this.path;
  16470. if (this.query)
  16471. result += '?' + this.query;
  16472. if (this.fragment)
  16473. result += '#' + this.fragment;
  16474. return result;
  16475. };
  16476. return URI;
  16477. });
  16478. /*global define*/
  16479. define('Core/TrustedServers',[
  16480. '../ThirdParty/Uri',
  16481. './defined',
  16482. './DeveloperError'
  16483. ], function(
  16484. Uri,
  16485. defined,
  16486. DeveloperError) {
  16487. 'use strict';
  16488. /**
  16489. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  16490. * any requests to these servers.
  16491. *
  16492. * @exports TrustedServers
  16493. *
  16494. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16495. */
  16496. var TrustedServers = {};
  16497. var _servers = {};
  16498. /**
  16499. * Adds a trusted server to the registry
  16500. *
  16501. * @param {String} host The host to be added.
  16502. * @param {Number} port The port used to access the host.
  16503. *
  16504. * @example
  16505. * // Add a trusted server
  16506. * TrustedServers.add('my.server.com', 80);
  16507. */
  16508. TrustedServers.add = function(host, port) {
  16509. if (!defined(host)) {
  16510. throw new DeveloperError('host is required.');
  16511. }
  16512. if (!defined(port) || port <= 0) {
  16513. throw new DeveloperError('port is required to be greater than 0.');
  16514. }
  16515. var authority = host.toLowerCase() + ':' + port;
  16516. if (!defined(_servers[authority])) {
  16517. _servers[authority] = true;
  16518. }
  16519. };
  16520. /**
  16521. * Removes a trusted server from the registry
  16522. *
  16523. * @param {String} host The host to be removed.
  16524. * @param {Number} port The port used to access the host.
  16525. *
  16526. * @example
  16527. * // Remove a trusted server
  16528. * TrustedServers.remove('my.server.com', 80);
  16529. */
  16530. TrustedServers.remove = function(host, port) {
  16531. if (!defined(host)) {
  16532. throw new DeveloperError('host is required.');
  16533. }
  16534. if (!defined(port) || port <= 0) {
  16535. throw new DeveloperError('port is required to be greater than 0.');
  16536. }
  16537. var authority = host.toLowerCase() + ':' + port;
  16538. if (defined(_servers[authority])) {
  16539. delete _servers[authority];
  16540. }
  16541. };
  16542. function getAuthority(url) {
  16543. var uri = new Uri(url);
  16544. uri.normalize();
  16545. // Removes username:password@ so we just have host[:port]
  16546. var authority = uri.getAuthority();
  16547. if (!defined(authority)) {
  16548. return undefined; // Relative URL
  16549. }
  16550. if (authority.indexOf('@') !== -1) {
  16551. var parts = authority.split('@');
  16552. authority = parts[1];
  16553. }
  16554. // If the port is missing add one based on the scheme
  16555. if (authority.indexOf(':') === -1) {
  16556. var scheme = uri.getScheme();
  16557. if (!defined(scheme)) {
  16558. scheme = window.location.protocol;
  16559. scheme = scheme.substring(0, scheme.length-1);
  16560. }
  16561. if (scheme === 'http') {
  16562. authority += ':80';
  16563. } else if (scheme === 'https') {
  16564. authority += ':443';
  16565. } else {
  16566. return undefined;
  16567. }
  16568. }
  16569. return authority;
  16570. }
  16571. /**
  16572. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  16573. *
  16574. * @param {String} url The url to be tested against the trusted list
  16575. *
  16576. * @returns {boolean} Returns true if url is trusted, false otherwise.
  16577. *
  16578. * @example
  16579. * // Add server
  16580. * TrustedServers.add('my.server.com', 81);
  16581. *
  16582. * // Check if server is trusted
  16583. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  16584. * // my.server.com:81 is trusted
  16585. * }
  16586. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  16587. * // my.server.com isn't trusted
  16588. * }
  16589. */
  16590. TrustedServers.contains = function(url) {
  16591. if (!defined(url)) {
  16592. throw new DeveloperError('url is required.');
  16593. }
  16594. var authority = getAuthority(url);
  16595. if (defined(authority) && defined(_servers[authority])) {
  16596. return true;
  16597. }
  16598. return false;
  16599. };
  16600. /**
  16601. * Clears the registry
  16602. *
  16603. * @example
  16604. * // Remove a trusted server
  16605. * TrustedServers.clear();
  16606. */
  16607. TrustedServers.clear = function() {
  16608. _servers = {};
  16609. };
  16610. return TrustedServers;
  16611. });
  16612. /*global define*/
  16613. define('Core/loadWithXhr',[
  16614. '../ThirdParty/when',
  16615. './defaultValue',
  16616. './defined',
  16617. './DeveloperError',
  16618. './RequestErrorEvent',
  16619. './RuntimeError',
  16620. './TrustedServers'
  16621. ], function(
  16622. when,
  16623. defaultValue,
  16624. defined,
  16625. DeveloperError,
  16626. RequestErrorEvent,
  16627. RuntimeError,
  16628. TrustedServers) {
  16629. 'use strict';
  16630. /**
  16631. * Asynchronously loads the given URL. Returns a promise that will resolve to
  16632. * the result once loaded, or reject if the URL failed to load. The data is loaded
  16633. * using XMLHttpRequest, which means that in order to make requests to another origin,
  16634. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  16635. *
  16636. * @exports loadWithXhr
  16637. *
  16638. * @param {Object} options Object with the following properties:
  16639. * @param {String|Promise.<String>} options.url The URL of the data, or a promise for the URL.
  16640. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  16641. * @param {String} [options.method='GET'] The HTTP method to use.
  16642. * @param {String} [options.data] The data to send with the request, if any.
  16643. * @param {Object} [options.headers] HTTP headers to send with the request, if any.
  16644. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  16645. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  16646. *
  16647. *
  16648. * @example
  16649. * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
  16650. * Cesium.loadWithXhr({
  16651. * url : 'some/url',
  16652. * responseType : 'blob'
  16653. * }).then(function(blob) {
  16654. * // use the data
  16655. * }).otherwise(function(error) {
  16656. * // an error occurred
  16657. * });
  16658. *
  16659. * @see loadArrayBuffer
  16660. * @see loadBlob
  16661. * @see loadJson
  16662. * @see loadText
  16663. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16664. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  16665. */
  16666. function loadWithXhr(options) {
  16667. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16668. if (!defined(options.url)) {
  16669. throw new DeveloperError('options.url is required.');
  16670. }
  16671. var responseType = options.responseType;
  16672. var method = defaultValue(options.method, 'GET');
  16673. var data = options.data;
  16674. var headers = options.headers;
  16675. var overrideMimeType = options.overrideMimeType;
  16676. return when(options.url, function(url) {
  16677. var deferred = when.defer();
  16678. loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
  16679. return deferred.promise;
  16680. });
  16681. }
  16682. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  16683. function decodeDataUriText(isBase64, data) {
  16684. var result = decodeURIComponent(data);
  16685. if (isBase64) {
  16686. return atob(result);
  16687. }
  16688. return result;
  16689. }
  16690. function decodeDataUriArrayBuffer(isBase64, data) {
  16691. var byteString = decodeDataUriText(isBase64, data);
  16692. var buffer = new ArrayBuffer(byteString.length);
  16693. var view = new Uint8Array(buffer);
  16694. for (var i = 0; i < byteString.length; i++) {
  16695. view[i] = byteString.charCodeAt(i);
  16696. }
  16697. return buffer;
  16698. }
  16699. function decodeDataUri(dataUriRegexResult, responseType) {
  16700. responseType = defaultValue(responseType, '');
  16701. var mimeType = dataUriRegexResult[1];
  16702. var isBase64 = !!dataUriRegexResult[2];
  16703. var data = dataUriRegexResult[3];
  16704. switch (responseType) {
  16705. case '':
  16706. case 'text':
  16707. return decodeDataUriText(isBase64, data);
  16708. case 'arraybuffer':
  16709. return decodeDataUriArrayBuffer(isBase64, data);
  16710. case 'blob':
  16711. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  16712. return new Blob([buffer], {
  16713. type : mimeType
  16714. });
  16715. case 'document':
  16716. var parser = new DOMParser();
  16717. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  16718. case 'json':
  16719. return JSON.parse(decodeDataUriText(isBase64, data));
  16720. default:
  16721. throw new DeveloperError('Unhandled responseType: ' + responseType);
  16722. }
  16723. }
  16724. // This is broken out into a separate function so that it can be mocked for testing purposes.
  16725. loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  16726. var dataUriRegexResult = dataUriRegex.exec(url);
  16727. if (dataUriRegexResult !== null) {
  16728. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  16729. return;
  16730. }
  16731. var xhr = new XMLHttpRequest();
  16732. if (TrustedServers.contains(url)) {
  16733. xhr.withCredentials = true;
  16734. }
  16735. if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
  16736. xhr.overrideMimeType(overrideMimeType);
  16737. }
  16738. xhr.open(method, url, true);
  16739. if (defined(headers)) {
  16740. for (var key in headers) {
  16741. if (headers.hasOwnProperty(key)) {
  16742. xhr.setRequestHeader(key, headers[key]);
  16743. }
  16744. }
  16745. }
  16746. if (defined(responseType)) {
  16747. xhr.responseType = responseType;
  16748. }
  16749. xhr.onload = function() {
  16750. if (xhr.status < 200 || xhr.status >= 300) {
  16751. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  16752. return;
  16753. }
  16754. var response = xhr.response;
  16755. var browserResponseType = xhr.responseType;
  16756. //All modern browsers will go into either the first if block or last else block.
  16757. //Other code paths support older browsers that either do not support the supplied responseType
  16758. //or do not support the xhr.response property.
  16759. if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
  16760. deferred.resolve(response);
  16761. } else if ((responseType === 'json') && typeof response === 'string') {
  16762. try {
  16763. deferred.resolve(JSON.parse(response));
  16764. } catch (e) {
  16765. deferred.reject(e);
  16766. }
  16767. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  16768. deferred.resolve(xhr.responseXML);
  16769. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
  16770. deferred.resolve(xhr.responseText);
  16771. } else {
  16772. deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
  16773. }
  16774. };
  16775. xhr.onerror = function(e) {
  16776. deferred.reject(new RequestErrorEvent());
  16777. };
  16778. xhr.send(data);
  16779. };
  16780. loadWithXhr.defaultLoad = loadWithXhr.load;
  16781. return loadWithXhr;
  16782. });
  16783. /*global define*/
  16784. define('Core/loadText',[
  16785. './loadWithXhr'
  16786. ], function(
  16787. loadWithXhr) {
  16788. 'use strict';
  16789. /**
  16790. * Asynchronously loads the given URL as text. Returns a promise that will resolve to
  16791. * a String once loaded, or reject if the URL failed to load. The data is loaded
  16792. * using XMLHttpRequest, which means that in order to make requests to another origin,
  16793. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  16794. *
  16795. * @exports loadText
  16796. *
  16797. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  16798. * @param {Object} [headers] HTTP headers to send with the request.
  16799. * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
  16800. *
  16801. *
  16802. * @example
  16803. * // load text from a URL, setting a custom header
  16804. * Cesium.loadText('http://someUrl.com/someJson.txt', {
  16805. * 'X-Custom-Header' : 'some value'
  16806. * }).then(function(text) {
  16807. * // Do something with the text
  16808. * }).otherwise(function(error) {
  16809. * // an error occurred
  16810. * });
  16811. *
  16812. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  16813. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16814. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  16815. */
  16816. function loadText(url, headers) {
  16817. return loadWithXhr({
  16818. url : url,
  16819. headers : headers
  16820. });
  16821. }
  16822. return loadText;
  16823. });
  16824. /*global define*/
  16825. define('Core/loadJson',[
  16826. './clone',
  16827. './defined',
  16828. './DeveloperError',
  16829. './loadText'
  16830. ], function(
  16831. clone,
  16832. defined,
  16833. DeveloperError,
  16834. loadText) {
  16835. 'use strict';
  16836. var defaultHeaders = {
  16837. Accept : 'application/json,*/*;q=0.01'
  16838. };
  16839. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  16840. /**
  16841. * Asynchronously loads the given URL as JSON. Returns a promise that will resolve to
  16842. * a JSON object once loaded, or reject if the URL failed to load. The data is loaded
  16843. * using XMLHttpRequest, which means that in order to make requests to another origin,
  16844. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  16845. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  16846. * already specified.
  16847. *
  16848. * @exports loadJson
  16849. *
  16850. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  16851. * @param {Object} [headers] HTTP headers to send with the request.
  16852. * 'Accept: application/json,&#42;&#47;&#42;;q=0.01' is added to the request headers automatically
  16853. * if not specified.
  16854. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  16855. *
  16856. *
  16857. * @example
  16858. * Cesium.loadJson('http://someUrl.com/someJson.txt').then(function(jsonData) {
  16859. * // Do something with the JSON object
  16860. * }).otherwise(function(error) {
  16861. * // an error occurred
  16862. * });
  16863. *
  16864. * @see loadText
  16865. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  16866. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  16867. */
  16868. function loadJson(url, headers) {
  16869. if (!defined(url)) {
  16870. throw new DeveloperError('url is required.');
  16871. }
  16872. if (!defined(headers)) {
  16873. headers = defaultHeaders;
  16874. } else if (!defined(headers.Accept)) {
  16875. // clone before adding the Accept header
  16876. headers = clone(headers);
  16877. headers.Accept = defaultHeaders.Accept;
  16878. }
  16879. return loadText(url, headers).then(function(value) {
  16880. return JSON.parse(value);
  16881. });
  16882. }
  16883. return loadJson;
  16884. });
  16885. /*global define*/
  16886. define('Core/EarthOrientationParameters',[
  16887. '../ThirdParty/when',
  16888. './binarySearch',
  16889. './defaultValue',
  16890. './defined',
  16891. './EarthOrientationParametersSample',
  16892. './freezeObject',
  16893. './JulianDate',
  16894. './LeapSecond',
  16895. './loadJson',
  16896. './RuntimeError',
  16897. './TimeConstants',
  16898. './TimeStandard'
  16899. ], function(
  16900. when,
  16901. binarySearch,
  16902. defaultValue,
  16903. defined,
  16904. EarthOrientationParametersSample,
  16905. freezeObject,
  16906. JulianDate,
  16907. LeapSecond,
  16908. loadJson,
  16909. RuntimeError,
  16910. TimeConstants,
  16911. TimeStandard) {
  16912. 'use strict';
  16913. /**
  16914. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  16915. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  16916. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  16917. * Reference Frame (ITRF).
  16918. *
  16919. * @alias EarthOrientationParameters
  16920. * @constructor
  16921. *
  16922. * @param {Object} [options] Object with the following properties:
  16923. * @param {String} [options.url] The URL from which to obtain EOP data. If neither this
  16924. * parameter nor options.data is specified, all EOP values are assumed
  16925. * to be 0.0. If options.data is specified, this parameter is
  16926. * ignored.
  16927. * @param {Object} [options.data] The actual EOP data. If neither this
  16928. * parameter nor options.data is specified, all EOP values are assumed
  16929. * to be 0.0.
  16930. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  16931. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  16932. * should be added to {@link JulianDate.leapSeconds}. False if
  16933. * new leap seconds should be handled correctly in the context
  16934. * of the EOP data but otherwise ignored.
  16935. *
  16936. * @example
  16937. * // An example EOP data file, EOP.json:
  16938. * {
  16939. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  16940. * "samples" : [
  16941. * "2011-07-01T00:00:00Z",55743.0,2.117957047295119e-7,2.111518721609984e-6,-0.2908948,-2.956e-4,3.393695767766752e-11,3.3452143996557983e-10,34.0,
  16942. * "2011-07-02T00:00:00Z",55744.0,2.193297093339541e-7,2.115460256837405e-6,-0.29065,-1.824e-4,-8.241832578862112e-11,5.623838700870617e-10,34.0,
  16943. * "2011-07-03T00:00:00Z",55745.0,2.262286080161428e-7,2.1191157519929706e-6,-0.2905572,1.9e-6,-3.490658503988659e-10,6.981317007977318e-10,34.0
  16944. * ]
  16945. * }
  16946. *
  16947. * @example
  16948. * // Loading the EOP data
  16949. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  16950. * Cesium.Transforms.earthOrientationParameters = eop;
  16951. *
  16952. * @private
  16953. */
  16954. function EarthOrientationParameters(options) {
  16955. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  16956. this._dates = undefined;
  16957. this._samples = undefined;
  16958. this._dateColumn = -1;
  16959. this._xPoleWanderRadiansColumn = -1;
  16960. this._yPoleWanderRadiansColumn = -1;
  16961. this._ut1MinusUtcSecondsColumn = -1;
  16962. this._xCelestialPoleOffsetRadiansColumn = -1;
  16963. this._yCelestialPoleOffsetRadiansColumn = -1;
  16964. this._taiMinusUtcSecondsColumn = -1;
  16965. this._columnCount = 0;
  16966. this._lastIndex = -1;
  16967. this._downloadPromise = undefined;
  16968. this._dataError = undefined;
  16969. this._addNewLeapSeconds = defaultValue(options.addNewLeapSeconds, true);
  16970. if (defined(options.data)) {
  16971. // Use supplied EOP data.
  16972. onDataReady(this, options.data);
  16973. } else if (defined(options.url)) {
  16974. // Download EOP data.
  16975. var that = this;
  16976. this._downloadPromise = when(loadJson(options.url), function(eopData) {
  16977. onDataReady(that, eopData);
  16978. }, function() {
  16979. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + options.url + '.';
  16980. });
  16981. } else {
  16982. // Use all zeros for EOP data.
  16983. onDataReady(this, {
  16984. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  16985. 'samples' : []
  16986. });
  16987. }
  16988. }
  16989. /**
  16990. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  16991. */
  16992. EarthOrientationParameters.NONE = freezeObject({
  16993. getPromiseToLoad : function() {
  16994. return when();
  16995. },
  16996. compute : function(date, result) {
  16997. if (!defined(result)) {
  16998. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  16999. } else {
  17000. result.xPoleWander = 0.0;
  17001. result.yPoleWander = 0.0;
  17002. result.xPoleOffset = 0.0;
  17003. result.yPoleOffset = 0.0;
  17004. result.ut1MinusUtc = 0.0;
  17005. }
  17006. return result;
  17007. }
  17008. });
  17009. /**
  17010. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  17011. * ready to use.
  17012. *
  17013. * @returns {Promise.<undefined>} The promise.
  17014. *
  17015. * @see when
  17016. */
  17017. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  17018. return when(this._downloadPromise);
  17019. };
  17020. /**
  17021. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  17022. * If the EOP data has not yet been download, this method returns undefined.
  17023. *
  17024. * @param {JulianDate} date The date for each to evaluate the EOP.
  17025. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  17026. * If this parameter is undefined, a new instance is created and returned.
  17027. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  17028. * undefined if the data necessary to evaluate EOP at the date has not yet been
  17029. * downloaded.
  17030. *
  17031. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  17032. *
  17033. * @see EarthOrientationParameters#getPromiseToLoad
  17034. */
  17035. EarthOrientationParameters.prototype.compute = function(date, result) {
  17036. // We cannot compute until the samples are available.
  17037. if (!defined(this._samples)) {
  17038. if (defined(this._dataError)) {
  17039. throw new RuntimeError(this._dataError);
  17040. }
  17041. return undefined;
  17042. }
  17043. if (!defined(result)) {
  17044. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  17045. }
  17046. if (this._samples.length === 0) {
  17047. result.xPoleWander = 0.0;
  17048. result.yPoleWander = 0.0;
  17049. result.xPoleOffset = 0.0;
  17050. result.yPoleOffset = 0.0;
  17051. result.ut1MinusUtc = 0.0;
  17052. return result;
  17053. }
  17054. var dates = this._dates;
  17055. var lastIndex = this._lastIndex;
  17056. var before = 0;
  17057. var after = 0;
  17058. if (defined(lastIndex)) {
  17059. var previousIndexDate = dates[lastIndex];
  17060. var nextIndexDate = dates[lastIndex + 1];
  17061. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  17062. var isAfterLastSample = !defined(nextIndexDate);
  17063. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  17064. if (isAfterPrevious && isBeforeNext) {
  17065. before = lastIndex;
  17066. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  17067. ++before;
  17068. }
  17069. after = before + 1;
  17070. interpolate(this, dates, this._samples, date, before, after, result);
  17071. return result;
  17072. }
  17073. }
  17074. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  17075. if (index >= 0) {
  17076. // If the next entry is the same date, use the later entry. This way, if two entries
  17077. // describe the same moment, one before a leap second and the other after, then we will use
  17078. // the post-leap second data.
  17079. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  17080. ++index;
  17081. }
  17082. before = index;
  17083. after = index;
  17084. } else {
  17085. after = ~index;
  17086. before = after - 1;
  17087. // Use the first entry if the date requested is before the beginning of the data.
  17088. if (before < 0) {
  17089. before = 0;
  17090. }
  17091. }
  17092. this._lastIndex = before;
  17093. interpolate(this, dates, this._samples, date, before, after, result);
  17094. return result;
  17095. };
  17096. function compareLeapSecondDates(leapSecond, dateToFind) {
  17097. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  17098. }
  17099. function onDataReady(eop, eopData) {
  17100. if (!defined(eopData.columnNames)) {
  17101. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  17102. return;
  17103. }
  17104. if (!defined(eopData.samples)) {
  17105. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  17106. return;
  17107. }
  17108. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  17109. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  17110. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  17111. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  17112. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  17113. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  17114. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  17115. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  17116. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  17117. return;
  17118. }
  17119. var samples = eop._samples = eopData.samples;
  17120. var dates = eop._dates = [];
  17121. eop._dateColumn = dateColumn;
  17122. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  17123. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  17124. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  17125. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  17126. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  17127. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  17128. eop._columnCount = eopData.columnNames.length;
  17129. eop._lastIndex = undefined;
  17130. var lastTaiMinusUtc;
  17131. var addNewLeapSeconds = eop._addNewLeapSeconds;
  17132. // Convert the ISO8601 dates to JulianDates.
  17133. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  17134. var mjd = samples[i + dateColumn];
  17135. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  17136. var day = mjd + TimeConstants.MODIFIED_JULIAN_DATE_DIFFERENCE;
  17137. var date = new JulianDate(day, taiMinusUtc, TimeStandard.TAI);
  17138. dates.push(date);
  17139. if (addNewLeapSeconds) {
  17140. if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
  17141. // We crossed a leap second boundary, so add the leap second
  17142. // if it does not already exist.
  17143. var leapSeconds = JulianDate.leapSeconds;
  17144. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates);
  17145. if (leapSecondIndex < 0) {
  17146. var leapSecond = new LeapSecond(date, taiMinusUtc);
  17147. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  17148. }
  17149. }
  17150. lastTaiMinusUtc = taiMinusUtc;
  17151. }
  17152. }
  17153. }
  17154. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  17155. var start = index * columnCount;
  17156. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  17157. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  17158. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  17159. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  17160. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  17161. }
  17162. function linearInterp(dx, y1, y2) {
  17163. return y1 + dx * (y2 - y1);
  17164. }
  17165. function interpolate(eop, dates, samples, date, before, after, result) {
  17166. var columnCount = eop._columnCount;
  17167. // First check the bounds on the EOP data
  17168. // If we are after the bounds of the data, return zeros.
  17169. // The 'before' index should never be less than zero.
  17170. if (after > dates.length - 1) {
  17171. result.xPoleWander = 0;
  17172. result.yPoleWander = 0;
  17173. result.xPoleOffset = 0;
  17174. result.yPoleOffset = 0;
  17175. result.ut1MinusUtc = 0;
  17176. return result;
  17177. }
  17178. var beforeDate = dates[before];
  17179. var afterDate = dates[after];
  17180. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  17181. fillResultFromIndex(eop, samples, before, columnCount, result);
  17182. return result;
  17183. } else if (date.equals(afterDate)) {
  17184. fillResultFromIndex(eop, samples, after, columnCount, result);
  17185. return result;
  17186. }
  17187. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  17188. var startBefore = before * columnCount;
  17189. var startAfter = after * columnCount;
  17190. // Handle UT1 leap second edge case
  17191. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  17192. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  17193. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  17194. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  17195. // The absolute difference between the values is more than 0.5, so we may have
  17196. // crossed a leap second. Check if this is the case and, if so, adjust the
  17197. // afterValue to account for the leap second. This way, our interpolation will
  17198. // produce reasonable results.
  17199. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  17200. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  17201. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  17202. if (afterDate.equals(date)) {
  17203. // If we are at the end of the leap second interval, take the second value
  17204. // Otherwise, the interpolation below will yield the wrong side of the
  17205. // discontinuity
  17206. // At the end of the leap second, we need to start accounting for the jump
  17207. beforeUt1MinusUtc = afterUt1MinusUtc;
  17208. } else {
  17209. // Otherwise, remove the leap second so that the interpolation is correct
  17210. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  17211. }
  17212. }
  17213. }
  17214. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  17215. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  17216. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  17217. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  17218. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  17219. return result;
  17220. }
  17221. return EarthOrientationParameters;
  17222. });
  17223. /*global define*/
  17224. define('Core/HeadingPitchRoll',[
  17225. './defaultValue',
  17226. './defined',
  17227. './DeveloperError',
  17228. './Math'
  17229. ], function(
  17230. defaultValue,
  17231. defined,
  17232. DeveloperError,
  17233. CesiumMath) {
  17234. "use strict";
  17235. /**
  17236. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  17237. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  17238. * the positive x axis.
  17239. * @alias HeadingPitchRoll
  17240. * @constructor
  17241. *
  17242. * @param {Number} [heading=0.0] The heading component in radians.
  17243. * @param {Number} [pitch=0.0] The pitch component in radians.
  17244. * @param {Number} [roll=0.0] The roll component in radians.
  17245. */
  17246. function HeadingPitchRoll(heading, pitch, roll) {
  17247. this.heading = defaultValue(heading, 0.0);
  17248. this.pitch = defaultValue(pitch, 0.0);
  17249. this.roll = defaultValue(roll, 0.0);
  17250. }
  17251. /**
  17252. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  17253. *
  17254. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  17255. * @param {Quaternion} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  17256. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  17257. */
  17258. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  17259. if (!defined(quaternion)) {
  17260. throw new DeveloperError('quaternion is required');
  17261. }
  17262. if (!defined(result)) {
  17263. result = new HeadingPitchRoll();
  17264. }
  17265. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  17266. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  17267. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  17268. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  17269. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  17270. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  17271. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  17272. result.pitch = -Math.asin(test);
  17273. return result;
  17274. };
  17275. /**
  17276. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  17277. *
  17278. * @param {Number} heading the heading in degrees
  17279. * @param {Number} pitch the pitch in degrees
  17280. * @param {Number} roll the heading in degrees
  17281. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  17282. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  17283. */
  17284. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  17285. if (!defined(heading)) {
  17286. throw new DeveloperError('heading is required');
  17287. }
  17288. if (!defined(pitch)) {
  17289. throw new DeveloperError('pitch is required');
  17290. }
  17291. if (!defined(roll)) {
  17292. throw new DeveloperError('roll is required');
  17293. }
  17294. if (!defined(result)) {
  17295. result = new HeadingPitchRoll();
  17296. }
  17297. result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
  17298. result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
  17299. result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
  17300. return result;
  17301. };
  17302. /**
  17303. * Duplicates a HeadingPitchRoll instance.
  17304. *
  17305. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  17306. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  17307. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  17308. */
  17309. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  17310. if (!defined(headingPitchRoll)) {
  17311. return undefined;
  17312. }
  17313. if (!defined(result)) {
  17314. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  17315. }
  17316. result.heading = headingPitchRoll.heading;
  17317. result.pitch = headingPitchRoll.pitch;
  17318. result.roll = headingPitchRoll.roll;
  17319. return result;
  17320. };
  17321. /**
  17322. * Compares the provided HeadingPitchRolls componentwise and returns
  17323. * <code>true</code> if they are equal, <code>false</code> otherwise.
  17324. *
  17325. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  17326. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  17327. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  17328. */
  17329. HeadingPitchRoll.equals = function(left, right) {
  17330. return (left === right) ||
  17331. ((defined(left)) &&
  17332. (defined(right)) &&
  17333. (left.heading === right.heading) &&
  17334. (left.pitch === right.pitch) &&
  17335. (left.roll === right.roll));
  17336. };
  17337. /**
  17338. * Compares the provided HeadingPitchRolls componentwise and returns
  17339. * <code>true</code> if they pass an absolute or relative tolerance test,
  17340. * <code>false</code> otherwise.
  17341. *
  17342. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  17343. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  17344. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  17345. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  17346. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  17347. */
  17348. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  17349. return (left === right) ||
  17350. (defined(left) &&
  17351. defined(right) &&
  17352. CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  17353. CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  17354. CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  17355. };
  17356. /**
  17357. * Duplicates this HeadingPitchRoll instance.
  17358. *
  17359. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  17360. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  17361. */
  17362. HeadingPitchRoll.prototype.clone = function(result) {
  17363. return HeadingPitchRoll.clone(this, result);
  17364. };
  17365. /**
  17366. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  17367. * <code>true</code> if they are equal, <code>false</code> otherwise.
  17368. *
  17369. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  17370. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  17371. */
  17372. HeadingPitchRoll.prototype.equals = function(right) {
  17373. return HeadingPitchRoll.equals(this, right);
  17374. };
  17375. /**
  17376. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  17377. * <code>true</code> if they pass an absolute or relative tolerance test,
  17378. * <code>false</code> otherwise.
  17379. *
  17380. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  17381. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  17382. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  17383. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  17384. */
  17385. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  17386. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  17387. };
  17388. /**
  17389. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  17390. *
  17391. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  17392. */
  17393. HeadingPitchRoll.prototype.toString = function() {
  17394. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  17395. };
  17396. return HeadingPitchRoll;
  17397. });
  17398. /*global define*/
  17399. define('Core/getAbsoluteUri',[
  17400. '../ThirdParty/Uri',
  17401. './defaultValue',
  17402. './defined',
  17403. './DeveloperError'
  17404. ], function(
  17405. Uri,
  17406. defaultValue,
  17407. defined,
  17408. DeveloperError) {
  17409. 'use strict';
  17410. /**
  17411. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  17412. * @exports getAbsoluteUri
  17413. *
  17414. * @param {String} relative The relative Uri.
  17415. * @param {String} [base] The base Uri.
  17416. * @returns {String} The absolute Uri of the given relative Uri.
  17417. *
  17418. * @example
  17419. * //absolute Uri will be "https://test.com/awesome.png";
  17420. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  17421. */
  17422. function getAbsoluteUri(relative, base) {
  17423. if (!defined(relative)) {
  17424. throw new DeveloperError('relative uri is required.');
  17425. }
  17426. base = defaultValue(base, document.location.href);
  17427. var baseUri = new Uri(base);
  17428. var relativeUri = new Uri(relative);
  17429. return relativeUri.resolve(baseUri).toString();
  17430. }
  17431. return getAbsoluteUri;
  17432. });
  17433. /*global define*/
  17434. define('Core/joinUrls',[
  17435. '../ThirdParty/Uri',
  17436. './defaultValue',
  17437. './defined',
  17438. './DeveloperError'
  17439. ], function(
  17440. Uri,
  17441. defaultValue,
  17442. defined,
  17443. DeveloperError) {
  17444. 'use strict';
  17445. /**
  17446. * Function for joining URLs in a manner that is aware of query strings and fragments.
  17447. * This is useful when the base URL has a query string that needs to be maintained
  17448. * (e.g. a presigned base URL).
  17449. * @param {String|Uri} first The base URL.
  17450. * @param {String|Uri} second The URL path to join to the base URL. If this URL is absolute, it is returned unmodified.
  17451. * @param {Boolean} [appendSlash=true] The boolean determining whether there should be a forward slash between first and second.
  17452. * @private
  17453. */
  17454. function joinUrls(first, second, appendSlash) {
  17455. if (!defined(first)) {
  17456. throw new DeveloperError('first is required');
  17457. }
  17458. if (!defined(second)) {
  17459. throw new DeveloperError('second is required');
  17460. }
  17461. appendSlash = defaultValue(appendSlash, true);
  17462. if (!(first instanceof Uri)) {
  17463. first = new Uri(first);
  17464. }
  17465. if (!(second instanceof Uri)) {
  17466. second = new Uri(second);
  17467. }
  17468. // Uri.isAbsolute returns false for a URL like '//foo.com'. So if we have an authority but
  17469. // not a scheme, add a scheme matching the page's scheme.
  17470. if (defined(second.authority) && !defined(second.scheme)) {
  17471. if (typeof document !== 'undefined' && defined(document.location) && defined(document.location.href)) {
  17472. second.scheme = new Uri(document.location.href).scheme;
  17473. } else {
  17474. // Not in a browser? Use the first URL's scheme instead.
  17475. second.scheme = first.scheme;
  17476. }
  17477. }
  17478. // If the second URL is absolute, use it for the scheme, authority, and path.
  17479. var baseUri = first;
  17480. if (second.isAbsolute()) {
  17481. baseUri = second;
  17482. }
  17483. var url = '';
  17484. if (defined(baseUri.scheme)) {
  17485. url += baseUri.scheme + ':';
  17486. }
  17487. if (defined(baseUri.authority)) {
  17488. url += '//' + baseUri.authority;
  17489. if (baseUri.path !== '' && baseUri.path !== '/') {
  17490. url = url.replace(/\/?$/, '/');
  17491. baseUri.path = baseUri.path.replace(/^\/?/g, '');
  17492. }
  17493. }
  17494. // Combine the paths (only if second is relative).
  17495. if (baseUri === first) {
  17496. if (appendSlash) {
  17497. url += first.path.replace(/\/?$/, '/') + second.path.replace(/^\/?/g, '');
  17498. } else {
  17499. url += first.path + second.path;
  17500. }
  17501. } else {
  17502. url += second.path;
  17503. }
  17504. // Combine the queries and fragments.
  17505. var hasFirstQuery = defined(first.query);
  17506. var hasSecondQuery = defined(second.query);
  17507. if (hasFirstQuery && hasSecondQuery) {
  17508. url += '?' + first.query + '&' + second.query;
  17509. } else if (hasFirstQuery && !hasSecondQuery) {
  17510. url += '?' + first.query;
  17511. } else if (!hasFirstQuery && hasSecondQuery) {
  17512. url += '?' + second.query;
  17513. }
  17514. var hasSecondFragment = defined(second.fragment);
  17515. if (defined(first.fragment) && !hasSecondFragment) {
  17516. url += '#' + first.fragment;
  17517. } else if (hasSecondFragment) {
  17518. url += '#' + second.fragment;
  17519. }
  17520. return url;
  17521. }
  17522. return joinUrls;
  17523. });
  17524. /*global define*/
  17525. define('Core/buildModuleUrl',[
  17526. '../ThirdParty/Uri',
  17527. './defined',
  17528. './DeveloperError',
  17529. './getAbsoluteUri',
  17530. './joinUrls',
  17531. 'require'
  17532. ], function(
  17533. Uri,
  17534. defined,
  17535. DeveloperError,
  17536. getAbsoluteUri,
  17537. joinUrls,
  17538. require) {
  17539. 'use strict';
  17540. /*global CESIUM_BASE_URL*/
  17541. var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
  17542. function getBaseUrlFromCesiumScript() {
  17543. var scripts = document.getElementsByTagName('script');
  17544. for ( var i = 0, len = scripts.length; i < len; ++i) {
  17545. var src = scripts[i].getAttribute('src');
  17546. var result = cesiumScriptRegex.exec(src);
  17547. if (result !== null) {
  17548. return result[1];
  17549. }
  17550. }
  17551. return undefined;
  17552. }
  17553. var baseUrl;
  17554. function getCesiumBaseUrl() {
  17555. if (defined(baseUrl)) {
  17556. return baseUrl;
  17557. }
  17558. var baseUrlString;
  17559. if (typeof CESIUM_BASE_URL !== 'undefined') {
  17560. baseUrlString = CESIUM_BASE_URL;
  17561. } else {
  17562. baseUrlString = getBaseUrlFromCesiumScript();
  17563. }
  17564. if (!defined(baseUrlString)) {
  17565. throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  17566. }
  17567. baseUrl = new Uri(getAbsoluteUri(baseUrlString));
  17568. return baseUrl;
  17569. }
  17570. function buildModuleUrlFromRequireToUrl(moduleID) {
  17571. //moduleID will be non-relative, so require it relative to this module, in Core.
  17572. return require.toUrl('../' + moduleID);
  17573. }
  17574. function buildModuleUrlFromBaseUrl(moduleID) {
  17575. return joinUrls(getCesiumBaseUrl(), moduleID);
  17576. }
  17577. var implementation;
  17578. var a;
  17579. /**
  17580. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  17581. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  17582. * the base URL of the Cesium.js script.
  17583. *
  17584. * @private
  17585. */
  17586. function buildModuleUrl(moduleID) {
  17587. if (!defined(implementation)) {
  17588. //select implementation
  17589. if (defined(require.toUrl)) {
  17590. implementation = buildModuleUrlFromRequireToUrl;
  17591. } else {
  17592. implementation = buildModuleUrlFromBaseUrl;
  17593. }
  17594. }
  17595. if (!defined(a)) {
  17596. a = document.createElement('a');
  17597. }
  17598. var url = implementation(moduleID);
  17599. a.href = url;
  17600. a.href = a.href; // IE only absolutizes href on get, not set
  17601. return a.href;
  17602. }
  17603. // exposed for testing
  17604. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  17605. /**
  17606. * Sets the base URL for resolving modules.
  17607. * @param {String} value The new base URL.
  17608. */
  17609. buildModuleUrl.setBaseUrl = function(value) {
  17610. baseUrl = new Uri(value).resolve(new Uri(document.location.href));
  17611. };
  17612. return buildModuleUrl;
  17613. });
  17614. /*global define*/
  17615. define('Core/Iau2006XysSample',[],function() {
  17616. 'use strict';
  17617. /**
  17618. * An IAU 2006 XYS value sampled at a particular time.
  17619. *
  17620. * @alias Iau2006XysSample
  17621. * @constructor
  17622. *
  17623. * @param {Number} x The X value.
  17624. * @param {Number} y The Y value.
  17625. * @param {Number} s The S value.
  17626. *
  17627. * @private
  17628. */
  17629. function Iau2006XysSample(x, y, s) {
  17630. /**
  17631. * The X value.
  17632. * @type {Number}
  17633. */
  17634. this.x = x;
  17635. /**
  17636. * The Y value.
  17637. * @type {Number}
  17638. */
  17639. this.y = y;
  17640. /**
  17641. * The S value.
  17642. * @type {Number}
  17643. */
  17644. this.s = s;
  17645. }
  17646. return Iau2006XysSample;
  17647. });
  17648. /*global define*/
  17649. define('Core/Iau2006XysData',[
  17650. '../ThirdParty/when',
  17651. './buildModuleUrl',
  17652. './defaultValue',
  17653. './defined',
  17654. './Iau2006XysSample',
  17655. './JulianDate',
  17656. './loadJson',
  17657. './TimeStandard'
  17658. ], function(
  17659. when,
  17660. buildModuleUrl,
  17661. defaultValue,
  17662. defined,
  17663. Iau2006XysSample,
  17664. JulianDate,
  17665. loadJson,
  17666. TimeStandard) {
  17667. 'use strict';
  17668. /**
  17669. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  17670. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  17671. *
  17672. * @alias Iau2006XysData
  17673. * @constructor
  17674. *
  17675. * @param {Object} [options] Object with the following properties:
  17676. * @param {String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  17677. * `{0}` will be replaced with the file index.
  17678. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  17679. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  17680. * first XYS sample.
  17681. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  17682. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  17683. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  17684. *
  17685. * @private
  17686. */
  17687. function Iau2006XysData(options) {
  17688. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  17689. this._xysFileUrlTemplate = options.xysFileUrlTemplate;
  17690. this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
  17691. this._sampleZeroJulianEphemerisDate = defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  17692. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard.TAI);
  17693. this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
  17694. this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
  17695. this._totalSamples = defaultValue(options.totalSamples, 27426);
  17696. this._samples = new Array(this._totalSamples * 3);
  17697. this._chunkDownloadsInProgress = [];
  17698. var order = this._interpolationOrder;
  17699. // Compute denominators and X values for interpolation.
  17700. var denom = this._denominators = new Array(order + 1);
  17701. var xTable = this._xTable = new Array(order + 1);
  17702. var stepN = Math.pow(this._stepSizeDays, order);
  17703. for ( var i = 0; i <= order; ++i) {
  17704. denom[i] = stepN;
  17705. xTable[i] = i * this._stepSizeDays;
  17706. for ( var j = 0; j <= order; ++j) {
  17707. if (j !== i) {
  17708. denom[i] *= (i - j);
  17709. }
  17710. }
  17711. denom[i] = 1.0 / denom[i];
  17712. }
  17713. // Allocate scratch arrays for interpolation.
  17714. this._work = new Array(order + 1);
  17715. this._coef = new Array(order + 1);
  17716. }
  17717. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard.TAI);
  17718. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  17719. var dateTT = julianDateScratch;
  17720. dateTT.dayNumber = dayTT;
  17721. dateTT.secondsOfDay = secondTT;
  17722. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  17723. }
  17724. /**
  17725. * Preloads XYS data for a specified date range.
  17726. *
  17727. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  17728. * the Terrestrial Time (TT) time standard.
  17729. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  17730. * the Terrestrial Time (TT) time standard.
  17731. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  17732. * the Terrestrial Time (TT) time standard.
  17733. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  17734. * the Terrestrial Time (TT) time standard.
  17735. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the requested interval has been
  17736. * preloaded.
  17737. */
  17738. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  17739. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  17740. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  17741. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  17742. if (startIndex < 0) {
  17743. startIndex = 0;
  17744. }
  17745. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  17746. if (stopIndex >= this._totalSamples) {
  17747. stopIndex = this._totalSamples - 1;
  17748. }
  17749. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  17750. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  17751. var promises = [];
  17752. for ( var i = startChunk; i <= stopChunk; ++i) {
  17753. promises.push(requestXysChunk(this, i));
  17754. }
  17755. return when.all(promises);
  17756. };
  17757. /**
  17758. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  17759. * this method will return undefined.
  17760. *
  17761. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  17762. * the Terrestrial Time (TT) time standard.
  17763. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  17764. * the Terrestrial Time (TT) time standard.
  17765. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  17766. * is undefined, a new instance is allocated and returned.
  17767. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  17768. * computation has not yet been downloaded.
  17769. *
  17770. * @see Iau2006XysData#preload
  17771. */
  17772. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  17773. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  17774. if (daysSinceEpoch < 0.0) {
  17775. // Can't evaluate prior to the epoch of the data.
  17776. return undefined;
  17777. }
  17778. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  17779. if (centerIndex >= this._totalSamples) {
  17780. // Can't evaluate after the last sample in the data.
  17781. return undefined;
  17782. }
  17783. var degree = this._interpolationOrder;
  17784. var firstIndex = centerIndex - ((degree / 2) | 0);
  17785. if (firstIndex < 0) {
  17786. firstIndex = 0;
  17787. }
  17788. var lastIndex = firstIndex + degree;
  17789. if (lastIndex >= this._totalSamples) {
  17790. lastIndex = this._totalSamples - 1;
  17791. firstIndex = lastIndex - degree;
  17792. if (firstIndex < 0) {
  17793. firstIndex = 0;
  17794. }
  17795. }
  17796. // Are all the samples we need present?
  17797. // We can assume so if the first and last are present
  17798. var isDataMissing = false;
  17799. var samples = this._samples;
  17800. if (!defined(samples[firstIndex * 3])) {
  17801. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  17802. isDataMissing = true;
  17803. }
  17804. if (!defined(samples[lastIndex * 3])) {
  17805. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  17806. isDataMissing = true;
  17807. }
  17808. if (isDataMissing) {
  17809. return undefined;
  17810. }
  17811. if (!defined(result)) {
  17812. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  17813. } else {
  17814. result.x = 0.0;
  17815. result.y = 0.0;
  17816. result.s = 0.0;
  17817. }
  17818. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  17819. var work = this._work;
  17820. var denom = this._denominators;
  17821. var coef = this._coef;
  17822. var xTable = this._xTable;
  17823. var i, j;
  17824. for (i = 0; i <= degree; ++i) {
  17825. work[i] = x - xTable[i];
  17826. }
  17827. for (i = 0; i <= degree; ++i) {
  17828. coef[i] = 1.0;
  17829. for (j = 0; j <= degree; ++j) {
  17830. if (j !== i) {
  17831. coef[i] *= work[j];
  17832. }
  17833. }
  17834. coef[i] *= denom[i];
  17835. var sampleIndex = (firstIndex + i) * 3;
  17836. result.x += coef[i] * samples[sampleIndex++];
  17837. result.y += coef[i] * samples[sampleIndex++];
  17838. result.s += coef[i] * samples[sampleIndex];
  17839. }
  17840. return result;
  17841. };
  17842. function requestXysChunk(xysData, chunkIndex) {
  17843. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  17844. // Chunk has already been requested.
  17845. return xysData._chunkDownloadsInProgress[chunkIndex];
  17846. }
  17847. var deferred = when.defer();
  17848. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  17849. var chunkUrl;
  17850. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  17851. if (defined(xysFileUrlTemplate)) {
  17852. chunkUrl = xysFileUrlTemplate.replace('{0}', chunkIndex);
  17853. } else {
  17854. chunkUrl = buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json');
  17855. }
  17856. when(loadJson(chunkUrl), function(chunk) {
  17857. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  17858. var samples = xysData._samples;
  17859. var newSamples = chunk.samples;
  17860. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  17861. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  17862. samples[startIndex + i] = newSamples[i];
  17863. }
  17864. deferred.resolve();
  17865. });
  17866. return deferred.promise;
  17867. }
  17868. return Iau2006XysData;
  17869. });
  17870. /*global define*/
  17871. define('Core/Quaternion',[
  17872. './Cartesian3',
  17873. './defaultValue',
  17874. './defined',
  17875. './DeveloperError',
  17876. './FeatureDetection',
  17877. './freezeObject',
  17878. './Math',
  17879. './Matrix3'
  17880. ], function(
  17881. Cartesian3,
  17882. defaultValue,
  17883. defined,
  17884. DeveloperError,
  17885. FeatureDetection,
  17886. freezeObject,
  17887. CesiumMath,
  17888. Matrix3) {
  17889. 'use strict';
  17890. /**
  17891. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  17892. * @alias Quaternion
  17893. * @constructor
  17894. *
  17895. * @param {Number} [x=0.0] The X component.
  17896. * @param {Number} [y=0.0] The Y component.
  17897. * @param {Number} [z=0.0] The Z component.
  17898. * @param {Number} [w=0.0] The W component.
  17899. *
  17900. * @see PackableForInterpolation
  17901. */
  17902. function Quaternion(x, y, z, w) {
  17903. /**
  17904. * The X component.
  17905. * @type {Number}
  17906. * @default 0.0
  17907. */
  17908. this.x = defaultValue(x, 0.0);
  17909. /**
  17910. * The Y component.
  17911. * @type {Number}
  17912. * @default 0.0
  17913. */
  17914. this.y = defaultValue(y, 0.0);
  17915. /**
  17916. * The Z component.
  17917. * @type {Number}
  17918. * @default 0.0
  17919. */
  17920. this.z = defaultValue(z, 0.0);
  17921. /**
  17922. * The W component.
  17923. * @type {Number}
  17924. * @default 0.0
  17925. */
  17926. this.w = defaultValue(w, 0.0);
  17927. }
  17928. var fromAxisAngleScratch = new Cartesian3();
  17929. /**
  17930. * Computes a quaternion representing a rotation around an axis.
  17931. *
  17932. * @param {Cartesian3} axis The axis of rotation.
  17933. * @param {Number} angle The angle in radians to rotate around the axis.
  17934. * @param {Quaternion} [result] The object onto which to store the result.
  17935. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17936. */
  17937. Quaternion.fromAxisAngle = function(axis, angle, result) {
  17938. if (!defined(axis)) {
  17939. throw new DeveloperError('axis is required.');
  17940. }
  17941. if (typeof angle !== 'number') {
  17942. throw new DeveloperError('angle is required and must be a number.');
  17943. }
  17944. var halfAngle = angle / 2.0;
  17945. var s = Math.sin(halfAngle);
  17946. fromAxisAngleScratch = Cartesian3.normalize(axis, fromAxisAngleScratch);
  17947. var x = fromAxisAngleScratch.x * s;
  17948. var y = fromAxisAngleScratch.y * s;
  17949. var z = fromAxisAngleScratch.z * s;
  17950. var w = Math.cos(halfAngle);
  17951. if (!defined(result)) {
  17952. return new Quaternion(x, y, z, w);
  17953. }
  17954. result.x = x;
  17955. result.y = y;
  17956. result.z = z;
  17957. result.w = w;
  17958. return result;
  17959. };
  17960. var fromRotationMatrixNext = [1, 2, 0];
  17961. var fromRotationMatrixQuat = new Array(3);
  17962. /**
  17963. * Computes a Quaternion from the provided Matrix3 instance.
  17964. *
  17965. * @param {Matrix3} matrix The rotation matrix.
  17966. * @param {Quaternion} [result] The object onto which to store the result.
  17967. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  17968. *
  17969. * @see Matrix3.fromQuaternion
  17970. */
  17971. Quaternion.fromRotationMatrix = function(matrix, result) {
  17972. if (!defined(matrix)) {
  17973. throw new DeveloperError('matrix is required.');
  17974. }
  17975. var root;
  17976. var x;
  17977. var y;
  17978. var z;
  17979. var w;
  17980. var m00 = matrix[Matrix3.COLUMN0ROW0];
  17981. var m11 = matrix[Matrix3.COLUMN1ROW1];
  17982. var m22 = matrix[Matrix3.COLUMN2ROW2];
  17983. var trace = m00 + m11 + m22;
  17984. if (trace > 0.0) {
  17985. // |w| > 1/2, may as well choose w > 1/2
  17986. root = Math.sqrt(trace + 1.0); // 2w
  17987. w = 0.5 * root;
  17988. root = 0.5 / root; // 1/(4w)
  17989. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  17990. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  17991. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  17992. } else {
  17993. // |w| <= 1/2
  17994. var next = fromRotationMatrixNext;
  17995. var i = 0;
  17996. if (m11 > m00) {
  17997. i = 1;
  17998. }
  17999. if (m22 > m00 && m22 > m11) {
  18000. i = 2;
  18001. }
  18002. var j = next[i];
  18003. var k = next[j];
  18004. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  18005. var quat = fromRotationMatrixQuat;
  18006. quat[i] = 0.5 * root;
  18007. root = 0.5 / root;
  18008. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  18009. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  18010. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  18011. x = -quat[0];
  18012. y = -quat[1];
  18013. z = -quat[2];
  18014. }
  18015. if (!defined(result)) {
  18016. return new Quaternion(x, y, z, w);
  18017. }
  18018. result.x = x;
  18019. result.y = y;
  18020. result.z = z;
  18021. result.w = w;
  18022. return result;
  18023. };
  18024. var scratchHPRQuaternion = new Quaternion();
  18025. /**
  18026. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  18027. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  18028. * the positive x axis.
  18029. *
  18030. * @param {Number} heading The heading angle in radians.
  18031. * @param {Number} pitch The pitch angle in radians.
  18032. * @param {Number} roll The roll angle in radians.
  18033. * @param {Quaternion} [result] The object onto which to store the result.
  18034. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  18035. */
  18036. Quaternion.fromHeadingPitchRoll = function(heading, pitch, roll, result) {
  18037. if (!defined(heading)) {
  18038. throw new DeveloperError('heading is required.');
  18039. }
  18040. if (!defined(pitch)) {
  18041. throw new DeveloperError('pitch is required.');
  18042. }
  18043. if (!defined(roll)) {
  18044. throw new DeveloperError('roll is required.');
  18045. }
  18046. var rollQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, roll, scratchHPRQuaternion);
  18047. var pitchQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, result);
  18048. result = Quaternion.multiply(pitchQuaternion, rollQuaternion, pitchQuaternion);
  18049. var headingQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchHPRQuaternion);
  18050. return Quaternion.multiply(headingQuaternion, result, result);
  18051. };
  18052. var sampledQuaternionAxis = new Cartesian3();
  18053. var sampledQuaternionRotation = new Cartesian3();
  18054. var sampledQuaternionTempQuaternion = new Quaternion();
  18055. var sampledQuaternionQuaternion0 = new Quaternion();
  18056. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  18057. /**
  18058. * The number of elements used to pack the object into an array.
  18059. * @type {Number}
  18060. */
  18061. Quaternion.packedLength = 4;
  18062. /**
  18063. * Stores the provided instance into the provided array.
  18064. *
  18065. * @param {Quaternion} value The value to pack.
  18066. * @param {Number[]} array The array to pack into.
  18067. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  18068. *
  18069. * @returns {Number[]} The array that was packed into
  18070. */
  18071. Quaternion.pack = function(value, array, startingIndex) {
  18072. if (!defined(value)) {
  18073. throw new DeveloperError('value is required');
  18074. }
  18075. if (!defined(array)) {
  18076. throw new DeveloperError('array is required');
  18077. }
  18078. startingIndex = defaultValue(startingIndex, 0);
  18079. array[startingIndex++] = value.x;
  18080. array[startingIndex++] = value.y;
  18081. array[startingIndex++] = value.z;
  18082. array[startingIndex] = value.w;
  18083. return array;
  18084. };
  18085. /**
  18086. * Retrieves an instance from a packed array.
  18087. *
  18088. * @param {Number[]} array The packed array.
  18089. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  18090. * @param {Quaternion} [result] The object into which to store the result.
  18091. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18092. */
  18093. Quaternion.unpack = function(array, startingIndex, result) {
  18094. if (!defined(array)) {
  18095. throw new DeveloperError('array is required');
  18096. }
  18097. startingIndex = defaultValue(startingIndex, 0);
  18098. if (!defined(result)) {
  18099. result = new Quaternion();
  18100. }
  18101. result.x = array[startingIndex];
  18102. result.y = array[startingIndex + 1];
  18103. result.z = array[startingIndex + 2];
  18104. result.w = array[startingIndex + 3];
  18105. return result;
  18106. };
  18107. /**
  18108. * The number of elements used to store the object into an array in its interpolatable form.
  18109. * @type {Number}
  18110. */
  18111. Quaternion.packedInterpolationLength = 3;
  18112. /**
  18113. * Converts a packed array into a form suitable for interpolation.
  18114. *
  18115. * @param {Number[]} packedArray The packed array.
  18116. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  18117. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  18118. * @param {Number[]} result The object into which to store the result.
  18119. */
  18120. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  18121. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  18122. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  18123. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  18124. var offset = i * 3;
  18125. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  18126. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  18127. if (sampledQuaternionTempQuaternion.w < 0) {
  18128. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  18129. }
  18130. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  18131. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  18132. result[offset] = sampledQuaternionAxis.x * angle;
  18133. result[offset + 1] = sampledQuaternionAxis.y * angle;
  18134. result[offset + 2] = sampledQuaternionAxis.z * angle;
  18135. }
  18136. };
  18137. /**
  18138. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  18139. *
  18140. * @param {Number[]} array The array previously packed for interpolation.
  18141. * @param {Number[]} sourceArray The original packed array.
  18142. * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
  18143. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  18144. * @param {Quaternion} [result] The object into which to store the result.
  18145. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18146. */
  18147. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  18148. if (!defined(result)) {
  18149. result = new Quaternion();
  18150. }
  18151. Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  18152. var magnitude = Cartesian3.magnitude(sampledQuaternionRotation);
  18153. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  18154. if (magnitude === 0) {
  18155. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  18156. } else {
  18157. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  18158. }
  18159. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  18160. };
  18161. /**
  18162. * Duplicates a Quaternion instance.
  18163. *
  18164. * @param {Quaternion} quaternion The quaternion to duplicate.
  18165. * @param {Quaternion} [result] The object onto which to store the result.
  18166. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  18167. */
  18168. Quaternion.clone = function(quaternion, result) {
  18169. if (!defined(quaternion)) {
  18170. return undefined;
  18171. }
  18172. if (!defined(result)) {
  18173. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  18174. }
  18175. result.x = quaternion.x;
  18176. result.y = quaternion.y;
  18177. result.z = quaternion.z;
  18178. result.w = quaternion.w;
  18179. return result;
  18180. };
  18181. /**
  18182. * Computes the conjugate of the provided quaternion.
  18183. *
  18184. * @param {Quaternion} quaternion The quaternion to conjugate.
  18185. * @param {Quaternion} result The object onto which to store the result.
  18186. * @returns {Quaternion} The modified result parameter.
  18187. */
  18188. Quaternion.conjugate = function(quaternion, result) {
  18189. if (!defined(quaternion)) {
  18190. throw new DeveloperError('quaternion is required');
  18191. }
  18192. if (!defined(result)) {
  18193. throw new DeveloperError('result is required');
  18194. }
  18195. result.x = -quaternion.x;
  18196. result.y = -quaternion.y;
  18197. result.z = -quaternion.z;
  18198. result.w = quaternion.w;
  18199. return result;
  18200. };
  18201. /**
  18202. * Computes magnitude squared for the provided quaternion.
  18203. *
  18204. * @param {Quaternion} quaternion The quaternion to conjugate.
  18205. * @returns {Number} The magnitude squared.
  18206. */
  18207. Quaternion.magnitudeSquared = function(quaternion) {
  18208. if (!defined(quaternion)) {
  18209. throw new DeveloperError('quaternion is required');
  18210. }
  18211. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  18212. };
  18213. /**
  18214. * Computes magnitude for the provided quaternion.
  18215. *
  18216. * @param {Quaternion} quaternion The quaternion to conjugate.
  18217. * @returns {Number} The magnitude.
  18218. */
  18219. Quaternion.magnitude = function(quaternion) {
  18220. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  18221. };
  18222. /**
  18223. * Computes the normalized form of the provided quaternion.
  18224. *
  18225. * @param {Quaternion} quaternion The quaternion to normalize.
  18226. * @param {Quaternion} result The object onto which to store the result.
  18227. * @returns {Quaternion} The modified result parameter.
  18228. */
  18229. Quaternion.normalize = function(quaternion, result) {
  18230. if (!defined(result)) {
  18231. throw new DeveloperError('result is required');
  18232. }
  18233. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  18234. var x = quaternion.x * inverseMagnitude;
  18235. var y = quaternion.y * inverseMagnitude;
  18236. var z = quaternion.z * inverseMagnitude;
  18237. var w = quaternion.w * inverseMagnitude;
  18238. result.x = x;
  18239. result.y = y;
  18240. result.z = z;
  18241. result.w = w;
  18242. return result;
  18243. };
  18244. /**
  18245. * Computes the inverse of the provided quaternion.
  18246. *
  18247. * @param {Quaternion} quaternion The quaternion to normalize.
  18248. * @param {Quaternion} result The object onto which to store the result.
  18249. * @returns {Quaternion} The modified result parameter.
  18250. */
  18251. Quaternion.inverse = function(quaternion, result) {
  18252. if (!defined(result)) {
  18253. throw new DeveloperError('result is required');
  18254. }
  18255. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  18256. result = Quaternion.conjugate(quaternion, result);
  18257. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  18258. };
  18259. /**
  18260. * Computes the componentwise sum of two quaternions.
  18261. *
  18262. * @param {Quaternion} left The first quaternion.
  18263. * @param {Quaternion} right The second quaternion.
  18264. * @param {Quaternion} result The object onto which to store the result.
  18265. * @returns {Quaternion} The modified result parameter.
  18266. */
  18267. Quaternion.add = function(left, right, result) {
  18268. if (!defined(left)) {
  18269. throw new DeveloperError('left is required');
  18270. }
  18271. if (!defined(right)) {
  18272. throw new DeveloperError('right is required');
  18273. }
  18274. if (!defined(result)) {
  18275. throw new DeveloperError('result is required');
  18276. }
  18277. result.x = left.x + right.x;
  18278. result.y = left.y + right.y;
  18279. result.z = left.z + right.z;
  18280. result.w = left.w + right.w;
  18281. return result;
  18282. };
  18283. /**
  18284. * Computes the componentwise difference of two quaternions.
  18285. *
  18286. * @param {Quaternion} left The first quaternion.
  18287. * @param {Quaternion} right The second quaternion.
  18288. * @param {Quaternion} result The object onto which to store the result.
  18289. * @returns {Quaternion} The modified result parameter.
  18290. */
  18291. Quaternion.subtract = function(left, right, result) {
  18292. if (!defined(left)) {
  18293. throw new DeveloperError('left is required');
  18294. }
  18295. if (!defined(right)) {
  18296. throw new DeveloperError('right is required');
  18297. }
  18298. if (!defined(result)) {
  18299. throw new DeveloperError('result is required');
  18300. }
  18301. result.x = left.x - right.x;
  18302. result.y = left.y - right.y;
  18303. result.z = left.z - right.z;
  18304. result.w = left.w - right.w;
  18305. return result;
  18306. };
  18307. /**
  18308. * Negates the provided quaternion.
  18309. *
  18310. * @param {Quaternion} quaternion The quaternion to be negated.
  18311. * @param {Quaternion} result The object onto which to store the result.
  18312. * @returns {Quaternion} The modified result parameter.
  18313. */
  18314. Quaternion.negate = function(quaternion, result) {
  18315. if (!defined(quaternion)) {
  18316. throw new DeveloperError('quaternion is required');
  18317. }
  18318. if (!defined(result)) {
  18319. throw new DeveloperError('result is required');
  18320. }
  18321. result.x = -quaternion.x;
  18322. result.y = -quaternion.y;
  18323. result.z = -quaternion.z;
  18324. result.w = -quaternion.w;
  18325. return result;
  18326. };
  18327. /**
  18328. * Computes the dot (scalar) product of two quaternions.
  18329. *
  18330. * @param {Quaternion} left The first quaternion.
  18331. * @param {Quaternion} right The second quaternion.
  18332. * @returns {Number} The dot product.
  18333. */
  18334. Quaternion.dot = function(left, right) {
  18335. if (!defined(left)) {
  18336. throw new DeveloperError('left is required');
  18337. }
  18338. if (!defined(right)) {
  18339. throw new DeveloperError('right is required');
  18340. }
  18341. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  18342. };
  18343. /**
  18344. * Computes the product of two quaternions.
  18345. *
  18346. * @param {Quaternion} left The first quaternion.
  18347. * @param {Quaternion} right The second quaternion.
  18348. * @param {Quaternion} result The object onto which to store the result.
  18349. * @returns {Quaternion} The modified result parameter.
  18350. */
  18351. Quaternion.multiply = function(left, right, result) {
  18352. if (!defined(left)) {
  18353. throw new DeveloperError('left is required');
  18354. }
  18355. if (!defined(right)) {
  18356. throw new DeveloperError('right is required');
  18357. }
  18358. if (!defined(result)) {
  18359. throw new DeveloperError('result is required');
  18360. }
  18361. var leftX = left.x;
  18362. var leftY = left.y;
  18363. var leftZ = left.z;
  18364. var leftW = left.w;
  18365. var rightX = right.x;
  18366. var rightY = right.y;
  18367. var rightZ = right.z;
  18368. var rightW = right.w;
  18369. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  18370. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  18371. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  18372. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  18373. result.x = x;
  18374. result.y = y;
  18375. result.z = z;
  18376. result.w = w;
  18377. return result;
  18378. };
  18379. /**
  18380. * Multiplies the provided quaternion componentwise by the provided scalar.
  18381. *
  18382. * @param {Quaternion} quaternion The quaternion to be scaled.
  18383. * @param {Number} scalar The scalar to multiply with.
  18384. * @param {Quaternion} result The object onto which to store the result.
  18385. * @returns {Quaternion} The modified result parameter.
  18386. */
  18387. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  18388. if (!defined(quaternion)) {
  18389. throw new DeveloperError('quaternion is required');
  18390. }
  18391. if (typeof scalar !== 'number') {
  18392. throw new DeveloperError('scalar is required and must be a number.');
  18393. }
  18394. if (!defined(result)) {
  18395. throw new DeveloperError('result is required');
  18396. }
  18397. result.x = quaternion.x * scalar;
  18398. result.y = quaternion.y * scalar;
  18399. result.z = quaternion.z * scalar;
  18400. result.w = quaternion.w * scalar;
  18401. return result;
  18402. };
  18403. /**
  18404. * Divides the provided quaternion componentwise by the provided scalar.
  18405. *
  18406. * @param {Quaternion} quaternion The quaternion to be divided.
  18407. * @param {Number} scalar The scalar to divide by.
  18408. * @param {Quaternion} result The object onto which to store the result.
  18409. * @returns {Quaternion} The modified result parameter.
  18410. */
  18411. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  18412. if (!defined(quaternion)) {
  18413. throw new DeveloperError('quaternion is required');
  18414. }
  18415. if (typeof scalar !== 'number') {
  18416. throw new DeveloperError('scalar is required and must be a number.');
  18417. }
  18418. if (!defined(result)) {
  18419. throw new DeveloperError('result is required');
  18420. }
  18421. result.x = quaternion.x / scalar;
  18422. result.y = quaternion.y / scalar;
  18423. result.z = quaternion.z / scalar;
  18424. result.w = quaternion.w / scalar;
  18425. return result;
  18426. };
  18427. /**
  18428. * Computes the axis of rotation of the provided quaternion.
  18429. *
  18430. * @param {Quaternion} quaternion The quaternion to use.
  18431. * @param {Cartesian3} result The object onto which to store the result.
  18432. * @returns {Cartesian3} The modified result parameter.
  18433. */
  18434. Quaternion.computeAxis = function(quaternion, result) {
  18435. if (!defined(quaternion)) {
  18436. throw new DeveloperError('quaternion is required');
  18437. }
  18438. if (!defined(result)) {
  18439. throw new DeveloperError('result is required');
  18440. }
  18441. var w = quaternion.w;
  18442. if (Math.abs(w - 1.0) < CesiumMath.EPSILON6) {
  18443. result.x = result.y = result.z = 0;
  18444. return result;
  18445. }
  18446. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  18447. result.x = quaternion.x * scalar;
  18448. result.y = quaternion.y * scalar;
  18449. result.z = quaternion.z * scalar;
  18450. return result;
  18451. };
  18452. /**
  18453. * Computes the angle of rotation of the provided quaternion.
  18454. *
  18455. * @param {Quaternion} quaternion The quaternion to use.
  18456. * @returns {Number} The angle of rotation.
  18457. */
  18458. Quaternion.computeAngle = function(quaternion) {
  18459. if (!defined(quaternion)) {
  18460. throw new DeveloperError('quaternion is required');
  18461. }
  18462. if (Math.abs(quaternion.w - 1.0) < CesiumMath.EPSILON6) {
  18463. return 0.0;
  18464. }
  18465. return 2.0 * Math.acos(quaternion.w);
  18466. };
  18467. var lerpScratch = new Quaternion();
  18468. /**
  18469. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  18470. *
  18471. * @param {Quaternion} start The value corresponding to t at 0.0.
  18472. * @param {Quaternion} end The value corresponding to t at 1.0.
  18473. * @param {Number} t The point along t at which to interpolate.
  18474. * @param {Quaternion} result The object onto which to store the result.
  18475. * @returns {Quaternion} The modified result parameter.
  18476. */
  18477. Quaternion.lerp = function(start, end, t, result) {
  18478. if (!defined(start)) {
  18479. throw new DeveloperError('start is required.');
  18480. }
  18481. if (!defined(end)) {
  18482. throw new DeveloperError('end is required.');
  18483. }
  18484. if (typeof t !== 'number') {
  18485. throw new DeveloperError('t is required and must be a number.');
  18486. }
  18487. if (!defined(result)) {
  18488. throw new DeveloperError('result is required');
  18489. }
  18490. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  18491. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  18492. return Quaternion.add(lerpScratch, result, result);
  18493. };
  18494. var slerpEndNegated = new Quaternion();
  18495. var slerpScaledP = new Quaternion();
  18496. var slerpScaledR = new Quaternion();
  18497. /**
  18498. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  18499. *
  18500. * @param {Quaternion} start The value corresponding to t at 0.0.
  18501. * @param {Quaternion} end The value corresponding to t at 1.0.
  18502. * @param {Number} t The point along t at which to interpolate.
  18503. * @param {Quaternion} result The object onto which to store the result.
  18504. * @returns {Quaternion} The modified result parameter.
  18505. *
  18506. * @see Quaternion#fastSlerp
  18507. */
  18508. Quaternion.slerp = function(start, end, t, result) {
  18509. if (!defined(start)) {
  18510. throw new DeveloperError('start is required.');
  18511. }
  18512. if (!defined(end)) {
  18513. throw new DeveloperError('end is required.');
  18514. }
  18515. if (typeof t !== 'number') {
  18516. throw new DeveloperError('t is required and must be a number.');
  18517. }
  18518. if (!defined(result)) {
  18519. throw new DeveloperError('result is required');
  18520. }
  18521. var dot = Quaternion.dot(start, end);
  18522. // The angle between start must be acute. Since q and -q represent
  18523. // the same rotation, negate q to get the acute angle.
  18524. var r = end;
  18525. if (dot < 0.0) {
  18526. dot = -dot;
  18527. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  18528. }
  18529. // dot > 0, as the dot product approaches 1, the angle between the
  18530. // quaternions vanishes. use linear interpolation.
  18531. if (1.0 - dot < CesiumMath.EPSILON6) {
  18532. return Quaternion.lerp(start, r, t, result);
  18533. }
  18534. var theta = Math.acos(dot);
  18535. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  18536. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  18537. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  18538. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  18539. };
  18540. /**
  18541. * The logarithmic quaternion function.
  18542. *
  18543. * @param {Quaternion} quaternion The unit quaternion.
  18544. * @param {Cartesian3} result The object onto which to store the result.
  18545. * @returns {Cartesian3} The modified result parameter.
  18546. */
  18547. Quaternion.log = function(quaternion, result) {
  18548. if (!defined(quaternion)) {
  18549. throw new DeveloperError('quaternion is required.');
  18550. }
  18551. if (!defined(result)) {
  18552. throw new DeveloperError('result is required');
  18553. }
  18554. var theta = CesiumMath.acosClamped(quaternion.w);
  18555. var thetaOverSinTheta = 0.0;
  18556. if (theta !== 0.0) {
  18557. thetaOverSinTheta = theta / Math.sin(theta);
  18558. }
  18559. return Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  18560. };
  18561. /**
  18562. * The exponential quaternion function.
  18563. *
  18564. * @param {Cartesian3} cartesian The cartesian.
  18565. * @param {Quaternion} result The object onto which to store the result.
  18566. * @returns {Quaternion} The modified result parameter.
  18567. */
  18568. Quaternion.exp = function(cartesian, result) {
  18569. if (!defined(cartesian)) {
  18570. throw new DeveloperError('cartesian is required.');
  18571. }
  18572. if (!defined(result)) {
  18573. throw new DeveloperError('result is required');
  18574. }
  18575. var theta = Cartesian3.magnitude(cartesian);
  18576. var sinThetaOverTheta = 0.0;
  18577. if (theta !== 0.0) {
  18578. sinThetaOverTheta = Math.sin(theta) / theta;
  18579. }
  18580. result.x = cartesian.x * sinThetaOverTheta;
  18581. result.y = cartesian.y * sinThetaOverTheta;
  18582. result.z = cartesian.z * sinThetaOverTheta;
  18583. result.w = Math.cos(theta);
  18584. return result;
  18585. };
  18586. var squadScratchCartesian0 = new Cartesian3();
  18587. var squadScratchCartesian1 = new Cartesian3();
  18588. var squadScratchQuaternion0 = new Quaternion();
  18589. var squadScratchQuaternion1 = new Quaternion();
  18590. /**
  18591. * Computes an inner quadrangle point.
  18592. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  18593. *
  18594. * @param {Quaternion} q0 The first quaternion.
  18595. * @param {Quaternion} q1 The second quaternion.
  18596. * @param {Quaternion} q2 The third quaternion.
  18597. * @param {Quaternion} result The object onto which to store the result.
  18598. * @returns {Quaternion} The modified result parameter.
  18599. *
  18600. * @see Quaternion#squad
  18601. */
  18602. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  18603. if (!defined(q0) || !defined(q1) || !defined(q2)) {
  18604. throw new DeveloperError('q0, q1, and q2 are required.');
  18605. }
  18606. if (!defined(result)) {
  18607. throw new DeveloperError('result is required');
  18608. }
  18609. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  18610. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  18611. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  18612. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  18613. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  18614. Cartesian3.add(cart0, cart1, cart0);
  18615. Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  18616. Cartesian3.negate(cart0, cart0);
  18617. Quaternion.exp(cart0, squadScratchQuaternion0);
  18618. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  18619. };
  18620. /**
  18621. * Computes the spherical quadrangle interpolation between quaternions.
  18622. *
  18623. * @param {Quaternion} q0 The first quaternion.
  18624. * @param {Quaternion} q1 The second quaternion.
  18625. * @param {Quaternion} s0 The first inner quadrangle.
  18626. * @param {Quaternion} s1 The second inner quadrangle.
  18627. * @param {Number} t The time in [0,1] used to interpolate.
  18628. * @param {Quaternion} result The object onto which to store the result.
  18629. * @returns {Quaternion} The modified result parameter.
  18630. *
  18631. *
  18632. * @example
  18633. * // 1. compute the squad interpolation between two quaternions on a curve
  18634. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  18635. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  18636. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  18637. *
  18638. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  18639. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  18640. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  18641. *
  18642. * @see Quaternion#computeInnerQuadrangle
  18643. */
  18644. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  18645. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  18646. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  18647. }
  18648. if (typeof t !== 'number') {
  18649. throw new DeveloperError('t is required and must be a number.');
  18650. }
  18651. if (!defined(result)) {
  18652. throw new DeveloperError('result is required');
  18653. }
  18654. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  18655. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  18656. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  18657. };
  18658. var fastSlerpScratchQuaternion = new Quaternion();
  18659. var opmu = 1.90110745351730037;
  18660. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18661. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18662. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18663. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  18664. for (var i = 0; i < 7; ++i) {
  18665. var s = i + 1.0;
  18666. var t = 2.0 * s + 1.0;
  18667. u[i] = 1.0 / (s * t);
  18668. v[i] = s / t;
  18669. }
  18670. u[7] = opmu / (8.0 * 17.0);
  18671. v[7] = opmu * 8.0 / 17.0;
  18672. /**
  18673. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  18674. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  18675. *
  18676. * @param {Quaternion} start The value corresponding to t at 0.0.
  18677. * @param {Quaternion} end The value corresponding to t at 1.0.
  18678. * @param {Number} t The point along t at which to interpolate.
  18679. * @param {Quaternion} result The object onto which to store the result.
  18680. * @returns {Quaternion} The modified result parameter.
  18681. *
  18682. * @see Quaternion#slerp
  18683. */
  18684. Quaternion.fastSlerp = function(start, end, t, result) {
  18685. if (!defined(start)) {
  18686. throw new DeveloperError('start is required.');
  18687. }
  18688. if (!defined(end)) {
  18689. throw new DeveloperError('end is required.');
  18690. }
  18691. if (typeof t !== 'number') {
  18692. throw new DeveloperError('t is required and must be a number.');
  18693. }
  18694. if (!defined(result)) {
  18695. throw new DeveloperError('result is required');
  18696. }
  18697. var x = Quaternion.dot(start, end);
  18698. var sign;
  18699. if (x >= 0) {
  18700. sign = 1.0;
  18701. } else {
  18702. sign = -1.0;
  18703. x = -x;
  18704. }
  18705. var xm1 = x - 1.0;
  18706. var d = 1.0 - t;
  18707. var sqrT = t * t;
  18708. var sqrD = d * d;
  18709. for (var i = 7; i >= 0; --i) {
  18710. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  18711. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  18712. }
  18713. var cT = sign * t * (
  18714. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  18715. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  18716. var cD = d * (
  18717. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  18718. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  18719. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  18720. Quaternion.multiplyByScalar(end, cT, result);
  18721. return Quaternion.add(temp, result, result);
  18722. };
  18723. /**
  18724. * Computes the spherical quadrangle interpolation between quaternions.
  18725. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  18726. *
  18727. * @param {Quaternion} q0 The first quaternion.
  18728. * @param {Quaternion} q1 The second quaternion.
  18729. * @param {Quaternion} s0 The first inner quadrangle.
  18730. * @param {Quaternion} s1 The second inner quadrangle.
  18731. * @param {Number} t The time in [0,1] used to interpolate.
  18732. * @param {Quaternion} result The object onto which to store the result.
  18733. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  18734. *
  18735. * @see Quaternion#squad
  18736. */
  18737. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  18738. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  18739. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  18740. }
  18741. if (typeof t !== 'number') {
  18742. throw new DeveloperError('t is required and must be a number.');
  18743. }
  18744. if (!defined(result)) {
  18745. throw new DeveloperError('result is required');
  18746. }
  18747. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  18748. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  18749. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  18750. };
  18751. /**
  18752. * Compares the provided quaternions componentwise and returns
  18753. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18754. *
  18755. * @param {Quaternion} [left] The first quaternion.
  18756. * @param {Quaternion} [right] The second quaternion.
  18757. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  18758. */
  18759. Quaternion.equals = function(left, right) {
  18760. return (left === right) ||
  18761. ((defined(left)) &&
  18762. (defined(right)) &&
  18763. (left.x === right.x) &&
  18764. (left.y === right.y) &&
  18765. (left.z === right.z) &&
  18766. (left.w === right.w));
  18767. };
  18768. /**
  18769. * Compares the provided quaternions componentwise and returns
  18770. * <code>true</code> if they are within the provided epsilon,
  18771. * <code>false</code> otherwise.
  18772. *
  18773. * @param {Quaternion} [left] The first quaternion.
  18774. * @param {Quaternion} [right] The second quaternion.
  18775. * @param {Number} epsilon The epsilon to use for equality testing.
  18776. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  18777. */
  18778. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  18779. if (typeof epsilon !== 'number') {
  18780. throw new DeveloperError('epsilon is required and must be a number.');
  18781. }
  18782. return (left === right) ||
  18783. ((defined(left)) &&
  18784. (defined(right)) &&
  18785. (Math.abs(left.x - right.x) <= epsilon) &&
  18786. (Math.abs(left.y - right.y) <= epsilon) &&
  18787. (Math.abs(left.z - right.z) <= epsilon) &&
  18788. (Math.abs(left.w - right.w) <= epsilon));
  18789. };
  18790. /**
  18791. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  18792. *
  18793. * @type {Quaternion}
  18794. * @constant
  18795. */
  18796. Quaternion.ZERO = freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  18797. /**
  18798. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  18799. *
  18800. * @type {Quaternion}
  18801. * @constant
  18802. */
  18803. Quaternion.IDENTITY = freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  18804. /**
  18805. * Duplicates this Quaternion instance.
  18806. *
  18807. * @param {Quaternion} [result] The object onto which to store the result.
  18808. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  18809. */
  18810. Quaternion.prototype.clone = function(result) {
  18811. return Quaternion.clone(this, result);
  18812. };
  18813. /**
  18814. * Compares this and the provided quaternion componentwise and returns
  18815. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18816. *
  18817. * @param {Quaternion} [right] The right hand side quaternion.
  18818. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  18819. */
  18820. Quaternion.prototype.equals = function(right) {
  18821. return Quaternion.equals(this, right);
  18822. };
  18823. /**
  18824. * Compares this and the provided quaternion componentwise and returns
  18825. * <code>true</code> if they are within the provided epsilon,
  18826. * <code>false</code> otherwise.
  18827. *
  18828. * @param {Quaternion} [right] The right hand side quaternion.
  18829. * @param {Number} epsilon The epsilon to use for equality testing.
  18830. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  18831. */
  18832. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  18833. return Quaternion.equalsEpsilon(this, right, epsilon);
  18834. };
  18835. /**
  18836. * Returns a string representing this quaternion in the format (x, y, z, w).
  18837. *
  18838. * @returns {String} A string representing this Quaternion.
  18839. */
  18840. Quaternion.prototype.toString = function() {
  18841. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  18842. };
  18843. return Quaternion;
  18844. });
  18845. /*global define*/
  18846. define('Core/Transforms',[
  18847. '../ThirdParty/when',
  18848. './Cartesian2',
  18849. './Cartesian3',
  18850. './Cartesian4',
  18851. './Cartographic',
  18852. './defaultValue',
  18853. './defined',
  18854. './deprecationWarning',
  18855. './DeveloperError',
  18856. './EarthOrientationParameters',
  18857. './EarthOrientationParametersSample',
  18858. './Ellipsoid',
  18859. './HeadingPitchRoll',
  18860. './Iau2006XysData',
  18861. './Iau2006XysSample',
  18862. './JulianDate',
  18863. './Math',
  18864. './Matrix3',
  18865. './Matrix4',
  18866. './Quaternion',
  18867. './TimeConstants'
  18868. ], function(
  18869. when,
  18870. Cartesian2,
  18871. Cartesian3,
  18872. Cartesian4,
  18873. Cartographic,
  18874. defaultValue,
  18875. defined,
  18876. deprecationWarning,
  18877. DeveloperError,
  18878. EarthOrientationParameters,
  18879. EarthOrientationParametersSample,
  18880. Ellipsoid,
  18881. HeadingPitchRoll,
  18882. Iau2006XysData,
  18883. Iau2006XysSample,
  18884. JulianDate,
  18885. CesiumMath,
  18886. Matrix3,
  18887. Matrix4,
  18888. Quaternion,
  18889. TimeConstants) {
  18890. 'use strict';
  18891. /**
  18892. * Contains functions for transforming positions to various reference frames.
  18893. *
  18894. * @exports Transforms
  18895. */
  18896. var Transforms = {};
  18897. var eastNorthUpToFixedFrameNormal = new Cartesian3();
  18898. var eastNorthUpToFixedFrameTangent = new Cartesian3();
  18899. var eastNorthUpToFixedFrameBitangent = new Cartesian3();
  18900. /**
  18901. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  18902. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  18903. * The local axes are defined as:
  18904. * <ul>
  18905. * <li>The <code>x</code> axis points in the local east direction.</li>
  18906. * <li>The <code>y</code> axis points in the local north direction.</li>
  18907. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  18908. * </ul>
  18909. *
  18910. * @param {Cartesian3} origin The center point of the local reference frame.
  18911. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  18912. * @param {Matrix4} [result] The object onto which to store the result.
  18913. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  18914. *
  18915. * @example
  18916. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  18917. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  18918. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  18919. */
  18920. Transforms.eastNorthUpToFixedFrame = function(origin, ellipsoid, result) {
  18921. if (!defined(origin)) {
  18922. throw new DeveloperError('origin is required.');
  18923. }
  18924. // If x and y are zero, assume origin is at a pole, which is a special case.
  18925. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  18926. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  18927. var sign = CesiumMath.sign(origin.z);
  18928. if (!defined(result)) {
  18929. return new Matrix4(
  18930. 0.0, -sign, 0.0, origin.x,
  18931. 1.0, 0.0, 0.0, origin.y,
  18932. 0.0, 0.0, sign, origin.z,
  18933. 0.0, 0.0, 0.0, 1.0);
  18934. }
  18935. result[0] = 0.0;
  18936. result[1] = 1.0;
  18937. result[2] = 0.0;
  18938. result[3] = 0.0;
  18939. result[4] = -sign;
  18940. result[5] = 0.0;
  18941. result[6] = 0.0;
  18942. result[7] = 0.0;
  18943. result[8] = 0.0;
  18944. result[9] = 0.0;
  18945. result[10] = sign;
  18946. result[11] = 0.0;
  18947. result[12] = origin.x;
  18948. result[13] = origin.y;
  18949. result[14] = origin.z;
  18950. result[15] = 1.0;
  18951. return result;
  18952. }
  18953. var normal = eastNorthUpToFixedFrameNormal;
  18954. var tangent = eastNorthUpToFixedFrameTangent;
  18955. var bitangent = eastNorthUpToFixedFrameBitangent;
  18956. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  18957. ellipsoid.geodeticSurfaceNormal(origin, normal);
  18958. tangent.x = -origin.y;
  18959. tangent.y = origin.x;
  18960. tangent.z = 0.0;
  18961. Cartesian3.normalize(tangent, tangent);
  18962. Cartesian3.cross(normal, tangent, bitangent);
  18963. if (!defined(result)) {
  18964. return new Matrix4(
  18965. tangent.x, bitangent.x, normal.x, origin.x,
  18966. tangent.y, bitangent.y, normal.y, origin.y,
  18967. tangent.z, bitangent.z, normal.z, origin.z,
  18968. 0.0, 0.0, 0.0, 1.0);
  18969. }
  18970. result[0] = tangent.x;
  18971. result[1] = tangent.y;
  18972. result[2] = tangent.z;
  18973. result[3] = 0.0;
  18974. result[4] = bitangent.x;
  18975. result[5] = bitangent.y;
  18976. result[6] = bitangent.z;
  18977. result[7] = 0.0;
  18978. result[8] = normal.x;
  18979. result[9] = normal.y;
  18980. result[10] = normal.z;
  18981. result[11] = 0.0;
  18982. result[12] = origin.x;
  18983. result[13] = origin.y;
  18984. result[14] = origin.z;
  18985. result[15] = 1.0;
  18986. return result;
  18987. };
  18988. var northEastDownToFixedFrameNormal = new Cartesian3();
  18989. var northEastDownToFixedFrameTangent = new Cartesian3();
  18990. var northEastDownToFixedFrameBitangent = new Cartesian3();
  18991. /**
  18992. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  18993. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  18994. * The local axes are defined as:
  18995. * <ul>
  18996. * <li>The <code>x</code> axis points in the local north direction.</li>
  18997. * <li>The <code>y</code> axis points in the local east direction.</li>
  18998. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  18999. * </ul>
  19000. *
  19001. * @param {Cartesian3} origin The center point of the local reference frame.
  19002. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19003. * @param {Matrix4} [result] The object onto which to store the result.
  19004. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19005. *
  19006. * @example
  19007. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  19008. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19009. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  19010. */
  19011. Transforms.northEastDownToFixedFrame = function(origin, ellipsoid, result) {
  19012. if (!defined(origin)) {
  19013. throw new DeveloperError('origin is required.');
  19014. }
  19015. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19016. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19017. // The poles are special cases. If x and y are zero, assume origin is at a pole.
  19018. var sign = CesiumMath.sign(origin.z);
  19019. if (!defined(result)) {
  19020. return new Matrix4(
  19021. -sign, 0.0, 0.0, origin.x,
  19022. 0.0, 1.0, 0.0, origin.y,
  19023. 0.0, 0.0, -sign, origin.z,
  19024. 0.0, 0.0, 0.0, 1.0);
  19025. }
  19026. result[0] = -sign;
  19027. result[1] = 0.0;
  19028. result[2] = 0.0;
  19029. result[3] = 0.0;
  19030. result[4] = 0.0;
  19031. result[5] = 1.0;
  19032. result[6] = 0.0;
  19033. result[7] = 0.0;
  19034. result[8] = 0.0;
  19035. result[9] = 0.0;
  19036. result[10] = -sign;
  19037. result[11] = 0.0;
  19038. result[12] = origin.x;
  19039. result[13] = origin.y;
  19040. result[14] = origin.z;
  19041. result[15] = 1.0;
  19042. return result;
  19043. }
  19044. var normal = northEastDownToFixedFrameNormal;
  19045. var tangent = northEastDownToFixedFrameTangent;
  19046. var bitangent = northEastDownToFixedFrameBitangent;
  19047. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19048. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19049. tangent.x = -origin.y;
  19050. tangent.y = origin.x;
  19051. tangent.z = 0.0;
  19052. Cartesian3.normalize(tangent, tangent);
  19053. Cartesian3.cross(normal, tangent, bitangent);
  19054. if (!defined(result)) {
  19055. return new Matrix4(
  19056. bitangent.x, tangent.x, -normal.x, origin.x,
  19057. bitangent.y, tangent.y, -normal.y, origin.y,
  19058. bitangent.z, tangent.z, -normal.z, origin.z,
  19059. 0.0, 0.0, 0.0, 1.0);
  19060. }
  19061. result[0] = bitangent.x;
  19062. result[1] = bitangent.y;
  19063. result[2] = bitangent.z;
  19064. result[3] = 0.0;
  19065. result[4] = tangent.x;
  19066. result[5] = tangent.y;
  19067. result[6] = tangent.z;
  19068. result[7] = 0.0;
  19069. result[8] = -normal.x;
  19070. result[9] = -normal.y;
  19071. result[10] = -normal.z;
  19072. result[11] = 0.0;
  19073. result[12] = origin.x;
  19074. result[13] = origin.y;
  19075. result[14] = origin.z;
  19076. result[15] = 1.0;
  19077. return result;
  19078. };
  19079. /**
  19080. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  19081. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19082. * The local axes are defined as:
  19083. * <ul>
  19084. * <li>The <code>x</code> axis points in the local north direction.</li>
  19085. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  19086. * <li>The <code>z</code> axis points in the local east direction.</li>
  19087. * </ul>
  19088. *
  19089. * @param {Cartesian3} origin The center point of the local reference frame.
  19090. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19091. * @param {Matrix4} [result] The object onto which to store the result.
  19092. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19093. *
  19094. * @example
  19095. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  19096. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19097. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  19098. */
  19099. Transforms.northUpEastToFixedFrame = function(origin, ellipsoid, result) {
  19100. if (!defined(origin)) {
  19101. throw new DeveloperError('origin is required.');
  19102. }
  19103. // If x and y are zero, assume origin is at a pole, which is a special case.
  19104. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19105. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19106. var sign = CesiumMath.sign(origin.z);
  19107. if (!defined(result)) {
  19108. return new Matrix4(
  19109. -sign, 0.0, 0.0, origin.x,
  19110. 0.0, 0.0, 1.0, origin.y,
  19111. 0.0, sign, 0.0, origin.z,
  19112. 0.0, 0.0, 0.0, 1.0);
  19113. }
  19114. result[0] = -sign;
  19115. result[1] = 0.0;
  19116. result[2] = 0.0;
  19117. result[3] = 0.0;
  19118. result[4] = 0.0;
  19119. result[5] = 0.0;
  19120. result[6] = sign;
  19121. result[7] = 0.0;
  19122. result[8] = 0.0;
  19123. result[9] = 1.0;
  19124. result[10] = 0.0;
  19125. result[11] = 0.0;
  19126. result[12] = origin.x;
  19127. result[13] = origin.y;
  19128. result[14] = origin.z;
  19129. result[15] = 1.0;
  19130. return result;
  19131. }
  19132. var normal = eastNorthUpToFixedFrameNormal;
  19133. var tangent = eastNorthUpToFixedFrameTangent;
  19134. var bitangent = eastNorthUpToFixedFrameBitangent;
  19135. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19136. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19137. tangent.x = -origin.y;
  19138. tangent.y = origin.x;
  19139. tangent.z = 0.0;
  19140. Cartesian3.normalize(tangent, tangent);
  19141. Cartesian3.cross(normal, tangent, bitangent);
  19142. if (!defined(result)) {
  19143. return new Matrix4(
  19144. bitangent.x, normal.x, tangent.x, origin.x,
  19145. bitangent.y, normal.y, tangent.y, origin.y,
  19146. bitangent.z, normal.z, tangent.z, origin.z,
  19147. 0.0, 0.0, 0.0, 1.0);
  19148. }
  19149. result[0] = bitangent.x;
  19150. result[1] = bitangent.y;
  19151. result[2] = bitangent.z;
  19152. result[3] = 0.0;
  19153. result[4] = normal.x;
  19154. result[5] = normal.y;
  19155. result[6] = normal.z;
  19156. result[7] = 0.0;
  19157. result[8] = tangent.x;
  19158. result[9] = tangent.y;
  19159. result[10] = tangent.z;
  19160. result[11] = 0.0;
  19161. result[12] = origin.x;
  19162. result[13] = origin.y;
  19163. result[14] = origin.z;
  19164. result[15] = 1.0;
  19165. return result;
  19166. };
  19167. /**
  19168. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  19169. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  19170. * The local axes are defined as:
  19171. * <ul>
  19172. * <li>The <code>x</code> axis points in the local north direction.</li>
  19173. * <li>The <code>y</code> axis points in the local west direction.</li>
  19174. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  19175. * </ul>
  19176. *
  19177. * @param {Cartesian3} origin The center point of the local reference frame.
  19178. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19179. * @param {Matrix4} [result] The object onto which to store the result.
  19180. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19181. *
  19182. * @example
  19183. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  19184. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19185. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  19186. */
  19187. Transforms.northWestUpToFixedFrame = function(origin, ellipsoid, result) {
  19188. if (!defined(origin)) {
  19189. throw new DeveloperError('origin is required.');
  19190. }
  19191. // If x and y are zero, assume origin is at a pole, which is a special case.
  19192. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  19193. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  19194. var sign = CesiumMath.sign(origin.z);
  19195. if (!defined(result)) {
  19196. return new Matrix4(
  19197. -sign, 0.0, 0.0, origin.x,
  19198. 0.0, -1.0, 0.0, origin.y,
  19199. 0.0, 0.0, sign, origin.z,
  19200. 0.0, 0.0, 0.0, 1.0);
  19201. }
  19202. result[0] = -sign;
  19203. result[1] = 0.0;
  19204. result[2] = 0.0;
  19205. result[3] = 0.0;
  19206. result[4] = 0.0;
  19207. result[5] = -1.0;
  19208. result[6] = 0.0;
  19209. result[7] = 0.0;
  19210. result[8] = 0.0;
  19211. result[9] = 0.0;
  19212. result[10] = sign;
  19213. result[11] = 0.0;
  19214. result[12] = origin.x;
  19215. result[13] = origin.y;
  19216. result[14] = origin.z;
  19217. result[15] = 1.0;
  19218. return result;
  19219. }
  19220. var normal = eastNorthUpToFixedFrameNormal;//Up
  19221. var tangent = eastNorthUpToFixedFrameTangent;//East
  19222. var bitangent = eastNorthUpToFixedFrameBitangent;//North
  19223. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19224. ellipsoid.geodeticSurfaceNormal(origin, normal);
  19225. tangent.x = -origin.y;
  19226. tangent.y = origin.x;
  19227. tangent.z = 0.0;
  19228. Cartesian3.normalize(tangent, tangent);
  19229. Cartesian3.cross(normal, tangent, bitangent);
  19230. if (!defined(result)) {
  19231. return new Matrix4(
  19232. bitangent.x, -tangent.x, normal.x, origin.x,
  19233. bitangent.y, -tangent.y, normal.y, origin.y,
  19234. bitangent.z, -tangent.z, normal.z, origin.z,
  19235. 0.0, 0.0, 0.0, 1.0);
  19236. }
  19237. result[0] = bitangent.x;
  19238. result[1] = bitangent.y;
  19239. result[2] = bitangent.z;
  19240. result[3] = 0.0;
  19241. result[4] = -tangent.x;
  19242. result[5] = -tangent.y;
  19243. result[6] = -tangent.z;
  19244. result[7] = 0.0;
  19245. result[8] = normal.x;
  19246. result[9] = normal.y;
  19247. result[10] = normal.z;
  19248. result[11] = 0.0;
  19249. result[12] = origin.x;
  19250. result[13] = origin.y;
  19251. result[14] = origin.z;
  19252. result[15] = 1.0;
  19253. return result;
  19254. };
  19255. var scratchHPRQuaternion = new Quaternion();
  19256. var scratchScale = new Cartesian3(1.0, 1.0, 1.0);
  19257. var scratchHPRMatrix4 = new Matrix4();
  19258. /**
  19259. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  19260. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  19261. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  19262. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  19263. *
  19264. * @param {Cartesian3} origin The center point of the local reference frame.
  19265. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  19266. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19267. * @param {Matrix4} [result] The object onto which to store the result.
  19268. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  19269. *
  19270. * @example
  19271. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  19272. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19273. * var heading = -Cesium.Math.PI_OVER_TWO;
  19274. * var pitch = Cesium.Math.PI_OVER_FOUR;
  19275. * var roll = 0.0;
  19276. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  19277. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  19278. */
  19279. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  19280. var heading;
  19281. if (typeof headingPitchRoll === 'object') {
  19282. // Shift arguments using assignments to encourage JIT optimization.
  19283. ellipsoid = pitch;
  19284. result = roll;
  19285. heading = headingPitchRoll.heading;
  19286. pitch = headingPitchRoll.pitch;
  19287. roll = headingPitchRoll.roll;
  19288. } else {
  19289. deprecationWarning('headingPitchRollToFixedFrame', 'headingPitchRollToFixedFrame with separate heading, pitch, and roll arguments was deprecated in 1.27. It will be removed in 1.30. Use a HeadingPitchRoll object.');
  19290. heading = headingPitchRoll;
  19291. }
  19292. // checks for required parameters happen in the called functions
  19293. var hprQuaternion = Quaternion.fromHeadingPitchRoll(heading, pitch, roll, scratchHPRQuaternion);
  19294. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, hprQuaternion, scratchScale, scratchHPRMatrix4);
  19295. result = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, result);
  19296. return Matrix4.multiply(result, hprMatrix, result);
  19297. };
  19298. var scratchHPR = new HeadingPitchRoll();
  19299. var scratchENUMatrix4 = new Matrix4();
  19300. var scratchHPRMatrix3 = new Matrix3();
  19301. /**
  19302. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  19303. * centered at the provided origin. Heading is the rotation from the local north
  19304. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  19305. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  19306. *
  19307. * @param {Cartesian3} origin The center point of the local reference frame.
  19308. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  19309. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  19310. * @param {Quaternion} [result] The object onto which to store the result.
  19311. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  19312. *
  19313. * @example
  19314. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  19315. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19316. * var heading = -Cesium.Math.PI_OVER_TWO;
  19317. * var pitch = Cesium.Math.PI_OVER_FOUR;
  19318. * var roll = 0.0;
  19319. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  19320. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  19321. */
  19322. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  19323. var hpr;
  19324. if (typeof headingPitchRoll === 'object') {
  19325. // Shift arguments using assignment to encourage JIT optimization.
  19326. hpr = headingPitchRoll;
  19327. ellipsoid = pitch;
  19328. result = roll;
  19329. } else {
  19330. deprecationWarning('headingPitchRollQuaternion', 'headingPitchRollQuaternion with separate heading, pitch, and roll arguments was deprecated in 1.27. It will be removed in 1.30. Use a HeadingPitchRoll object.');
  19331. scratchHPR.heading = headingPitchRoll;
  19332. scratchHPR.pitch = pitch;
  19333. scratchHPR.roll = roll;
  19334. hpr = scratchHPR;
  19335. }
  19336. // checks for required parameters happen in the called functions
  19337. var transform = Transforms.headingPitchRollToFixedFrame(origin, hpr, ellipsoid, scratchENUMatrix4);
  19338. var rotation = Matrix4.getRotation(transform, scratchHPRMatrix3);
  19339. return Quaternion.fromRotationMatrix(rotation, result);
  19340. };
  19341. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  19342. var gmstConstant1 = 8640184.812866;
  19343. var gmstConstant2 = 0.093104;
  19344. var gmstConstant3 = -6.2E-6;
  19345. var rateCoef = 1.1772758384668e-19;
  19346. var wgs84WRPrecessing = 7.2921158553E-5;
  19347. var twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  19348. var dateInUtc = new JulianDate();
  19349. /**
  19350. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  19351. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  19352. *
  19353. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19354. * @param {Matrix3} [result] The object onto which to store the result.
  19355. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  19356. *
  19357. * @example
  19358. * //Set the view to in the inertial frame.
  19359. * scene.preRender.addEventListener(function(scene, time) {
  19360. * var now = Cesium.JulianDate.now();
  19361. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  19362. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  19363. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  19364. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  19365. * camera.lookAtTransform(transform, offset);
  19366. * });
  19367. */
  19368. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  19369. if (!defined(date)) {
  19370. throw new DeveloperError('date is required.');
  19371. }
  19372. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  19373. // We do not want to use the function like convertTaiToUtc in JulianDate because
  19374. // we explicitly do not want to fail when inside the leap second.
  19375. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  19376. var utcDayNumber = dateInUtc.dayNumber;
  19377. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  19378. var t;
  19379. var diffDays = utcDayNumber - 2451545;
  19380. if (utcSecondsIntoDay >= 43200.0) {
  19381. t = (diffDays + 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  19382. } else {
  19383. t = (diffDays - 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  19384. }
  19385. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  19386. var angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
  19387. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  19388. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants.SECONDS_PER_DAY * 0.5) % TimeConstants.SECONDS_PER_DAY;
  19389. var gha = angle + (ratio * secondsSinceMidnight);
  19390. var cosGha = Math.cos(gha);
  19391. var sinGha = Math.sin(gha);
  19392. if (!defined(result)) {
  19393. return new Matrix3(cosGha, sinGha, 0.0,
  19394. -sinGha, cosGha, 0.0,
  19395. 0.0, 0.0, 1.0);
  19396. }
  19397. result[0] = cosGha;
  19398. result[1] = -sinGha;
  19399. result[2] = 0.0;
  19400. result[3] = sinGha;
  19401. result[4] = cosGha;
  19402. result[5] = 0.0;
  19403. result[6] = 0.0;
  19404. result[7] = 0.0;
  19405. result[8] = 1.0;
  19406. return result;
  19407. };
  19408. /**
  19409. * The source of IAU 2006 XYS data, used for computing the transformation between the
  19410. * Fixed and ICRF axes.
  19411. * @type {Iau2006XysData}
  19412. *
  19413. * @see Transforms.computeIcrfToFixedMatrix
  19414. * @see Transforms.computeFixedToIcrfMatrix
  19415. *
  19416. * @private
  19417. */
  19418. Transforms.iau2006XysData = new Iau2006XysData();
  19419. /**
  19420. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  19421. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  19422. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  19423. * @type {EarthOrientationParameters}
  19424. *
  19425. * @see Transforms.computeIcrfToFixedMatrix
  19426. * @see Transforms.computeFixedToIcrfMatrix
  19427. *
  19428. * @private
  19429. */
  19430. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  19431. var ttMinusTai = 32.184;
  19432. var j2000ttDays = 2451545.0;
  19433. /**
  19434. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  19435. * direction, over a given interval. This function returns a promise that, when resolved,
  19436. * indicates that the preload has completed.
  19437. *
  19438. * @param {TimeInterval} timeInterval The interval to preload.
  19439. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the preload has completed
  19440. * and evaluation of the transformation between the fixed and ICRF axes will
  19441. * no longer return undefined for a time inside the interval.
  19442. *
  19443. *
  19444. * @example
  19445. * var interval = new Cesium.TimeInterval(...);
  19446. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  19447. * // the data is now loaded
  19448. * });
  19449. *
  19450. * @see Transforms.computeIcrfToFixedMatrix
  19451. * @see Transforms.computeFixedToIcrfMatrix
  19452. * @see when
  19453. */
  19454. Transforms.preloadIcrfFixed = function(timeInterval) {
  19455. var startDayTT = timeInterval.start.dayNumber;
  19456. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  19457. var stopDayTT = timeInterval.stop.dayNumber;
  19458. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  19459. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  19460. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  19461. return when.all([xysPromise, eopPromise]);
  19462. };
  19463. /**
  19464. * Computes a rotation matrix to transform a point or vector from the International Celestial
  19465. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  19466. * at a given time. This function may return undefined if the data necessary to
  19467. * do the transformation is not yet loaded.
  19468. *
  19469. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19470. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  19471. * not specified, a new instance is created and returned.
  19472. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  19473. * transformation is not yet loaded.
  19474. *
  19475. *
  19476. * @example
  19477. * scene.preRender.addEventListener(function(scene, time) {
  19478. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  19479. * if (Cesium.defined(icrfToFixed)) {
  19480. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  19481. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed)
  19482. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  19483. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  19484. * camera.lookAtTransform(transform, offset);
  19485. * }
  19486. * });
  19487. *
  19488. * @see Transforms.preloadIcrfFixed
  19489. */
  19490. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  19491. if (!defined(date)) {
  19492. throw new DeveloperError('date is required.');
  19493. }
  19494. if (!defined(result)) {
  19495. result = new Matrix3();
  19496. }
  19497. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  19498. if (!defined(fixedToIcrfMtx)) {
  19499. return undefined;
  19500. }
  19501. return Matrix3.transpose(fixedToIcrfMtx, result);
  19502. };
  19503. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  19504. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  19505. var rotation1Scratch = new Matrix3();
  19506. var rotation2Scratch = new Matrix3();
  19507. /**
  19508. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  19509. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  19510. * at a given time. This function may return undefined if the data necessary to
  19511. * do the transformation is not yet loaded.
  19512. *
  19513. * @param {JulianDate} date The time at which to compute the rotation matrix.
  19514. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  19515. * not specified, a new instance is created and returned.
  19516. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  19517. * transformation is not yet loaded.
  19518. *
  19519. *
  19520. * @example
  19521. * // Transform a point from the ICRF axes to the Fixed axes.
  19522. * var now = Cesium.JulianDate.now();
  19523. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  19524. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  19525. * var pointInInertial = new Cesium.Cartesian3();
  19526. * if (Cesium.defined(fixedToIcrf)) {
  19527. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  19528. * }
  19529. *
  19530. * @see Transforms.preloadIcrfFixed
  19531. */
  19532. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  19533. if (!defined(date)) {
  19534. throw new DeveloperError('date is required.');
  19535. }
  19536. if (!defined(result)) {
  19537. result = new Matrix3();
  19538. }
  19539. // Compute pole wander
  19540. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  19541. if (!defined(eop)) {
  19542. return undefined;
  19543. }
  19544. // There is no external conversion to Terrestrial Time (TT).
  19545. // So use International Atomic Time (TAI) and convert using offsets.
  19546. // Here we are assuming that dayTT and secondTT are positive
  19547. var dayTT = date.dayNumber;
  19548. // It's possible here that secondTT could roll over 86400
  19549. // This does not seem to affect the precision (unit tests check for this)
  19550. var secondTT = date.secondsOfDay + ttMinusTai;
  19551. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  19552. if (!defined(xys)) {
  19553. return undefined;
  19554. }
  19555. var x = xys.x + eop.xPoleOffset;
  19556. var y = xys.y + eop.yPoleOffset;
  19557. // Compute XYS rotation
  19558. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  19559. var rotation1 = rotation1Scratch;
  19560. rotation1[0] = 1.0 - a * x * x;
  19561. rotation1[3] = -a * x * y;
  19562. rotation1[6] = x;
  19563. rotation1[1] = -a * x * y;
  19564. rotation1[4] = 1 - a * y * y;
  19565. rotation1[7] = y;
  19566. rotation1[2] = -x;
  19567. rotation1[5] = -y;
  19568. rotation1[8] = 1 - a * (x * x + y * y);
  19569. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  19570. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  19571. // Similar to TT conversions above
  19572. // It's possible here that secondTT could roll over 86400
  19573. // This does not seem to affect the precision (unit tests check for this)
  19574. var dateUt1day = date.dayNumber;
  19575. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  19576. // Compute Earth rotation angle
  19577. // The IERS standard for era is
  19578. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  19579. // where
  19580. // Tu = JulianDateInUt1 - 2451545.0
  19581. // However, you get much more precision if you make the following simplification
  19582. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  19583. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  19584. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  19585. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  19586. var daysSinceJ2000 = dateUt1day - 2451545;
  19587. var fractionOfDay = dateUt1sec / TimeConstants.SECONDS_PER_DAY;
  19588. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  19589. era = (era % 1.0) * CesiumMath.TWO_PI;
  19590. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  19591. // pseudoFixed to ICRF
  19592. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  19593. // Compute pole wander matrix
  19594. var cosxp = Math.cos(eop.xPoleWander);
  19595. var cosyp = Math.cos(eop.yPoleWander);
  19596. var sinxp = Math.sin(eop.xPoleWander);
  19597. var sinyp = Math.sin(eop.yPoleWander);
  19598. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants.SECONDS_PER_DAY;
  19599. ttt /= 36525.0;
  19600. // approximate sp value in rad
  19601. var sp = -47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  19602. var cossp = Math.cos(sp);
  19603. var sinsp = Math.sin(sp);
  19604. var fToPfMtx = rotation2Scratch;
  19605. fToPfMtx[0] = cosxp * cossp;
  19606. fToPfMtx[1] = cosxp * sinsp;
  19607. fToPfMtx[2] = sinxp;
  19608. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  19609. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  19610. fToPfMtx[5] = -sinyp * cosxp;
  19611. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  19612. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  19613. fToPfMtx[8] = cosyp * cosxp;
  19614. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  19615. };
  19616. var pointToWindowCoordinatesTemp = new Cartesian4();
  19617. /**
  19618. * Transform a point from model coordinates to window coordinates.
  19619. *
  19620. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  19621. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  19622. * @param {Cartesian3} point The point to transform.
  19623. * @param {Cartesian2} [result] The object onto which to store the result.
  19624. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  19625. */
  19626. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  19627. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  19628. result.y = 2.0 * viewportTransformation[5] - result.y;
  19629. return result;
  19630. };
  19631. /**
  19632. * @private
  19633. */
  19634. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  19635. if (!defined(modelViewProjectionMatrix)) {
  19636. throw new DeveloperError('modelViewProjectionMatrix is required.');
  19637. }
  19638. if (!defined(viewportTransformation)) {
  19639. throw new DeveloperError('viewportTransformation is required.');
  19640. }
  19641. if (!defined(point)) {
  19642. throw new DeveloperError('point is required.');
  19643. }
  19644. if (!defined(result)) {
  19645. result = new Cartesian2();
  19646. }
  19647. var tmp = pointToWindowCoordinatesTemp;
  19648. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  19649. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  19650. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  19651. return Cartesian2.fromCartesian4(tmp, result);
  19652. };
  19653. var normalScratch = new Cartesian3();
  19654. var rightScratch = new Cartesian3();
  19655. var upScratch = new Cartesian3();
  19656. /**
  19657. * @private
  19658. */
  19659. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  19660. if (!defined(position)) {
  19661. throw new DeveloperError('position is required.');
  19662. }
  19663. if (!defined(velocity)) {
  19664. throw new DeveloperError('velocity is required.');
  19665. }
  19666. var normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  19667. var right = Cartesian3.cross(velocity, normal, rightScratch);
  19668. if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
  19669. right = Cartesian3.clone(Cartesian3.UNIT_X, right);
  19670. }
  19671. var up = Cartesian3.cross(right, velocity, upScratch);
  19672. Cartesian3.cross(velocity, up, right);
  19673. Cartesian3.negate(right, right);
  19674. if (!defined(result)) {
  19675. result = new Matrix3();
  19676. }
  19677. result[0] = velocity.x;
  19678. result[1] = velocity.y;
  19679. result[2] = velocity.z;
  19680. result[3] = right.x;
  19681. result[4] = right.y;
  19682. result[5] = right.z;
  19683. result[6] = up.x;
  19684. result[7] = up.y;
  19685. result[8] = up.z;
  19686. return result;
  19687. };
  19688. var scratchCartographic = new Cartographic();
  19689. var scratchCartesian3Projection = new Cartesian3();
  19690. var scratchCartesian3 = new Cartesian3();
  19691. var scratchCartesian4Origin = new Cartesian4();
  19692. var scratchCartesian4NewOrigin = new Cartesian4();
  19693. var scratchCartesian4NewXAxis = new Cartesian4();
  19694. var scratchCartesian4NewYAxis = new Cartesian4();
  19695. var scratchCartesian4NewZAxis = new Cartesian4();
  19696. var scratchFromENU = new Matrix4();
  19697. var scratchToENU = new Matrix4();
  19698. /**
  19699. * @private
  19700. */
  19701. Transforms.basisTo2D = function(projection, matrix, result) {
  19702. if (!defined(projection)) {
  19703. throw new DeveloperError('projection is required.');
  19704. }
  19705. if (!defined(matrix)) {
  19706. throw new DeveloperError('matrix is required.');
  19707. }
  19708. if (!defined(result)) {
  19709. throw new DeveloperError('result is required.');
  19710. }
  19711. var ellipsoid = projection.ellipsoid;
  19712. var origin = Matrix4.getColumn(matrix, 3, scratchCartesian4Origin);
  19713. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  19714. var fromENU = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchFromENU);
  19715. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  19716. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  19717. var newOrigin = scratchCartesian4NewOrigin;
  19718. newOrigin.x = projectedPosition.z;
  19719. newOrigin.y = projectedPosition.x;
  19720. newOrigin.z = projectedPosition.y;
  19721. newOrigin.w = 1.0;
  19722. var xAxis = Matrix4.getColumn(matrix, 0, scratchCartesian3);
  19723. var xScale = Cartesian3.magnitude(xAxis);
  19724. var newXAxis = Matrix4.multiplyByVector(toENU, xAxis, scratchCartesian4NewXAxis);
  19725. Cartesian4.fromElements(newXAxis.z, newXAxis.x, newXAxis.y, 0.0, newXAxis);
  19726. var yAxis = Matrix4.getColumn(matrix, 1, scratchCartesian3);
  19727. var yScale = Cartesian3.magnitude(yAxis);
  19728. var newYAxis = Matrix4.multiplyByVector(toENU, yAxis, scratchCartesian4NewYAxis);
  19729. Cartesian4.fromElements(newYAxis.z, newYAxis.x, newYAxis.y, 0.0, newYAxis);
  19730. var zAxis = Matrix4.getColumn(matrix, 2, scratchCartesian3);
  19731. var zScale = Cartesian3.magnitude(zAxis);
  19732. var newZAxis = scratchCartesian4NewZAxis;
  19733. Cartesian3.cross(newXAxis, newYAxis, newZAxis);
  19734. Cartesian3.normalize(newZAxis, newZAxis);
  19735. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  19736. Cartesian3.normalize(newXAxis, newXAxis);
  19737. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  19738. Cartesian3.normalize(newYAxis, newYAxis);
  19739. Cartesian3.multiplyByScalar(newXAxis, xScale, newXAxis);
  19740. Cartesian3.multiplyByScalar(newYAxis, yScale, newYAxis);
  19741. Cartesian3.multiplyByScalar(newZAxis, zScale, newZAxis);
  19742. Matrix4.setColumn(result, 0, newXAxis, result);
  19743. Matrix4.setColumn(result, 1, newYAxis, result);
  19744. Matrix4.setColumn(result, 2, newZAxis, result);
  19745. Matrix4.setColumn(result, 3, newOrigin, result);
  19746. return result;
  19747. };
  19748. return Transforms;
  19749. });
  19750. /*global define*/
  19751. define('Core/EllipsoidTangentPlane',[
  19752. './AxisAlignedBoundingBox',
  19753. './Cartesian2',
  19754. './Cartesian3',
  19755. './Cartesian4',
  19756. './defaultValue',
  19757. './defined',
  19758. './defineProperties',
  19759. './DeveloperError',
  19760. './Ellipsoid',
  19761. './IntersectionTests',
  19762. './Matrix4',
  19763. './Plane',
  19764. './Ray',
  19765. './Transforms'
  19766. ], function(
  19767. AxisAlignedBoundingBox,
  19768. Cartesian2,
  19769. Cartesian3,
  19770. Cartesian4,
  19771. defaultValue,
  19772. defined,
  19773. defineProperties,
  19774. DeveloperError,
  19775. Ellipsoid,
  19776. IntersectionTests,
  19777. Matrix4,
  19778. Plane,
  19779. Ray,
  19780. Transforms) {
  19781. 'use strict';
  19782. var scratchCart4 = new Cartesian4();
  19783. /**
  19784. * A plane tangent to the provided ellipsoid at the provided origin.
  19785. * If origin is not on the surface of the ellipsoid, it's surface projection will be used.
  19786. * If origin is at the center of the ellipsoid, an exception will be thrown.
  19787. * @alias EllipsoidTangentPlane
  19788. * @constructor
  19789. *
  19790. * @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
  19791. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  19792. *
  19793. * @exception {DeveloperError} origin must not be at the center of the ellipsoid.
  19794. */
  19795. function EllipsoidTangentPlane(origin, ellipsoid) {
  19796. if (!defined(origin)) {
  19797. throw new DeveloperError('origin is required.');
  19798. }
  19799. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  19800. origin = ellipsoid.scaleToGeodeticSurface(origin);
  19801. if (!defined(origin)) {
  19802. throw new DeveloperError('origin must not be at the center of the ellipsoid.');
  19803. }
  19804. var eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
  19805. this._ellipsoid = ellipsoid;
  19806. this._origin = origin;
  19807. this._xAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 0, scratchCart4));
  19808. this._yAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 1, scratchCart4));
  19809. var normal = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 2, scratchCart4));
  19810. this._plane = Plane.fromPointNormal(origin, normal);
  19811. }
  19812. defineProperties(EllipsoidTangentPlane.prototype, {
  19813. /**
  19814. * Gets the ellipsoid.
  19815. * @memberof EllipsoidTangentPlane.prototype
  19816. * @type {Ellipsoid}
  19817. */
  19818. ellipsoid : {
  19819. get : function() {
  19820. return this._ellipsoid;
  19821. }
  19822. },
  19823. /**
  19824. * Gets the origin.
  19825. * @memberof EllipsoidTangentPlane.prototype
  19826. * @type {Cartesian3}
  19827. */
  19828. origin : {
  19829. get : function() {
  19830. return this._origin;
  19831. }
  19832. },
  19833. /**
  19834. * Gets the plane which is tangent to the ellipsoid.
  19835. * @memberof EllipsoidTangentPlane.prototype
  19836. * @readonly
  19837. * @type {Plane}
  19838. */
  19839. plane : {
  19840. get : function() {
  19841. return this._plane;
  19842. }
  19843. },
  19844. /**
  19845. * Gets the local X-axis (east) of the tangent plane.
  19846. * @memberof EllipsoidTangentPlane.prototype
  19847. * @readonly
  19848. * @type {Cartesian3}
  19849. */
  19850. xAxis : {
  19851. get : function() {
  19852. return this._xAxis;
  19853. }
  19854. },
  19855. /**
  19856. * Gets the local Y-axis (north) of the tangent plane.
  19857. * @memberof EllipsoidTangentPlane.prototype
  19858. * @readonly
  19859. * @type {Cartesian3}
  19860. */
  19861. yAxis : {
  19862. get : function() {
  19863. return this._yAxis;
  19864. }
  19865. },
  19866. /**
  19867. * Gets the local Z-axis (up) of the tangent plane.
  19868. * @member EllipsoidTangentPlane.prototype
  19869. * @readonly
  19870. * @type {Cartesian3}
  19871. */
  19872. zAxis : {
  19873. get : function() {
  19874. return this._plane.normal;
  19875. }
  19876. }
  19877. });
  19878. var tmp = new AxisAlignedBoundingBox();
  19879. /**
  19880. * Creates a new instance from the provided ellipsoid and the center
  19881. * point of the provided Cartesians.
  19882. *
  19883. * @param {Ellipsoid} ellipsoid The ellipsoid to use.
  19884. * @param {Cartesian3} cartesians The list of positions surrounding the center point.
  19885. */
  19886. EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
  19887. if (!defined(cartesians)) {
  19888. throw new DeveloperError('cartesians is required.');
  19889. }
  19890. var box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
  19891. return new EllipsoidTangentPlane(box.center, ellipsoid);
  19892. };
  19893. var scratchProjectPointOntoPlaneRay = new Ray();
  19894. var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3();
  19895. /**
  19896. * Computes the projection of the provided 3D position onto the 2D plane, radially outward from the {@link EllipsoidTangentPlane.ellipsoid} coordinate system origin.
  19897. *
  19898. * @param {Cartesian3} cartesian The point to project.
  19899. * @param {Cartesian2} [result] The object onto which to store the result.
  19900. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided. Undefined if there is no intersection point
  19901. */
  19902. EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian, result) {
  19903. if (!defined(cartesian)) {
  19904. throw new DeveloperError('cartesian is required.');
  19905. }
  19906. var ray = scratchProjectPointOntoPlaneRay;
  19907. ray.origin = cartesian;
  19908. Cartesian3.normalize(cartesian, ray.direction);
  19909. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19910. if (!defined(intersectionPoint)) {
  19911. Cartesian3.negate(ray.direction, ray.direction);
  19912. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19913. }
  19914. if (defined(intersectionPoint)) {
  19915. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  19916. var x = Cartesian3.dot(this._xAxis, v);
  19917. var y = Cartesian3.dot(this._yAxis, v);
  19918. if (!defined(result)) {
  19919. return new Cartesian2(x, y);
  19920. }
  19921. result.x = x;
  19922. result.y = y;
  19923. return result;
  19924. }
  19925. return undefined;
  19926. };
  19927. /**
  19928. * Computes the projection of the provided 3D positions onto the 2D plane (where possible), radially outward from the global origin.
  19929. * The resulting array may be shorter than the input array - if a single projection is impossible it will not be included.
  19930. *
  19931. * @see EllipsoidTangentPlane.projectPointOntoPlane
  19932. *
  19933. * @param {Cartesian3[]} cartesians The array of points to project.
  19934. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  19935. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
  19936. */
  19937. EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
  19938. if (!defined(cartesians)) {
  19939. throw new DeveloperError('cartesians is required.');
  19940. }
  19941. if (!defined(result)) {
  19942. result = [];
  19943. }
  19944. var count = 0;
  19945. var length = cartesians.length;
  19946. for ( var i = 0; i < length; i++) {
  19947. var p = this.projectPointOntoPlane(cartesians[i], result[count]);
  19948. if (defined(p)) {
  19949. result[count] = p;
  19950. count++;
  19951. }
  19952. }
  19953. result.length = count;
  19954. return result;
  19955. };
  19956. /**
  19957. * Computes the projection of the provided 3D position onto the 2D plane, along the plane normal.
  19958. *
  19959. * @param {Cartesian3} cartesian The point to project.
  19960. * @param {Cartesian2} [result] The object onto which to store the result.
  19961. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  19962. */
  19963. EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian, result) {
  19964. if (!defined(cartesian)) {
  19965. throw new DeveloperError('cartesian is required.');
  19966. }
  19967. if (!defined(result)) {
  19968. result = new Cartesian2();
  19969. }
  19970. var ray = scratchProjectPointOntoPlaneRay;
  19971. ray.origin = cartesian;
  19972. Cartesian3.clone(this._plane.normal, ray.direction);
  19973. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19974. if (!defined(intersectionPoint)) {
  19975. Cartesian3.negate(ray.direction, ray.direction);
  19976. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  19977. }
  19978. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  19979. var x = Cartesian3.dot(this._xAxis, v);
  19980. var y = Cartesian3.dot(this._yAxis, v);
  19981. result.x = x;
  19982. result.y = y;
  19983. return result;
  19984. };
  19985. /**
  19986. * Computes the projection of the provided 3D positions onto the 2D plane, along the plane normal.
  19987. *
  19988. * @see EllipsoidTangentPlane.projectPointToNearestOnPlane
  19989. *
  19990. * @param {Cartesian3[]} cartesians The array of points to project.
  19991. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  19992. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided. This will have the same length as <code>cartesians</code>.
  19993. */
  19994. EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
  19995. if (!defined(cartesians)) {
  19996. throw new DeveloperError('cartesians is required.');
  19997. }
  19998. if (!defined(result)) {
  19999. result = [];
  20000. }
  20001. var length = cartesians.length;
  20002. result.length = length;
  20003. for (var i = 0; i < length; i++) {
  20004. result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
  20005. }
  20006. return result;
  20007. };
  20008. var projectPointsOntoEllipsoidScratch = new Cartesian3();
  20009. /**
  20010. * Computes the projection of the provided 2D positions onto the 3D ellipsoid.
  20011. *
  20012. * @param {Cartesian2[]} cartesians The array of points to project.
  20013. * @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
  20014. * @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
  20015. */
  20016. EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
  20017. if (!defined(cartesians)) {
  20018. throw new DeveloperError('cartesians is required.');
  20019. }
  20020. var length = cartesians.length;
  20021. if (!defined(result)) {
  20022. result = new Array(length);
  20023. } else {
  20024. result.length = length;
  20025. }
  20026. var ellipsoid = this._ellipsoid;
  20027. var origin = this._origin;
  20028. var xAxis = this._xAxis;
  20029. var yAxis = this._yAxis;
  20030. var tmp = projectPointsOntoEllipsoidScratch;
  20031. for ( var i = 0; i < length; ++i) {
  20032. var position = cartesians[i];
  20033. Cartesian3.multiplyByScalar(xAxis, position.x, tmp);
  20034. if (!defined(result[i])) {
  20035. result[i] = new Cartesian3();
  20036. }
  20037. var point = Cartesian3.add(origin, tmp, result[i]);
  20038. Cartesian3.multiplyByScalar(yAxis, position.y, tmp);
  20039. Cartesian3.add(point, tmp, point);
  20040. ellipsoid.scaleToGeocentricSurface(point, point);
  20041. }
  20042. return result;
  20043. };
  20044. return EllipsoidTangentPlane;
  20045. });
  20046. /*global define*/
  20047. define('Core/GeometryType',[
  20048. './freezeObject'
  20049. ], function(
  20050. freezeObject) {
  20051. 'use strict';
  20052. /**
  20053. * @private
  20054. */
  20055. var GeometryType = {
  20056. NONE : 0,
  20057. TRIANGLES : 1,
  20058. LINES : 2,
  20059. POLYLINES : 3
  20060. };
  20061. return freezeObject(GeometryType);
  20062. });
  20063. /*global define*/
  20064. define('Core/PrimitiveType',[
  20065. './freezeObject',
  20066. './WebGLConstants'
  20067. ], function(
  20068. freezeObject,
  20069. WebGLConstants) {
  20070. 'use strict';
  20071. /**
  20072. * The type of a geometric primitive, i.e., points, lines, and triangles.
  20073. *
  20074. * @exports PrimitiveType
  20075. */
  20076. var PrimitiveType = {
  20077. /**
  20078. * Points primitive where each vertex (or index) is a separate point.
  20079. *
  20080. * @type {Number}
  20081. * @constant
  20082. */
  20083. POINTS : WebGLConstants.POINTS,
  20084. /**
  20085. * Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
  20086. *
  20087. * @type {Number}
  20088. * @constant
  20089. */
  20090. LINES : WebGLConstants.LINES,
  20091. /**
  20092. * Line loop primitive where each vertex (or index) after the first connects a line to
  20093. * the previous vertex, and the last vertex implicitly connects to the first.
  20094. *
  20095. * @type {Number}
  20096. * @constant
  20097. */
  20098. LINE_LOOP : WebGLConstants.LINE_LOOP,
  20099. /**
  20100. * Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
  20101. *
  20102. * @type {Number}
  20103. * @constant
  20104. */
  20105. LINE_STRIP : WebGLConstants.LINE_STRIP,
  20106. /**
  20107. * Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
  20108. *
  20109. * @type {Number}
  20110. * @constant
  20111. */
  20112. TRIANGLES : WebGLConstants.TRIANGLES,
  20113. /**
  20114. * Triangle strip primitive where each vertex (or index) after the first two connect to
  20115. * the previous two vertices forming a triangle. For example, this can be used to model a wall.
  20116. *
  20117. * @type {Number}
  20118. * @constant
  20119. */
  20120. TRIANGLE_STRIP : WebGLConstants.TRIANGLE_STRIP,
  20121. /**
  20122. * Triangle fan primitive where each vertex (or index) after the first two connect to
  20123. * the previous vertex and the first vertex forming a triangle. For example, this can be used
  20124. * to model a cone or circle.
  20125. *
  20126. * @type {Number}
  20127. * @constant
  20128. */
  20129. TRIANGLE_FAN : WebGLConstants.TRIANGLE_FAN,
  20130. /**
  20131. * @private
  20132. */
  20133. validate : function(primitiveType) {
  20134. return primitiveType === PrimitiveType.POINTS ||
  20135. primitiveType === PrimitiveType.LINES ||
  20136. primitiveType === PrimitiveType.LINE_LOOP ||
  20137. primitiveType === PrimitiveType.LINE_STRIP ||
  20138. primitiveType === PrimitiveType.TRIANGLES ||
  20139. primitiveType === PrimitiveType.TRIANGLE_STRIP ||
  20140. primitiveType === PrimitiveType.TRIANGLE_FAN;
  20141. }
  20142. };
  20143. return freezeObject(PrimitiveType);
  20144. });
  20145. /*global define*/
  20146. define('Core/Geometry',[
  20147. './defaultValue',
  20148. './defined',
  20149. './DeveloperError',
  20150. './GeometryType',
  20151. './PrimitiveType'
  20152. ], function(
  20153. defaultValue,
  20154. defined,
  20155. DeveloperError,
  20156. GeometryType,
  20157. PrimitiveType) {
  20158. 'use strict';
  20159. /**
  20160. * A geometry representation with attributes forming vertices and optional index data
  20161. * defining primitives. Geometries and an {@link Appearance}, which describes the shading,
  20162. * can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
  20163. * be created from many heterogeneous - in many cases - geometries for performance.
  20164. * <p>
  20165. * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
  20166. * </p>
  20167. *
  20168. * @alias Geometry
  20169. * @constructor
  20170. *
  20171. * @param {Object} options Object with the following properties:
  20172. * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
  20173. * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
  20174. * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
  20175. * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
  20176. *
  20177. * @see PolygonGeometry
  20178. * @see RectangleGeometry
  20179. * @see EllipseGeometry
  20180. * @see CircleGeometry
  20181. * @see WallGeometry
  20182. * @see SimplePolylineGeometry
  20183. * @see BoxGeometry
  20184. * @see EllipsoidGeometry
  20185. *
  20186. * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
  20187. *
  20188. * @example
  20189. * // Create geometry with a position attribute and indexed lines.
  20190. * var positions = new Float64Array([
  20191. * 0.0, 0.0, 0.0,
  20192. * 7500000.0, 0.0, 0.0,
  20193. * 0.0, 7500000.0, 0.0
  20194. * ]);
  20195. *
  20196. * var geometry = new Cesium.Geometry({
  20197. * attributes : {
  20198. * position : new Cesium.GeometryAttribute({
  20199. * componentDatatype : Cesium.ComponentDatatype.DOUBLE,
  20200. * componentsPerAttribute : 3,
  20201. * values : positions
  20202. * })
  20203. * },
  20204. * indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
  20205. * primitiveType : Cesium.PrimitiveType.LINES,
  20206. * boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
  20207. * });
  20208. */
  20209. function Geometry(options) {
  20210. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  20211. if (!defined(options.attributes)) {
  20212. throw new DeveloperError('options.attributes is required.');
  20213. }
  20214. /**
  20215. * Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
  20216. * {@link GeometryAttribute} containing the attribute's data.
  20217. * <p>
  20218. * Attributes are always stored non-interleaved in a Geometry.
  20219. * </p>
  20220. * <p>
  20221. * There are reserved attribute names with well-known semantics. The following attributes
  20222. * are created by a Geometry (depending on the provided {@link VertexFormat}.
  20223. * <ul>
  20224. * <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
  20225. * <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
  20226. * <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
  20227. * <li><code>binormal</code> - Binormal (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#binormal}.</li>
  20228. * <li><code>tangent</code> - Tangent (normalized), used for tangent-space effects like bump mapping. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#tangent}.</li>
  20229. * </ul>
  20230. * </p>
  20231. * <p>
  20232. * The following attribute names are generally not created by a Geometry, but are added
  20233. * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
  20234. * the geometry for rendering.
  20235. * <ul>
  20236. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  20237. * <li><code>position3DLow</code> - Low 32 bits for encoded 64-bit position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  20238. * <li><code>position3DHigh</code> - High 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  20239. * <li><code>position2DLow</code> - Low 32 bits for encoded 64-bit 2D (Columbus view) position computed with {@link GeometryPipeline.encodeAttribute}. 32-bit floating-point. 4 components per attribute.</li>
  20240. * <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
  20241. * <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
  20242. * </ul>
  20243. * </p>
  20244. *
  20245. * @type GeometryAttributes
  20246. *
  20247. * @default undefined
  20248. *
  20249. *
  20250. * @example
  20251. * geometry.attributes.position = new Cesium.GeometryAttribute({
  20252. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  20253. * componentsPerAttribute : 3,
  20254. * values : new Float32Array(0)
  20255. * });
  20256. *
  20257. * @see GeometryAttribute
  20258. * @see VertexFormat
  20259. */
  20260. this.attributes = options.attributes;
  20261. /**
  20262. * Optional index data that - along with {@link Geometry#primitiveType} -
  20263. * determines the primitives in the geometry.
  20264. *
  20265. * @type Array
  20266. *
  20267. * @default undefined
  20268. */
  20269. this.indices = options.indices;
  20270. /**
  20271. * The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
  20272. * but can varying based on the specific geometry.
  20273. *
  20274. * @type PrimitiveType
  20275. *
  20276. * @default undefined
  20277. */
  20278. this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);
  20279. /**
  20280. * An optional bounding sphere that fully encloses the geometry. This is
  20281. * commonly used for culling.
  20282. *
  20283. * @type BoundingSphere
  20284. *
  20285. * @default undefined
  20286. */
  20287. this.boundingSphere = options.boundingSphere;
  20288. /**
  20289. * @private
  20290. */
  20291. this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
  20292. /**
  20293. * @private
  20294. */
  20295. this.boundingSphereCV = options.boundingSphereCV;
  20296. }
  20297. /**
  20298. * Computes the number of vertices in a geometry. The runtime is linear with
  20299. * respect to the number of attributes in a vertex, not the number of vertices.
  20300. *
  20301. * @param {Geometry} geometry The geometry.
  20302. * @returns {Number} The number of vertices in the geometry.
  20303. *
  20304. * @example
  20305. * var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
  20306. */
  20307. Geometry.computeNumberOfVertices = function(geometry) {
  20308. if (!defined(geometry)) {
  20309. throw new DeveloperError('geometry is required.');
  20310. }
  20311. var numberOfVertices = -1;
  20312. for ( var property in geometry.attributes) {
  20313. if (geometry.attributes.hasOwnProperty(property) &&
  20314. defined(geometry.attributes[property]) &&
  20315. defined(geometry.attributes[property].values)) {
  20316. var attribute = geometry.attributes[property];
  20317. var num = attribute.values.length / attribute.componentsPerAttribute;
  20318. if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
  20319. throw new DeveloperError('All attribute lists must have the same number of attributes.');
  20320. }
  20321. numberOfVertices = num;
  20322. }
  20323. }
  20324. return numberOfVertices;
  20325. };
  20326. return Geometry;
  20327. });
  20328. /*global define*/
  20329. define('Core/GeometryAttribute',[
  20330. './defaultValue',
  20331. './defined',
  20332. './DeveloperError'
  20333. ], function(
  20334. defaultValue,
  20335. defined,
  20336. DeveloperError) {
  20337. 'use strict';
  20338. /**
  20339. * Values and type information for geometry attributes. A {@link Geometry}
  20340. * generally contains one or more attributes. All attributes together form
  20341. * the geometry's vertices.
  20342. *
  20343. * @alias GeometryAttribute
  20344. * @constructor
  20345. *
  20346. * @param {Object} [options] Object with the following properties:
  20347. * @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
  20348. * @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
  20349. * @param {Boolean} [options.normalize=false] When <code>true</code> and <code>componentDatatype</code> is an integer format, indicate that the components should be mapped to the range [0, 1] (unsigned) or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  20350. * @param {TypedArray} [options.values] The values for the attributes stored in a typed array.
  20351. *
  20352. * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
  20353. *
  20354. *
  20355. * @example
  20356. * var geometry = new Cesium.Geometry({
  20357. * attributes : {
  20358. * position : new Cesium.GeometryAttribute({
  20359. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  20360. * componentsPerAttribute : 3,
  20361. * values : new Float32Array([
  20362. * 0.0, 0.0, 0.0,
  20363. * 7500000.0, 0.0, 0.0,
  20364. * 0.0, 7500000.0, 0.0
  20365. * ])
  20366. * })
  20367. * },
  20368. * primitiveType : Cesium.PrimitiveType.LINE_LOOP
  20369. * });
  20370. *
  20371. * @see Geometry
  20372. */
  20373. function GeometryAttribute(options) {
  20374. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  20375. if (!defined(options.componentDatatype)) {
  20376. throw new DeveloperError('options.componentDatatype is required.');
  20377. }
  20378. if (!defined(options.componentsPerAttribute)) {
  20379. throw new DeveloperError('options.componentsPerAttribute is required.');
  20380. }
  20381. if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
  20382. throw new DeveloperError('options.componentsPerAttribute must be between 1 and 4.');
  20383. }
  20384. if (!defined(options.values)) {
  20385. throw new DeveloperError('options.values is required.');
  20386. }
  20387. /**
  20388. * The datatype of each component in the attribute, e.g., individual elements in
  20389. * {@link GeometryAttribute#values}.
  20390. *
  20391. * @type ComponentDatatype
  20392. *
  20393. * @default undefined
  20394. */
  20395. this.componentDatatype = options.componentDatatype;
  20396. /**
  20397. * A number between 1 and 4 that defines the number of components in an attributes.
  20398. * For example, a position attribute with x, y, and z components would have 3 as
  20399. * shown in the code example.
  20400. *
  20401. * @type Number
  20402. *
  20403. * @default undefined
  20404. *
  20405. * @example
  20406. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  20407. * attribute.componentsPerAttribute = 3;
  20408. * attribute.values = new Float32Array([
  20409. * 0.0, 0.0, 0.0,
  20410. * 7500000.0, 0.0, 0.0,
  20411. * 0.0, 7500000.0, 0.0
  20412. * ]);
  20413. */
  20414. this.componentsPerAttribute = options.componentsPerAttribute;
  20415. /**
  20416. * When <code>true</code> and <code>componentDatatype</code> is an integer format,
  20417. * indicate that the components should be mapped to the range [0, 1] (unsigned)
  20418. * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  20419. * <p>
  20420. * This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
  20421. * </p>
  20422. *
  20423. * @type Boolean
  20424. *
  20425. * @default false
  20426. *
  20427. * @example
  20428. * attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
  20429. * attribute.componentsPerAttribute = 4;
  20430. * attribute.normalize = true;
  20431. * attribute.values = new Uint8Array([
  20432. * Cesium.Color.floatToByte(color.red),
  20433. * Cesium.Color.floatToByte(color.green),
  20434. * Cesium.Color.floatToByte(color.blue),
  20435. * Cesium.Color.floatToByte(color.alpha)
  20436. * ]);
  20437. */
  20438. this.normalize = defaultValue(options.normalize, false);
  20439. /**
  20440. * The values for the attributes stored in a typed array. In the code example,
  20441. * every three elements in <code>values</code> defines one attributes since
  20442. * <code>componentsPerAttribute</code> is 3.
  20443. *
  20444. * @type TypedArray
  20445. *
  20446. * @default undefined
  20447. *
  20448. * @example
  20449. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  20450. * attribute.componentsPerAttribute = 3;
  20451. * attribute.values = new Float32Array([
  20452. * 0.0, 0.0, 0.0,
  20453. * 7500000.0, 0.0, 0.0,
  20454. * 0.0, 7500000.0, 0.0
  20455. * ]);
  20456. */
  20457. this.values = options.values;
  20458. }
  20459. return GeometryAttribute;
  20460. });
  20461. /*global define*/
  20462. define('Core/GeometryAttributes',[
  20463. './defaultValue'
  20464. ], function(
  20465. defaultValue) {
  20466. 'use strict';
  20467. /**
  20468. * Attributes, which make up a geometry's vertices. Each property in this object corresponds to a
  20469. * {@link GeometryAttribute} containing the attribute's data.
  20470. * <p>
  20471. * Attributes are always stored non-interleaved in a Geometry.
  20472. * </p>
  20473. *
  20474. * @alias GeometryAttributes
  20475. * @constructor
  20476. */
  20477. function GeometryAttributes(options) {
  20478. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  20479. /**
  20480. * The 3D position attribute.
  20481. * <p>
  20482. * 64-bit floating-point (for precision). 3 components per attribute.
  20483. * </p>
  20484. *
  20485. * @type GeometryAttribute
  20486. *
  20487. * @default undefined
  20488. */
  20489. this.position = options.position;
  20490. /**
  20491. * The normal attribute (normalized), which is commonly used for lighting.
  20492. * <p>
  20493. * 32-bit floating-point. 3 components per attribute.
  20494. * </p>
  20495. *
  20496. * @type GeometryAttribute
  20497. *
  20498. * @default undefined
  20499. */
  20500. this.normal = options.normal;
  20501. /**
  20502. * The 2D texture coordinate attribute.
  20503. * <p>
  20504. * 32-bit floating-point. 2 components per attribute
  20505. * </p>
  20506. *
  20507. * @type GeometryAttribute
  20508. *
  20509. * @default undefined
  20510. */
  20511. this.st = options.st;
  20512. /**
  20513. * The binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  20514. * <p>
  20515. * 32-bit floating-point. 3 components per attribute.
  20516. * </p>
  20517. *
  20518. * @type GeometryAttribute
  20519. *
  20520. * @default undefined
  20521. */
  20522. this.binormal = options.binormal;
  20523. /**
  20524. * The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  20525. * <p>
  20526. * 32-bit floating-point. 3 components per attribute.
  20527. * </p>
  20528. *
  20529. * @type GeometryAttribute
  20530. *
  20531. * @default undefined
  20532. */
  20533. this.tangent = options.tangent;
  20534. /**
  20535. * The color attribute.
  20536. * <p>
  20537. * 8-bit unsigned integer. 4 components per attribute.
  20538. * </p>
  20539. *
  20540. * @type GeometryAttribute
  20541. *
  20542. * @default undefined
  20543. */
  20544. this.color = options.color;
  20545. }
  20546. return GeometryAttributes;
  20547. });
  20548. /*global define*/
  20549. define('Core/GeometryInstance',[
  20550. './defaultValue',
  20551. './defined',
  20552. './DeveloperError',
  20553. './Matrix4'
  20554. ], function(
  20555. defaultValue,
  20556. defined,
  20557. DeveloperError,
  20558. Matrix4) {
  20559. 'use strict';
  20560. /**
  20561. * Geometry instancing allows one {@link Geometry} object to be positions in several
  20562. * different locations and colored uniquely. For example, one {@link BoxGeometry} can
  20563. * be instanced several times, each with a different <code>modelMatrix</code> to change
  20564. * its position, rotation, and scale.
  20565. *
  20566. * @alias GeometryInstance
  20567. * @constructor
  20568. *
  20569. * @param {Object} options Object with the following properties:
  20570. * @param {Geometry} options.geometry The geometry to instance.
  20571. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The model matrix that transforms to transform the geometry from model to world coordinates.
  20572. * @param {Object} [options.id] A user-defined object to return when the instance is picked with {@link Scene#pick} or get/set per-instance attributes with {@link Primitive#getGeometryInstanceAttributes}.
  20573. * @param {Object} [options.attributes] Per-instance attributes like a show or color attribute shown in the example below.
  20574. *
  20575. *
  20576. * @example
  20577. * // Create geometry for a box, and two instances that refer to it.
  20578. * // One instance positions the box on the bottom and colored aqua.
  20579. * // The other instance positions the box on the top and color white.
  20580. * var geometry = Cesium.BoxGeometry.fromDimensions({
  20581. * vertexFormat : Cesium.VertexFormat.POSITION_AND_NORMAL,
  20582. * dimensions : new Cesium.Cartesian3(1000000.0, 1000000.0, 500000.0)
  20583. * });
  20584. * var instanceBottom = new Cesium.GeometryInstance({
  20585. * geometry : geometry,
  20586. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  20587. * Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 1000000.0), new Cesium.Matrix4()),
  20588. * attributes : {
  20589. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  20590. * },
  20591. * id : 'bottom'
  20592. * });
  20593. * var instanceTop = new Cesium.GeometryInstance({
  20594. * geometry : geometry,
  20595. * modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
  20596. * Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883)), new Cesium.Cartesian3(0.0, 0.0, 3000000.0), new Cesium.Matrix4()),
  20597. * attributes : {
  20598. * color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.AQUA)
  20599. * },
  20600. * id : 'top'
  20601. * });
  20602. *
  20603. * @see Geometry
  20604. */
  20605. function GeometryInstance(options) {
  20606. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  20607. if (!defined(options.geometry)) {
  20608. throw new DeveloperError('options.geometry is required.');
  20609. }
  20610. /**
  20611. * The geometry being instanced.
  20612. *
  20613. * @type Geometry
  20614. *
  20615. * @default undefined
  20616. */
  20617. this.geometry = options.geometry;
  20618. /**
  20619. * The 4x4 transformation matrix that transforms the geometry from model to world coordinates.
  20620. * When this is the identity matrix, the geometry is drawn in world coordinates, i.e., Earth's WGS84 coordinates.
  20621. * Local reference frames can be used by providing a different transformation matrix, like that returned
  20622. * by {@link Transforms.eastNorthUpToFixedFrame}.
  20623. *
  20624. * @type Matrix4
  20625. *
  20626. * @default Matrix4.IDENTITY
  20627. */
  20628. this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY));
  20629. /**
  20630. * User-defined object returned when the instance is picked or used to get/set per-instance attributes.
  20631. *
  20632. * @type Object
  20633. *
  20634. * @default undefined
  20635. *
  20636. * @see Scene#pick
  20637. * @see Primitive#getGeometryInstanceAttributes
  20638. */
  20639. this.id = options.id;
  20640. /**
  20641. * Used for picking primitives that wrap geometry instances.
  20642. *
  20643. * @private
  20644. */
  20645. this.pickPrimitive = options.pickPrimitive;
  20646. /**
  20647. * Per-instance attributes like {@link ColorGeometryInstanceAttribute} or {@link ShowGeometryInstanceAttribute}.
  20648. * {@link Geometry} attributes varying per vertex; these attributes are constant for the entire instance.
  20649. *
  20650. * @type Object
  20651. *
  20652. * @default undefined
  20653. */
  20654. this.attributes = defaultValue(options.attributes, {});
  20655. /**
  20656. * @private
  20657. */
  20658. this.westHemisphereGeometry = undefined;
  20659. /**
  20660. * @private
  20661. */
  20662. this.eastHemisphereGeometry = undefined;
  20663. }
  20664. return GeometryInstance;
  20665. });
  20666. /*global define*/
  20667. define('Core/AttributeCompression',[
  20668. './Cartesian2',
  20669. './Cartesian3',
  20670. './defined',
  20671. './DeveloperError',
  20672. './Math'
  20673. ], function(
  20674. Cartesian2,
  20675. Cartesian3,
  20676. defined,
  20677. DeveloperError,
  20678. CesiumMath) {
  20679. 'use strict';
  20680. /**
  20681. * Attribute compression and decompression functions.
  20682. *
  20683. * @exports AttributeCompression
  20684. *
  20685. * @private
  20686. */
  20687. var AttributeCompression = {};
  20688. /**
  20689. * Encodes a normalized vector into 2 SNORM values in the range of [0-rangeMax] following the 'oct' encoding.
  20690. *
  20691. * Oct encoding is a compact representation of unit length vectors.
  20692. * The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
  20693. * Cigolle et al 2014: {@link http://jcgt.org/published/0003/02/01/}
  20694. *
  20695. * @param {Cartesian3} vector The normalized vector to be compressed into 2 component 'oct' encoding.
  20696. * @param {Cartesian2} result The 2 component oct-encoded unit length vector.
  20697. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  20698. * @returns {Cartesian2} The 2 component oct-encoded unit length vector.
  20699. *
  20700. * @exception {DeveloperError} vector must be normalized.
  20701. *
  20702. * @see AttributeCompression.octDecodeInRange
  20703. */
  20704. AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
  20705. if (!defined(vector)) {
  20706. throw new DeveloperError('vector is required.');
  20707. }
  20708. if (!defined(result)) {
  20709. throw new DeveloperError('result is required.');
  20710. }
  20711. var magSquared = Cartesian3.magnitudeSquared(vector);
  20712. if (Math.abs(magSquared - 1.0) > CesiumMath.EPSILON6) {
  20713. throw new DeveloperError('vector must be normalized.');
  20714. }
  20715. result.x = vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  20716. result.y = vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  20717. if (vector.z < 0) {
  20718. var x = result.x;
  20719. var y = result.y;
  20720. result.x = (1.0 - Math.abs(y)) * CesiumMath.signNotZero(x);
  20721. result.y = (1.0 - Math.abs(x)) * CesiumMath.signNotZero(y);
  20722. }
  20723. result.x = CesiumMath.toSNorm(result.x, rangeMax);
  20724. result.y = CesiumMath.toSNorm(result.y, rangeMax);
  20725. return result;
  20726. };
  20727. /**
  20728. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding.
  20729. *
  20730. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  20731. * @param {Cartesian2} result The 2 byte oct-encoded unit length vector.
  20732. * @returns {Cartesian2} The 2 byte oct-encoded unit length vector.
  20733. *
  20734. * @exception {DeveloperError} vector must be normalized.
  20735. *
  20736. * @see AttributeCompression.octEncodeInRange
  20737. * @see AttributeCompression.octDecode
  20738. */
  20739. AttributeCompression.octEncode = function(vector, result) {
  20740. return AttributeCompression.octEncodeInRange(vector, 255, result);
  20741. };
  20742. /**
  20743. * Decodes a unit-length vector in 'oct' encoding to a normalized 3-component vector.
  20744. *
  20745. * @param {Number} x The x component of the oct-encoded unit length vector.
  20746. * @param {Number} y The y component of the oct-encoded unit length vector.
  20747. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  20748. * @param {Cartesian3} result The decoded and normalized vector
  20749. * @returns {Cartesian3} The decoded and normalized vector.
  20750. *
  20751. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and rangeMax.
  20752. *
  20753. * @see AttributeCompression.octEncodeInRange
  20754. */
  20755. AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
  20756. if (!defined(result)) {
  20757. throw new DeveloperError('result is required.');
  20758. }
  20759. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  20760. throw new DeveloperError('x and y must be a signed normalized integer between 0 and ' + rangeMax);
  20761. }
  20762. result.x = CesiumMath.fromSNorm(x, rangeMax);
  20763. result.y = CesiumMath.fromSNorm(y, rangeMax);
  20764. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  20765. if (result.z < 0.0)
  20766. {
  20767. var oldVX = result.x;
  20768. result.x = (1.0 - Math.abs(result.y)) * CesiumMath.signNotZero(oldVX);
  20769. result.y = (1.0 - Math.abs(oldVX)) * CesiumMath.signNotZero(result.y);
  20770. }
  20771. return Cartesian3.normalize(result, result);
  20772. };
  20773. /**
  20774. * Decodes a unit-length vector in 2 byte 'oct' encoding to a normalized 3-component vector.
  20775. *
  20776. * @param {Number} x The x component of the oct-encoded unit length vector.
  20777. * @param {Number} y The y component of the oct-encoded unit length vector.
  20778. * @param {Cartesian3} result The decoded and normalized vector.
  20779. * @returns {Cartesian3} The decoded and normalized vector.
  20780. *
  20781. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and 255.
  20782. *
  20783. * @see AttributeCompression.octDecodeInRange
  20784. */
  20785. AttributeCompression.octDecode = function(x, y, result) {
  20786. return AttributeCompression.octDecodeInRange(x, y, 255, result);
  20787. };
  20788. /**
  20789. * Packs an oct encoded vector into a single floating-point number.
  20790. *
  20791. * @param {Cartesian2} encoded The oct encoded vector.
  20792. * @returns {Number} The oct encoded vector packed into a single float.
  20793. *
  20794. */
  20795. AttributeCompression.octPackFloat = function(encoded) {
  20796. if (!defined(encoded)) {
  20797. throw new DeveloperError('encoded is required.');
  20798. }
  20799. return 256.0 * encoded.x + encoded.y;
  20800. };
  20801. var scratchEncodeCart2 = new Cartesian2();
  20802. /**
  20803. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding and
  20804. * stores those values in a single float-point number.
  20805. *
  20806. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  20807. * @returns {Number} The 2 byte oct-encoded unit length vector.
  20808. *
  20809. * @exception {DeveloperError} vector must be normalized.
  20810. */
  20811. AttributeCompression.octEncodeFloat = function(vector) {
  20812. AttributeCompression.octEncode(vector, scratchEncodeCart2);
  20813. return AttributeCompression.octPackFloat(scratchEncodeCart2);
  20814. };
  20815. /**
  20816. * Decodes a unit-length vector in 'oct' encoding packed in a floating-point number to a normalized 3-component vector.
  20817. *
  20818. * @param {Number} value The oct-encoded unit length vector stored as a single floating-point number.
  20819. * @param {Cartesian3} result The decoded and normalized vector
  20820. * @returns {Cartesian3} The decoded and normalized vector.
  20821. *
  20822. */
  20823. AttributeCompression.octDecodeFloat = function(value, result) {
  20824. if (!defined(value)) {
  20825. throw new DeveloperError('value is required.');
  20826. }
  20827. var temp = value / 256.0;
  20828. var x = Math.floor(temp);
  20829. var y = (temp - x) * 256.0;
  20830. return AttributeCompression.octDecode(x, y, result);
  20831. };
  20832. /**
  20833. * Encodes three normalized vectors into 6 SNORM values in the range of [0-255] following the 'oct' encoding and
  20834. * packs those into two floating-point numbers.
  20835. *
  20836. * @param {Cartesian3} v1 A normalized vector to be compressed.
  20837. * @param {Cartesian3} v2 A normalized vector to be compressed.
  20838. * @param {Cartesian3} v3 A normalized vector to be compressed.
  20839. * @param {Cartesian2} result The 'oct' encoded vectors packed into two floating-point numbers.
  20840. * @returns {Cartesian2} The 'oct' encoded vectors packed into two floating-point numbers.
  20841. *
  20842. */
  20843. AttributeCompression.octPack = function(v1, v2, v3, result) {
  20844. if (!defined(v1)) {
  20845. throw new DeveloperError('v1 is required.');
  20846. }
  20847. if (!defined(v2)) {
  20848. throw new DeveloperError('v2 is required.');
  20849. }
  20850. if (!defined(v3)) {
  20851. throw new DeveloperError('v3 is required.');
  20852. }
  20853. if (!defined(result)) {
  20854. throw new DeveloperError('result is required.');
  20855. }
  20856. var encoded1 = AttributeCompression.octEncodeFloat(v1);
  20857. var encoded2 = AttributeCompression.octEncodeFloat(v2);
  20858. var encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
  20859. result.x = 65536.0 * encoded3.x + encoded1;
  20860. result.y = 65536.0 * encoded3.y + encoded2;
  20861. return result;
  20862. };
  20863. /**
  20864. * Decodes three unit-length vectors in 'oct' encoding packed into a floating-point number to a normalized 3-component vector.
  20865. *
  20866. * @param {Cartesian2} packed The three oct-encoded unit length vectors stored as two floating-point number.
  20867. * @param {Cartesian3} v1 One decoded and normalized vector.
  20868. * @param {Cartesian3} v2 One decoded and normalized vector.
  20869. * @param {Cartesian3} v3 One decoded and normalized vector.
  20870. */
  20871. AttributeCompression.octUnpack = function(packed, v1, v2, v3) {
  20872. if (!defined(packed)) {
  20873. throw new DeveloperError('packed is required.');
  20874. }
  20875. if (!defined(v1)) {
  20876. throw new DeveloperError('v1 is required.');
  20877. }
  20878. if (!defined(v2)) {
  20879. throw new DeveloperError('v2 is required.');
  20880. }
  20881. if (!defined(v3)) {
  20882. throw new DeveloperError('v3 is required.');
  20883. }
  20884. var temp = packed.x / 65536.0;
  20885. var x = Math.floor(temp);
  20886. var encodedFloat1 = (temp - x) * 65536.0;
  20887. temp = packed.y / 65536.0;
  20888. var y = Math.floor(temp);
  20889. var encodedFloat2 = (temp - y) * 65536.0;
  20890. AttributeCompression.octDecodeFloat(encodedFloat1, v1);
  20891. AttributeCompression.octDecodeFloat(encodedFloat2, v2);
  20892. AttributeCompression.octDecode(x, y, v3);
  20893. };
  20894. /**
  20895. * Pack texture coordinates into a single float. The texture coordinates will only preserve 12 bits of precision.
  20896. *
  20897. * @param {Cartesian2} textureCoordinates The texture coordinates to compress. Both coordinates must be in the range 0.0-1.0.
  20898. * @returns {Number} The packed texture coordinates.
  20899. *
  20900. */
  20901. AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
  20902. if (!defined(textureCoordinates)) {
  20903. throw new DeveloperError('textureCoordinates is required.');
  20904. }
  20905. // Move x and y to the range 0-4095;
  20906. var x = (textureCoordinates.x * 4095.0) | 0;
  20907. var y = (textureCoordinates.y * 4095.0) | 0;
  20908. return 4096.0 * x + y;
  20909. };
  20910. /**
  20911. * Decompresses texture coordinates that were packed into a single float.
  20912. *
  20913. * @param {Number} compressed The compressed texture coordinates.
  20914. * @param {Cartesian2} result The decompressed texture coordinates.
  20915. * @returns {Cartesian2} The modified result parameter.
  20916. *
  20917. */
  20918. AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
  20919. if (!defined(compressed)) {
  20920. throw new DeveloperError('compressed is required.');
  20921. }
  20922. if (!defined(result)) {
  20923. throw new DeveloperError('result is required.');
  20924. }
  20925. var temp = compressed / 4096.0;
  20926. var xZeroTo4095 = Math.floor(temp);
  20927. result.x = xZeroTo4095 / 4095.0;
  20928. result.y = (compressed - xZeroTo4095 * 4096) / 4095;
  20929. return result;
  20930. };
  20931. return AttributeCompression;
  20932. });
  20933. /*global define*/
  20934. define('Core/barycentricCoordinates',[
  20935. './Cartesian2',
  20936. './Cartesian3',
  20937. './defined',
  20938. './DeveloperError'
  20939. ], function(
  20940. Cartesian2,
  20941. Cartesian3,
  20942. defined,
  20943. DeveloperError) {
  20944. 'use strict';
  20945. var scratchCartesian1 = new Cartesian3();
  20946. var scratchCartesian2 = new Cartesian3();
  20947. var scratchCartesian3 = new Cartesian3();
  20948. /**
  20949. * Computes the barycentric coordinates for a point with respect to a triangle.
  20950. *
  20951. * @exports barycentricCoordinates
  20952. *
  20953. * @param {Cartesian2|Cartesian3} point The point to test.
  20954. * @param {Cartesian2|Cartesian3} p0 The first point of the triangle, corresponding to the barycentric x-axis.
  20955. * @param {Cartesian2|Cartesian3} p1 The second point of the triangle, corresponding to the barycentric y-axis.
  20956. * @param {Cartesian2|Cartesian3} p2 The third point of the triangle, corresponding to the barycentric z-axis.
  20957. * @param {Cartesian3} [result] The object onto which to store the result.
  20958. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  20959. *
  20960. * @example
  20961. * // Returns Cartesian3.UNIT_X
  20962. * var p = new Cesium.Cartesian3(-1.0, 0.0, 0.0);
  20963. * var b = Cesium.barycentricCoordinates(p,
  20964. * new Cesium.Cartesian3(-1.0, 0.0, 0.0),
  20965. * new Cesium.Cartesian3( 1.0, 0.0, 0.0),
  20966. * new Cesium.Cartesian3( 0.0, 1.0, 1.0));
  20967. */
  20968. function barycentricCoordinates(point, p0, p1, p2, result) {
  20969. if (!defined(point) || !defined(p0) || !defined(p1) || !defined(p2)) {
  20970. throw new DeveloperError('point, p0, p1, and p2 are required.');
  20971. }
  20972. if (!defined(result)) {
  20973. result = new Cartesian3();
  20974. }
  20975. // Implementation based on http://www.blackpawn.com/texts/pointinpoly/default.html.
  20976. var v0, v1, v2;
  20977. var dot00, dot01, dot02, dot11, dot12;
  20978. if(!defined(p0.z)) {
  20979. v0 = Cartesian2.subtract(p1, p0, scratchCartesian1);
  20980. v1 = Cartesian2.subtract(p2, p0, scratchCartesian2);
  20981. v2 = Cartesian2.subtract(point, p0, scratchCartesian3);
  20982. dot00 = Cartesian2.dot(v0, v0);
  20983. dot01 = Cartesian2.dot(v0, v1);
  20984. dot02 = Cartesian2.dot(v0, v2);
  20985. dot11 = Cartesian2.dot(v1, v1);
  20986. dot12 = Cartesian2.dot(v1, v2);
  20987. } else {
  20988. v0 = Cartesian3.subtract(p1, p0, scratchCartesian1);
  20989. v1 = Cartesian3.subtract(p2, p0, scratchCartesian2);
  20990. v2 = Cartesian3.subtract(point, p0, scratchCartesian3);
  20991. dot00 = Cartesian3.dot(v0, v0);
  20992. dot01 = Cartesian3.dot(v0, v1);
  20993. dot02 = Cartesian3.dot(v0, v2);
  20994. dot11 = Cartesian3.dot(v1, v1);
  20995. dot12 = Cartesian3.dot(v1, v2);
  20996. }
  20997. var q = 1.0 / (dot00 * dot11 - dot01 * dot01);
  20998. result.y = (dot11 * dot02 - dot01 * dot12) * q;
  20999. result.z = (dot00 * dot12 - dot01 * dot02) * q;
  21000. result.x = 1.0 - result.y - result.z;
  21001. return result;
  21002. }
  21003. return barycentricCoordinates;
  21004. });
  21005. /*global define*/
  21006. define('Core/EncodedCartesian3',[
  21007. './Cartesian3',
  21008. './defined',
  21009. './DeveloperError'
  21010. ], function(
  21011. Cartesian3,
  21012. defined,
  21013. DeveloperError) {
  21014. 'use strict';
  21015. /**
  21016. * A fixed-point encoding of a {@link Cartesian3} with 64-bit floating-point components, as two {@link Cartesian3}
  21017. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  21018. * <p>
  21019. * This is used to encode positions in vertex buffers for rendering without jittering artifacts
  21020. * as described in {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  21021. * </p>
  21022. *
  21023. * @alias EncodedCartesian3
  21024. * @constructor
  21025. *
  21026. * @private
  21027. */
  21028. function EncodedCartesian3() {
  21029. /**
  21030. * The high bits for each component. Bits 0 to 22 store the whole value. Bits 23 to 31 are not used.
  21031. *
  21032. * @type {Cartesian3}
  21033. * @default {@link Cartesian3.ZERO}
  21034. */
  21035. this.high = Cartesian3.clone(Cartesian3.ZERO);
  21036. /**
  21037. * The low bits for each component. Bits 7 to 22 store the whole value, and bits 0 to 6 store the fraction. Bits 23 to 31 are not used.
  21038. *
  21039. * @type {Cartesian3}
  21040. * @default {@link Cartesian3.ZERO}
  21041. */
  21042. this.low = Cartesian3.clone(Cartesian3.ZERO);
  21043. }
  21044. /**
  21045. * Encodes a 64-bit floating-point value as two floating-point values that, when converted to
  21046. * 32-bit floating-point and added, approximate the original input. The returned object
  21047. * has <code>high</code> and <code>low</code> properties for the high and low bits, respectively.
  21048. * <p>
  21049. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  21050. * </p>
  21051. *
  21052. * @param {Number} value The floating-point value to encode.
  21053. * @param {Object} [result] The object onto which to store the result.
  21054. * @returns {Object} The modified result parameter or a new instance if one was not provided.
  21055. *
  21056. * @example
  21057. * var value = 1234567.1234567;
  21058. * var splitValue = Cesium.EncodedCartesian3.encode(value);
  21059. */
  21060. EncodedCartesian3.encode = function(value, result) {
  21061. if (!defined(value)) {
  21062. throw new DeveloperError('value is required');
  21063. }
  21064. if (!defined(result)) {
  21065. result = {
  21066. high : 0.0,
  21067. low : 0.0
  21068. };
  21069. }
  21070. var doubleHigh;
  21071. if (value >= 0.0) {
  21072. doubleHigh = Math.floor(value / 65536.0) * 65536.0;
  21073. result.high = doubleHigh;
  21074. result.low = value - doubleHigh;
  21075. } else {
  21076. doubleHigh = Math.floor(-value / 65536.0) * 65536.0;
  21077. result.high = -doubleHigh;
  21078. result.low = value + doubleHigh;
  21079. }
  21080. return result;
  21081. };
  21082. var scratchEncode = {
  21083. high : 0.0,
  21084. low : 0.0
  21085. };
  21086. /**
  21087. * Encodes a {@link Cartesian3} with 64-bit floating-point components as two {@link Cartesian3}
  21088. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  21089. * <p>
  21090. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  21091. * </p>
  21092. *
  21093. * @param {Cartesian3} cartesian The cartesian to encode.
  21094. * @param {EncodedCartesian3} [result] The object onto which to store the result.
  21095. * @returns {EncodedCartesian3} The modified result parameter or a new EncodedCartesian3 instance if one was not provided.
  21096. *
  21097. * @example
  21098. * var cart = new Cesium.Cartesian3(-10000000.0, 0.0, 10000000.0);
  21099. * var encoded = Cesium.EncodedCartesian3.fromCartesian(cart);
  21100. */
  21101. EncodedCartesian3.fromCartesian = function(cartesian, result) {
  21102. if (!defined(cartesian)) {
  21103. throw new DeveloperError('cartesian is required');
  21104. }
  21105. if (!defined(result)) {
  21106. result = new EncodedCartesian3();
  21107. }
  21108. var high = result.high;
  21109. var low = result.low;
  21110. EncodedCartesian3.encode(cartesian.x, scratchEncode);
  21111. high.x = scratchEncode.high;
  21112. low.x = scratchEncode.low;
  21113. EncodedCartesian3.encode(cartesian.y, scratchEncode);
  21114. high.y = scratchEncode.high;
  21115. low.y = scratchEncode.low;
  21116. EncodedCartesian3.encode(cartesian.z, scratchEncode);
  21117. high.z = scratchEncode.high;
  21118. low.z = scratchEncode.low;
  21119. return result;
  21120. };
  21121. var encodedP = new EncodedCartesian3();
  21122. /**
  21123. * Encodes the provided <code>cartesian</code>, and writes it to an array with <code>high</code>
  21124. * components followed by <code>low</code> components, i.e. <code>[high.x, high.y, high.z, low.x, low.y, low.z]</code>.
  21125. * <p>
  21126. * This is used to create interleaved high-precision position vertex attributes.
  21127. * </p>
  21128. *
  21129. * @param {Cartesian3} cartesian The cartesian to encode.
  21130. * @param {Number[]} cartesianArray The array to write to.
  21131. * @param {Number} index The index into the array to start writing. Six elements will be written.
  21132. *
  21133. * @exception {DeveloperError} index must be a number greater than or equal to 0.
  21134. *
  21135. * @example
  21136. * var positions = [
  21137. * new Cesium.Cartesian3(),
  21138. * // ...
  21139. * ];
  21140. * var encodedPositions = new Float32Array(2 * 3 * positions.length);
  21141. * var j = 0;
  21142. * for (var i = 0; i < positions.length; ++i) {
  21143. * Cesium.EncodedCartesian3.writeElement(positions[i], encodedPositions, j);
  21144. * j += 6;
  21145. * }
  21146. */
  21147. EncodedCartesian3.writeElements = function(cartesian, cartesianArray, index) {
  21148. if (!defined(cartesian)) {
  21149. throw new DeveloperError('cartesian is required');
  21150. }
  21151. if (!defined(cartesianArray)) {
  21152. throw new DeveloperError('cartesianArray is required');
  21153. }
  21154. if (typeof index !== 'number' || index < 0) {
  21155. throw new DeveloperError('index must be a number greater than or equal to 0.');
  21156. }
  21157. EncodedCartesian3.fromCartesian(cartesian, encodedP);
  21158. var high = encodedP.high;
  21159. var low = encodedP.low;
  21160. cartesianArray[index] = high.x;
  21161. cartesianArray[index + 1] = high.y;
  21162. cartesianArray[index + 2] = high.z;
  21163. cartesianArray[index + 3] = low.x;
  21164. cartesianArray[index + 4] = low.y;
  21165. cartesianArray[index + 5] = low.z;
  21166. };
  21167. return EncodedCartesian3;
  21168. });
  21169. /*global define*/
  21170. define('Core/IndexDatatype',[
  21171. './defined',
  21172. './DeveloperError',
  21173. './freezeObject',
  21174. './Math',
  21175. './WebGLConstants'
  21176. ], function(
  21177. defined,
  21178. DeveloperError,
  21179. freezeObject,
  21180. CesiumMath,
  21181. WebGLConstants) {
  21182. 'use strict';
  21183. /**
  21184. * Constants for WebGL index datatypes. These corresponds to the
  21185. * <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
  21186. *
  21187. * @exports IndexDatatype
  21188. */
  21189. var IndexDatatype = {
  21190. /**
  21191. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  21192. * of an element in <code>Uint8Array</code>.
  21193. *
  21194. * @type {Number}
  21195. * @constant
  21196. */
  21197. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  21198. /**
  21199. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  21200. * of an element in <code>Uint16Array</code>.
  21201. *
  21202. * @type {Number}
  21203. * @constant
  21204. */
  21205. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  21206. /**
  21207. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  21208. * of an element in <code>Uint32Array</code>.
  21209. *
  21210. * @type {Number}
  21211. * @constant
  21212. */
  21213. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT
  21214. };
  21215. /**
  21216. * Returns the size, in bytes, of the corresponding datatype.
  21217. *
  21218. * @param {IndexDatatype} indexDatatype The index datatype to get the size of.
  21219. * @returns {Number} The size in bytes.
  21220. *
  21221. * @example
  21222. * // Returns 2
  21223. * var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
  21224. */
  21225. IndexDatatype.getSizeInBytes = function(indexDatatype) {
  21226. switch(indexDatatype) {
  21227. case IndexDatatype.UNSIGNED_BYTE:
  21228. return Uint8Array.BYTES_PER_ELEMENT;
  21229. case IndexDatatype.UNSIGNED_SHORT:
  21230. return Uint16Array.BYTES_PER_ELEMENT;
  21231. case IndexDatatype.UNSIGNED_INT:
  21232. return Uint32Array.BYTES_PER_ELEMENT;
  21233. }
  21234. throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
  21235. };
  21236. /**
  21237. * Validates that the provided index datatype is a valid {@link IndexDatatype}.
  21238. *
  21239. * @param {IndexDatatype} indexDatatype The index datatype to validate.
  21240. * @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
  21241. *
  21242. * @example
  21243. * if (!Cesium.IndexDatatype.validate(indexDatatype)) {
  21244. * throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
  21245. * }
  21246. */
  21247. IndexDatatype.validate = function(indexDatatype) {
  21248. return defined(indexDatatype) &&
  21249. (indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
  21250. indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
  21251. indexDatatype === IndexDatatype.UNSIGNED_INT);
  21252. };
  21253. /**
  21254. * Creates a typed array that will store indices, using either <code><Uint16Array</code>
  21255. * or <code>Uint32Array</code> depending on the number of vertices.
  21256. *
  21257. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  21258. * @param {Any} indicesLengthOrArray Passed through to the typed array constructor.
  21259. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
  21260. *
  21261. * @example
  21262. * this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
  21263. */
  21264. IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
  21265. if (!defined(numberOfVertices)) {
  21266. throw new DeveloperError('numberOfVertices is required.');
  21267. }
  21268. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  21269. return new Uint32Array(indicesLengthOrArray);
  21270. }
  21271. return new Uint16Array(indicesLengthOrArray);
  21272. };
  21273. /**
  21274. * Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
  21275. * or <code>Uint32Array</code> depending on the number of vertices.
  21276. *
  21277. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  21278. * @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
  21279. * @param {Number} byteOffset Passed through to the typed array constructor.
  21280. * @param {Number} length Passed through to the typed array constructor.
  21281. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
  21282. *
  21283. */
  21284. IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
  21285. if (!defined(numberOfVertices)) {
  21286. throw new DeveloperError('numberOfVertices is required.');
  21287. }
  21288. if (!defined(sourceArray)) {
  21289. throw new DeveloperError('sourceArray is required.');
  21290. }
  21291. if (!defined(byteOffset)) {
  21292. throw new DeveloperError('byteOffset is required.');
  21293. }
  21294. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  21295. return new Uint32Array(sourceArray, byteOffset, length);
  21296. }
  21297. return new Uint16Array(sourceArray, byteOffset, length);
  21298. };
  21299. return freezeObject(IndexDatatype);
  21300. });
  21301. /*global define*/
  21302. define('Core/Tipsify',[
  21303. './defaultValue',
  21304. './defined',
  21305. './DeveloperError'
  21306. ], function(
  21307. defaultValue,
  21308. defined,
  21309. DeveloperError) {
  21310. 'use strict';
  21311. /**
  21312. * Encapsulates an algorithm to optimize triangles for the post
  21313. * vertex-shader cache. This is based on the 2007 SIGGRAPH paper
  21314. * 'Fast Triangle Reordering for Vertex Locality and Reduced Overdraw.'
  21315. * The runtime is linear but several passes are made.
  21316. *
  21317. * @exports Tipsify
  21318. *
  21319. * @see <a href='http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf'>
  21320. * Fast Triangle Reordering for Vertex Locality and Reduced Overdraw</a>
  21321. * by Sander, Nehab, and Barczak
  21322. *
  21323. * @private
  21324. */
  21325. var Tipsify = {};
  21326. /**
  21327. * Calculates the average cache miss ratio (ACMR) for a given set of indices.
  21328. *
  21329. * @param {Object} options Object with the following properties:
  21330. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  21331. * in the vertex buffer that define the geometry's triangles.
  21332. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  21333. * If not supplied, this value will be computed.
  21334. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  21335. * @returns {Number} The average cache miss ratio (ACMR).
  21336. *
  21337. * @exception {DeveloperError} indices length must be a multiple of three.
  21338. * @exception {DeveloperError} cacheSize must be greater than two.
  21339. *
  21340. * @example
  21341. * var indices = [0, 1, 2, 3, 4, 5];
  21342. * var maxIndex = 5;
  21343. * var cacheSize = 3;
  21344. * var acmr = Cesium.Tipsify.calculateACMR({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  21345. */
  21346. Tipsify.calculateACMR = function(options) {
  21347. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21348. var indices = options.indices;
  21349. var maximumIndex = options.maximumIndex;
  21350. var cacheSize = defaultValue(options.cacheSize, 24);
  21351. if (!defined(indices)) {
  21352. throw new DeveloperError('indices is required.');
  21353. }
  21354. var numIndices = indices.length;
  21355. if (numIndices < 3 || numIndices % 3 !== 0) {
  21356. throw new DeveloperError('indices length must be a multiple of three.');
  21357. }
  21358. if (maximumIndex <= 0) {
  21359. throw new DeveloperError('maximumIndex must be greater than zero.');
  21360. }
  21361. if (cacheSize < 3) {
  21362. throw new DeveloperError('cacheSize must be greater than two.');
  21363. }
  21364. // Compute the maximumIndex if not given
  21365. if (!defined(maximumIndex)) {
  21366. maximumIndex = 0;
  21367. var currentIndex = 0;
  21368. var intoIndices = indices[currentIndex];
  21369. while (currentIndex < numIndices) {
  21370. if (intoIndices > maximumIndex) {
  21371. maximumIndex = intoIndices;
  21372. }
  21373. ++currentIndex;
  21374. intoIndices = indices[currentIndex];
  21375. }
  21376. }
  21377. // Vertex time stamps
  21378. var vertexTimeStamps = [];
  21379. for ( var i = 0; i < maximumIndex + 1; i++) {
  21380. vertexTimeStamps[i] = 0;
  21381. }
  21382. // Cache processing
  21383. var s = cacheSize + 1;
  21384. for ( var j = 0; j < numIndices; ++j) {
  21385. if ((s - vertexTimeStamps[indices[j]]) > cacheSize) {
  21386. vertexTimeStamps[indices[j]] = s;
  21387. ++s;
  21388. }
  21389. }
  21390. return (s - cacheSize + 1) / (numIndices / 3);
  21391. };
  21392. /**
  21393. * Optimizes triangles for the post-vertex shader cache.
  21394. *
  21395. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  21396. * in the vertex buffer that define the geometry's triangles.
  21397. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  21398. * If not supplied, this value will be computed.
  21399. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  21400. * @returns {Number[]} A list of the input indices in an optimized order.
  21401. *
  21402. * @exception {DeveloperError} indices length must be a multiple of three.
  21403. * @exception {DeveloperError} cacheSize must be greater than two.
  21404. *
  21405. * @example
  21406. * var indices = [0, 1, 2, 3, 4, 5];
  21407. * var maxIndex = 5;
  21408. * var cacheSize = 3;
  21409. * var reorderedIndices = Cesium.Tipsify.tipsify({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  21410. */
  21411. Tipsify.tipsify = function(options) {
  21412. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21413. var indices = options.indices;
  21414. var maximumIndex = options.maximumIndex;
  21415. var cacheSize = defaultValue(options.cacheSize, 24);
  21416. var cursor;
  21417. function skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne) {
  21418. while (deadEnd.length >= 1) {
  21419. // while the stack is not empty
  21420. var d = deadEnd[deadEnd.length - 1]; // top of the stack
  21421. deadEnd.splice(deadEnd.length - 1, 1); // pop the stack
  21422. if (vertices[d].numLiveTriangles > 0) {
  21423. return d;
  21424. }
  21425. }
  21426. while (cursor < maximumIndexPlusOne) {
  21427. if (vertices[cursor].numLiveTriangles > 0) {
  21428. ++cursor;
  21429. return cursor - 1;
  21430. }
  21431. ++cursor;
  21432. }
  21433. return -1;
  21434. }
  21435. function getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne) {
  21436. var n = -1;
  21437. var p;
  21438. var m = -1;
  21439. var itOneRing = 0;
  21440. while (itOneRing < oneRing.length) {
  21441. var index = oneRing[itOneRing];
  21442. if (vertices[index].numLiveTriangles) {
  21443. p = 0;
  21444. if ((s - vertices[index].timeStamp + (2 * vertices[index].numLiveTriangles)) <= cacheSize) {
  21445. p = s - vertices[index].timeStamp;
  21446. }
  21447. if ((p > m) || (m === -1)) {
  21448. m = p;
  21449. n = index;
  21450. }
  21451. }
  21452. ++itOneRing;
  21453. }
  21454. if (n === -1) {
  21455. return skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne);
  21456. }
  21457. return n;
  21458. }
  21459. if (!defined(indices)) {
  21460. throw new DeveloperError('indices is required.');
  21461. }
  21462. var numIndices = indices.length;
  21463. if (numIndices < 3 || numIndices % 3 !== 0) {
  21464. throw new DeveloperError('indices length must be a multiple of three.');
  21465. }
  21466. if (maximumIndex <= 0) {
  21467. throw new DeveloperError('maximumIndex must be greater than zero.');
  21468. }
  21469. if (cacheSize < 3) {
  21470. throw new DeveloperError('cacheSize must be greater than two.');
  21471. }
  21472. // Determine maximum index
  21473. var maximumIndexPlusOne = 0;
  21474. var currentIndex = 0;
  21475. var intoIndices = indices[currentIndex];
  21476. var endIndex = numIndices;
  21477. if (defined(maximumIndex)) {
  21478. maximumIndexPlusOne = maximumIndex + 1;
  21479. } else {
  21480. while (currentIndex < endIndex) {
  21481. if (intoIndices > maximumIndexPlusOne) {
  21482. maximumIndexPlusOne = intoIndices;
  21483. }
  21484. ++currentIndex;
  21485. intoIndices = indices[currentIndex];
  21486. }
  21487. if (maximumIndexPlusOne === -1) {
  21488. return 0;
  21489. }
  21490. ++maximumIndexPlusOne;
  21491. }
  21492. // Vertices
  21493. var vertices = [];
  21494. for ( var i = 0; i < maximumIndexPlusOne; i++) {
  21495. vertices[i] = {
  21496. numLiveTriangles : 0,
  21497. timeStamp : 0,
  21498. vertexTriangles : []
  21499. };
  21500. }
  21501. currentIndex = 0;
  21502. var triangle = 0;
  21503. while (currentIndex < endIndex) {
  21504. vertices[indices[currentIndex]].vertexTriangles.push(triangle);
  21505. ++(vertices[indices[currentIndex]]).numLiveTriangles;
  21506. vertices[indices[currentIndex + 1]].vertexTriangles.push(triangle);
  21507. ++(vertices[indices[currentIndex + 1]]).numLiveTriangles;
  21508. vertices[indices[currentIndex + 2]].vertexTriangles.push(triangle);
  21509. ++(vertices[indices[currentIndex + 2]]).numLiveTriangles;
  21510. ++triangle;
  21511. currentIndex += 3;
  21512. }
  21513. // Starting index
  21514. var f = 0;
  21515. // Time Stamp
  21516. var s = cacheSize + 1;
  21517. cursor = 1;
  21518. // Process
  21519. var oneRing = [];
  21520. var deadEnd = []; //Stack
  21521. var vertex;
  21522. var intoVertices;
  21523. var currentOutputIndex = 0;
  21524. var outputIndices = [];
  21525. var numTriangles = numIndices / 3;
  21526. var triangleEmitted = [];
  21527. for (i = 0; i < numTriangles; i++) {
  21528. triangleEmitted[i] = false;
  21529. }
  21530. var index;
  21531. var limit;
  21532. while (f !== -1) {
  21533. oneRing = [];
  21534. intoVertices = vertices[f];
  21535. limit = intoVertices.vertexTriangles.length;
  21536. for ( var k = 0; k < limit; ++k) {
  21537. triangle = intoVertices.vertexTriangles[k];
  21538. if (!triangleEmitted[triangle]) {
  21539. triangleEmitted[triangle] = true;
  21540. currentIndex = triangle + triangle + triangle;
  21541. for ( var j = 0; j < 3; ++j) {
  21542. // Set this index as a possible next index
  21543. index = indices[currentIndex];
  21544. oneRing.push(index);
  21545. deadEnd.push(index);
  21546. // Output index
  21547. outputIndices[currentOutputIndex] = index;
  21548. ++currentOutputIndex;
  21549. // Cache processing
  21550. vertex = vertices[index];
  21551. --vertex.numLiveTriangles;
  21552. if ((s - vertex.timeStamp) > cacheSize) {
  21553. vertex.timeStamp = s;
  21554. ++s;
  21555. }
  21556. ++currentIndex;
  21557. }
  21558. }
  21559. }
  21560. f = getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne);
  21561. }
  21562. return outputIndices;
  21563. };
  21564. return Tipsify;
  21565. });
  21566. /*global define*/
  21567. define('Core/GeometryPipeline',[
  21568. './AttributeCompression',
  21569. './barycentricCoordinates',
  21570. './BoundingSphere',
  21571. './Cartesian2',
  21572. './Cartesian3',
  21573. './Cartesian4',
  21574. './Cartographic',
  21575. './ComponentDatatype',
  21576. './defaultValue',
  21577. './defined',
  21578. './DeveloperError',
  21579. './EncodedCartesian3',
  21580. './GeographicProjection',
  21581. './Geometry',
  21582. './GeometryAttribute',
  21583. './GeometryType',
  21584. './IndexDatatype',
  21585. './Intersect',
  21586. './IntersectionTests',
  21587. './Math',
  21588. './Matrix3',
  21589. './Matrix4',
  21590. './Plane',
  21591. './PrimitiveType',
  21592. './Tipsify'
  21593. ], function(
  21594. AttributeCompression,
  21595. barycentricCoordinates,
  21596. BoundingSphere,
  21597. Cartesian2,
  21598. Cartesian3,
  21599. Cartesian4,
  21600. Cartographic,
  21601. ComponentDatatype,
  21602. defaultValue,
  21603. defined,
  21604. DeveloperError,
  21605. EncodedCartesian3,
  21606. GeographicProjection,
  21607. Geometry,
  21608. GeometryAttribute,
  21609. GeometryType,
  21610. IndexDatatype,
  21611. Intersect,
  21612. IntersectionTests,
  21613. CesiumMath,
  21614. Matrix3,
  21615. Matrix4,
  21616. Plane,
  21617. PrimitiveType,
  21618. Tipsify) {
  21619. 'use strict';
  21620. /**
  21621. * Content pipeline functions for geometries.
  21622. *
  21623. * @exports GeometryPipeline
  21624. *
  21625. * @see Geometry
  21626. */
  21627. var GeometryPipeline = {};
  21628. function addTriangle(lines, index, i0, i1, i2) {
  21629. lines[index++] = i0;
  21630. lines[index++] = i1;
  21631. lines[index++] = i1;
  21632. lines[index++] = i2;
  21633. lines[index++] = i2;
  21634. lines[index] = i0;
  21635. }
  21636. function trianglesToLines(triangles) {
  21637. var count = triangles.length;
  21638. var size = (count / 3) * 6;
  21639. var lines = IndexDatatype.createTypedArray(count, size);
  21640. var index = 0;
  21641. for ( var i = 0; i < count; i += 3, index += 6) {
  21642. addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]);
  21643. }
  21644. return lines;
  21645. }
  21646. function triangleStripToLines(triangles) {
  21647. var count = triangles.length;
  21648. if (count >= 3) {
  21649. var size = (count - 2) * 6;
  21650. var lines = IndexDatatype.createTypedArray(count, size);
  21651. addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]);
  21652. var index = 6;
  21653. for ( var i = 3; i < count; ++i, index += 6) {
  21654. addTriangle(lines, index, triangles[i - 1], triangles[i], triangles[i - 2]);
  21655. }
  21656. return lines;
  21657. }
  21658. return new Uint16Array();
  21659. }
  21660. function triangleFanToLines(triangles) {
  21661. if (triangles.length > 0) {
  21662. var count = triangles.length - 1;
  21663. var size = (count - 1) * 6;
  21664. var lines = IndexDatatype.createTypedArray(count, size);
  21665. var base = triangles[0];
  21666. var index = 0;
  21667. for ( var i = 1; i < count; ++i, index += 6) {
  21668. addTriangle(lines, index, base, triangles[i], triangles[i + 1]);
  21669. }
  21670. return lines;
  21671. }
  21672. return new Uint16Array();
  21673. }
  21674. /**
  21675. * Converts a geometry's triangle indices to line indices. If the geometry has an <code>indices</code>
  21676. * and its <code>primitiveType</code> is <code>TRIANGLES</code>, <code>TRIANGLE_STRIP</code>,
  21677. * <code>TRIANGLE_FAN</code>, it is converted to <code>LINES</code>; otherwise, the geometry is not changed.
  21678. * <p>
  21679. * This is commonly used to create a wireframe geometry for visual debugging.
  21680. * </p>
  21681. *
  21682. * @param {Geometry} geometry The geometry to modify.
  21683. * @returns {Geometry} The modified <code>geometry</code> argument, with its triangle indices converted to lines.
  21684. *
  21685. * @exception {DeveloperError} geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.
  21686. *
  21687. * @example
  21688. * geometry = Cesium.GeometryPipeline.toWireframe(geometry);
  21689. */
  21690. GeometryPipeline.toWireframe = function(geometry) {
  21691. if (!defined(geometry)) {
  21692. throw new DeveloperError('geometry is required.');
  21693. }
  21694. var indices = geometry.indices;
  21695. if (defined(indices)) {
  21696. switch (geometry.primitiveType) {
  21697. case PrimitiveType.TRIANGLES:
  21698. geometry.indices = trianglesToLines(indices);
  21699. break;
  21700. case PrimitiveType.TRIANGLE_STRIP:
  21701. geometry.indices = triangleStripToLines(indices);
  21702. break;
  21703. case PrimitiveType.TRIANGLE_FAN:
  21704. geometry.indices = triangleFanToLines(indices);
  21705. break;
  21706. default:
  21707. throw new DeveloperError('geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.');
  21708. }
  21709. geometry.primitiveType = PrimitiveType.LINES;
  21710. }
  21711. return geometry;
  21712. };
  21713. /**
  21714. * Creates a new {@link Geometry} with <code>LINES</code> representing the provided
  21715. * attribute (<code>attributeName</code>) for the provided geometry. This is used to
  21716. * visualize vector attributes like normals, binormals, and tangents.
  21717. *
  21718. * @param {Geometry} geometry The <code>Geometry</code> instance with the attribute.
  21719. * @param {String} [attributeName='normal'] The name of the attribute.
  21720. * @param {Number} [length=10000.0] The length of each line segment in meters. This can be negative to point the vector in the opposite direction.
  21721. * @returns {Geometry} A new <code>Geometry</code> instance with line segments for the vector.
  21722. *
  21723. * @exception {DeveloperError} geometry.attributes must have an attribute with the same name as the attributeName parameter.
  21724. *
  21725. * @example
  21726. * var geometry = Cesium.GeometryPipeline.createLineSegmentsForVectors(instance.geometry, 'binormal', 100000.0);
  21727. */
  21728. GeometryPipeline.createLineSegmentsForVectors = function(geometry, attributeName, length) {
  21729. attributeName = defaultValue(attributeName, 'normal');
  21730. if (!defined(geometry)) {
  21731. throw new DeveloperError('geometry is required.');
  21732. }
  21733. if (!defined(geometry.attributes.position)) {
  21734. throw new DeveloperError('geometry.attributes.position is required.');
  21735. }
  21736. if (!defined(geometry.attributes[attributeName])) {
  21737. throw new DeveloperError('geometry.attributes must have an attribute with the same name as the attributeName parameter, ' + attributeName + '.');
  21738. }
  21739. length = defaultValue(length, 10000.0);
  21740. var positions = geometry.attributes.position.values;
  21741. var vectors = geometry.attributes[attributeName].values;
  21742. var positionsLength = positions.length;
  21743. var newPositions = new Float64Array(2 * positionsLength);
  21744. var j = 0;
  21745. for (var i = 0; i < positionsLength; i += 3) {
  21746. newPositions[j++] = positions[i];
  21747. newPositions[j++] = positions[i + 1];
  21748. newPositions[j++] = positions[i + 2];
  21749. newPositions[j++] = positions[i] + (vectors[i] * length);
  21750. newPositions[j++] = positions[i + 1] + (vectors[i + 1] * length);
  21751. newPositions[j++] = positions[i + 2] + (vectors[i + 2] * length);
  21752. }
  21753. var newBoundingSphere;
  21754. var bs = geometry.boundingSphere;
  21755. if (defined(bs)) {
  21756. newBoundingSphere = new BoundingSphere(bs.center, bs.radius + length);
  21757. }
  21758. return new Geometry({
  21759. attributes : {
  21760. position : new GeometryAttribute({
  21761. componentDatatype : ComponentDatatype.DOUBLE,
  21762. componentsPerAttribute : 3,
  21763. values : newPositions
  21764. })
  21765. },
  21766. primitiveType : PrimitiveType.LINES,
  21767. boundingSphere : newBoundingSphere
  21768. });
  21769. };
  21770. /**
  21771. * Creates an object that maps attribute names to unique locations (indices)
  21772. * for matching vertex attributes and shader programs.
  21773. *
  21774. * @param {Geometry} geometry The geometry, which is not modified, to create the object for.
  21775. * @returns {Object} An object with attribute name / index pairs.
  21776. *
  21777. * @example
  21778. * var attributeLocations = Cesium.GeometryPipeline.createAttributeLocations(geometry);
  21779. * // Example output
  21780. * // {
  21781. * // 'position' : 0,
  21782. * // 'normal' : 1
  21783. * // }
  21784. */
  21785. GeometryPipeline.createAttributeLocations = function(geometry) {
  21786. if (!defined(geometry)) {
  21787. throw new DeveloperError('geometry is required.');
  21788. }
  21789. // There can be a WebGL performance hit when attribute 0 is disabled, so
  21790. // assign attribute locations to well-known attributes.
  21791. var semantics = [
  21792. 'position',
  21793. 'positionHigh',
  21794. 'positionLow',
  21795. // From VertexFormat.position - after 2D projection and high-precision encoding
  21796. 'position3DHigh',
  21797. 'position3DLow',
  21798. 'position2DHigh',
  21799. 'position2DLow',
  21800. // From Primitive
  21801. 'pickColor',
  21802. // From VertexFormat
  21803. 'normal',
  21804. 'st',
  21805. 'binormal',
  21806. 'tangent',
  21807. // From compressing texture coordinates and normals
  21808. 'compressedAttributes'
  21809. ];
  21810. var attributes = geometry.attributes;
  21811. var indices = {};
  21812. var j = 0;
  21813. var i;
  21814. var len = semantics.length;
  21815. // Attribute locations for well-known attributes
  21816. for (i = 0; i < len; ++i) {
  21817. var semantic = semantics[i];
  21818. if (defined(attributes[semantic])) {
  21819. indices[semantic] = j++;
  21820. }
  21821. }
  21822. // Locations for custom attributes
  21823. for (var name in attributes) {
  21824. if (attributes.hasOwnProperty(name) && (!defined(indices[name]))) {
  21825. indices[name] = j++;
  21826. }
  21827. }
  21828. return indices;
  21829. };
  21830. /**
  21831. * Reorders a geometry's attributes and <code>indices</code> to achieve better performance from the GPU's pre-vertex-shader cache.
  21832. *
  21833. * @param {Geometry} geometry The geometry to modify.
  21834. * @returns {Geometry} The modified <code>geometry</code> argument, with its attributes and indices reordered for the GPU's pre-vertex-shader cache.
  21835. *
  21836. * @exception {DeveloperError} Each attribute array in geometry.attributes must have the same number of attributes.
  21837. *
  21838. *
  21839. * @example
  21840. * geometry = Cesium.GeometryPipeline.reorderForPreVertexCache(geometry);
  21841. *
  21842. * @see GeometryPipeline.reorderForPostVertexCache
  21843. */
  21844. GeometryPipeline.reorderForPreVertexCache = function(geometry) {
  21845. if (!defined(geometry)) {
  21846. throw new DeveloperError('geometry is required.');
  21847. }
  21848. var numVertices = Geometry.computeNumberOfVertices(geometry);
  21849. var indices = geometry.indices;
  21850. if (defined(indices)) {
  21851. var indexCrossReferenceOldToNew = new Int32Array(numVertices);
  21852. for ( var i = 0; i < numVertices; i++) {
  21853. indexCrossReferenceOldToNew[i] = -1;
  21854. }
  21855. // Construct cross reference and reorder indices
  21856. var indicesIn = indices;
  21857. var numIndices = indicesIn.length;
  21858. var indicesOut = IndexDatatype.createTypedArray(numVertices, numIndices);
  21859. var intoIndicesIn = 0;
  21860. var intoIndicesOut = 0;
  21861. var nextIndex = 0;
  21862. var tempIndex;
  21863. while (intoIndicesIn < numIndices) {
  21864. tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]];
  21865. if (tempIndex !== -1) {
  21866. indicesOut[intoIndicesOut] = tempIndex;
  21867. } else {
  21868. tempIndex = indicesIn[intoIndicesIn];
  21869. indexCrossReferenceOldToNew[tempIndex] = nextIndex;
  21870. indicesOut[intoIndicesOut] = nextIndex;
  21871. ++nextIndex;
  21872. }
  21873. ++intoIndicesIn;
  21874. ++intoIndicesOut;
  21875. }
  21876. geometry.indices = indicesOut;
  21877. // Reorder attributes
  21878. var attributes = geometry.attributes;
  21879. for ( var property in attributes) {
  21880. if (attributes.hasOwnProperty(property) &&
  21881. defined(attributes[property]) &&
  21882. defined(attributes[property].values)) {
  21883. var attribute = attributes[property];
  21884. var elementsIn = attribute.values;
  21885. var intoElementsIn = 0;
  21886. var numComponents = attribute.componentsPerAttribute;
  21887. var elementsOut = ComponentDatatype.createTypedArray(attribute.componentDatatype, nextIndex * numComponents);
  21888. while (intoElementsIn < numVertices) {
  21889. var temp = indexCrossReferenceOldToNew[intoElementsIn];
  21890. if (temp !== -1) {
  21891. for (i = 0; i < numComponents; i++) {
  21892. elementsOut[numComponents * temp + i] = elementsIn[numComponents * intoElementsIn + i];
  21893. }
  21894. }
  21895. ++intoElementsIn;
  21896. }
  21897. attribute.values = elementsOut;
  21898. }
  21899. }
  21900. }
  21901. return geometry;
  21902. };
  21903. /**
  21904. * Reorders a geometry's <code>indices</code> to achieve better performance from the GPU's
  21905. * post vertex-shader cache by using the Tipsify algorithm. If the geometry <code>primitiveType</code>
  21906. * is not <code>TRIANGLES</code> or the geometry does not have an <code>indices</code>, this function has no effect.
  21907. *
  21908. * @param {Geometry} geometry The geometry to modify.
  21909. * @param {Number} [cacheCapacity=24] The number of vertices that can be held in the GPU's vertex cache.
  21910. * @returns {Geometry} The modified <code>geometry</code> argument, with its indices reordered for the post-vertex-shader cache.
  21911. *
  21912. * @exception {DeveloperError} cacheCapacity must be greater than two.
  21913. *
  21914. *
  21915. * @example
  21916. * geometry = Cesium.GeometryPipeline.reorderForPostVertexCache(geometry);
  21917. *
  21918. * @see GeometryPipeline.reorderForPreVertexCache
  21919. * @see {@link http://gfx.cs.princ0eton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf|Fast Triangle Reordering for Vertex Locality and Reduced Overdraw}
  21920. * by Sander, Nehab, and Barczak
  21921. */
  21922. GeometryPipeline.reorderForPostVertexCache = function(geometry, cacheCapacity) {
  21923. if (!defined(geometry)) {
  21924. throw new DeveloperError('geometry is required.');
  21925. }
  21926. var indices = geometry.indices;
  21927. if ((geometry.primitiveType === PrimitiveType.TRIANGLES) && (defined(indices))) {
  21928. var numIndices = indices.length;
  21929. var maximumIndex = 0;
  21930. for ( var j = 0; j < numIndices; j++) {
  21931. if (indices[j] > maximumIndex) {
  21932. maximumIndex = indices[j];
  21933. }
  21934. }
  21935. geometry.indices = Tipsify.tipsify({
  21936. indices : indices,
  21937. maximumIndex : maximumIndex,
  21938. cacheSize : cacheCapacity
  21939. });
  21940. }
  21941. return geometry;
  21942. };
  21943. function copyAttributesDescriptions(attributes) {
  21944. var newAttributes = {};
  21945. for ( var attribute in attributes) {
  21946. if (attributes.hasOwnProperty(attribute) &&
  21947. defined(attributes[attribute]) &&
  21948. defined(attributes[attribute].values)) {
  21949. var attr = attributes[attribute];
  21950. newAttributes[attribute] = new GeometryAttribute({
  21951. componentDatatype : attr.componentDatatype,
  21952. componentsPerAttribute : attr.componentsPerAttribute,
  21953. normalize : attr.normalize,
  21954. values : []
  21955. });
  21956. }
  21957. }
  21958. return newAttributes;
  21959. }
  21960. function copyVertex(destinationAttributes, sourceAttributes, index) {
  21961. for ( var attribute in sourceAttributes) {
  21962. if (sourceAttributes.hasOwnProperty(attribute) &&
  21963. defined(sourceAttributes[attribute]) &&
  21964. defined(sourceAttributes[attribute].values)) {
  21965. var attr = sourceAttributes[attribute];
  21966. for ( var k = 0; k < attr.componentsPerAttribute; ++k) {
  21967. destinationAttributes[attribute].values.push(attr.values[(index * attr.componentsPerAttribute) + k]);
  21968. }
  21969. }
  21970. }
  21971. }
  21972. /**
  21973. * Splits a geometry into multiple geometries, if necessary, to ensure that indices in the
  21974. * <code>indices</code> fit into unsigned shorts. This is used to meet the WebGL requirements
  21975. * when unsigned int indices are not supported.
  21976. * <p>
  21977. * If the geometry does not have any <code>indices</code>, this function has no effect.
  21978. * </p>
  21979. *
  21980. * @param {Geometry} geometry The geometry to be split into multiple geometries.
  21981. * @returns {Geometry[]} An array of geometries, each with indices that fit into unsigned shorts.
  21982. *
  21983. * @exception {DeveloperError} geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS
  21984. * @exception {DeveloperError} All geometry attribute lists must have the same number of attributes.
  21985. *
  21986. * @example
  21987. * var geometries = Cesium.GeometryPipeline.fitToUnsignedShortIndices(geometry);
  21988. */
  21989. GeometryPipeline.fitToUnsignedShortIndices = function(geometry) {
  21990. if (!defined(geometry)) {
  21991. throw new DeveloperError('geometry is required.');
  21992. }
  21993. if ((defined(geometry.indices)) &&
  21994. ((geometry.primitiveType !== PrimitiveType.TRIANGLES) &&
  21995. (geometry.primitiveType !== PrimitiveType.LINES) &&
  21996. (geometry.primitiveType !== PrimitiveType.POINTS))) {
  21997. throw new DeveloperError('geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS.');
  21998. }
  21999. var geometries = [];
  22000. // If there's an index list and more than 64K attributes, it is possible that
  22001. // some indices are outside the range of unsigned short [0, 64K - 1]
  22002. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22003. if (defined(geometry.indices) && (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES)) {
  22004. var oldToNewIndex = [];
  22005. var newIndices = [];
  22006. var currentIndex = 0;
  22007. var newAttributes = copyAttributesDescriptions(geometry.attributes);
  22008. var originalIndices = geometry.indices;
  22009. var numberOfIndices = originalIndices.length;
  22010. var indicesPerPrimitive;
  22011. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  22012. indicesPerPrimitive = 3;
  22013. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  22014. indicesPerPrimitive = 2;
  22015. } else if (geometry.primitiveType === PrimitiveType.POINTS) {
  22016. indicesPerPrimitive = 1;
  22017. }
  22018. for ( var j = 0; j < numberOfIndices; j += indicesPerPrimitive) {
  22019. for (var k = 0; k < indicesPerPrimitive; ++k) {
  22020. var x = originalIndices[j + k];
  22021. var i = oldToNewIndex[x];
  22022. if (!defined(i)) {
  22023. i = currentIndex++;
  22024. oldToNewIndex[x] = i;
  22025. copyVertex(newAttributes, geometry.attributes, x);
  22026. }
  22027. newIndices.push(i);
  22028. }
  22029. if (currentIndex + indicesPerPrimitive >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  22030. geometries.push(new Geometry({
  22031. attributes : newAttributes,
  22032. indices : newIndices,
  22033. primitiveType : geometry.primitiveType,
  22034. boundingSphere : geometry.boundingSphere,
  22035. boundingSphereCV : geometry.boundingSphereCV
  22036. }));
  22037. // Reset for next vertex-array
  22038. oldToNewIndex = [];
  22039. newIndices = [];
  22040. currentIndex = 0;
  22041. newAttributes = copyAttributesDescriptions(geometry.attributes);
  22042. }
  22043. }
  22044. if (newIndices.length !== 0) {
  22045. geometries.push(new Geometry({
  22046. attributes : newAttributes,
  22047. indices : newIndices,
  22048. primitiveType : geometry.primitiveType,
  22049. boundingSphere : geometry.boundingSphere,
  22050. boundingSphereCV : geometry.boundingSphereCV
  22051. }));
  22052. }
  22053. } else {
  22054. // No need to split into multiple geometries
  22055. geometries.push(geometry);
  22056. }
  22057. return geometries;
  22058. };
  22059. var scratchProjectTo2DCartesian3 = new Cartesian3();
  22060. var scratchProjectTo2DCartographic = new Cartographic();
  22061. /**
  22062. * Projects a geometry's 3D <code>position</code> attribute to 2D, replacing the <code>position</code>
  22063. * attribute with separate <code>position3D</code> and <code>position2D</code> attributes.
  22064. * <p>
  22065. * If the geometry does not have a <code>position</code>, this function has no effect.
  22066. * </p>
  22067. *
  22068. * @param {Geometry} geometry The geometry to modify.
  22069. * @param {String} attributeName The name of the attribute.
  22070. * @param {String} attributeName3D The name of the attribute in 3D.
  22071. * @param {String} attributeName2D The name of the attribute in 2D.
  22072. * @param {Object} [projection=new GeographicProjection()] The projection to use.
  22073. * @returns {Geometry} The modified <code>geometry</code> argument with <code>position3D</code> and <code>position2D</code> attributes.
  22074. *
  22075. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  22076. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  22077. * @exception {DeveloperError} Could not project a point to 2D.
  22078. *
  22079. * @example
  22080. * geometry = Cesium.GeometryPipeline.projectTo2D(geometry, 'position', 'position3D', 'position2D');
  22081. */
  22082. GeometryPipeline.projectTo2D = function(geometry, attributeName, attributeName3D, attributeName2D, projection) {
  22083. if (!defined(geometry)) {
  22084. throw new DeveloperError('geometry is required.');
  22085. }
  22086. if (!defined(attributeName)) {
  22087. throw new DeveloperError('attributeName is required.');
  22088. }
  22089. if (!defined(attributeName3D)) {
  22090. throw new DeveloperError('attributeName3D is required.');
  22091. }
  22092. if (!defined(attributeName2D)) {
  22093. throw new DeveloperError('attributeName2D is required.');
  22094. }
  22095. if (!defined(geometry.attributes[attributeName])) {
  22096. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  22097. }
  22098. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  22099. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  22100. }
  22101. var attribute = geometry.attributes[attributeName];
  22102. projection = (defined(projection)) ? projection : new GeographicProjection();
  22103. var ellipsoid = projection.ellipsoid;
  22104. // Project original values to 2D.
  22105. var values3D = attribute.values;
  22106. var projectedValues = new Float64Array(values3D.length);
  22107. var index = 0;
  22108. for ( var i = 0; i < values3D.length; i += 3) {
  22109. var value = Cartesian3.fromArray(values3D, i, scratchProjectTo2DCartesian3);
  22110. var lonLat = ellipsoid.cartesianToCartographic(value, scratchProjectTo2DCartographic);
  22111. if (!defined(lonLat)) {
  22112. throw new DeveloperError('Could not project point (' + value.x + ', ' + value.y + ', ' + value.z + ') to 2D.');
  22113. }
  22114. var projectedLonLat = projection.project(lonLat, scratchProjectTo2DCartesian3);
  22115. projectedValues[index++] = projectedLonLat.x;
  22116. projectedValues[index++] = projectedLonLat.y;
  22117. projectedValues[index++] = projectedLonLat.z;
  22118. }
  22119. // Rename original cartesians to WGS84 cartesians.
  22120. geometry.attributes[attributeName3D] = attribute;
  22121. // Replace original cartesians with 2D projected cartesians
  22122. geometry.attributes[attributeName2D] = new GeometryAttribute({
  22123. componentDatatype : ComponentDatatype.DOUBLE,
  22124. componentsPerAttribute : 3,
  22125. values : projectedValues
  22126. });
  22127. delete geometry.attributes[attributeName];
  22128. return geometry;
  22129. };
  22130. var encodedResult = {
  22131. high : 0.0,
  22132. low : 0.0
  22133. };
  22134. /**
  22135. * Encodes floating-point geometry attribute values as two separate attributes to improve
  22136. * rendering precision.
  22137. * <p>
  22138. * This is commonly used to create high-precision position vertex attributes.
  22139. * </p>
  22140. *
  22141. * @param {Geometry} geometry The geometry to modify.
  22142. * @param {String} attributeName The name of the attribute.
  22143. * @param {String} attributeHighName The name of the attribute for the encoded high bits.
  22144. * @param {String} attributeLowName The name of the attribute for the encoded low bits.
  22145. * @returns {Geometry} The modified <code>geometry</code> argument, with its encoded attribute.
  22146. *
  22147. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  22148. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  22149. *
  22150. * @example
  22151. * geometry = Cesium.GeometryPipeline.encodeAttribute(geometry, 'position3D', 'position3DHigh', 'position3DLow');
  22152. */
  22153. GeometryPipeline.encodeAttribute = function(geometry, attributeName, attributeHighName, attributeLowName) {
  22154. if (!defined(geometry)) {
  22155. throw new DeveloperError('geometry is required.');
  22156. }
  22157. if (!defined(attributeName)) {
  22158. throw new DeveloperError('attributeName is required.');
  22159. }
  22160. if (!defined(attributeHighName)) {
  22161. throw new DeveloperError('attributeHighName is required.');
  22162. }
  22163. if (!defined(attributeLowName)) {
  22164. throw new DeveloperError('attributeLowName is required.');
  22165. }
  22166. if (!defined(geometry.attributes[attributeName])) {
  22167. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  22168. }
  22169. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  22170. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  22171. }
  22172. var attribute = geometry.attributes[attributeName];
  22173. var values = attribute.values;
  22174. var length = values.length;
  22175. var highValues = new Float32Array(length);
  22176. var lowValues = new Float32Array(length);
  22177. for (var i = 0; i < length; ++i) {
  22178. EncodedCartesian3.encode(values[i], encodedResult);
  22179. highValues[i] = encodedResult.high;
  22180. lowValues[i] = encodedResult.low;
  22181. }
  22182. var componentsPerAttribute = attribute.componentsPerAttribute;
  22183. geometry.attributes[attributeHighName] = new GeometryAttribute({
  22184. componentDatatype : ComponentDatatype.FLOAT,
  22185. componentsPerAttribute : componentsPerAttribute,
  22186. values : highValues
  22187. });
  22188. geometry.attributes[attributeLowName] = new GeometryAttribute({
  22189. componentDatatype : ComponentDatatype.FLOAT,
  22190. componentsPerAttribute : componentsPerAttribute,
  22191. values : lowValues
  22192. });
  22193. delete geometry.attributes[attributeName];
  22194. return geometry;
  22195. };
  22196. var scratchCartesian3 = new Cartesian3();
  22197. function transformPoint(matrix, attribute) {
  22198. if (defined(attribute)) {
  22199. var values = attribute.values;
  22200. var length = values.length;
  22201. for (var i = 0; i < length; i += 3) {
  22202. Cartesian3.unpack(values, i, scratchCartesian3);
  22203. Matrix4.multiplyByPoint(matrix, scratchCartesian3, scratchCartesian3);
  22204. Cartesian3.pack(scratchCartesian3, values, i);
  22205. }
  22206. }
  22207. }
  22208. function transformVector(matrix, attribute) {
  22209. if (defined(attribute)) {
  22210. var values = attribute.values;
  22211. var length = values.length;
  22212. for (var i = 0; i < length; i += 3) {
  22213. Cartesian3.unpack(values, i, scratchCartesian3);
  22214. Matrix3.multiplyByVector(matrix, scratchCartesian3, scratchCartesian3);
  22215. scratchCartesian3 = Cartesian3.normalize(scratchCartesian3, scratchCartesian3);
  22216. Cartesian3.pack(scratchCartesian3, values, i);
  22217. }
  22218. }
  22219. }
  22220. var inverseTranspose = new Matrix4();
  22221. var normalMatrix = new Matrix3();
  22222. /**
  22223. * Transforms a geometry instance to world coordinates. This changes
  22224. * the instance's <code>modelMatrix</code> to {@link Matrix4.IDENTITY} and transforms the
  22225. * following attributes if they are present: <code>position</code>, <code>normal</code>,
  22226. * <code>binormal</code>, and <code>tangent</code>.
  22227. *
  22228. * @param {GeometryInstance} instance The geometry instance to modify.
  22229. * @returns {GeometryInstance} The modified <code>instance</code> argument, with its attributes transforms to world coordinates.
  22230. *
  22231. * @example
  22232. * Cesium.GeometryPipeline.transformToWorldCoordinates(instance);
  22233. */
  22234. GeometryPipeline.transformToWorldCoordinates = function(instance) {
  22235. if (!defined(instance)) {
  22236. throw new DeveloperError('instance is required.');
  22237. }
  22238. var modelMatrix = instance.modelMatrix;
  22239. if (Matrix4.equals(modelMatrix, Matrix4.IDENTITY)) {
  22240. // Already in world coordinates
  22241. return instance;
  22242. }
  22243. var attributes = instance.geometry.attributes;
  22244. // Transform attributes in known vertex formats
  22245. transformPoint(modelMatrix, attributes.position);
  22246. transformPoint(modelMatrix, attributes.prevPosition);
  22247. transformPoint(modelMatrix, attributes.nextPosition);
  22248. if ((defined(attributes.normal)) ||
  22249. (defined(attributes.binormal)) ||
  22250. (defined(attributes.tangent))) {
  22251. Matrix4.inverse(modelMatrix, inverseTranspose);
  22252. Matrix4.transpose(inverseTranspose, inverseTranspose);
  22253. Matrix4.getRotation(inverseTranspose, normalMatrix);
  22254. transformVector(normalMatrix, attributes.normal);
  22255. transformVector(normalMatrix, attributes.binormal);
  22256. transformVector(normalMatrix, attributes.tangent);
  22257. }
  22258. var boundingSphere = instance.geometry.boundingSphere;
  22259. if (defined(boundingSphere)) {
  22260. instance.geometry.boundingSphere = BoundingSphere.transform(boundingSphere, modelMatrix, boundingSphere);
  22261. }
  22262. instance.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
  22263. return instance;
  22264. };
  22265. function findAttributesInAllGeometries(instances, propertyName) {
  22266. var length = instances.length;
  22267. var attributesInAllGeometries = {};
  22268. var attributes0 = instances[0][propertyName].attributes;
  22269. var name;
  22270. for (name in attributes0) {
  22271. if (attributes0.hasOwnProperty(name) &&
  22272. defined(attributes0[name]) &&
  22273. defined(attributes0[name].values)) {
  22274. var attribute = attributes0[name];
  22275. var numberOfComponents = attribute.values.length;
  22276. var inAllGeometries = true;
  22277. // Does this same attribute exist in all geometries?
  22278. for (var i = 1; i < length; ++i) {
  22279. var otherAttribute = instances[i][propertyName].attributes[name];
  22280. if ((!defined(otherAttribute)) ||
  22281. (attribute.componentDatatype !== otherAttribute.componentDatatype) ||
  22282. (attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute) ||
  22283. (attribute.normalize !== otherAttribute.normalize)) {
  22284. inAllGeometries = false;
  22285. break;
  22286. }
  22287. numberOfComponents += otherAttribute.values.length;
  22288. }
  22289. if (inAllGeometries) {
  22290. attributesInAllGeometries[name] = new GeometryAttribute({
  22291. componentDatatype : attribute.componentDatatype,
  22292. componentsPerAttribute : attribute.componentsPerAttribute,
  22293. normalize : attribute.normalize,
  22294. values : ComponentDatatype.createTypedArray(attribute.componentDatatype, numberOfComponents)
  22295. });
  22296. }
  22297. }
  22298. }
  22299. return attributesInAllGeometries;
  22300. }
  22301. var tempScratch = new Cartesian3();
  22302. function combineGeometries(instances, propertyName) {
  22303. var length = instances.length;
  22304. var name;
  22305. var i;
  22306. var j;
  22307. var k;
  22308. var m = instances[0].modelMatrix;
  22309. var haveIndices = (defined(instances[0][propertyName].indices));
  22310. var primitiveType = instances[0][propertyName].primitiveType;
  22311. for (i = 1; i < length; ++i) {
  22312. if (!Matrix4.equals(instances[i].modelMatrix, m)) {
  22313. throw new DeveloperError('All instances must have the same modelMatrix.');
  22314. }
  22315. if ((defined(instances[i][propertyName].indices)) !== haveIndices) {
  22316. throw new DeveloperError('All instance geometries must have an indices or not have one.');
  22317. }
  22318. if (instances[i][propertyName].primitiveType !== primitiveType) {
  22319. throw new DeveloperError('All instance geometries must have the same primitiveType.');
  22320. }
  22321. }
  22322. // Find subset of attributes in all geometries
  22323. var attributes = findAttributesInAllGeometries(instances, propertyName);
  22324. var values;
  22325. var sourceValues;
  22326. var sourceValuesLength;
  22327. // Combine attributes from each geometry into a single typed array
  22328. for (name in attributes) {
  22329. if (attributes.hasOwnProperty(name)) {
  22330. values = attributes[name].values;
  22331. k = 0;
  22332. for (i = 0; i < length; ++i) {
  22333. sourceValues = instances[i][propertyName].attributes[name].values;
  22334. sourceValuesLength = sourceValues.length;
  22335. for (j = 0; j < sourceValuesLength; ++j) {
  22336. values[k++] = sourceValues[j];
  22337. }
  22338. }
  22339. }
  22340. }
  22341. // Combine index lists
  22342. var indices;
  22343. if (haveIndices) {
  22344. var numberOfIndices = 0;
  22345. for (i = 0; i < length; ++i) {
  22346. numberOfIndices += instances[i][propertyName].indices.length;
  22347. }
  22348. var numberOfVertices = Geometry.computeNumberOfVertices(new Geometry({
  22349. attributes : attributes,
  22350. primitiveType : PrimitiveType.POINTS
  22351. }));
  22352. var destIndices = IndexDatatype.createTypedArray(numberOfVertices, numberOfIndices);
  22353. var destOffset = 0;
  22354. var offset = 0;
  22355. for (i = 0; i < length; ++i) {
  22356. var sourceIndices = instances[i][propertyName].indices;
  22357. var sourceIndicesLen = sourceIndices.length;
  22358. for (k = 0; k < sourceIndicesLen; ++k) {
  22359. destIndices[destOffset++] = offset + sourceIndices[k];
  22360. }
  22361. offset += Geometry.computeNumberOfVertices(instances[i][propertyName]);
  22362. }
  22363. indices = destIndices;
  22364. }
  22365. // Create bounding sphere that includes all instances
  22366. var center = new Cartesian3();
  22367. var radius = 0.0;
  22368. var bs;
  22369. for (i = 0; i < length; ++i) {
  22370. bs = instances[i][propertyName].boundingSphere;
  22371. if (!defined(bs)) {
  22372. // If any geometries have an undefined bounding sphere, then so does the combined geometry
  22373. center = undefined;
  22374. break;
  22375. }
  22376. Cartesian3.add(bs.center, center, center);
  22377. }
  22378. if (defined(center)) {
  22379. Cartesian3.divideByScalar(center, length, center);
  22380. for (i = 0; i < length; ++i) {
  22381. bs = instances[i][propertyName].boundingSphere;
  22382. var tempRadius = Cartesian3.magnitude(Cartesian3.subtract(bs.center, center, tempScratch)) + bs.radius;
  22383. if (tempRadius > radius) {
  22384. radius = tempRadius;
  22385. }
  22386. }
  22387. }
  22388. return new Geometry({
  22389. attributes : attributes,
  22390. indices : indices,
  22391. primitiveType : primitiveType,
  22392. boundingSphere : (defined(center)) ? new BoundingSphere(center, radius) : undefined
  22393. });
  22394. }
  22395. /**
  22396. * Combines geometry from several {@link GeometryInstance} objects into one geometry.
  22397. * This concatenates the attributes, concatenates and adjusts the indices, and creates
  22398. * a bounding sphere encompassing all instances.
  22399. * <p>
  22400. * If the instances do not have the same attributes, a subset of attributes common
  22401. * to all instances is used, and the others are ignored.
  22402. * </p>
  22403. * <p>
  22404. * This is used by {@link Primitive} to efficiently render a large amount of static data.
  22405. * </p>
  22406. *
  22407. * @private
  22408. *
  22409. * @param {GeometryInstance[]} [instances] The array of {@link GeometryInstance} objects whose geometry will be combined.
  22410. * @returns {Geometry} A single geometry created from the provided geometry instances.
  22411. *
  22412. * @exception {DeveloperError} All instances must have the same modelMatrix.
  22413. * @exception {DeveloperError} All instance geometries must have an indices or not have one.
  22414. * @exception {DeveloperError} All instance geometries must have the same primitiveType.
  22415. *
  22416. *
  22417. * @example
  22418. * for (var i = 0; i < instances.length; ++i) {
  22419. * Cesium.GeometryPipeline.transformToWorldCoordinates(instances[i]);
  22420. * }
  22421. * var geometries = Cesium.GeometryPipeline.combineInstances(instances);
  22422. *
  22423. * @see GeometryPipeline.transformToWorldCoordinates
  22424. */
  22425. GeometryPipeline.combineInstances = function(instances) {
  22426. if ((!defined(instances)) || (instances.length < 1)) {
  22427. throw new DeveloperError('instances is required and must have length greater than zero.');
  22428. }
  22429. var instanceGeometry = [];
  22430. var instanceSplitGeometry = [];
  22431. var length = instances.length;
  22432. for (var i = 0; i < length; ++i) {
  22433. var instance = instances[i];
  22434. if (defined(instance.geometry)) {
  22435. instanceGeometry.push(instance);
  22436. } else if (defined(instance.westHemisphereGeometry) && defined(instance.eastHemisphereGeometry)) {
  22437. instanceSplitGeometry.push(instance);
  22438. }
  22439. }
  22440. var geometries = [];
  22441. if (instanceGeometry.length > 0) {
  22442. geometries.push(combineGeometries(instanceGeometry, 'geometry'));
  22443. }
  22444. if (instanceSplitGeometry.length > 0) {
  22445. geometries.push(combineGeometries(instanceSplitGeometry, 'westHemisphereGeometry'));
  22446. geometries.push(combineGeometries(instanceSplitGeometry, 'eastHemisphereGeometry'));
  22447. }
  22448. return geometries;
  22449. };
  22450. var normal = new Cartesian3();
  22451. var v0 = new Cartesian3();
  22452. var v1 = new Cartesian3();
  22453. var v2 = new Cartesian3();
  22454. /**
  22455. * Computes per-vertex normals for a geometry containing <code>TRIANGLES</code> by averaging the normals of
  22456. * all triangles incident to the vertex. The result is a new <code>normal</code> attribute added to the geometry.
  22457. * This assumes a counter-clockwise winding order.
  22458. *
  22459. * @param {Geometry} geometry The geometry to modify.
  22460. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>normal</code> attribute.
  22461. *
  22462. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  22463. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  22464. *
  22465. * @example
  22466. * Cesium.GeometryPipeline.computeNormal(geometry);
  22467. */
  22468. GeometryPipeline.computeNormal = function(geometry) {
  22469. if (!defined(geometry)) {
  22470. throw new DeveloperError('geometry is required.');
  22471. }
  22472. if (!defined(geometry.attributes.position) || !defined(geometry.attributes.position.values)) {
  22473. throw new DeveloperError('geometry.attributes.position.values is required.');
  22474. }
  22475. if (!defined(geometry.indices)) {
  22476. throw new DeveloperError('geometry.indices is required.');
  22477. }
  22478. if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) {
  22479. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  22480. }
  22481. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  22482. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  22483. }
  22484. var indices = geometry.indices;
  22485. var attributes = geometry.attributes;
  22486. var vertices = attributes.position.values;
  22487. var numVertices = attributes.position.values.length / 3;
  22488. var numIndices = indices.length;
  22489. var normalsPerVertex = new Array(numVertices);
  22490. var normalsPerTriangle = new Array(numIndices / 3);
  22491. var normalIndices = new Array(numIndices);
  22492. for ( var i = 0; i < numVertices; i++) {
  22493. normalsPerVertex[i] = {
  22494. indexOffset : 0,
  22495. count : 0,
  22496. currentCount : 0
  22497. };
  22498. }
  22499. var j = 0;
  22500. for (i = 0; i < numIndices; i += 3) {
  22501. var i0 = indices[i];
  22502. var i1 = indices[i + 1];
  22503. var i2 = indices[i + 2];
  22504. var i03 = i0 * 3;
  22505. var i13 = i1 * 3;
  22506. var i23 = i2 * 3;
  22507. v0.x = vertices[i03];
  22508. v0.y = vertices[i03 + 1];
  22509. v0.z = vertices[i03 + 2];
  22510. v1.x = vertices[i13];
  22511. v1.y = vertices[i13 + 1];
  22512. v1.z = vertices[i13 + 2];
  22513. v2.x = vertices[i23];
  22514. v2.y = vertices[i23 + 1];
  22515. v2.z = vertices[i23 + 2];
  22516. normalsPerVertex[i0].count++;
  22517. normalsPerVertex[i1].count++;
  22518. normalsPerVertex[i2].count++;
  22519. Cartesian3.subtract(v1, v0, v1);
  22520. Cartesian3.subtract(v2, v0, v2);
  22521. normalsPerTriangle[j] = Cartesian3.cross(v1, v2, new Cartesian3());
  22522. j++;
  22523. }
  22524. var indexOffset = 0;
  22525. for (i = 0; i < numVertices; i++) {
  22526. normalsPerVertex[i].indexOffset += indexOffset;
  22527. indexOffset += normalsPerVertex[i].count;
  22528. }
  22529. j = 0;
  22530. var vertexNormalData;
  22531. for (i = 0; i < numIndices; i += 3) {
  22532. vertexNormalData = normalsPerVertex[indices[i]];
  22533. var index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  22534. normalIndices[index] = j;
  22535. vertexNormalData.currentCount++;
  22536. vertexNormalData = normalsPerVertex[indices[i + 1]];
  22537. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  22538. normalIndices[index] = j;
  22539. vertexNormalData.currentCount++;
  22540. vertexNormalData = normalsPerVertex[indices[i + 2]];
  22541. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  22542. normalIndices[index] = j;
  22543. vertexNormalData.currentCount++;
  22544. j++;
  22545. }
  22546. var normalValues = new Float32Array(numVertices * 3);
  22547. for (i = 0; i < numVertices; i++) {
  22548. var i3 = i * 3;
  22549. vertexNormalData = normalsPerVertex[i];
  22550. if (vertexNormalData.count > 0) {
  22551. Cartesian3.clone(Cartesian3.ZERO, normal);
  22552. for (j = 0; j < vertexNormalData.count; j++) {
  22553. Cartesian3.add(normal, normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]], normal);
  22554. }
  22555. Cartesian3.normalize(normal, normal);
  22556. normalValues[i3] = normal.x;
  22557. normalValues[i3 + 1] = normal.y;
  22558. normalValues[i3 + 2] = normal.z;
  22559. } else {
  22560. normalValues[i3] = 0.0;
  22561. normalValues[i3 + 1] = 0.0;
  22562. normalValues[i3 + 2] = 1.0;
  22563. }
  22564. }
  22565. geometry.attributes.normal = new GeometryAttribute({
  22566. componentDatatype : ComponentDatatype.FLOAT,
  22567. componentsPerAttribute : 3,
  22568. values : normalValues
  22569. });
  22570. return geometry;
  22571. };
  22572. var normalScratch = new Cartesian3();
  22573. var normalScale = new Cartesian3();
  22574. var tScratch = new Cartesian3();
  22575. /**
  22576. * Computes per-vertex binormals and tangents for a geometry containing <code>TRIANGLES</code>.
  22577. * The result is new <code>binormal</code> and <code>tangent</code> attributes added to the geometry.
  22578. * This assumes a counter-clockwise winding order.
  22579. * <p>
  22580. * Based on <a href="http://www.terathon.com/code/tangent.html">Computing Tangent Space Basis Vectors
  22581. * for an Arbitrary Mesh</a> by Eric Lengyel.
  22582. * </p>
  22583. *
  22584. * @param {Geometry} geometry The geometry to modify.
  22585. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>binormal</code> and <code>tangent</code> attributes.
  22586. *
  22587. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  22588. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  22589. *
  22590. * @example
  22591. * Cesium.GeometryPipeline.computeBinormalAndTangent(geometry);
  22592. */
  22593. GeometryPipeline.computeBinormalAndTangent = function(geometry) {
  22594. if (!defined(geometry)) {
  22595. throw new DeveloperError('geometry is required.');
  22596. }
  22597. var attributes = geometry.attributes;
  22598. var indices = geometry.indices;
  22599. if (!defined(attributes.position) || !defined(attributes.position.values)) {
  22600. throw new DeveloperError('geometry.attributes.position.values is required.');
  22601. }
  22602. if (!defined(attributes.normal) || !defined(attributes.normal.values)) {
  22603. throw new DeveloperError('geometry.attributes.normal.values is required.');
  22604. }
  22605. if (!defined(attributes.st) || !defined(attributes.st.values)) {
  22606. throw new DeveloperError('geometry.attributes.st.values is required.');
  22607. }
  22608. if (!defined(indices)) {
  22609. throw new DeveloperError('geometry.indices is required.');
  22610. }
  22611. if (indices.length < 2 || indices.length % 3 !== 0) {
  22612. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  22613. }
  22614. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  22615. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  22616. }
  22617. var vertices = geometry.attributes.position.values;
  22618. var normals = geometry.attributes.normal.values;
  22619. var st = geometry.attributes.st.values;
  22620. var numVertices = geometry.attributes.position.values.length / 3;
  22621. var numIndices = indices.length;
  22622. var tan1 = new Array(numVertices * 3);
  22623. for ( var i = 0; i < tan1.length; i++) {
  22624. tan1[i] = 0;
  22625. }
  22626. var i03;
  22627. var i13;
  22628. var i23;
  22629. for (i = 0; i < numIndices; i += 3) {
  22630. var i0 = indices[i];
  22631. var i1 = indices[i + 1];
  22632. var i2 = indices[i + 2];
  22633. i03 = i0 * 3;
  22634. i13 = i1 * 3;
  22635. i23 = i2 * 3;
  22636. var i02 = i0 * 2;
  22637. var i12 = i1 * 2;
  22638. var i22 = i2 * 2;
  22639. var ux = vertices[i03];
  22640. var uy = vertices[i03 + 1];
  22641. var uz = vertices[i03 + 2];
  22642. var wx = st[i02];
  22643. var wy = st[i02 + 1];
  22644. var t1 = st[i12 + 1] - wy;
  22645. var t2 = st[i22 + 1] - wy;
  22646. var r = 1.0 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1);
  22647. var sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r;
  22648. var sdiry = (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r;
  22649. var sdirz = (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r;
  22650. tan1[i03] += sdirx;
  22651. tan1[i03 + 1] += sdiry;
  22652. tan1[i03 + 2] += sdirz;
  22653. tan1[i13] += sdirx;
  22654. tan1[i13 + 1] += sdiry;
  22655. tan1[i13 + 2] += sdirz;
  22656. tan1[i23] += sdirx;
  22657. tan1[i23 + 1] += sdiry;
  22658. tan1[i23 + 2] += sdirz;
  22659. }
  22660. var binormalValues = new Float32Array(numVertices * 3);
  22661. var tangentValues = new Float32Array(numVertices * 3);
  22662. for (i = 0; i < numVertices; i++) {
  22663. i03 = i * 3;
  22664. i13 = i03 + 1;
  22665. i23 = i03 + 2;
  22666. var n = Cartesian3.fromArray(normals, i03, normalScratch);
  22667. var t = Cartesian3.fromArray(tan1, i03, tScratch);
  22668. var scalar = Cartesian3.dot(n, t);
  22669. Cartesian3.multiplyByScalar(n, scalar, normalScale);
  22670. Cartesian3.normalize(Cartesian3.subtract(t, normalScale, t), t);
  22671. tangentValues[i03] = t.x;
  22672. tangentValues[i13] = t.y;
  22673. tangentValues[i23] = t.z;
  22674. Cartesian3.normalize(Cartesian3.cross(n, t, t), t);
  22675. binormalValues[i03] = t.x;
  22676. binormalValues[i13] = t.y;
  22677. binormalValues[i23] = t.z;
  22678. }
  22679. geometry.attributes.tangent = new GeometryAttribute({
  22680. componentDatatype : ComponentDatatype.FLOAT,
  22681. componentsPerAttribute : 3,
  22682. values : tangentValues
  22683. });
  22684. geometry.attributes.binormal = new GeometryAttribute({
  22685. componentDatatype : ComponentDatatype.FLOAT,
  22686. componentsPerAttribute : 3,
  22687. values : binormalValues
  22688. });
  22689. return geometry;
  22690. };
  22691. var scratchCartesian2 = new Cartesian2();
  22692. var toEncode1 = new Cartesian3();
  22693. var toEncode2 = new Cartesian3();
  22694. var toEncode3 = new Cartesian3();
  22695. /**
  22696. * Compresses and packs geometry normal attribute values to save memory.
  22697. *
  22698. * @param {Geometry} geometry The geometry to modify.
  22699. * @returns {Geometry} The modified <code>geometry</code> argument, with its normals compressed and packed.
  22700. *
  22701. * @example
  22702. * geometry = Cesium.GeometryPipeline.compressVertices(geometry);
  22703. */
  22704. GeometryPipeline.compressVertices = function(geometry) {
  22705. if (!defined(geometry)) {
  22706. throw new DeveloperError('geometry is required.');
  22707. }
  22708. var normalAttribute = geometry.attributes.normal;
  22709. var stAttribute = geometry.attributes.st;
  22710. if (!defined(normalAttribute) && !defined(stAttribute)) {
  22711. return geometry;
  22712. }
  22713. var tangentAttribute = geometry.attributes.tangent;
  22714. var binormalAttribute = geometry.attributes.binormal;
  22715. var normals;
  22716. var st;
  22717. var tangents;
  22718. var binormals;
  22719. if (defined(normalAttribute)) {
  22720. normals = normalAttribute.values;
  22721. }
  22722. if (defined(stAttribute)) {
  22723. st = stAttribute.values;
  22724. }
  22725. if (defined(tangentAttribute)) {
  22726. tangents = tangentAttribute.values;
  22727. }
  22728. if (binormalAttribute) {
  22729. binormals = binormalAttribute.values;
  22730. }
  22731. var length = defined(normals) ? normals.length : st.length;
  22732. var numComponents = defined(normals) ? 3.0 : 2.0;
  22733. var numVertices = length / numComponents;
  22734. var compressedLength = numVertices;
  22735. var numCompressedComponents = defined(st) && defined(normals) ? 2.0 : 1.0;
  22736. numCompressedComponents += defined(tangents) || defined(binormals) ? 1.0 : 0.0;
  22737. compressedLength *= numCompressedComponents;
  22738. var compressedAttributes = new Float32Array(compressedLength);
  22739. var normalIndex = 0;
  22740. for (var i = 0; i < numVertices; ++i) {
  22741. if (defined(st)) {
  22742. Cartesian2.fromArray(st, i * 2.0, scratchCartesian2);
  22743. compressedAttributes[normalIndex++] = AttributeCompression.compressTextureCoordinates(scratchCartesian2);
  22744. }
  22745. var index = i * 3.0;
  22746. if (defined(normals) && defined(tangents) && defined(binormals)) {
  22747. Cartesian3.fromArray(normals, index, toEncode1);
  22748. Cartesian3.fromArray(tangents, index, toEncode2);
  22749. Cartesian3.fromArray(binormals, index, toEncode3);
  22750. AttributeCompression.octPack(toEncode1, toEncode2, toEncode3, scratchCartesian2);
  22751. compressedAttributes[normalIndex++] = scratchCartesian2.x;
  22752. compressedAttributes[normalIndex++] = scratchCartesian2.y;
  22753. } else {
  22754. if (defined(normals)) {
  22755. Cartesian3.fromArray(normals, index, toEncode1);
  22756. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  22757. }
  22758. if (defined(tangents)) {
  22759. Cartesian3.fromArray(tangents, index, toEncode1);
  22760. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  22761. }
  22762. if (defined(binormals)) {
  22763. Cartesian3.fromArray(binormals, index, toEncode1);
  22764. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  22765. }
  22766. }
  22767. }
  22768. geometry.attributes.compressedAttributes = new GeometryAttribute({
  22769. componentDatatype : ComponentDatatype.FLOAT,
  22770. componentsPerAttribute : numCompressedComponents,
  22771. values : compressedAttributes
  22772. });
  22773. if (defined(normals)) {
  22774. delete geometry.attributes.normal;
  22775. }
  22776. if (defined(st)) {
  22777. delete geometry.attributes.st;
  22778. }
  22779. if (defined(tangents)) {
  22780. delete geometry.attributes.tangent;
  22781. }
  22782. if (defined(binormals)) {
  22783. delete geometry.attributes.binormal;
  22784. }
  22785. return geometry;
  22786. };
  22787. function indexTriangles(geometry) {
  22788. if (defined(geometry.indices)) {
  22789. return geometry;
  22790. }
  22791. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22792. if (numberOfVertices < 3) {
  22793. throw new DeveloperError('The number of vertices must be at least three.');
  22794. }
  22795. if (numberOfVertices % 3 !== 0) {
  22796. throw new DeveloperError('The number of vertices must be a multiple of three.');
  22797. }
  22798. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  22799. for (var i = 0; i < numberOfVertices; ++i) {
  22800. indices[i] = i;
  22801. }
  22802. geometry.indices = indices;
  22803. return geometry;
  22804. }
  22805. function indexTriangleFan(geometry) {
  22806. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22807. if (numberOfVertices < 3) {
  22808. throw new DeveloperError('The number of vertices must be at least three.');
  22809. }
  22810. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  22811. indices[0] = 1;
  22812. indices[1] = 0;
  22813. indices[2] = 2;
  22814. var indicesIndex = 3;
  22815. for (var i = 3; i < numberOfVertices; ++i) {
  22816. indices[indicesIndex++] = i - 1;
  22817. indices[indicesIndex++] = 0;
  22818. indices[indicesIndex++] = i;
  22819. }
  22820. geometry.indices = indices;
  22821. geometry.primitiveType = PrimitiveType.TRIANGLES;
  22822. return geometry;
  22823. }
  22824. function indexTriangleStrip(geometry) {
  22825. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22826. if (numberOfVertices < 3) {
  22827. throw new DeveloperError('The number of vertices must be at least 3.');
  22828. }
  22829. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  22830. indices[0] = 0;
  22831. indices[1] = 1;
  22832. indices[2] = 2;
  22833. if (numberOfVertices > 3) {
  22834. indices[3] = 0;
  22835. indices[4] = 2;
  22836. indices[5] = 3;
  22837. }
  22838. var indicesIndex = 6;
  22839. for (var i = 3; i < numberOfVertices - 1; i += 2) {
  22840. indices[indicesIndex++] = i;
  22841. indices[indicesIndex++] = i - 1;
  22842. indices[indicesIndex++] = i + 1;
  22843. if (i + 2 < numberOfVertices) {
  22844. indices[indicesIndex++] = i;
  22845. indices[indicesIndex++] = i + 1;
  22846. indices[indicesIndex++] = i + 2;
  22847. }
  22848. }
  22849. geometry.indices = indices;
  22850. geometry.primitiveType = PrimitiveType.TRIANGLES;
  22851. return geometry;
  22852. }
  22853. function indexLines(geometry) {
  22854. if (defined(geometry.indices)) {
  22855. return geometry;
  22856. }
  22857. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22858. if (numberOfVertices < 2) {
  22859. throw new DeveloperError('The number of vertices must be at least two.');
  22860. }
  22861. if (numberOfVertices % 2 !== 0) {
  22862. throw new DeveloperError('The number of vertices must be a multiple of 2.');
  22863. }
  22864. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  22865. for (var i = 0; i < numberOfVertices; ++i) {
  22866. indices[i] = i;
  22867. }
  22868. geometry.indices = indices;
  22869. return geometry;
  22870. }
  22871. function indexLineStrip(geometry) {
  22872. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22873. if (numberOfVertices < 2) {
  22874. throw new DeveloperError('The number of vertices must be at least two.');
  22875. }
  22876. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 1) * 2);
  22877. indices[0] = 0;
  22878. indices[1] = 1;
  22879. var indicesIndex = 2;
  22880. for (var i = 2; i < numberOfVertices; ++i) {
  22881. indices[indicesIndex++] = i - 1;
  22882. indices[indicesIndex++] = i;
  22883. }
  22884. geometry.indices = indices;
  22885. geometry.primitiveType = PrimitiveType.LINES;
  22886. return geometry;
  22887. }
  22888. function indexLineLoop(geometry) {
  22889. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  22890. if (numberOfVertices < 2) {
  22891. throw new DeveloperError('The number of vertices must be at least two.');
  22892. }
  22893. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices * 2);
  22894. indices[0] = 0;
  22895. indices[1] = 1;
  22896. var indicesIndex = 2;
  22897. for (var i = 2; i < numberOfVertices; ++i) {
  22898. indices[indicesIndex++] = i - 1;
  22899. indices[indicesIndex++] = i;
  22900. }
  22901. indices[indicesIndex++] = numberOfVertices - 1;
  22902. indices[indicesIndex] = 0;
  22903. geometry.indices = indices;
  22904. geometry.primitiveType = PrimitiveType.LINES;
  22905. return geometry;
  22906. }
  22907. function indexPrimitive(geometry) {
  22908. switch (geometry.primitiveType) {
  22909. case PrimitiveType.TRIANGLE_FAN:
  22910. return indexTriangleFan(geometry);
  22911. case PrimitiveType.TRIANGLE_STRIP:
  22912. return indexTriangleStrip(geometry);
  22913. case PrimitiveType.TRIANGLES:
  22914. return indexTriangles(geometry);
  22915. case PrimitiveType.LINE_STRIP:
  22916. return indexLineStrip(geometry);
  22917. case PrimitiveType.LINE_LOOP:
  22918. return indexLineLoop(geometry);
  22919. case PrimitiveType.LINES:
  22920. return indexLines(geometry);
  22921. }
  22922. return geometry;
  22923. }
  22924. function offsetPointFromXZPlane(p, isBehind) {
  22925. if (Math.abs(p.y) < CesiumMath.EPSILON6){
  22926. if (isBehind) {
  22927. p.y = -CesiumMath.EPSILON6;
  22928. } else {
  22929. p.y = CesiumMath.EPSILON6;
  22930. }
  22931. }
  22932. }
  22933. function offsetTriangleFromXZPlane(p0, p1, p2) {
  22934. if (p0.y !== 0.0 && p1.y !== 0.0 && p2.y !== 0.0) {
  22935. offsetPointFromXZPlane(p0, p0.y < 0.0);
  22936. offsetPointFromXZPlane(p1, p1.y < 0.0);
  22937. offsetPointFromXZPlane(p2, p2.y < 0.0);
  22938. return;
  22939. }
  22940. var p0y = Math.abs(p0.y);
  22941. var p1y = Math.abs(p1.y);
  22942. var p2y = Math.abs(p2.y);
  22943. var sign;
  22944. if (p0y > p1y) {
  22945. if (p0y > p2y) {
  22946. sign = CesiumMath.sign(p0.y);
  22947. } else {
  22948. sign = CesiumMath.sign(p2.y);
  22949. }
  22950. } else if (p1y > p2y) {
  22951. sign = CesiumMath.sign(p1.y);
  22952. } else {
  22953. sign = CesiumMath.sign(p2.y);
  22954. }
  22955. var isBehind = sign < 0.0;
  22956. offsetPointFromXZPlane(p0, isBehind);
  22957. offsetPointFromXZPlane(p1, isBehind);
  22958. offsetPointFromXZPlane(p2, isBehind);
  22959. }
  22960. var c3 = new Cartesian3();
  22961. function getXZIntersectionOffsetPoints(p, p1, u1, v1) {
  22962. Cartesian3.add(p, Cartesian3.multiplyByScalar(Cartesian3.subtract(p1, p, c3), p.y/(p.y-p1.y), c3), u1);
  22963. Cartesian3.clone(u1, v1);
  22964. offsetPointFromXZPlane(u1, true);
  22965. offsetPointFromXZPlane(v1, false);
  22966. }
  22967. var u1 = new Cartesian3();
  22968. var u2 = new Cartesian3();
  22969. var q1 = new Cartesian3();
  22970. var q2 = new Cartesian3();
  22971. var splitTriangleResult = {
  22972. positions : new Array(7),
  22973. indices : new Array(3 * 3)
  22974. };
  22975. function splitTriangle(p0, p1, p2) {
  22976. // In WGS84 coordinates, for a triangle approximately on the
  22977. // ellipsoid to cross the IDL, first it needs to be on the
  22978. // negative side of the plane x = 0.
  22979. if ((p0.x >= 0.0) || (p1.x >= 0.0) || (p2.x >= 0.0)) {
  22980. return undefined;
  22981. }
  22982. offsetTriangleFromXZPlane(p0, p1, p2);
  22983. var p0Behind = p0.y < 0.0;
  22984. var p1Behind = p1.y < 0.0;
  22985. var p2Behind = p2.y < 0.0;
  22986. var numBehind = 0;
  22987. numBehind += p0Behind ? 1 : 0;
  22988. numBehind += p1Behind ? 1 : 0;
  22989. numBehind += p2Behind ? 1 : 0;
  22990. var indices = splitTriangleResult.indices;
  22991. if (numBehind === 1) {
  22992. indices[1] = 3;
  22993. indices[2] = 4;
  22994. indices[5] = 6;
  22995. indices[7] = 6;
  22996. indices[8] = 5;
  22997. if (p0Behind) {
  22998. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  22999. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  23000. indices[0] = 0;
  23001. indices[3] = 1;
  23002. indices[4] = 2;
  23003. indices[6] = 1;
  23004. } else if (p1Behind) {
  23005. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  23006. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  23007. indices[0] = 1;
  23008. indices[3] = 2;
  23009. indices[4] = 0;
  23010. indices[6] = 2;
  23011. } else if (p2Behind) {
  23012. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  23013. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  23014. indices[0] = 2;
  23015. indices[3] = 0;
  23016. indices[4] = 1;
  23017. indices[6] = 0;
  23018. }
  23019. } else if (numBehind === 2) {
  23020. indices[2] = 4;
  23021. indices[4] = 4;
  23022. indices[5] = 3;
  23023. indices[7] = 5;
  23024. indices[8] = 6;
  23025. if (!p0Behind) {
  23026. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  23027. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  23028. indices[0] = 1;
  23029. indices[1] = 2;
  23030. indices[3] = 1;
  23031. indices[6] = 0;
  23032. } else if (!p1Behind) {
  23033. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  23034. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  23035. indices[0] = 2;
  23036. indices[1] = 0;
  23037. indices[3] = 2;
  23038. indices[6] = 1;
  23039. } else if (!p2Behind) {
  23040. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  23041. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  23042. indices[0] = 0;
  23043. indices[1] = 1;
  23044. indices[3] = 0;
  23045. indices[6] = 2;
  23046. }
  23047. }
  23048. var positions = splitTriangleResult.positions;
  23049. positions[0] = p0;
  23050. positions[1] = p1;
  23051. positions[2] = p2;
  23052. positions.length = 3;
  23053. if (numBehind === 1 || numBehind === 2) {
  23054. positions[3] = u1;
  23055. positions[4] = u2;
  23056. positions[5] = q1;
  23057. positions[6] = q2;
  23058. positions.length = 7;
  23059. }
  23060. return splitTriangleResult;
  23061. }
  23062. function updateGeometryAfterSplit(geometry, computeBoundingSphere) {
  23063. var attributes = geometry.attributes;
  23064. if (attributes.position.values.length === 0) {
  23065. return undefined;
  23066. }
  23067. for (var property in attributes) {
  23068. if (attributes.hasOwnProperty(property) &&
  23069. defined(attributes[property]) &&
  23070. defined(attributes[property].values)) {
  23071. var attribute = attributes[property];
  23072. attribute.values = ComponentDatatype.createTypedArray(attribute.componentDatatype, attribute.values);
  23073. }
  23074. }
  23075. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  23076. geometry.indices = IndexDatatype.createTypedArray(numberOfVertices, geometry.indices);
  23077. if (computeBoundingSphere) {
  23078. geometry.boundingSphere = BoundingSphere.fromVertices(attributes.position.values);
  23079. }
  23080. return geometry;
  23081. }
  23082. function copyGeometryForSplit(geometry) {
  23083. var attributes = geometry.attributes;
  23084. var copiedAttributes = {};
  23085. for (var property in attributes) {
  23086. if (attributes.hasOwnProperty(property) &&
  23087. defined(attributes[property]) &&
  23088. defined(attributes[property].values)) {
  23089. var attribute = attributes[property];
  23090. copiedAttributes[property] = new GeometryAttribute({
  23091. componentDatatype : attribute.componentDatatype,
  23092. componentsPerAttribute : attribute.componentsPerAttribute,
  23093. normalize : attribute.normalize,
  23094. values : []
  23095. });
  23096. }
  23097. }
  23098. return new Geometry({
  23099. attributes : copiedAttributes,
  23100. indices : [],
  23101. primitiveType : geometry.primitiveType
  23102. });
  23103. }
  23104. function updateInstanceAfterSplit(instance, westGeometry, eastGeometry) {
  23105. var computeBoundingSphere = defined(instance.geometry.boundingSphere);
  23106. westGeometry = updateGeometryAfterSplit(westGeometry, computeBoundingSphere);
  23107. eastGeometry = updateGeometryAfterSplit(eastGeometry, computeBoundingSphere);
  23108. if (defined(eastGeometry) && !defined(westGeometry)) {
  23109. instance.geometry = eastGeometry;
  23110. } else if (!defined(eastGeometry) && defined(westGeometry)) {
  23111. instance.geometry = westGeometry;
  23112. } else {
  23113. instance.westHemisphereGeometry = westGeometry;
  23114. instance.eastHemisphereGeometry = eastGeometry;
  23115. instance.geometry = undefined;
  23116. }
  23117. }
  23118. var p0Scratch = new Cartesian3();
  23119. var p1Scratch = new Cartesian3();
  23120. var p2Scratch = new Cartesian3();
  23121. var barycentricScratch = new Cartesian3();
  23122. var s0Scratch = new Cartesian2();
  23123. var s1Scratch = new Cartesian2();
  23124. var s2Scratch = new Cartesian2();
  23125. function computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex) {
  23126. if (!defined(normals) && !defined(binormals) && !defined(tangents) && !defined(texCoords)) {
  23127. return;
  23128. }
  23129. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  23130. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  23131. var p2 = Cartesian3.fromArray(positions, i2 * 3, p2Scratch);
  23132. var coords = barycentricCoordinates(point, p0, p1, p2, barycentricScratch);
  23133. if (defined(normals)) {
  23134. var n0 = Cartesian3.fromArray(normals, i0 * 3, p0Scratch);
  23135. var n1 = Cartesian3.fromArray(normals, i1 * 3, p1Scratch);
  23136. var n2 = Cartesian3.fromArray(normals, i2 * 3, p2Scratch);
  23137. Cartesian3.multiplyByScalar(n0, coords.x, n0);
  23138. Cartesian3.multiplyByScalar(n1, coords.y, n1);
  23139. Cartesian3.multiplyByScalar(n2, coords.z, n2);
  23140. var normal = Cartesian3.add(n0, n1, n0);
  23141. Cartesian3.add(normal, n2, normal);
  23142. Cartesian3.normalize(normal, normal);
  23143. Cartesian3.pack(normal, currentAttributes.normal.values, insertedIndex * 3);
  23144. }
  23145. if (defined(binormals)) {
  23146. var b0 = Cartesian3.fromArray(binormals, i0 * 3, p0Scratch);
  23147. var b1 = Cartesian3.fromArray(binormals, i1 * 3, p1Scratch);
  23148. var b2 = Cartesian3.fromArray(binormals, i2 * 3, p2Scratch);
  23149. Cartesian3.multiplyByScalar(b0, coords.x, b0);
  23150. Cartesian3.multiplyByScalar(b1, coords.y, b1);
  23151. Cartesian3.multiplyByScalar(b2, coords.z, b2);
  23152. var binormal = Cartesian3.add(b0, b1, b0);
  23153. Cartesian3.add(binormal, b2, binormal);
  23154. Cartesian3.normalize(binormal, binormal);
  23155. Cartesian3.pack(binormal, currentAttributes.binormal.values, insertedIndex * 3);
  23156. }
  23157. if (defined(tangents)) {
  23158. var t0 = Cartesian3.fromArray(tangents, i0 * 3, p0Scratch);
  23159. var t1 = Cartesian3.fromArray(tangents, i1 * 3, p1Scratch);
  23160. var t2 = Cartesian3.fromArray(tangents, i2 * 3, p2Scratch);
  23161. Cartesian3.multiplyByScalar(t0, coords.x, t0);
  23162. Cartesian3.multiplyByScalar(t1, coords.y, t1);
  23163. Cartesian3.multiplyByScalar(t2, coords.z, t2);
  23164. var tangent = Cartesian3.add(t0, t1, t0);
  23165. Cartesian3.add(tangent, t2, tangent);
  23166. Cartesian3.normalize(tangent, tangent);
  23167. Cartesian3.pack(tangent, currentAttributes.tangent.values, insertedIndex * 3);
  23168. }
  23169. if (defined(texCoords)) {
  23170. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, s0Scratch);
  23171. var s1 = Cartesian2.fromArray(texCoords, i1 * 2, s1Scratch);
  23172. var s2 = Cartesian2.fromArray(texCoords, i2 * 2, s2Scratch);
  23173. Cartesian2.multiplyByScalar(s0, coords.x, s0);
  23174. Cartesian2.multiplyByScalar(s1, coords.y, s1);
  23175. Cartesian2.multiplyByScalar(s2, coords.z, s2);
  23176. var texCoord = Cartesian2.add(s0, s1, s0);
  23177. Cartesian2.add(texCoord, s2, texCoord);
  23178. Cartesian2.pack(texCoord, currentAttributes.st.values, insertedIndex * 2);
  23179. }
  23180. }
  23181. function insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, currentIndex, point) {
  23182. var insertIndex = currentAttributes.position.values.length / 3;
  23183. if (currentIndex !== -1) {
  23184. var prevIndex = indices[currentIndex];
  23185. var newIndex = currentIndexMap[prevIndex];
  23186. if (newIndex === -1) {
  23187. currentIndexMap[prevIndex] = insertIndex;
  23188. currentAttributes.position.values.push(point.x, point.y, point.z);
  23189. currentIndices.push(insertIndex);
  23190. return insertIndex;
  23191. }
  23192. currentIndices.push(newIndex);
  23193. return newIndex;
  23194. }
  23195. currentAttributes.position.values.push(point.x, point.y, point.z);
  23196. currentIndices.push(insertIndex);
  23197. return insertIndex;
  23198. }
  23199. function splitLongitudeTriangles(instance) {
  23200. var geometry = instance.geometry;
  23201. var attributes = geometry.attributes;
  23202. var positions = attributes.position.values;
  23203. var normals = (defined(attributes.normal)) ? attributes.normal.values : undefined;
  23204. var binormals = (defined(attributes.binormal)) ? attributes.binormal.values : undefined;
  23205. var tangents = (defined(attributes.tangent)) ? attributes.tangent.values : undefined;
  23206. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  23207. var indices = geometry.indices;
  23208. var eastGeometry = copyGeometryForSplit(geometry);
  23209. var westGeometry = copyGeometryForSplit(geometry);
  23210. var currentAttributes;
  23211. var currentIndices;
  23212. var currentIndexMap;
  23213. var insertedIndex;
  23214. var i;
  23215. var westGeometryIndexMap = [];
  23216. westGeometryIndexMap.length = positions.length / 3;
  23217. var eastGeometryIndexMap = [];
  23218. eastGeometryIndexMap.length = positions.length / 3;
  23219. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  23220. westGeometryIndexMap[i] = -1;
  23221. eastGeometryIndexMap[i] = -1;
  23222. }
  23223. var len = indices.length;
  23224. for (i = 0; i < len; i += 3) {
  23225. var i0 = indices[i];
  23226. var i1 = indices[i + 1];
  23227. var i2 = indices[i + 2];
  23228. var p0 = Cartesian3.fromArray(positions, i0 * 3);
  23229. var p1 = Cartesian3.fromArray(positions, i1 * 3);
  23230. var p2 = Cartesian3.fromArray(positions, i2 * 3);
  23231. var result = splitTriangle(p0, p1, p2);
  23232. if (defined(result) && result.positions.length > 3) {
  23233. var resultPositions = result.positions;
  23234. var resultIndices = result.indices;
  23235. var resultLength = resultIndices.length;
  23236. for (var j = 0; j < resultLength; ++j) {
  23237. var resultIndex = resultIndices[j];
  23238. var point = resultPositions[resultIndex];
  23239. if (point.y < 0.0) {
  23240. currentAttributes = westGeometry.attributes;
  23241. currentIndices = westGeometry.indices;
  23242. currentIndexMap = westGeometryIndexMap;
  23243. } else {
  23244. currentAttributes = eastGeometry.attributes;
  23245. currentIndices = eastGeometry.indices;
  23246. currentIndexMap = eastGeometryIndexMap;
  23247. }
  23248. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, resultIndex < 3 ? i + resultIndex : -1, point);
  23249. computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23250. }
  23251. } else {
  23252. if (defined(result)) {
  23253. p0 = result.positions[0];
  23254. p1 = result.positions[1];
  23255. p2 = result.positions[2];
  23256. }
  23257. if (p0.y < 0.0) {
  23258. currentAttributes = westGeometry.attributes;
  23259. currentIndices = westGeometry.indices;
  23260. currentIndexMap = westGeometryIndexMap;
  23261. } else {
  23262. currentAttributes = eastGeometry.attributes;
  23263. currentIndices = eastGeometry.indices;
  23264. currentIndexMap = eastGeometryIndexMap;
  23265. }
  23266. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  23267. computeTriangleAttributes(i0, i1, i2, p0, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23268. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  23269. computeTriangleAttributes(i0, i1, i2, p1, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23270. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 2, p2);
  23271. computeTriangleAttributes(i0, i1, i2, p2, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  23272. }
  23273. }
  23274. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  23275. }
  23276. var xzPlane = Plane.fromPointNormal(Cartesian3.ZERO, Cartesian3.UNIT_Y);
  23277. var offsetScratch = new Cartesian3();
  23278. var offsetPointScratch = new Cartesian3();
  23279. function splitLongitudeLines(instance) {
  23280. var geometry = instance.geometry;
  23281. var attributes = geometry.attributes;
  23282. var positions = attributes.position.values;
  23283. var indices = geometry.indices;
  23284. var eastGeometry = copyGeometryForSplit(geometry);
  23285. var westGeometry = copyGeometryForSplit(geometry);
  23286. var i;
  23287. var length = indices.length;
  23288. var westGeometryIndexMap = [];
  23289. westGeometryIndexMap.length = positions.length / 3;
  23290. var eastGeometryIndexMap = [];
  23291. eastGeometryIndexMap.length = positions.length / 3;
  23292. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  23293. westGeometryIndexMap[i] = -1;
  23294. eastGeometryIndexMap[i] = -1;
  23295. }
  23296. for (i = 0; i < length; i += 2) {
  23297. var i0 = indices[i];
  23298. var i1 = indices[i + 1];
  23299. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  23300. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  23301. if (Math.abs(p0.y) < CesiumMath.EPSILON6){
  23302. if (p0.y < 0.0) {
  23303. p0.y = -CesiumMath.EPSILON6;
  23304. } else {
  23305. p0.y = CesiumMath.EPSILON6;
  23306. }
  23307. }
  23308. if (Math.abs(p1.y) < CesiumMath.EPSILON6){
  23309. if (p1.y < 0.0) {
  23310. p1.y = -CesiumMath.EPSILON6;
  23311. } else {
  23312. p1.y = CesiumMath.EPSILON6;
  23313. }
  23314. }
  23315. var p0Attributes = eastGeometry.attributes;
  23316. var p0Indices = eastGeometry.indices;
  23317. var p0IndexMap = eastGeometryIndexMap;
  23318. var p1Attributes = westGeometry.attributes;
  23319. var p1Indices = westGeometry.indices;
  23320. var p1IndexMap = westGeometryIndexMap;
  23321. var intersection = IntersectionTests.lineSegmentPlane(p0, p1, xzPlane, p2Scratch);
  23322. if (defined(intersection)) {
  23323. // move point on the xz-plane slightly away from the plane
  23324. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, 5.0 * CesiumMath.EPSILON9, offsetScratch);
  23325. if (p0.y < 0.0) {
  23326. Cartesian3.negate(offset, offset);
  23327. p0Attributes = westGeometry.attributes;
  23328. p0Indices = westGeometry.indices;
  23329. p0IndexMap = westGeometryIndexMap;
  23330. p1Attributes = eastGeometry.attributes;
  23331. p1Indices = eastGeometry.indices;
  23332. p1IndexMap = eastGeometryIndexMap;
  23333. }
  23334. var offsetPoint = Cartesian3.add(intersection, offset, offsetPointScratch);
  23335. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, i, p0);
  23336. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, -1, offsetPoint);
  23337. Cartesian3.negate(offset, offset);
  23338. Cartesian3.add(intersection, offset, offsetPoint);
  23339. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, -1, offsetPoint);
  23340. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, i + 1, p1);
  23341. } else {
  23342. var currentAttributes;
  23343. var currentIndices;
  23344. var currentIndexMap;
  23345. if (p0.y < 0.0) {
  23346. currentAttributes = westGeometry.attributes;
  23347. currentIndices = westGeometry.indices;
  23348. currentIndexMap = westGeometryIndexMap;
  23349. } else {
  23350. currentAttributes = eastGeometry.attributes;
  23351. currentIndices = eastGeometry.indices;
  23352. currentIndexMap = eastGeometryIndexMap;
  23353. }
  23354. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  23355. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  23356. }
  23357. }
  23358. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  23359. }
  23360. var cartesian2Scratch0 = new Cartesian2();
  23361. var cartesian2Scratch1 = new Cartesian2();
  23362. var cartesian3Scratch0 = new Cartesian3();
  23363. var cartesian3Scratch2 = new Cartesian3();
  23364. var cartesian3Scratch3 = new Cartesian3();
  23365. var cartesian3Scratch4 = new Cartesian3();
  23366. var cartesian3Scratch5 = new Cartesian3();
  23367. var cartesian3Scratch6 = new Cartesian3();
  23368. var cartesian4Scratch0 = new Cartesian4();
  23369. function updateAdjacencyAfterSplit(geometry) {
  23370. var attributes = geometry.attributes;
  23371. var positions = attributes.position.values;
  23372. var prevPositions = attributes.prevPosition.values;
  23373. var nextPositions = attributes.nextPosition.values;
  23374. var length = positions.length;
  23375. for (var j = 0; j < length; j += 3) {
  23376. var position = Cartesian3.unpack(positions, j, cartesian3Scratch0);
  23377. if (position.x > 0.0) {
  23378. continue;
  23379. }
  23380. var prevPosition = Cartesian3.unpack(prevPositions, j, cartesian3Scratch2);
  23381. if ((position.y < 0.0 && prevPosition.y > 0.0) || (position.y > 0.0 && prevPosition.y < 0.0)) {
  23382. if (j - 3 > 0) {
  23383. prevPositions[j] = positions[j - 3];
  23384. prevPositions[j + 1] = positions[j - 2];
  23385. prevPositions[j + 2] = positions[j - 1];
  23386. } else {
  23387. Cartesian3.pack(position, prevPositions, j);
  23388. }
  23389. }
  23390. var nextPosition = Cartesian3.unpack(nextPositions, j, cartesian3Scratch3);
  23391. if ((position.y < 0.0 && nextPosition.y > 0.0) || (position.y > 0.0 && nextPosition.y < 0.0)) {
  23392. if (j + 3 < length) {
  23393. nextPositions[j] = positions[j + 3];
  23394. nextPositions[j + 1] = positions[j + 4];
  23395. nextPositions[j + 2] = positions[j + 5];
  23396. } else {
  23397. Cartesian3.pack(position, nextPositions, j);
  23398. }
  23399. }
  23400. }
  23401. }
  23402. var offsetScalar = 5.0 * CesiumMath.EPSILON9;
  23403. var coplanarOffset = CesiumMath.EPSILON6;
  23404. function splitLongitudePolyline(instance) {
  23405. var geometry = instance.geometry;
  23406. var attributes = geometry.attributes;
  23407. var positions = attributes.position.values;
  23408. var prevPositions = attributes.prevPosition.values;
  23409. var nextPositions = attributes.nextPosition.values;
  23410. var expandAndWidths = attributes.expandAndWidth.values;
  23411. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  23412. var colors = (defined(attributes.color)) ? attributes.color.values : undefined;
  23413. var eastGeometry = copyGeometryForSplit(geometry);
  23414. var westGeometry = copyGeometryForSplit(geometry);
  23415. var i;
  23416. var j;
  23417. var index;
  23418. var intersectionFound = false;
  23419. var length = positions.length / 3;
  23420. for (i = 0; i < length; i += 4) {
  23421. var i0 = i;
  23422. var i2 = i + 2;
  23423. var p0 = Cartesian3.fromArray(positions, i0 * 3, cartesian3Scratch0);
  23424. var p2 = Cartesian3.fromArray(positions, i2 * 3, cartesian3Scratch2);
  23425. // Offset points that are close to the 180 longitude and change the previous/next point
  23426. // to be the same offset point so it can be projected to 2D. There is special handling in the
  23427. // shader for when position == prevPosition || position == nextPosition.
  23428. if (Math.abs(p0.y) < coplanarOffset) {
  23429. p0.y = coplanarOffset * (p2.y < 0.0 ? -1.0 : 1.0);
  23430. positions[i * 3 + 1] = p0.y;
  23431. positions[(i + 1) * 3 + 1] = p0.y;
  23432. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  23433. prevPositions[j] = positions[i * 3];
  23434. prevPositions[j + 1] = positions[i * 3 + 1];
  23435. prevPositions[j + 2] = positions[i * 3 + 2];
  23436. }
  23437. }
  23438. // Do the same but for when the line crosses 180 longitude in the opposite direction.
  23439. if (Math.abs(p2.y) < coplanarOffset) {
  23440. p2.y = coplanarOffset * (p0.y < 0.0 ? -1.0 : 1.0);
  23441. positions[(i + 2) * 3 + 1] = p2.y;
  23442. positions[(i + 3) * 3 + 1] = p2.y;
  23443. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  23444. nextPositions[j] = positions[(i + 2) * 3];
  23445. nextPositions[j + 1] = positions[(i + 2) * 3 + 1];
  23446. nextPositions[j + 2] = positions[(i + 2) * 3 + 2];
  23447. }
  23448. }
  23449. var p0Attributes = eastGeometry.attributes;
  23450. var p0Indices = eastGeometry.indices;
  23451. var p2Attributes = westGeometry.attributes;
  23452. var p2Indices = westGeometry.indices;
  23453. var intersection = IntersectionTests.lineSegmentPlane(p0, p2, xzPlane, cartesian3Scratch4);
  23454. if (defined(intersection)) {
  23455. intersectionFound = true;
  23456. // move point on the xz-plane slightly away from the plane
  23457. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, offsetScalar, cartesian3Scratch5);
  23458. if (p0.y < 0.0) {
  23459. Cartesian3.negate(offset, offset);
  23460. p0Attributes = westGeometry.attributes;
  23461. p0Indices = westGeometry.indices;
  23462. p2Attributes = eastGeometry.attributes;
  23463. p2Indices = eastGeometry.indices;
  23464. }
  23465. var offsetPoint = Cartesian3.add(intersection, offset, cartesian3Scratch6);
  23466. p0Attributes.position.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  23467. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23468. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23469. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3], prevPositions[i0 * 3 + 1], prevPositions[i0 * 3 + 2]);
  23470. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3 + 3], prevPositions[i0 * 3 + 4], prevPositions[i0 * 3 + 5]);
  23471. p0Attributes.prevPosition.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  23472. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23473. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23474. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23475. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23476. Cartesian3.negate(offset, offset);
  23477. Cartesian3.add(intersection, offset, offsetPoint);
  23478. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23479. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23480. p2Attributes.position.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  23481. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23482. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23483. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23484. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  23485. p2Attributes.nextPosition.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  23486. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3], nextPositions[i2 * 3 + 1], nextPositions[i2 * 3 + 2]);
  23487. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3 + 3], nextPositions[i2 * 3 + 4], nextPositions[i2 * 3 + 5]);
  23488. var ew0 = Cartesian2.fromArray(expandAndWidths, i0 * 2, cartesian2Scratch0);
  23489. var width = Math.abs(ew0.y);
  23490. p0Attributes.expandAndWidth.values.push(-1, width, 1, width);
  23491. p0Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  23492. p2Attributes.expandAndWidth.values.push(-1, width, 1, width);
  23493. p2Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  23494. var t = Cartesian3.magnitudeSquared(Cartesian3.subtract(intersection, p0, cartesian3Scratch3));
  23495. t /= Cartesian3.magnitudeSquared(Cartesian3.subtract(p2, p0, cartesian3Scratch3));
  23496. if (defined(colors)) {
  23497. var c0 = Cartesian4.fromArray(colors, i0 * 4, cartesian4Scratch0);
  23498. var c2 = Cartesian4.fromArray(colors, i2 * 4, cartesian4Scratch0);
  23499. var r = CesiumMath.lerp(c0.x, c2.x, t);
  23500. var g = CesiumMath.lerp(c0.y, c2.y, t);
  23501. var b = CesiumMath.lerp(c0.z, c2.z, t);
  23502. var a = CesiumMath.lerp(c0.w, c2.w, t);
  23503. for (j = i0 * 4; j < i0 * 4 + 2 * 4; ++j) {
  23504. p0Attributes.color.values.push(colors[j]);
  23505. }
  23506. p0Attributes.color.values.push(r, g, b, a);
  23507. p0Attributes.color.values.push(r, g, b, a);
  23508. p2Attributes.color.values.push(r, g, b, a);
  23509. p2Attributes.color.values.push(r, g, b, a);
  23510. for (j = i2 * 4; j < i2 * 4 + 2 * 4; ++j) {
  23511. p2Attributes.color.values.push(colors[j]);
  23512. }
  23513. }
  23514. if (defined(texCoords)) {
  23515. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, cartesian2Scratch0);
  23516. var s3 = Cartesian2.fromArray(texCoords, (i + 3) * 2, cartesian2Scratch1);
  23517. var sx = CesiumMath.lerp(s0.x, s3.x, t);
  23518. for (j = i0 * 2; j < i0 * 2 + 2 * 2; ++j) {
  23519. p0Attributes.st.values.push(texCoords[j]);
  23520. }
  23521. p0Attributes.st.values.push(sx, s0.y);
  23522. p0Attributes.st.values.push(sx, s3.y);
  23523. p2Attributes.st.values.push(sx, s0.y);
  23524. p2Attributes.st.values.push(sx, s3.y);
  23525. for (j = i2 * 2; j < i2 * 2 + 2 * 2; ++j) {
  23526. p2Attributes.st.values.push(texCoords[j]);
  23527. }
  23528. }
  23529. index = p0Attributes.position.values.length / 3 - 4;
  23530. p0Indices.push(index, index + 2, index + 1);
  23531. p0Indices.push(index + 1, index + 2, index + 3);
  23532. index = p2Attributes.position.values.length / 3 - 4;
  23533. p2Indices.push(index, index + 2, index + 1);
  23534. p2Indices.push(index + 1, index + 2, index + 3);
  23535. } else {
  23536. var currentAttributes;
  23537. var currentIndices;
  23538. if (p0.y < 0.0) {
  23539. currentAttributes = westGeometry.attributes;
  23540. currentIndices = westGeometry.indices;
  23541. } else {
  23542. currentAttributes = eastGeometry.attributes;
  23543. currentIndices = eastGeometry.indices;
  23544. }
  23545. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  23546. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  23547. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  23548. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  23549. for (j = i * 3; j < i * 3 + 4 * 3; ++j) {
  23550. currentAttributes.prevPosition.values.push(prevPositions[j]);
  23551. currentAttributes.nextPosition.values.push(nextPositions[j]);
  23552. }
  23553. for (j = i * 2; j < i * 2 + 4 * 2; ++j) {
  23554. currentAttributes.expandAndWidth.values.push(expandAndWidths[j]);
  23555. if (defined(texCoords)) {
  23556. currentAttributes.st.values.push(texCoords[j]);
  23557. }
  23558. }
  23559. if (defined(colors)) {
  23560. for (j = i * 4; j < i * 4 + 4 * 4; ++j) {
  23561. currentAttributes.color.values.push(colors[j]);
  23562. }
  23563. }
  23564. index = currentAttributes.position.values.length / 3 - 4;
  23565. currentIndices.push(index, index + 2, index + 1);
  23566. currentIndices.push(index + 1, index + 2, index + 3);
  23567. }
  23568. }
  23569. if (intersectionFound) {
  23570. updateAdjacencyAfterSplit(westGeometry);
  23571. updateAdjacencyAfterSplit(eastGeometry);
  23572. }
  23573. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  23574. }
  23575. /**
  23576. * Splits the instances's geometry, by introducing new vertices and indices,that
  23577. * intersect the International Date Line and Prime Meridian so that no primitives cross longitude
  23578. * -180/180 degrees. This is not required for 3D drawing, but is required for
  23579. * correcting drawing in 2D and Columbus view.
  23580. *
  23581. * @private
  23582. *
  23583. * @param {GeometryInstance} instance The instance to modify.
  23584. * @returns {GeometryInstance} The modified <code>instance</code> argument, with it's geometry split at the International Date Line.
  23585. *
  23586. * @example
  23587. * instance = Cesium.GeometryPipeline.splitLongitude(instance);
  23588. */
  23589. GeometryPipeline.splitLongitude = function(instance) {
  23590. if (!defined(instance)) {
  23591. throw new DeveloperError('instance is required.');
  23592. }
  23593. var geometry = instance.geometry;
  23594. var boundingSphere = geometry.boundingSphere;
  23595. if (defined(boundingSphere)) {
  23596. var minX = boundingSphere.center.x - boundingSphere.radius;
  23597. if (minX > 0 || BoundingSphere.intersectPlane(boundingSphere, Plane.ORIGIN_ZX_PLANE) !== Intersect.INTERSECTING) {
  23598. return instance;
  23599. }
  23600. }
  23601. if (geometry.geometryType !== GeometryType.NONE) {
  23602. switch (geometry.geometryType) {
  23603. case GeometryType.POLYLINES:
  23604. splitLongitudePolyline(instance);
  23605. break;
  23606. case GeometryType.TRIANGLES:
  23607. splitLongitudeTriangles(instance);
  23608. break;
  23609. case GeometryType.LINES:
  23610. splitLongitudeLines(instance);
  23611. break;
  23612. }
  23613. } else {
  23614. indexPrimitive(geometry);
  23615. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  23616. splitLongitudeTriangles(instance);
  23617. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  23618. splitLongitudeLines(instance);
  23619. }
  23620. }
  23621. return instance;
  23622. };
  23623. return GeometryPipeline;
  23624. });
  23625. /*global define*/
  23626. define('ThirdParty/earcut-2.1.1',[], function() {
  23627. 'use strict';
  23628. function earcut(data, holeIndices, dim) {
  23629. dim = dim || 2;
  23630. var hasHoles = holeIndices && holeIndices.length,
  23631. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  23632. outerNode = linkedList(data, 0, outerLen, dim, true),
  23633. triangles = [];
  23634. if (!outerNode) return triangles;
  23635. var minX, minY, maxX, maxY, x, y, size;
  23636. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  23637. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  23638. if (data.length > 80 * dim) {
  23639. minX = maxX = data[0];
  23640. minY = maxY = data[1];
  23641. for (var i = dim; i < outerLen; i += dim) {
  23642. x = data[i];
  23643. y = data[i + 1];
  23644. if (x < minX) minX = x;
  23645. if (y < minY) minY = y;
  23646. if (x > maxX) maxX = x;
  23647. if (y > maxY) maxY = y;
  23648. }
  23649. // minX, minY and size are later used to transform coords into integers for z-order calculation
  23650. size = Math.max(maxX - minX, maxY - minY);
  23651. }
  23652. earcutLinked(outerNode, triangles, dim, minX, minY, size);
  23653. return triangles;
  23654. }
  23655. // create a circular doubly linked list from polygon points in the specified winding order
  23656. function linkedList(data, start, end, dim, clockwise) {
  23657. var i, last;
  23658. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  23659. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  23660. } else {
  23661. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  23662. }
  23663. if (last && equals(last, last.next)) {
  23664. removeNode(last);
  23665. last = last.next;
  23666. }
  23667. return last;
  23668. }
  23669. // eliminate colinear or duplicate points
  23670. function filterPoints(start, end) {
  23671. if (!start) return start;
  23672. if (!end) end = start;
  23673. var p = start,
  23674. again;
  23675. do {
  23676. again = false;
  23677. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  23678. removeNode(p);
  23679. p = end = p.prev;
  23680. if (p === p.next) return null;
  23681. again = true;
  23682. } else {
  23683. p = p.next;
  23684. }
  23685. } while (again || p !== end);
  23686. return end;
  23687. }
  23688. // main ear slicing loop which triangulates a polygon (given as a linked list)
  23689. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  23690. if (!ear) return;
  23691. // interlink polygon nodes in z-order
  23692. if (!pass && size) indexCurve(ear, minX, minY, size);
  23693. var stop = ear,
  23694. prev, next;
  23695. // iterate through ears, slicing them one by one
  23696. while (ear.prev !== ear.next) {
  23697. prev = ear.prev;
  23698. next = ear.next;
  23699. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  23700. // cut off the triangle
  23701. triangles.push(prev.i / dim);
  23702. triangles.push(ear.i / dim);
  23703. triangles.push(next.i / dim);
  23704. removeNode(ear);
  23705. // skipping the next vertice leads to less sliver triangles
  23706. ear = next.next;
  23707. stop = next.next;
  23708. continue;
  23709. }
  23710. ear = next;
  23711. // if we looped through the whole remaining polygon and can't find any more ears
  23712. if (ear === stop) {
  23713. // try filtering points and slicing again
  23714. if (!pass) {
  23715. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
  23716. // if this didn't work, try curing all small self-intersections locally
  23717. } else if (pass === 1) {
  23718. ear = cureLocalIntersections(ear, triangles, dim);
  23719. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  23720. // as a last resort, try splitting the remaining polygon into two
  23721. } else if (pass === 2) {
  23722. splitEarcut(ear, triangles, dim, minX, minY, size);
  23723. }
  23724. break;
  23725. }
  23726. }
  23727. }
  23728. // check whether a polygon node forms a valid ear with adjacent nodes
  23729. function isEar(ear) {
  23730. var a = ear.prev,
  23731. b = ear,
  23732. c = ear.next;
  23733. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  23734. // now make sure we don't have other points inside the potential ear
  23735. var p = ear.next.next;
  23736. while (p !== ear.prev) {
  23737. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  23738. area(p.prev, p, p.next) >= 0) return false;
  23739. p = p.next;
  23740. }
  23741. return true;
  23742. }
  23743. function isEarHashed(ear, minX, minY, size) {
  23744. var a = ear.prev,
  23745. b = ear,
  23746. c = ear.next;
  23747. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  23748. // triangle bbox; min & max are calculated like this for speed
  23749. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  23750. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  23751. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  23752. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  23753. // z-order range for the current triangle bbox;
  23754. var minZ = zOrder(minTX, minTY, minX, minY, size),
  23755. maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  23756. // first look for points inside the triangle in increasing z-order
  23757. var p = ear.nextZ;
  23758. while (p && p.z <= maxZ) {
  23759. if (p !== ear.prev && p !== ear.next &&
  23760. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  23761. area(p.prev, p, p.next) >= 0) return false;
  23762. p = p.nextZ;
  23763. }
  23764. // then look for points in decreasing z-order
  23765. p = ear.prevZ;
  23766. while (p && p.z >= minZ) {
  23767. if (p !== ear.prev && p !== ear.next &&
  23768. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  23769. area(p.prev, p, p.next) >= 0) return false;
  23770. p = p.prevZ;
  23771. }
  23772. return true;
  23773. }
  23774. // go through all polygon nodes and cure small local self-intersections
  23775. function cureLocalIntersections(start, triangles, dim) {
  23776. var p = start;
  23777. do {
  23778. var a = p.prev,
  23779. b = p.next.next;
  23780. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  23781. triangles.push(a.i / dim);
  23782. triangles.push(p.i / dim);
  23783. triangles.push(b.i / dim);
  23784. // remove two nodes involved
  23785. removeNode(p);
  23786. removeNode(p.next);
  23787. p = start = b;
  23788. }
  23789. p = p.next;
  23790. } while (p !== start);
  23791. return p;
  23792. }
  23793. // try splitting polygon into two and triangulate them independently
  23794. function splitEarcut(start, triangles, dim, minX, minY, size) {
  23795. // look for a valid diagonal that divides the polygon into two
  23796. var a = start;
  23797. do {
  23798. var b = a.next.next;
  23799. while (b !== a.prev) {
  23800. if (a.i !== b.i && isValidDiagonal(a, b)) {
  23801. // split the polygon in two by the diagonal
  23802. var c = splitPolygon(a, b);
  23803. // filter colinear points around the cuts
  23804. a = filterPoints(a, a.next);
  23805. c = filterPoints(c, c.next);
  23806. // run earcut on each half
  23807. earcutLinked(a, triangles, dim, minX, minY, size);
  23808. earcutLinked(c, triangles, dim, minX, minY, size);
  23809. return;
  23810. }
  23811. b = b.next;
  23812. }
  23813. a = a.next;
  23814. } while (a !== start);
  23815. }
  23816. // link every hole into the outer loop, producing a single-ring polygon without holes
  23817. function eliminateHoles(data, holeIndices, outerNode, dim) {
  23818. var queue = [],
  23819. i, len, start, end, list;
  23820. for (i = 0, len = holeIndices.length; i < len; i++) {
  23821. start = holeIndices[i] * dim;
  23822. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  23823. list = linkedList(data, start, end, dim, false);
  23824. if (list === list.next) list.steiner = true;
  23825. queue.push(getLeftmost(list));
  23826. }
  23827. queue.sort(compareX);
  23828. // process holes from left to right
  23829. for (i = 0; i < queue.length; i++) {
  23830. eliminateHole(queue[i], outerNode);
  23831. outerNode = filterPoints(outerNode, outerNode.next);
  23832. }
  23833. return outerNode;
  23834. }
  23835. function compareX(a, b) {
  23836. return a.x - b.x;
  23837. }
  23838. // find a bridge between vertices that connects hole with an outer ring and and link it
  23839. function eliminateHole(hole, outerNode) {
  23840. outerNode = findHoleBridge(hole, outerNode);
  23841. if (outerNode) {
  23842. var b = splitPolygon(outerNode, hole);
  23843. filterPoints(b, b.next);
  23844. }
  23845. }
  23846. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  23847. function findHoleBridge(hole, outerNode) {
  23848. var p = outerNode,
  23849. hx = hole.x,
  23850. hy = hole.y,
  23851. qx = -Infinity,
  23852. m;
  23853. // find a segment intersected by a ray from the hole's leftmost point to the left;
  23854. // segment's endpoint with lesser x will be potential connection point
  23855. do {
  23856. if (hy <= p.y && hy >= p.next.y) {
  23857. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  23858. if (x <= hx && x > qx) {
  23859. qx = x;
  23860. if (x === hx) {
  23861. if (hy === p.y) return p;
  23862. if (hy === p.next.y) return p.next;
  23863. }
  23864. m = p.x < p.next.x ? p : p.next;
  23865. }
  23866. }
  23867. p = p.next;
  23868. } while (p !== outerNode);
  23869. if (!m) return null;
  23870. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  23871. // look for points inside the triangle of hole point, segment intersection and endpoint;
  23872. // if there are no points found, we have a valid connection;
  23873. // otherwise choose the point of the minimum angle with the ray as connection point
  23874. var stop = m,
  23875. mx = m.x,
  23876. my = m.y,
  23877. tanMin = Infinity,
  23878. tan;
  23879. p = m.next;
  23880. while (p !== stop) {
  23881. if (hx >= p.x && p.x >= mx &&
  23882. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  23883. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  23884. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  23885. m = p;
  23886. tanMin = tan;
  23887. }
  23888. }
  23889. p = p.next;
  23890. }
  23891. return m;
  23892. }
  23893. // interlink polygon nodes in z-order
  23894. function indexCurve(start, minX, minY, size) {
  23895. var p = start;
  23896. do {
  23897. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
  23898. p.prevZ = p.prev;
  23899. p.nextZ = p.next;
  23900. p = p.next;
  23901. } while (p !== start);
  23902. p.prevZ.nextZ = null;
  23903. p.prevZ = null;
  23904. sortLinked(p);
  23905. }
  23906. // Simon Tatham's linked list merge sort algorithm
  23907. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  23908. function sortLinked(list) {
  23909. var i, p, q, e, tail, numMerges, pSize, qSize,
  23910. inSize = 1;
  23911. do {
  23912. p = list;
  23913. list = null;
  23914. tail = null;
  23915. numMerges = 0;
  23916. while (p) {
  23917. numMerges++;
  23918. q = p;
  23919. pSize = 0;
  23920. for (i = 0; i < inSize; i++) {
  23921. pSize++;
  23922. q = q.nextZ;
  23923. if (!q) break;
  23924. }
  23925. qSize = inSize;
  23926. while (pSize > 0 || (qSize > 0 && q)) {
  23927. if (pSize === 0) {
  23928. e = q;
  23929. q = q.nextZ;
  23930. qSize--;
  23931. } else if (qSize === 0 || !q) {
  23932. e = p;
  23933. p = p.nextZ;
  23934. pSize--;
  23935. } else if (p.z <= q.z) {
  23936. e = p;
  23937. p = p.nextZ;
  23938. pSize--;
  23939. } else {
  23940. e = q;
  23941. q = q.nextZ;
  23942. qSize--;
  23943. }
  23944. if (tail) tail.nextZ = e;
  23945. else list = e;
  23946. e.prevZ = tail;
  23947. tail = e;
  23948. }
  23949. p = q;
  23950. }
  23951. tail.nextZ = null;
  23952. inSize *= 2;
  23953. } while (numMerges > 1);
  23954. return list;
  23955. }
  23956. // z-order of a point given coords and size of the data bounding box
  23957. function zOrder(x, y, minX, minY, size) {
  23958. // coords are transformed into non-negative 15-bit integer range
  23959. x = 32767 * (x - minX) / size;
  23960. y = 32767 * (y - minY) / size;
  23961. x = (x | (x << 8)) & 0x00FF00FF;
  23962. x = (x | (x << 4)) & 0x0F0F0F0F;
  23963. x = (x | (x << 2)) & 0x33333333;
  23964. x = (x | (x << 1)) & 0x55555555;
  23965. y = (y | (y << 8)) & 0x00FF00FF;
  23966. y = (y | (y << 4)) & 0x0F0F0F0F;
  23967. y = (y | (y << 2)) & 0x33333333;
  23968. y = (y | (y << 1)) & 0x55555555;
  23969. return x | (y << 1);
  23970. }
  23971. // find the leftmost node of a polygon ring
  23972. function getLeftmost(start) {
  23973. var p = start,
  23974. leftmost = start;
  23975. do {
  23976. if (p.x < leftmost.x) leftmost = p;
  23977. p = p.next;
  23978. } while (p !== start);
  23979. return leftmost;
  23980. }
  23981. // check if a point lies within a convex triangle
  23982. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  23983. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  23984. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  23985. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  23986. }
  23987. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  23988. function isValidDiagonal(a, b) {
  23989. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
  23990. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  23991. }
  23992. // signed area of a triangle
  23993. function area(p, q, r) {
  23994. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  23995. }
  23996. // check if two points are equal
  23997. function equals(p1, p2) {
  23998. return p1.x === p2.x && p1.y === p2.y;
  23999. }
  24000. // check if two segments intersect
  24001. function intersects(p1, q1, p2, q2) {
  24002. if ((equals(p1, q1) && equals(p2, q2)) ||
  24003. (equals(p1, q2) && equals(p2, q1))) return true;
  24004. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  24005. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  24006. }
  24007. // check if a polygon diagonal intersects any polygon segments
  24008. function intersectsPolygon(a, b) {
  24009. var p = a;
  24010. do {
  24011. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  24012. intersects(p, p.next, a, b)) return true;
  24013. p = p.next;
  24014. } while (p !== a);
  24015. return false;
  24016. }
  24017. // check if a polygon diagonal is locally inside the polygon
  24018. function locallyInside(a, b) {
  24019. return area(a.prev, a, a.next) < 0 ?
  24020. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  24021. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  24022. }
  24023. // check if the middle point of a polygon diagonal is inside the polygon
  24024. function middleInside(a, b) {
  24025. var p = a,
  24026. inside = false,
  24027. px = (a.x + b.x) / 2,
  24028. py = (a.y + b.y) / 2;
  24029. do {
  24030. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  24031. inside = !inside;
  24032. p = p.next;
  24033. } while (p !== a);
  24034. return inside;
  24035. }
  24036. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  24037. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  24038. function splitPolygon(a, b) {
  24039. var a2 = new Node(a.i, a.x, a.y),
  24040. b2 = new Node(b.i, b.x, b.y),
  24041. an = a.next,
  24042. bp = b.prev;
  24043. a.next = b;
  24044. b.prev = a;
  24045. a2.next = an;
  24046. an.prev = a2;
  24047. b2.next = a2;
  24048. a2.prev = b2;
  24049. bp.next = b2;
  24050. b2.prev = bp;
  24051. return b2;
  24052. }
  24053. // create a node and optionally link it with previous one (in a circular doubly linked list)
  24054. function insertNode(i, x, y, last) {
  24055. var p = new Node(i, x, y);
  24056. if (!last) {
  24057. p.prev = p;
  24058. p.next = p;
  24059. } else {
  24060. p.next = last.next;
  24061. p.prev = last;
  24062. last.next.prev = p;
  24063. last.next = p;
  24064. }
  24065. return p;
  24066. }
  24067. function removeNode(p) {
  24068. p.next.prev = p.prev;
  24069. p.prev.next = p.next;
  24070. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  24071. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  24072. }
  24073. function Node(i, x, y) {
  24074. // vertice index in coordinates array
  24075. this.i = i;
  24076. // vertex coordinates
  24077. this.x = x;
  24078. this.y = y;
  24079. // previous and next vertice nodes in a polygon ring
  24080. this.prev = null;
  24081. this.next = null;
  24082. // z-order curve value
  24083. this.z = null;
  24084. // previous and next nodes in z-order
  24085. this.prevZ = null;
  24086. this.nextZ = null;
  24087. // indicates whether this is a steiner point
  24088. this.steiner = false;
  24089. }
  24090. // return a percentage difference between the polygon area and its triangulation area;
  24091. // used to verify correctness of triangulation
  24092. earcut.deviation = function (data, holeIndices, dim, triangles) {
  24093. var hasHoles = holeIndices && holeIndices.length;
  24094. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  24095. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  24096. if (hasHoles) {
  24097. for (var i = 0, len = holeIndices.length; i < len; i++) {
  24098. var start = holeIndices[i] * dim;
  24099. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  24100. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  24101. }
  24102. }
  24103. var trianglesArea = 0;
  24104. for (i = 0; i < triangles.length; i += 3) {
  24105. var a = triangles[i] * dim;
  24106. var b = triangles[i + 1] * dim;
  24107. var c = triangles[i + 2] * dim;
  24108. trianglesArea += Math.abs(
  24109. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  24110. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  24111. }
  24112. return polygonArea === 0 && trianglesArea === 0 ? 0 :
  24113. Math.abs((trianglesArea - polygonArea) / polygonArea);
  24114. };
  24115. function signedArea(data, start, end, dim) {
  24116. var sum = 0;
  24117. for (var i = start, j = end - dim; i < end; i += dim) {
  24118. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  24119. j = i;
  24120. }
  24121. return sum;
  24122. }
  24123. // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  24124. earcut.flatten = function (data) {
  24125. var dim = data[0][0].length,
  24126. result = {vertices: [], holes: [], dimensions: dim},
  24127. holeIndex = 0;
  24128. for (var i = 0; i < data.length; i++) {
  24129. for (var j = 0; j < data[i].length; j++) {
  24130. for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  24131. }
  24132. if (i > 0) {
  24133. holeIndex += data[i - 1].length;
  24134. result.holes.push(holeIndex);
  24135. }
  24136. }
  24137. return result;
  24138. };
  24139. return earcut;
  24140. });
  24141. /*global define*/
  24142. define('Core/WindingOrder',[
  24143. './freezeObject',
  24144. './WebGLConstants'
  24145. ], function(
  24146. freezeObject,
  24147. WebGLConstants) {
  24148. 'use strict';
  24149. /**
  24150. * Winding order defines the order of vertices for a triangle to be considered front-facing.
  24151. *
  24152. * @exports WindingOrder
  24153. */
  24154. var WindingOrder = {
  24155. /**
  24156. * Vertices are in clockwise order.
  24157. *
  24158. * @type {Number}
  24159. * @constant
  24160. */
  24161. CLOCKWISE : WebGLConstants.CW,
  24162. /**
  24163. * Vertices are in counter-clockwise order.
  24164. *
  24165. * @type {Number}
  24166. * @constant
  24167. */
  24168. COUNTER_CLOCKWISE : WebGLConstants.CCW,
  24169. /**
  24170. * @private
  24171. */
  24172. validate : function(windingOrder) {
  24173. return windingOrder === WindingOrder.CLOCKWISE ||
  24174. windingOrder === WindingOrder.COUNTER_CLOCKWISE;
  24175. }
  24176. };
  24177. return freezeObject(WindingOrder);
  24178. });
  24179. /*global define*/
  24180. define('Core/PolygonPipeline',[
  24181. '../ThirdParty/earcut-2.1.1',
  24182. './Cartesian2',
  24183. './Cartesian3',
  24184. './ComponentDatatype',
  24185. './defaultValue',
  24186. './defined',
  24187. './DeveloperError',
  24188. './Ellipsoid',
  24189. './Geometry',
  24190. './GeometryAttribute',
  24191. './Math',
  24192. './PrimitiveType',
  24193. './WindingOrder'
  24194. ], function(
  24195. earcut,
  24196. Cartesian2,
  24197. Cartesian3,
  24198. ComponentDatatype,
  24199. defaultValue,
  24200. defined,
  24201. DeveloperError,
  24202. Ellipsoid,
  24203. Geometry,
  24204. GeometryAttribute,
  24205. CesiumMath,
  24206. PrimitiveType,
  24207. WindingOrder) {
  24208. 'use strict';
  24209. var scaleToGeodeticHeightN = new Cartesian3();
  24210. var scaleToGeodeticHeightP = new Cartesian3();
  24211. /**
  24212. * @private
  24213. */
  24214. var PolygonPipeline = {};
  24215. /**
  24216. * @exception {DeveloperError} At least three positions are required.
  24217. */
  24218. PolygonPipeline.computeArea2D = function(positions) {
  24219. if (!defined(positions)) {
  24220. throw new DeveloperError('positions is required.');
  24221. }
  24222. if (positions.length < 3) {
  24223. throw new DeveloperError('At least three positions are required.');
  24224. }
  24225. var length = positions.length;
  24226. var area = 0.0;
  24227. for ( var i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
  24228. var v0 = positions[i0];
  24229. var v1 = positions[i1];
  24230. area += (v0.x * v1.y) - (v1.x * v0.y);
  24231. }
  24232. return area * 0.5;
  24233. };
  24234. /**
  24235. * @returns {WindingOrder} The winding order.
  24236. *
  24237. * @exception {DeveloperError} At least three positions are required.
  24238. */
  24239. PolygonPipeline.computeWindingOrder2D = function(positions) {
  24240. var area = PolygonPipeline.computeArea2D(positions);
  24241. return (area > 0.0) ? WindingOrder.COUNTER_CLOCKWISE : WindingOrder.CLOCKWISE;
  24242. };
  24243. /**
  24244. * Triangulate a polygon.
  24245. *
  24246. * @param {Cartesian2[]} positions Cartesian2 array containing the vertices of the polygon
  24247. * @param {Number[]} [holes] An array of the staring indices of the holes.
  24248. * @returns {Number[]} Index array representing triangles that fill the polygon
  24249. */
  24250. PolygonPipeline.triangulate = function(positions, holes) {
  24251. if (!defined(positions)) {
  24252. throw new DeveloperError('positions is required.');
  24253. }
  24254. var flattenedPositions = Cartesian2.packArray(positions);
  24255. return earcut(flattenedPositions, holes, 2);
  24256. };
  24257. var subdivisionV0Scratch = new Cartesian3();
  24258. var subdivisionV1Scratch = new Cartesian3();
  24259. var subdivisionV2Scratch = new Cartesian3();
  24260. var subdivisionS0Scratch = new Cartesian3();
  24261. var subdivisionS1Scratch = new Cartesian3();
  24262. var subdivisionS2Scratch = new Cartesian3();
  24263. var subdivisionMidScratch = new Cartesian3();
  24264. /**
  24265. * Subdivides positions and raises points to the surface of the ellipsoid.
  24266. *
  24267. * @param {Ellipsoid} ellipsoid The ellipsoid the polygon in on.
  24268. * @param {Cartesian3[]} positions An array of {@link Cartesian3} positions of the polygon.
  24269. * @param {Number[]} indices An array of indices that determines the triangles in the polygon.
  24270. * @param {Number} [granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  24271. *
  24272. * @exception {DeveloperError} At least three indices are required.
  24273. * @exception {DeveloperError} The number of indices must be divisable by three.
  24274. * @exception {DeveloperError} Granularity must be greater than zero.
  24275. */
  24276. PolygonPipeline.computeSubdivision = function(ellipsoid, positions, indices, granularity) {
  24277. granularity = defaultValue(granularity, CesiumMath.RADIANS_PER_DEGREE);
  24278. if (!defined(ellipsoid)) {
  24279. throw new DeveloperError('ellipsoid is required.');
  24280. }
  24281. if (!defined(positions)) {
  24282. throw new DeveloperError('positions is required.');
  24283. }
  24284. if (!defined(indices)) {
  24285. throw new DeveloperError('indices is required.');
  24286. }
  24287. if (indices.length < 3) {
  24288. throw new DeveloperError('At least three indices are required.');
  24289. }
  24290. if (indices.length % 3 !== 0) {
  24291. throw new DeveloperError('The number of indices must be divisable by three.');
  24292. }
  24293. if (granularity <= 0.0) {
  24294. throw new DeveloperError('granularity must be greater than zero.');
  24295. }
  24296. // triangles that need (or might need) to be subdivided.
  24297. var triangles = indices.slice(0);
  24298. // New positions due to edge splits are appended to the positions list.
  24299. var i;
  24300. var length = positions.length;
  24301. var subdividedPositions = new Array(length * 3);
  24302. var q = 0;
  24303. for (i = 0; i < length; i++) {
  24304. var item = positions[i];
  24305. subdividedPositions[q++] = item.x;
  24306. subdividedPositions[q++] = item.y;
  24307. subdividedPositions[q++] = item.z;
  24308. }
  24309. var subdividedIndices = [];
  24310. // Used to make sure shared edges are not split more than once.
  24311. var edges = {};
  24312. var radius = ellipsoid.maximumRadius;
  24313. var minDistance = CesiumMath.chordLength(granularity, radius);
  24314. var minDistanceSqrd = minDistance * minDistance;
  24315. while (triangles.length > 0) {
  24316. var i2 = triangles.pop();
  24317. var i1 = triangles.pop();
  24318. var i0 = triangles.pop();
  24319. var v0 = Cartesian3.fromArray(subdividedPositions, i0 * 3, subdivisionV0Scratch);
  24320. var v1 = Cartesian3.fromArray(subdividedPositions, i1 * 3, subdivisionV1Scratch);
  24321. var v2 = Cartesian3.fromArray(subdividedPositions, i2 * 3, subdivisionV2Scratch);
  24322. var s0 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v0, subdivisionS0Scratch), radius, subdivisionS0Scratch);
  24323. var s1 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v1, subdivisionS1Scratch), radius, subdivisionS1Scratch);
  24324. var s2 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v2, subdivisionS2Scratch), radius, subdivisionS2Scratch);
  24325. var g0 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s0, s1, subdivisionMidScratch));
  24326. var g1 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s1, s2, subdivisionMidScratch));
  24327. var g2 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s2, s0, subdivisionMidScratch));
  24328. var max = Math.max(g0, g1, g2);
  24329. var edge;
  24330. var mid;
  24331. // if the max length squared of a triangle edge is greater than the chord length of squared
  24332. // of the granularity, subdivide the triangle
  24333. if (max > minDistanceSqrd) {
  24334. if (g0 === max) {
  24335. edge = Math.min(i0, i1) + ' ' + Math.max(i0, i1);
  24336. i = edges[edge];
  24337. if (!defined(i)) {
  24338. mid = Cartesian3.add(v0, v1, subdivisionMidScratch);
  24339. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  24340. subdividedPositions.push(mid.x, mid.y, mid.z);
  24341. i = subdividedPositions.length / 3 - 1;
  24342. edges[edge] = i;
  24343. }
  24344. triangles.push(i0, i, i2);
  24345. triangles.push(i, i1, i2);
  24346. } else if (g1 === max) {
  24347. edge = Math.min(i1, i2) + ' ' + Math.max(i1, i2);
  24348. i = edges[edge];
  24349. if (!defined(i)) {
  24350. mid = Cartesian3.add(v1, v2, subdivisionMidScratch);
  24351. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  24352. subdividedPositions.push(mid.x, mid.y, mid.z);
  24353. i = subdividedPositions.length / 3 - 1;
  24354. edges[edge] = i;
  24355. }
  24356. triangles.push(i1, i, i0);
  24357. triangles.push(i, i2, i0);
  24358. } else if (g2 === max) {
  24359. edge = Math.min(i2, i0) + ' ' + Math.max(i2, i0);
  24360. i = edges[edge];
  24361. if (!defined(i)) {
  24362. mid = Cartesian3.add(v2, v0, subdivisionMidScratch);
  24363. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  24364. subdividedPositions.push(mid.x, mid.y, mid.z);
  24365. i = subdividedPositions.length / 3 - 1;
  24366. edges[edge] = i;
  24367. }
  24368. triangles.push(i2, i, i1);
  24369. triangles.push(i, i0, i1);
  24370. }
  24371. } else {
  24372. subdividedIndices.push(i0);
  24373. subdividedIndices.push(i1);
  24374. subdividedIndices.push(i2);
  24375. }
  24376. }
  24377. return new Geometry({
  24378. attributes : {
  24379. position : new GeometryAttribute({
  24380. componentDatatype : ComponentDatatype.DOUBLE,
  24381. componentsPerAttribute : 3,
  24382. values : subdividedPositions
  24383. })
  24384. },
  24385. indices : subdividedIndices,
  24386. primitiveType : PrimitiveType.TRIANGLES
  24387. });
  24388. };
  24389. /**
  24390. * Scales each position of a geometry's position attribute to a height, in place.
  24391. *
  24392. * @param {Number[]} positions The array of numbers representing the positions to be scaled
  24393. * @param {Number} [height=0.0] The desired height to add to the positions
  24394. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  24395. * @param {Boolean} [scaleToSurface=true] <code>true</code> if the positions need to be scaled to the surface before the height is added.
  24396. * @returns {Number[]} The input array of positions, scaled to height
  24397. */
  24398. PolygonPipeline.scaleToGeodeticHeight = function(positions, height, ellipsoid, scaleToSurface) {
  24399. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  24400. var n = scaleToGeodeticHeightN;
  24401. var p = scaleToGeodeticHeightP;
  24402. height = defaultValue(height, 0.0);
  24403. scaleToSurface = defaultValue(scaleToSurface, true);
  24404. if (defined(positions)) {
  24405. var length = positions.length;
  24406. for ( var i = 0; i < length; i += 3) {
  24407. Cartesian3.fromArray(positions, i, p);
  24408. if (scaleToSurface) {
  24409. p = ellipsoid.scaleToGeodeticSurface(p, p);
  24410. }
  24411. if (height !== 0) {
  24412. n = ellipsoid.geodeticSurfaceNormal(p, n);
  24413. Cartesian3.multiplyByScalar(n, height, n);
  24414. Cartesian3.add(p, n, p);
  24415. }
  24416. positions[i] = p.x;
  24417. positions[i + 1] = p.y;
  24418. positions[i + 2] = p.z;
  24419. }
  24420. }
  24421. return positions;
  24422. };
  24423. return PolygonPipeline;
  24424. });
  24425. /*global define*/
  24426. define('Core/Queue',[
  24427. './defineProperties'
  24428. ], function(
  24429. defineProperties) {
  24430. 'use strict';
  24431. /**
  24432. * A queue that can enqueue items at the end, and dequeue items from the front.
  24433. *
  24434. * @alias Queue
  24435. * @constructor
  24436. */
  24437. function Queue() {
  24438. this._array = [];
  24439. this._offset = 0;
  24440. this._length = 0;
  24441. }
  24442. defineProperties(Queue.prototype, {
  24443. /**
  24444. * The length of the queue.
  24445. *
  24446. * @memberof Queue.prototype
  24447. *
  24448. * @type {Number}
  24449. * @readonly
  24450. */
  24451. length : {
  24452. get : function() {
  24453. return this._length;
  24454. }
  24455. }
  24456. });
  24457. /**
  24458. * Enqueues the specified item.
  24459. *
  24460. * @param {Object} item The item to enqueue.
  24461. */
  24462. Queue.prototype.enqueue = function(item) {
  24463. this._array.push(item);
  24464. this._length++;
  24465. };
  24466. /**
  24467. * Dequeues an item. Returns undefined if the queue is empty.
  24468. *
  24469. * @returns {Object} The the dequeued item.
  24470. */
  24471. Queue.prototype.dequeue = function() {
  24472. if (this._length === 0) {
  24473. return undefined;
  24474. }
  24475. var array = this._array;
  24476. var offset = this._offset;
  24477. var item = array[offset];
  24478. array[offset] = undefined;
  24479. offset++;
  24480. if ((offset > 10) && (offset * 2 > array.length)) {
  24481. //compact array
  24482. this._array = array.slice(offset);
  24483. offset = 0;
  24484. }
  24485. this._offset = offset;
  24486. this._length--;
  24487. return item;
  24488. };
  24489. /**
  24490. * Returns the item at the front of the queue. Returns undefined if the queue is empty.
  24491. *
  24492. * @returns {Object} The item at the front of the queue.
  24493. */
  24494. Queue.prototype.peek = function() {
  24495. if (this._length === 0) {
  24496. return undefined;
  24497. }
  24498. return this._array[this._offset];
  24499. };
  24500. /**
  24501. * Check whether this queue contains the specified item.
  24502. *
  24503. * @param {Object} item The item to search for.
  24504. */
  24505. Queue.prototype.contains = function(item) {
  24506. return this._array.indexOf(item) !== -1;
  24507. };
  24508. /**
  24509. * Remove all items from the queue.
  24510. */
  24511. Queue.prototype.clear = function() {
  24512. this._array.length = this._offset = this._length = 0;
  24513. };
  24514. /**
  24515. * Sort the items in the queue in-place.
  24516. *
  24517. * @param {Queue~Comparator} compareFunction A function that defines the sort order.
  24518. */
  24519. Queue.prototype.sort = function(compareFunction) {
  24520. if (this._offset > 0) {
  24521. //compact array
  24522. this._array = this._array.slice(this._offset);
  24523. this._offset = 0;
  24524. }
  24525. this._array.sort(compareFunction);
  24526. };
  24527. /**
  24528. * A function used to compare two items while sorting a queue.
  24529. * @callback Queue~Comparator
  24530. *
  24531. * @param {Object} a An item in the array.
  24532. * @param {Object} b An item in the array.
  24533. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  24534. * a positive value if <code>a</code> is greater than <code>b</code>, or
  24535. * 0 if <code>a</code> is equal to <code>b</code>.
  24536. *
  24537. * @example
  24538. * function compareNumbers(a, b) {
  24539. * return a - b;
  24540. * }
  24541. */
  24542. return Queue;
  24543. });
  24544. /*global define*/
  24545. define('Core/PolygonGeometryLibrary',[
  24546. './arrayRemoveDuplicates',
  24547. './Cartesian3',
  24548. './ComponentDatatype',
  24549. './defaultValue',
  24550. './defined',
  24551. './Ellipsoid',
  24552. './Geometry',
  24553. './GeometryAttribute',
  24554. './GeometryAttributes',
  24555. './GeometryPipeline',
  24556. './IndexDatatype',
  24557. './Math',
  24558. './PolygonPipeline',
  24559. './PrimitiveType',
  24560. './Queue',
  24561. './WindingOrder'
  24562. ], function(
  24563. arrayRemoveDuplicates,
  24564. Cartesian3,
  24565. ComponentDatatype,
  24566. defaultValue,
  24567. defined,
  24568. Ellipsoid,
  24569. Geometry,
  24570. GeometryAttribute,
  24571. GeometryAttributes,
  24572. GeometryPipeline,
  24573. IndexDatatype,
  24574. CesiumMath,
  24575. PolygonPipeline,
  24576. PrimitiveType,
  24577. Queue,
  24578. WindingOrder) {
  24579. 'use strict';
  24580. /**
  24581. * @private
  24582. */
  24583. var PolygonGeometryLibrary = {};
  24584. PolygonGeometryLibrary.computeHierarchyPackedLength = function(polygonHierarchy) {
  24585. var numComponents = 0;
  24586. var stack = [polygonHierarchy];
  24587. while (stack.length > 0) {
  24588. var hierarchy = stack.pop();
  24589. if (!defined(hierarchy)) {
  24590. continue;
  24591. }
  24592. numComponents += 2;
  24593. var positions = hierarchy.positions;
  24594. var holes = hierarchy.holes;
  24595. if (defined(positions)) {
  24596. numComponents += positions.length * Cartesian3.packedLength;
  24597. }
  24598. if (defined(holes)) {
  24599. var length = holes.length;
  24600. for (var i = 0; i < length; ++i) {
  24601. stack.push(holes[i]);
  24602. }
  24603. }
  24604. }
  24605. return numComponents;
  24606. };
  24607. PolygonGeometryLibrary.packPolygonHierarchy = function(polygonHierarchy, array, startingIndex) {
  24608. var stack = [polygonHierarchy];
  24609. while (stack.length > 0) {
  24610. var hierarchy = stack.pop();
  24611. if (!defined(hierarchy)) {
  24612. continue;
  24613. }
  24614. var positions = hierarchy.positions;
  24615. var holes = hierarchy.holes;
  24616. array[startingIndex++] = defined(positions) ? positions.length : 0;
  24617. array[startingIndex++] = defined(holes) ? holes.length : 0;
  24618. if (defined(positions)) {
  24619. var positionsLength = positions.length;
  24620. for (var i = 0; i < positionsLength; ++i, startingIndex += 3) {
  24621. Cartesian3.pack(positions[i], array, startingIndex);
  24622. }
  24623. }
  24624. if (defined(holes)) {
  24625. var holesLength = holes.length;
  24626. for (var j = 0; j < holesLength; ++j) {
  24627. stack.push(holes[j]);
  24628. }
  24629. }
  24630. }
  24631. return startingIndex;
  24632. };
  24633. PolygonGeometryLibrary.unpackPolygonHierarchy = function(array, startingIndex) {
  24634. var positionsLength = array[startingIndex++];
  24635. var holesLength = array[startingIndex++];
  24636. var positions = new Array(positionsLength);
  24637. var holes = holesLength > 0 ? new Array(holesLength) : undefined;
  24638. for (var i = 0; i < positionsLength; ++i, startingIndex += Cartesian3.packedLength) {
  24639. positions[i] = Cartesian3.unpack(array, startingIndex);
  24640. }
  24641. for (var j = 0; j < holesLength; ++j) {
  24642. holes[j] = PolygonGeometryLibrary.unpackPolygonHierarchy(array, startingIndex);
  24643. startingIndex = holes[j].startingIndex;
  24644. delete holes[j].startingIndex;
  24645. }
  24646. return {
  24647. positions : positions,
  24648. holes : holes,
  24649. startingIndex : startingIndex
  24650. };
  24651. };
  24652. var distanceScratch = new Cartesian3();
  24653. function getPointAtDistance(p0, p1, distance, length) {
  24654. Cartesian3.subtract(p1, p0, distanceScratch);
  24655. Cartesian3.multiplyByScalar(distanceScratch, distance / length, distanceScratch);
  24656. Cartesian3.add(p0, distanceScratch, distanceScratch);
  24657. return [distanceScratch.x, distanceScratch.y, distanceScratch.z];
  24658. }
  24659. PolygonGeometryLibrary.subdivideLineCount = function(p0, p1, minDistance) {
  24660. var distance = Cartesian3.distance(p0, p1);
  24661. var n = distance / minDistance;
  24662. var countDivide = Math.max(0, Math.ceil(Math.log(n) / Math.log(2)));
  24663. return Math.pow(2, countDivide);
  24664. };
  24665. PolygonGeometryLibrary.subdivideLine = function(p0, p1, minDistance, result) {
  24666. var numVertices = PolygonGeometryLibrary.subdivideLineCount(p0, p1, minDistance);
  24667. var length = Cartesian3.distance(p0, p1);
  24668. var distanceBetweenVertices = length / numVertices;
  24669. if (!defined(result)) {
  24670. result = [];
  24671. }
  24672. var positions = result;
  24673. positions.length = numVertices * 3;
  24674. var index = 0;
  24675. for ( var i = 0; i < numVertices; i++) {
  24676. var p = getPointAtDistance(p0, p1, i * distanceBetweenVertices, length);
  24677. positions[index++] = p[0];
  24678. positions[index++] = p[1];
  24679. positions[index++] = p[2];
  24680. }
  24681. return positions;
  24682. };
  24683. var scaleToGeodeticHeightN1 = new Cartesian3();
  24684. var scaleToGeodeticHeightN2 = new Cartesian3();
  24685. var scaleToGeodeticHeightP1 = new Cartesian3();
  24686. var scaleToGeodeticHeightP2 = new Cartesian3();
  24687. PolygonGeometryLibrary.scaleToGeodeticHeightExtruded = function(geometry, maxHeight, minHeight, ellipsoid, perPositionHeight) {
  24688. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  24689. var n1 = scaleToGeodeticHeightN1;
  24690. var n2 = scaleToGeodeticHeightN2;
  24691. var p = scaleToGeodeticHeightP1;
  24692. var p2 = scaleToGeodeticHeightP2;
  24693. if (defined(geometry) && defined(geometry.attributes) && defined(geometry.attributes.position)) {
  24694. var positions = geometry.attributes.position.values;
  24695. var length = positions.length / 2;
  24696. for ( var i = 0; i < length; i += 3) {
  24697. Cartesian3.fromArray(positions, i, p);
  24698. ellipsoid.geodeticSurfaceNormal(p, n1);
  24699. p2 = ellipsoid.scaleToGeodeticSurface(p, p2);
  24700. n2 = Cartesian3.multiplyByScalar(n1, minHeight, n2);
  24701. n2 = Cartesian3.add(p2, n2, n2);
  24702. positions[i + length] = n2.x;
  24703. positions[i + 1 + length] = n2.y;
  24704. positions[i + 2 + length] = n2.z;
  24705. if (perPositionHeight) {
  24706. p2 = Cartesian3.clone(p, p2);
  24707. }
  24708. n2 = Cartesian3.multiplyByScalar(n1, maxHeight, n2);
  24709. n2 = Cartesian3.add(p2, n2, n2);
  24710. positions[i] = n2.x;
  24711. positions[i + 1] = n2.y;
  24712. positions[i + 2] = n2.z;
  24713. }
  24714. }
  24715. return geometry;
  24716. };
  24717. PolygonGeometryLibrary.polygonsFromHierarchy = function(polygonHierarchy, perPositionHeight, tangentPlane, ellipsoid) {
  24718. // create from a polygon hierarchy
  24719. // Algorithm adapted from http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
  24720. var hierarchy = [];
  24721. var polygons = [];
  24722. var queue = new Queue();
  24723. queue.enqueue(polygonHierarchy);
  24724. while (queue.length !== 0) {
  24725. var outerNode = queue.dequeue();
  24726. var outerRing = outerNode.positions;
  24727. var holes = outerNode.holes;
  24728. outerRing = arrayRemoveDuplicates(outerRing, Cartesian3.equalsEpsilon, true);
  24729. if (outerRing.length < 3) {
  24730. continue;
  24731. }
  24732. var positions2D = tangentPlane.projectPointsOntoPlane(outerRing);
  24733. var holeIndices = [];
  24734. var originalWindingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
  24735. if (originalWindingOrder === WindingOrder.CLOCKWISE) {
  24736. positions2D.reverse();
  24737. outerRing = outerRing.slice().reverse();
  24738. }
  24739. var positions = outerRing.slice();
  24740. var numChildren = defined(holes) ? holes.length : 0;
  24741. var polygonHoles = [];
  24742. var i;
  24743. var j;
  24744. for (i = 0; i < numChildren; i++) {
  24745. var hole = holes[i];
  24746. var holePositions = arrayRemoveDuplicates(hole.positions, Cartesian3.equalsEpsilon, true);
  24747. if (holePositions.length < 3) {
  24748. continue;
  24749. }
  24750. var holePositions2D = tangentPlane.projectPointsOntoPlane(holePositions);
  24751. originalWindingOrder = PolygonPipeline.computeWindingOrder2D(holePositions2D);
  24752. if (originalWindingOrder === WindingOrder.CLOCKWISE) {
  24753. holePositions2D.reverse();
  24754. holePositions = holePositions.slice().reverse();
  24755. }
  24756. polygonHoles.push(holePositions);
  24757. holeIndices.push(positions.length);
  24758. positions = positions.concat(holePositions);
  24759. positions2D = positions2D.concat(holePositions2D);
  24760. var numGrandchildren = 0;
  24761. if (defined(hole.holes)) {
  24762. numGrandchildren = hole.holes.length;
  24763. }
  24764. for (j = 0; j < numGrandchildren; j++) {
  24765. queue.enqueue(hole.holes[j]);
  24766. }
  24767. }
  24768. if (!perPositionHeight) {
  24769. for (i = 0; i < outerRing.length; i++) {
  24770. ellipsoid.scaleToGeodeticSurface(outerRing[i], outerRing[i]);
  24771. }
  24772. for (i = 0; i < polygonHoles.length; i++) {
  24773. var polygonHole = polygonHoles[i];
  24774. for (j = 0; j < polygonHole.length; ++j) {
  24775. ellipsoid.scaleToGeodeticSurface(polygonHole[j], polygonHole[j]);
  24776. }
  24777. }
  24778. }
  24779. hierarchy.push({
  24780. outerRing : outerRing,
  24781. holes : polygonHoles
  24782. });
  24783. polygons.push({
  24784. positions : positions,
  24785. positions2D : positions2D,
  24786. holes : holeIndices
  24787. });
  24788. }
  24789. return {
  24790. hierarchy : hierarchy,
  24791. polygons : polygons
  24792. };
  24793. };
  24794. PolygonGeometryLibrary.createGeometryFromPositions = function(ellipsoid, polygon, granularity, perPositionHeight, vertexFormat) {
  24795. var indices = PolygonPipeline.triangulate(polygon.positions2D, polygon.holes);
  24796. /* If polygon is completely unrenderable, just use the first three vertices */
  24797. if (indices.length < 3) {
  24798. indices = [0, 1, 2];
  24799. }
  24800. var positions = polygon.positions;
  24801. if (perPositionHeight) {
  24802. var length = positions.length;
  24803. var flattenedPositions = new Array(length * 3);
  24804. var index = 0;
  24805. for ( var i = 0; i < length; i++) {
  24806. var p = positions[i];
  24807. flattenedPositions[index++] = p.x;
  24808. flattenedPositions[index++] = p.y;
  24809. flattenedPositions[index++] = p.z;
  24810. }
  24811. var geometry = new Geometry({
  24812. attributes : {
  24813. position : new GeometryAttribute({
  24814. componentDatatype : ComponentDatatype.DOUBLE,
  24815. componentsPerAttribute : 3,
  24816. values : flattenedPositions
  24817. })
  24818. },
  24819. indices : indices,
  24820. primitiveType : PrimitiveType.TRIANGLES
  24821. });
  24822. if (vertexFormat.normal) {
  24823. return GeometryPipeline.computeNormal(geometry);
  24824. }
  24825. return geometry;
  24826. }
  24827. return PolygonPipeline.computeSubdivision(ellipsoid, positions, indices, granularity);
  24828. };
  24829. var computeWallIndicesSubdivided = [];
  24830. var p1Scratch = new Cartesian3();
  24831. var p2Scratch = new Cartesian3();
  24832. PolygonGeometryLibrary.computeWallGeometry = function(positions, ellipsoid, granularity, perPositionHeight) {
  24833. var edgePositions;
  24834. var topEdgeLength;
  24835. var i;
  24836. var p1;
  24837. var p2;
  24838. var length = positions.length;
  24839. var index = 0;
  24840. if (!perPositionHeight) {
  24841. var minDistance = CesiumMath.chordLength(granularity, ellipsoid.maximumRadius);
  24842. var numVertices = 0;
  24843. for (i = 0; i < length; i++) {
  24844. numVertices += PolygonGeometryLibrary.subdivideLineCount(positions[i], positions[(i + 1) % length], minDistance);
  24845. }
  24846. topEdgeLength = (numVertices + length) * 3;
  24847. edgePositions = new Array(topEdgeLength * 2);
  24848. for (i = 0; i < length; i++) {
  24849. p1 = positions[i];
  24850. p2 = positions[(i + 1) % length];
  24851. var tempPositions = PolygonGeometryLibrary.subdivideLine(p1, p2, minDistance, computeWallIndicesSubdivided);
  24852. var tempPositionsLength = tempPositions.length;
  24853. for (var j = 0; j < tempPositionsLength; ++j, ++index) {
  24854. edgePositions[index] = tempPositions[j];
  24855. edgePositions[index + topEdgeLength] = tempPositions[j];
  24856. }
  24857. edgePositions[index] = p2.x;
  24858. edgePositions[index + topEdgeLength] = p2.x;
  24859. ++index;
  24860. edgePositions[index] = p2.y;
  24861. edgePositions[index + topEdgeLength] = p2.y;
  24862. ++index;
  24863. edgePositions[index] = p2.z;
  24864. edgePositions[index + topEdgeLength] = p2.z;
  24865. ++index;
  24866. }
  24867. } else {
  24868. topEdgeLength = length * 3 * 2;
  24869. edgePositions = new Array(topEdgeLength * 2);
  24870. for (i = 0; i < length; i++) {
  24871. p1 = positions[i];
  24872. p2 = positions[(i + 1) % length];
  24873. edgePositions[index] = edgePositions[index + topEdgeLength] = p1.x;
  24874. ++index;
  24875. edgePositions[index] = edgePositions[index + topEdgeLength] = p1.y;
  24876. ++index;
  24877. edgePositions[index] = edgePositions[index + topEdgeLength] = p1.z;
  24878. ++index;
  24879. edgePositions[index] = edgePositions[index + topEdgeLength] = p2.x;
  24880. ++index;
  24881. edgePositions[index] = edgePositions[index + topEdgeLength] = p2.y;
  24882. ++index;
  24883. edgePositions[index] = edgePositions[index + topEdgeLength] = p2.z;
  24884. ++index;
  24885. }
  24886. }
  24887. length = edgePositions.length;
  24888. var indices = IndexDatatype.createTypedArray(length / 3, length - positions.length * 6);
  24889. var edgeIndex = 0;
  24890. length /= 6;
  24891. for (i = 0; i < length; i++) {
  24892. var UL = i;
  24893. var UR = UL + 1;
  24894. var LL = UL + length;
  24895. var LR = LL + 1;
  24896. p1 = Cartesian3.fromArray(edgePositions, UL * 3, p1Scratch);
  24897. p2 = Cartesian3.fromArray(edgePositions, UR * 3, p2Scratch);
  24898. if (Cartesian3.equalsEpsilon(p1, p2, CesiumMath.EPSILON14)) {
  24899. continue;
  24900. }
  24901. indices[edgeIndex++] = UL;
  24902. indices[edgeIndex++] = LL;
  24903. indices[edgeIndex++] = UR;
  24904. indices[edgeIndex++] = UR;
  24905. indices[edgeIndex++] = LL;
  24906. indices[edgeIndex++] = LR;
  24907. }
  24908. return new Geometry({
  24909. attributes : new GeometryAttributes({
  24910. position : new GeometryAttribute({
  24911. componentDatatype : ComponentDatatype.DOUBLE,
  24912. componentsPerAttribute : 3,
  24913. values : edgePositions
  24914. })
  24915. }),
  24916. indices : indices,
  24917. primitiveType : PrimitiveType.TRIANGLES
  24918. });
  24919. };
  24920. return PolygonGeometryLibrary;
  24921. });
  24922. /*global define*/
  24923. define('Core/PolygonOutlineGeometry',[
  24924. './arrayRemoveDuplicates',
  24925. './BoundingSphere',
  24926. './Cartesian3',
  24927. './ComponentDatatype',
  24928. './defaultValue',
  24929. './defined',
  24930. './DeveloperError',
  24931. './Ellipsoid',
  24932. './EllipsoidTangentPlane',
  24933. './Geometry',
  24934. './GeometryAttribute',
  24935. './GeometryAttributes',
  24936. './GeometryInstance',
  24937. './GeometryPipeline',
  24938. './IndexDatatype',
  24939. './Math',
  24940. './PolygonGeometryLibrary',
  24941. './PolygonPipeline',
  24942. './PrimitiveType',
  24943. './Queue',
  24944. './WindingOrder'
  24945. ], function(
  24946. arrayRemoveDuplicates,
  24947. BoundingSphere,
  24948. Cartesian3,
  24949. ComponentDatatype,
  24950. defaultValue,
  24951. defined,
  24952. DeveloperError,
  24953. Ellipsoid,
  24954. EllipsoidTangentPlane,
  24955. Geometry,
  24956. GeometryAttribute,
  24957. GeometryAttributes,
  24958. GeometryInstance,
  24959. GeometryPipeline,
  24960. IndexDatatype,
  24961. CesiumMath,
  24962. PolygonGeometryLibrary,
  24963. PolygonPipeline,
  24964. PrimitiveType,
  24965. Queue,
  24966. WindingOrder) {
  24967. 'use strict';
  24968. var createGeometryFromPositionsPositions = [];
  24969. var createGeometryFromPositionsSubdivided = [];
  24970. function createGeometryFromPositions(ellipsoid, positions, minDistance, perPositionHeight) {
  24971. var tangentPlane = EllipsoidTangentPlane.fromPoints(positions, ellipsoid);
  24972. var positions2D = tangentPlane.projectPointsOntoPlane(positions, createGeometryFromPositionsPositions);
  24973. var originalWindingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
  24974. if (originalWindingOrder === WindingOrder.CLOCKWISE) {
  24975. positions2D.reverse();
  24976. positions = positions.slice().reverse();
  24977. }
  24978. var subdividedPositions;
  24979. var i;
  24980. var length = positions.length;
  24981. var index = 0;
  24982. if (!perPositionHeight) {
  24983. var numVertices = 0;
  24984. for (i = 0; i < length; i++) {
  24985. numVertices += PolygonGeometryLibrary.subdivideLineCount(positions[i], positions[(i + 1) % length], minDistance);
  24986. }
  24987. subdividedPositions = new Float64Array(numVertices * 3);
  24988. for (i = 0; i < length; i++) {
  24989. var tempPositions = PolygonGeometryLibrary.subdivideLine(positions[i], positions[(i + 1) % length], minDistance, createGeometryFromPositionsSubdivided);
  24990. var tempPositionsLength = tempPositions.length;
  24991. for (var j = 0; j < tempPositionsLength; ++j) {
  24992. subdividedPositions[index++] = tempPositions[j];
  24993. }
  24994. }
  24995. } else {
  24996. subdividedPositions = new Float64Array(length * 2 * 3);
  24997. for (i = 0; i < length; i++) {
  24998. var p0 = positions[i];
  24999. var p1 = positions[(i + 1) % length];
  25000. subdividedPositions[index++] = p0.x;
  25001. subdividedPositions[index++] = p0.y;
  25002. subdividedPositions[index++] = p0.z;
  25003. subdividedPositions[index++] = p1.x;
  25004. subdividedPositions[index++] = p1.y;
  25005. subdividedPositions[index++] = p1.z;
  25006. }
  25007. }
  25008. length = subdividedPositions.length / 3;
  25009. var indicesSize = length * 2;
  25010. var indices = IndexDatatype.createTypedArray(length, indicesSize);
  25011. index = 0;
  25012. for (i = 0; i < length - 1; i++) {
  25013. indices[index++] = i;
  25014. indices[index++] = i + 1;
  25015. }
  25016. indices[index++] = length - 1;
  25017. indices[index++] = 0;
  25018. return new GeometryInstance({
  25019. geometry : new Geometry({
  25020. attributes : new GeometryAttributes({
  25021. position : new GeometryAttribute({
  25022. componentDatatype : ComponentDatatype.DOUBLE,
  25023. componentsPerAttribute : 3,
  25024. values : subdividedPositions
  25025. })
  25026. }),
  25027. indices : indices,
  25028. primitiveType : PrimitiveType.LINES
  25029. })
  25030. });
  25031. }
  25032. function createGeometryFromPositionsExtruded(ellipsoid, positions, minDistance, perPositionHeight) {
  25033. var tangentPlane = EllipsoidTangentPlane.fromPoints(positions, ellipsoid);
  25034. var positions2D = tangentPlane.projectPointsOntoPlane(positions, createGeometryFromPositionsPositions);
  25035. var originalWindingOrder = PolygonPipeline.computeWindingOrder2D(positions2D);
  25036. if (originalWindingOrder === WindingOrder.CLOCKWISE) {
  25037. positions2D.reverse();
  25038. positions = positions.slice().reverse();
  25039. }
  25040. var subdividedPositions;
  25041. var i;
  25042. var length = positions.length;
  25043. var corners = new Array(length);
  25044. var index = 0;
  25045. if (!perPositionHeight) {
  25046. var numVertices = 0;
  25047. for (i = 0; i < length; i++) {
  25048. numVertices += PolygonGeometryLibrary.subdivideLineCount(positions[i], positions[(i + 1) % length], minDistance);
  25049. }
  25050. subdividedPositions = new Float64Array(numVertices * 3 * 2);
  25051. for (i = 0; i < length; ++i) {
  25052. corners[i] = index / 3;
  25053. var tempPositions = PolygonGeometryLibrary.subdivideLine(positions[i], positions[(i + 1) % length], minDistance, createGeometryFromPositionsSubdivided);
  25054. var tempPositionsLength = tempPositions.length;
  25055. for (var j = 0; j < tempPositionsLength; ++j) {
  25056. subdividedPositions[index++] = tempPositions[j];
  25057. }
  25058. }
  25059. } else {
  25060. subdividedPositions = new Float64Array(length * 2 * 3 * 2);
  25061. for (i = 0; i < length; ++i) {
  25062. corners[i] = index / 3;
  25063. var p0 = positions[i];
  25064. var p1 = positions[(i + 1) % length];
  25065. subdividedPositions[index++] = p0.x;
  25066. subdividedPositions[index++] = p0.y;
  25067. subdividedPositions[index++] = p0.z;
  25068. subdividedPositions[index++] = p1.x;
  25069. subdividedPositions[index++] = p1.y;
  25070. subdividedPositions[index++] = p1.z;
  25071. }
  25072. }
  25073. length = subdividedPositions.length / (3 * 2);
  25074. var cornersLength = corners.length;
  25075. var indicesSize = ((length * 2) + cornersLength) * 2;
  25076. var indices = IndexDatatype.createTypedArray(length, indicesSize);
  25077. index = 0;
  25078. for (i = 0; i < length; ++i) {
  25079. indices[index++] = i;
  25080. indices[index++] = (i + 1) % length;
  25081. indices[index++] = i + length;
  25082. indices[index++] = ((i + 1) % length) + length;
  25083. }
  25084. for (i = 0; i < cornersLength; i++) {
  25085. var corner = corners[i];
  25086. indices[index++] = corner;
  25087. indices[index++] = corner + length;
  25088. }
  25089. return new GeometryInstance({
  25090. geometry : new Geometry({
  25091. attributes : new GeometryAttributes({
  25092. position : new GeometryAttribute({
  25093. componentDatatype : ComponentDatatype.DOUBLE,
  25094. componentsPerAttribute : 3,
  25095. values : subdividedPositions
  25096. })
  25097. }),
  25098. indices : indices,
  25099. primitiveType : PrimitiveType.LINES
  25100. })
  25101. });
  25102. }
  25103. /**
  25104. * A description of the outline of a polygon on the ellipsoid. The polygon is defined by a polygon hierarchy.
  25105. *
  25106. * @alias PolygonOutlineGeometry
  25107. * @constructor
  25108. *
  25109. * @param {Object} options Object with the following properties:
  25110. * @param {PolygonHierarchy} options.polygonHierarchy A polygon hierarchy that can include holes.
  25111. * @param {Number} [options.height=0.0] The distance in meters between the polygon and the ellipsoid surface.
  25112. * @param {Number} [options.extrudedHeight] The distance in meters between the polygon's extruded face and the ellipsoid surface.
  25113. * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
  25114. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
  25115. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  25116. * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
  25117. *
  25118. * @see PolygonOutlineGeometry#createGeometry
  25119. * @see PolygonOutlineGeometry#fromPositions
  25120. *
  25121. * @example
  25122. * // 1. create a polygon outline from points
  25123. * var polygon = new Cesium.PolygonOutlineGeometry({
  25124. * polygonHierarchy : new Cesium.PolygonHierarchy(
  25125. * Cesium.Cartesian3.fromDegreesArray([
  25126. * -72.0, 40.0,
  25127. * -70.0, 35.0,
  25128. * -75.0, 30.0,
  25129. * -70.0, 30.0,
  25130. * -68.0, 40.0
  25131. * ])
  25132. * )
  25133. * });
  25134. * var geometry = Cesium.PolygonOutlineGeometry.createGeometry(polygon);
  25135. *
  25136. * // 2. create a nested polygon with holes outline
  25137. * var polygonWithHole = new Cesium.PolygonOutlineGeometry({
  25138. * polygonHierarchy : new Cesium.PolygonHierarchy(
  25139. * Cesium.Cartesian3.fromDegreesArray([
  25140. * -109.0, 30.0,
  25141. * -95.0, 30.0,
  25142. * -95.0, 40.0,
  25143. * -109.0, 40.0
  25144. * ]),
  25145. * [new Cesium.PolygonHierarchy(
  25146. * Cesium.Cartesian3.fromDegreesArray([
  25147. * -107.0, 31.0,
  25148. * -107.0, 39.0,
  25149. * -97.0, 39.0,
  25150. * -97.0, 31.0
  25151. * ]),
  25152. * [new Cesium.PolygonHierarchy(
  25153. * Cesium.Cartesian3.fromDegreesArray([
  25154. * -105.0, 33.0,
  25155. * -99.0, 33.0,
  25156. * -99.0, 37.0,
  25157. * -105.0, 37.0
  25158. * ]),
  25159. * [new Cesium.PolygonHierarchy(
  25160. * Cesium.Cartesian3.fromDegreesArray([
  25161. * -103.0, 34.0,
  25162. * -101.0, 34.0,
  25163. * -101.0, 36.0,
  25164. * -103.0, 36.0
  25165. * ])
  25166. * )]
  25167. * )]
  25168. * )]
  25169. * )
  25170. * });
  25171. * var geometry = Cesium.PolygonOutlineGeometry.createGeometry(polygonWithHole);
  25172. *
  25173. * // 3. create extruded polygon outline
  25174. * var extrudedPolygon = new Cesium.PolygonOutlineGeometry({
  25175. * polygonHierarchy : new Cesium.PolygonHierarchy(
  25176. * Cesium.Cartesian3.fromDegreesArray([
  25177. * -72.0, 40.0,
  25178. * -70.0, 35.0,
  25179. * -75.0, 30.0,
  25180. * -70.0, 30.0,
  25181. * -68.0, 40.0
  25182. * ])
  25183. * ),
  25184. * extrudedHeight: 300000
  25185. * });
  25186. * var geometry = Cesium.PolygonOutlineGeometry.createGeometry(extrudedPolygon);
  25187. */
  25188. function PolygonOutlineGeometry(options) {
  25189. if (!defined(options) || !defined(options.polygonHierarchy)) {
  25190. throw new DeveloperError('options.polygonHierarchy is required.');
  25191. }
  25192. if (defined(options.perPositionHeight) && options.perPositionHeight && defined(options.height)) {
  25193. throw new DeveloperError('Cannot use both options.perPositionHeight and options.height');
  25194. }
  25195. var polygonHierarchy = options.polygonHierarchy;
  25196. var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  25197. var granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
  25198. var height = defaultValue(options.height, 0.0);
  25199. var perPositionHeight = defaultValue(options.perPositionHeight, false);
  25200. var extrudedHeight = options.extrudedHeight;
  25201. var extrude = defined(extrudedHeight);
  25202. if (extrude && !perPositionHeight) {
  25203. var h = extrudedHeight;
  25204. extrudedHeight = Math.min(h, height);
  25205. height = Math.max(h, height);
  25206. }
  25207. this._ellipsoid = Ellipsoid.clone(ellipsoid);
  25208. this._granularity = granularity;
  25209. this._height = height;
  25210. this._extrudedHeight = defaultValue(extrudedHeight, 0.0);
  25211. this._extrude = extrude;
  25212. this._polygonHierarchy = polygonHierarchy;
  25213. this._perPositionHeight = perPositionHeight;
  25214. this._workerName = 'createPolygonOutlineGeometry';
  25215. /**
  25216. * The number of elements used to pack the object into an array.
  25217. * @type {Number}
  25218. */
  25219. this.packedLength = PolygonGeometryLibrary.computeHierarchyPackedLength(polygonHierarchy) + Ellipsoid.packedLength + 6;
  25220. }
  25221. /**
  25222. * Stores the provided instance into the provided array.
  25223. *
  25224. * @param {PolygonOutlineGeometry} value The value to pack.
  25225. * @param {Number[]} array The array to pack into.
  25226. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  25227. *
  25228. * @returns {Number[]} The array that was packed into
  25229. */
  25230. PolygonOutlineGeometry.pack = function(value, array, startingIndex) {
  25231. if (!defined(value)) {
  25232. throw new DeveloperError('value is required');
  25233. }
  25234. if (!defined(array)) {
  25235. throw new DeveloperError('array is required');
  25236. }
  25237. startingIndex = defaultValue(startingIndex, 0);
  25238. startingIndex = PolygonGeometryLibrary.packPolygonHierarchy(value._polygonHierarchy, array, startingIndex);
  25239. Ellipsoid.pack(value._ellipsoid, array, startingIndex);
  25240. startingIndex += Ellipsoid.packedLength;
  25241. array[startingIndex++] = value._height;
  25242. array[startingIndex++] = value._extrudedHeight;
  25243. array[startingIndex++] = value._granularity;
  25244. array[startingIndex++] = value._extrude ? 1.0 : 0.0;
  25245. array[startingIndex++] = value._perPositionHeight ? 1.0 : 0.0;
  25246. array[startingIndex++] = value.packedLength;
  25247. return array;
  25248. };
  25249. var scratchEllipsoid = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  25250. var dummyOptions = {
  25251. polygonHierarchy : {}
  25252. };
  25253. /**
  25254. * Retrieves an instance from a packed array.
  25255. *
  25256. * @param {Number[]} array The packed array.
  25257. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  25258. * @param {PolygonOutlineGeometry} [result] The object into which to store the result.
  25259. * @returns {PolygonOutlineGeometry} The modified result parameter or a new PolygonOutlineGeometry instance if one was not provided.
  25260. */
  25261. PolygonOutlineGeometry.unpack = function(array, startingIndex, result) {
  25262. if (!defined(array)) {
  25263. throw new DeveloperError('array is required');
  25264. }
  25265. startingIndex = defaultValue(startingIndex, 0);
  25266. var polygonHierarchy = PolygonGeometryLibrary.unpackPolygonHierarchy(array, startingIndex);
  25267. startingIndex = polygonHierarchy.startingIndex;
  25268. delete polygonHierarchy.startingIndex;
  25269. var ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
  25270. startingIndex += Ellipsoid.packedLength;
  25271. var height = array[startingIndex++];
  25272. var extrudedHeight = array[startingIndex++];
  25273. var granularity = array[startingIndex++];
  25274. var extrude = array[startingIndex++] === 1.0;
  25275. var perPositionHeight = array[startingIndex++] === 1.0;
  25276. var packedLength = array[startingIndex++];
  25277. if (!defined(result)) {
  25278. result = new PolygonOutlineGeometry(dummyOptions);
  25279. }
  25280. result._polygonHierarchy = polygonHierarchy;
  25281. result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
  25282. result._height = height;
  25283. result._extrudedHeight = extrudedHeight;
  25284. result._granularity = granularity;
  25285. result._extrude = extrude;
  25286. result._perPositionHeight = perPositionHeight;
  25287. result.packedLength = packedLength;
  25288. return result;
  25289. };
  25290. /**
  25291. * A description of a polygon outline from an array of positions.
  25292. *
  25293. * @param {Object} options Object with the following properties:
  25294. * @param {Cartesian3[]} options.positions An array of positions that defined the corner points of the polygon.
  25295. * @param {Number} [options.height=0.0] The height of the polygon.
  25296. * @param {Number} [options.extrudedHeight] The height of the polygon extrusion.
  25297. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
  25298. * @param {Number} [options.granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  25299. * @param {Boolean} [options.perPositionHeight=false] Use the height of options.positions for each position instead of using options.height to determine the height.
  25300. * @returns {PolygonOutlineGeometry}
  25301. *
  25302. *
  25303. * @example
  25304. * // create a polygon from points
  25305. * var polygon = Cesium.PolygonOutlineGeometry.fromPositions({
  25306. * positions : Cesium.Cartesian3.fromDegreesArray([
  25307. * -72.0, 40.0,
  25308. * -70.0, 35.0,
  25309. * -75.0, 30.0,
  25310. * -70.0, 30.0,
  25311. * -68.0, 40.0
  25312. * ])
  25313. * });
  25314. * var geometry = Cesium.PolygonOutlineGeometry.createGeometry(polygon);
  25315. *
  25316. * @see PolygonOutlineGeometry#createGeometry
  25317. */
  25318. PolygonOutlineGeometry.fromPositions = function(options) {
  25319. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  25320. if (!defined(options.positions)) {
  25321. throw new DeveloperError('options.positions is required.');
  25322. }
  25323. var newOptions = {
  25324. polygonHierarchy : {
  25325. positions : options.positions
  25326. },
  25327. height : options.height,
  25328. extrudedHeight : options.extrudedHeight,
  25329. ellipsoid : options.ellipsoid,
  25330. granularity : options.granularity,
  25331. perPositionHeight : options.perPositionHeight
  25332. };
  25333. return new PolygonOutlineGeometry(newOptions);
  25334. };
  25335. /**
  25336. * Computes the geometric representation of a polygon outline, including its vertices, indices, and a bounding sphere.
  25337. *
  25338. * @param {PolygonOutlineGeometry} polygonGeometry A description of the polygon outline.
  25339. * @returns {Geometry|undefined} The computed vertices and indices.
  25340. */
  25341. PolygonOutlineGeometry.createGeometry = function(polygonGeometry) {
  25342. var ellipsoid = polygonGeometry._ellipsoid;
  25343. var granularity = polygonGeometry._granularity;
  25344. var height = polygonGeometry._height;
  25345. var extrudedHeight = polygonGeometry._extrudedHeight;
  25346. var extrude = polygonGeometry._extrude;
  25347. var polygonHierarchy = polygonGeometry._polygonHierarchy;
  25348. var perPositionHeight = polygonGeometry._perPositionHeight;
  25349. // create from a polygon hierarchy
  25350. // Algorithm adapted from http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
  25351. var polygons = [];
  25352. var queue = new Queue();
  25353. queue.enqueue(polygonHierarchy);
  25354. var i;
  25355. while (queue.length !== 0) {
  25356. var outerNode = queue.dequeue();
  25357. var outerRing = outerNode.positions;
  25358. outerRing = arrayRemoveDuplicates(outerRing, Cartesian3.equalsEpsilon, true);
  25359. if (outerRing.length < 3) {
  25360. continue;
  25361. }
  25362. var numChildren = outerNode.holes ? outerNode.holes.length : 0;
  25363. // The outer polygon contains inner polygons
  25364. for (i = 0; i < numChildren; i++) {
  25365. var hole = outerNode.holes[i];
  25366. hole.positions = arrayRemoveDuplicates(hole.positions, Cartesian3.equalsEpsilon, true);
  25367. if (hole.positions.length < 3) {
  25368. continue;
  25369. }
  25370. polygons.push(hole.positions);
  25371. var numGrandchildren = 0;
  25372. if (defined(hole.holes)) {
  25373. numGrandchildren = hole.holes.length;
  25374. }
  25375. for ( var j = 0; j < numGrandchildren; j++) {
  25376. queue.enqueue(hole.holes[j]);
  25377. }
  25378. }
  25379. polygons.push(outerRing);
  25380. }
  25381. if (polygons.length === 0) {
  25382. return undefined;
  25383. }
  25384. var geometry;
  25385. var geometries = [];
  25386. var minDistance = CesiumMath.chordLength(granularity, ellipsoid.maximumRadius);
  25387. if (extrude) {
  25388. for (i = 0; i < polygons.length; i++) {
  25389. geometry = createGeometryFromPositionsExtruded(ellipsoid, polygons[i], minDistance, perPositionHeight);
  25390. geometry.geometry = PolygonGeometryLibrary.scaleToGeodeticHeightExtruded(geometry.geometry, height, extrudedHeight, ellipsoid, perPositionHeight);
  25391. geometries.push(geometry);
  25392. }
  25393. } else {
  25394. for (i = 0; i < polygons.length; i++) {
  25395. geometry = createGeometryFromPositions(ellipsoid, polygons[i], minDistance, perPositionHeight);
  25396. geometry.geometry.attributes.position.values = PolygonPipeline.scaleToGeodeticHeight(geometry.geometry.attributes.position.values, height, ellipsoid, !perPositionHeight);
  25397. geometries.push(geometry);
  25398. }
  25399. }
  25400. geometry = GeometryPipeline.combineInstances(geometries)[0];
  25401. var boundingSphere = BoundingSphere.fromVertices(geometry.attributes.position.values);
  25402. return new Geometry({
  25403. attributes : geometry.attributes,
  25404. indices : geometry.indices,
  25405. primitiveType : geometry.primitiveType,
  25406. boundingSphere : boundingSphere
  25407. });
  25408. };
  25409. return PolygonOutlineGeometry;
  25410. });
  25411. /*global define*/
  25412. define('Workers/createPolygonOutlineGeometry',[
  25413. '../Core/defined',
  25414. '../Core/Ellipsoid',
  25415. '../Core/PolygonOutlineGeometry'
  25416. ], function(
  25417. defined,
  25418. Ellipsoid,
  25419. PolygonOutlineGeometry) {
  25420. 'use strict';
  25421. function createPolygonOutlineGeometry(polygonGeometry, offset) {
  25422. if (defined(offset)) {
  25423. polygonGeometry = PolygonOutlineGeometry.unpack(polygonGeometry, offset);
  25424. }
  25425. polygonGeometry._ellipsoid = Ellipsoid.clone(polygonGeometry._ellipsoid);
  25426. return PolygonOutlineGeometry.createGeometry(polygonGeometry);
  25427. }
  25428. return createPolygonOutlineGeometry;
  25429. });
  25430. }());