createPolylineVolumeGeometry.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783
  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/Cartesian2',[
  3145. './defaultValue',
  3146. './defined',
  3147. './DeveloperError',
  3148. './freezeObject',
  3149. './Math'
  3150. ], function(
  3151. defaultValue,
  3152. defined,
  3153. DeveloperError,
  3154. freezeObject,
  3155. CesiumMath) {
  3156. 'use strict';
  3157. /**
  3158. * A 2D Cartesian point.
  3159. * @alias Cartesian2
  3160. * @constructor
  3161. *
  3162. * @param {Number} [x=0.0] The X component.
  3163. * @param {Number} [y=0.0] The Y component.
  3164. *
  3165. * @see Cartesian3
  3166. * @see Cartesian4
  3167. * @see Packable
  3168. */
  3169. function Cartesian2(x, y) {
  3170. /**
  3171. * The X component.
  3172. * @type {Number}
  3173. * @default 0.0
  3174. */
  3175. this.x = defaultValue(x, 0.0);
  3176. /**
  3177. * The Y component.
  3178. * @type {Number}
  3179. * @default 0.0
  3180. */
  3181. this.y = defaultValue(y, 0.0);
  3182. }
  3183. /**
  3184. * Creates a Cartesian2 instance from x and y coordinates.
  3185. *
  3186. * @param {Number} x The x coordinate.
  3187. * @param {Number} y The y coordinate.
  3188. * @param {Cartesian2} [result] The object onto which to store the result.
  3189. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3190. */
  3191. Cartesian2.fromElements = function(x, y, result) {
  3192. if (!defined(result)) {
  3193. return new Cartesian2(x, y);
  3194. }
  3195. result.x = x;
  3196. result.y = y;
  3197. return result;
  3198. };
  3199. /**
  3200. * Duplicates a Cartesian2 instance.
  3201. *
  3202. * @param {Cartesian2} cartesian The Cartesian to duplicate.
  3203. * @param {Cartesian2} [result] The object onto which to store the result.
  3204. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. (Returns undefined if cartesian is undefined)
  3205. */
  3206. Cartesian2.clone = function(cartesian, result) {
  3207. if (!defined(cartesian)) {
  3208. return undefined;
  3209. }
  3210. if (!defined(result)) {
  3211. return new Cartesian2(cartesian.x, cartesian.y);
  3212. }
  3213. result.x = cartesian.x;
  3214. result.y = cartesian.y;
  3215. return result;
  3216. };
  3217. /**
  3218. * Creates a Cartesian2 instance from an existing Cartesian3. This simply takes the
  3219. * x and y properties of the Cartesian3 and drops z.
  3220. * @function
  3221. *
  3222. * @param {Cartesian3} cartesian The Cartesian3 instance to create a Cartesian2 instance from.
  3223. * @param {Cartesian2} [result] The object onto which to store the result.
  3224. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3225. */
  3226. Cartesian2.fromCartesian3 = Cartesian2.clone;
  3227. /**
  3228. * Creates a Cartesian2 instance from an existing Cartesian4. This simply takes the
  3229. * x and y properties of the Cartesian4 and drops z and w.
  3230. * @function
  3231. *
  3232. * @param {Cartesian4} cartesian The Cartesian4 instance to create a Cartesian2 instance from.
  3233. * @param {Cartesian2} [result] The object onto which to store the result.
  3234. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3235. */
  3236. Cartesian2.fromCartesian4 = Cartesian2.clone;
  3237. /**
  3238. * The number of elements used to pack the object into an array.
  3239. * @type {Number}
  3240. */
  3241. Cartesian2.packedLength = 2;
  3242. /**
  3243. * Stores the provided instance into the provided array.
  3244. *
  3245. * @param {Cartesian2} value The value to pack.
  3246. * @param {Number[]} array The array to pack into.
  3247. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  3248. *
  3249. * @returns {Number[]} The array that was packed into
  3250. */
  3251. Cartesian2.pack = function(value, array, startingIndex) {
  3252. if (!defined(value)) {
  3253. throw new DeveloperError('value is required');
  3254. }
  3255. if (!defined(array)) {
  3256. throw new DeveloperError('array is required');
  3257. }
  3258. startingIndex = defaultValue(startingIndex, 0);
  3259. array[startingIndex++] = value.x;
  3260. array[startingIndex] = value.y;
  3261. return array;
  3262. };
  3263. /**
  3264. * Retrieves an instance from a packed array.
  3265. *
  3266. * @param {Number[]} array The packed array.
  3267. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  3268. * @param {Cartesian2} [result] The object into which to store the result.
  3269. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3270. */
  3271. Cartesian2.unpack = function(array, startingIndex, result) {
  3272. if (!defined(array)) {
  3273. throw new DeveloperError('array is required');
  3274. }
  3275. startingIndex = defaultValue(startingIndex, 0);
  3276. if (!defined(result)) {
  3277. result = new Cartesian2();
  3278. }
  3279. result.x = array[startingIndex++];
  3280. result.y = array[startingIndex];
  3281. return result;
  3282. };
  3283. /**
  3284. * Flattens an array of Cartesian2s into and array of components.
  3285. *
  3286. * @param {Cartesian2[]} array The array of cartesians to pack.
  3287. * @param {Number[]} result The array onto which to store the result.
  3288. * @returns {Number[]} The packed array.
  3289. */
  3290. Cartesian2.packArray = function(array, result) {
  3291. if (!defined(array)) {
  3292. throw new DeveloperError('array is required');
  3293. }
  3294. var length = array.length;
  3295. if (!defined(result)) {
  3296. result = new Array(length * 2);
  3297. } else {
  3298. result.length = length * 2;
  3299. }
  3300. for (var i = 0; i < length; ++i) {
  3301. Cartesian2.pack(array[i], result, i * 2);
  3302. }
  3303. return result;
  3304. };
  3305. /**
  3306. * Unpacks an array of cartesian components into and array of Cartesian2s.
  3307. *
  3308. * @param {Number[]} array The array of components to unpack.
  3309. * @param {Cartesian2[]} result The array onto which to store the result.
  3310. * @returns {Cartesian2[]} The unpacked array.
  3311. */
  3312. Cartesian2.unpackArray = function(array, result) {
  3313. if (!defined(array)) {
  3314. throw new DeveloperError('array is required');
  3315. }
  3316. var length = array.length;
  3317. if (!defined(result)) {
  3318. result = new Array(length / 2);
  3319. } else {
  3320. result.length = length / 2;
  3321. }
  3322. for (var i = 0; i < length; i += 2) {
  3323. var index = i / 2;
  3324. result[index] = Cartesian2.unpack(array, i, result[index]);
  3325. }
  3326. return result;
  3327. };
  3328. /**
  3329. * Creates a Cartesian2 from two consecutive elements in an array.
  3330. * @function
  3331. *
  3332. * @param {Number[]} array The array whose two consecutive elements correspond to the x and y components, respectively.
  3333. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  3334. * @param {Cartesian2} [result] The object onto which to store the result.
  3335. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3336. *
  3337. * @example
  3338. * // Create a Cartesian2 with (1.0, 2.0)
  3339. * var v = [1.0, 2.0];
  3340. * var p = Cesium.Cartesian2.fromArray(v);
  3341. *
  3342. * // Create a Cartesian2 with (1.0, 2.0) using an offset into an array
  3343. * var v2 = [0.0, 0.0, 1.0, 2.0];
  3344. * var p2 = Cesium.Cartesian2.fromArray(v2, 2);
  3345. */
  3346. Cartesian2.fromArray = Cartesian2.unpack;
  3347. /**
  3348. * Computes the value of the maximum component for the supplied Cartesian.
  3349. *
  3350. * @param {Cartesian2} cartesian The cartesian to use.
  3351. * @returns {Number} The value of the maximum component.
  3352. */
  3353. Cartesian2.maximumComponent = function(cartesian) {
  3354. if (!defined(cartesian)) {
  3355. throw new DeveloperError('cartesian is required');
  3356. }
  3357. return Math.max(cartesian.x, cartesian.y);
  3358. };
  3359. /**
  3360. * Computes the value of the minimum component for the supplied Cartesian.
  3361. *
  3362. * @param {Cartesian2} cartesian The cartesian to use.
  3363. * @returns {Number} The value of the minimum component.
  3364. */
  3365. Cartesian2.minimumComponent = function(cartesian) {
  3366. if (!defined(cartesian)) {
  3367. throw new DeveloperError('cartesian is required');
  3368. }
  3369. return Math.min(cartesian.x, cartesian.y);
  3370. };
  3371. /**
  3372. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  3373. *
  3374. * @param {Cartesian2} first A cartesian to compare.
  3375. * @param {Cartesian2} second A cartesian to compare.
  3376. * @param {Cartesian2} result The object into which to store the result.
  3377. * @returns {Cartesian2} A cartesian with the minimum components.
  3378. */
  3379. Cartesian2.minimumByComponent = function(first, second, result) {
  3380. if (!defined(first)) {
  3381. throw new DeveloperError('first is required.');
  3382. }
  3383. if (!defined(second)) {
  3384. throw new DeveloperError('second is required.');
  3385. }
  3386. if (!defined(result)) {
  3387. throw new DeveloperError('result is required.');
  3388. }
  3389. result.x = Math.min(first.x, second.x);
  3390. result.y = Math.min(first.y, second.y);
  3391. return result;
  3392. };
  3393. /**
  3394. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  3395. *
  3396. * @param {Cartesian2} first A cartesian to compare.
  3397. * @param {Cartesian2} second A cartesian to compare.
  3398. * @param {Cartesian2} result The object into which to store the result.
  3399. * @returns {Cartesian2} A cartesian with the maximum components.
  3400. */
  3401. Cartesian2.maximumByComponent = function(first, second, result) {
  3402. if (!defined(first)) {
  3403. throw new DeveloperError('first is required.');
  3404. }
  3405. if (!defined(second)) {
  3406. throw new DeveloperError('second is required.');
  3407. }
  3408. if (!defined(result)) {
  3409. throw new DeveloperError('result is required.');
  3410. }
  3411. result.x = Math.max(first.x, second.x);
  3412. result.y = Math.max(first.y, second.y);
  3413. return result;
  3414. };
  3415. /**
  3416. * Computes the provided Cartesian's squared magnitude.
  3417. *
  3418. * @param {Cartesian2} cartesian The Cartesian instance whose squared magnitude is to be computed.
  3419. * @returns {Number} The squared magnitude.
  3420. */
  3421. Cartesian2.magnitudeSquared = function(cartesian) {
  3422. if (!defined(cartesian)) {
  3423. throw new DeveloperError('cartesian is required');
  3424. }
  3425. return cartesian.x * cartesian.x + cartesian.y * cartesian.y;
  3426. };
  3427. /**
  3428. * Computes the Cartesian's magnitude (length).
  3429. *
  3430. * @param {Cartesian2} cartesian The Cartesian instance whose magnitude is to be computed.
  3431. * @returns {Number} The magnitude.
  3432. */
  3433. Cartesian2.magnitude = function(cartesian) {
  3434. return Math.sqrt(Cartesian2.magnitudeSquared(cartesian));
  3435. };
  3436. var distanceScratch = new Cartesian2();
  3437. /**
  3438. * Computes the distance between two points.
  3439. *
  3440. * @param {Cartesian2} left The first point to compute the distance from.
  3441. * @param {Cartesian2} right The second point to compute the distance to.
  3442. * @returns {Number} The distance between two points.
  3443. *
  3444. * @example
  3445. * // Returns 1.0
  3446. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(2.0, 0.0));
  3447. */
  3448. Cartesian2.distance = function(left, right) {
  3449. if (!defined(left) || !defined(right)) {
  3450. throw new DeveloperError('left and right are required.');
  3451. }
  3452. Cartesian2.subtract(left, right, distanceScratch);
  3453. return Cartesian2.magnitude(distanceScratch);
  3454. };
  3455. /**
  3456. * Computes the squared distance between two points. Comparing squared distances
  3457. * using this function is more efficient than comparing distances using {@link Cartesian2#distance}.
  3458. *
  3459. * @param {Cartesian2} left The first point to compute the distance from.
  3460. * @param {Cartesian2} right The second point to compute the distance to.
  3461. * @returns {Number} The distance between two points.
  3462. *
  3463. * @example
  3464. * // Returns 4.0, not 2.0
  3465. * var d = Cesium.Cartesian2.distance(new Cesium.Cartesian2(1.0, 0.0), new Cesium.Cartesian2(3.0, 0.0));
  3466. */
  3467. Cartesian2.distanceSquared = function(left, right) {
  3468. if (!defined(left) || !defined(right)) {
  3469. throw new DeveloperError('left and right are required.');
  3470. }
  3471. Cartesian2.subtract(left, right, distanceScratch);
  3472. return Cartesian2.magnitudeSquared(distanceScratch);
  3473. };
  3474. /**
  3475. * Computes the normalized form of the supplied Cartesian.
  3476. *
  3477. * @param {Cartesian2} cartesian The Cartesian to be normalized.
  3478. * @param {Cartesian2} result The object onto which to store the result.
  3479. * @returns {Cartesian2} The modified result parameter.
  3480. */
  3481. Cartesian2.normalize = function(cartesian, result) {
  3482. if (!defined(cartesian)) {
  3483. throw new DeveloperError('cartesian is required');
  3484. }
  3485. if (!defined(result)) {
  3486. throw new DeveloperError('result is required');
  3487. }
  3488. var magnitude = Cartesian2.magnitude(cartesian);
  3489. result.x = cartesian.x / magnitude;
  3490. result.y = cartesian.y / magnitude;
  3491. if (isNaN(result.x) || isNaN(result.y)) {
  3492. throw new DeveloperError('normalized result is not a number');
  3493. }
  3494. return result;
  3495. };
  3496. /**
  3497. * Computes the dot (scalar) product of two Cartesians.
  3498. *
  3499. * @param {Cartesian2} left The first Cartesian.
  3500. * @param {Cartesian2} right The second Cartesian.
  3501. * @returns {Number} The dot product.
  3502. */
  3503. Cartesian2.dot = function(left, right) {
  3504. if (!defined(left)) {
  3505. throw new DeveloperError('left is required');
  3506. }
  3507. if (!defined(right)) {
  3508. throw new DeveloperError('right is required');
  3509. }
  3510. return left.x * right.x + left.y * right.y;
  3511. };
  3512. /**
  3513. * Computes the componentwise product of two Cartesians.
  3514. *
  3515. * @param {Cartesian2} left The first Cartesian.
  3516. * @param {Cartesian2} right The second Cartesian.
  3517. * @param {Cartesian2} result The object onto which to store the result.
  3518. * @returns {Cartesian2} The modified result parameter.
  3519. */
  3520. Cartesian2.multiplyComponents = function(left, right, result) {
  3521. if (!defined(left)) {
  3522. throw new DeveloperError('left is required');
  3523. }
  3524. if (!defined(right)) {
  3525. throw new DeveloperError('right is required');
  3526. }
  3527. if (!defined(result)) {
  3528. throw new DeveloperError('result is required');
  3529. }
  3530. result.x = left.x * right.x;
  3531. result.y = left.y * right.y;
  3532. return result;
  3533. };
  3534. /**
  3535. * Computes the componentwise quotient of two Cartesians.
  3536. *
  3537. * @param {Cartesian2} left The first Cartesian.
  3538. * @param {Cartesian2} right The second Cartesian.
  3539. * @param {Cartesian2} result The object onto which to store the result.
  3540. * @returns {Cartesian2} The modified result parameter.
  3541. */
  3542. Cartesian2.divideComponents = function(left, right, result) {
  3543. if (!defined(left)) {
  3544. throw new DeveloperError('left is required');
  3545. }
  3546. if (!defined(right)) {
  3547. throw new DeveloperError('right is required');
  3548. }
  3549. if (!defined(result)) {
  3550. throw new DeveloperError('result is required');
  3551. }
  3552. result.x = left.x / right.x;
  3553. result.y = left.y / right.y;
  3554. return result;
  3555. };
  3556. /**
  3557. * Computes the componentwise sum of two Cartesians.
  3558. *
  3559. * @param {Cartesian2} left The first Cartesian.
  3560. * @param {Cartesian2} right The second Cartesian.
  3561. * @param {Cartesian2} result The object onto which to store the result.
  3562. * @returns {Cartesian2} The modified result parameter.
  3563. */
  3564. Cartesian2.add = function(left, right, result) {
  3565. if (!defined(left)) {
  3566. throw new DeveloperError('left is required');
  3567. }
  3568. if (!defined(right)) {
  3569. throw new DeveloperError('right is required');
  3570. }
  3571. if (!defined(result)) {
  3572. throw new DeveloperError('result is required');
  3573. }
  3574. result.x = left.x + right.x;
  3575. result.y = left.y + right.y;
  3576. return result;
  3577. };
  3578. /**
  3579. * Computes the componentwise difference of two Cartesians.
  3580. *
  3581. * @param {Cartesian2} left The first Cartesian.
  3582. * @param {Cartesian2} right The second Cartesian.
  3583. * @param {Cartesian2} result The object onto which to store the result.
  3584. * @returns {Cartesian2} The modified result parameter.
  3585. */
  3586. Cartesian2.subtract = function(left, right, result) {
  3587. if (!defined(left)) {
  3588. throw new DeveloperError('left is required');
  3589. }
  3590. if (!defined(right)) {
  3591. throw new DeveloperError('right is required');
  3592. }
  3593. if (!defined(result)) {
  3594. throw new DeveloperError('result is required');
  3595. }
  3596. result.x = left.x - right.x;
  3597. result.y = left.y - right.y;
  3598. return result;
  3599. };
  3600. /**
  3601. * Multiplies the provided Cartesian componentwise by the provided scalar.
  3602. *
  3603. * @param {Cartesian2} cartesian The Cartesian to be scaled.
  3604. * @param {Number} scalar The scalar to multiply with.
  3605. * @param {Cartesian2} result The object onto which to store the result.
  3606. * @returns {Cartesian2} The modified result parameter.
  3607. */
  3608. Cartesian2.multiplyByScalar = function(cartesian, scalar, result) {
  3609. if (!defined(cartesian)) {
  3610. throw new DeveloperError('cartesian is required');
  3611. }
  3612. if (typeof scalar !== 'number') {
  3613. throw new DeveloperError('scalar is required and must be a number.');
  3614. }
  3615. if (!defined(result)) {
  3616. throw new DeveloperError('result is required');
  3617. }
  3618. result.x = cartesian.x * scalar;
  3619. result.y = cartesian.y * scalar;
  3620. return result;
  3621. };
  3622. /**
  3623. * Divides the provided Cartesian componentwise by the provided scalar.
  3624. *
  3625. * @param {Cartesian2} cartesian The Cartesian to be divided.
  3626. * @param {Number} scalar The scalar to divide by.
  3627. * @param {Cartesian2} result The object onto which to store the result.
  3628. * @returns {Cartesian2} The modified result parameter.
  3629. */
  3630. Cartesian2.divideByScalar = function(cartesian, scalar, result) {
  3631. if (!defined(cartesian)) {
  3632. throw new DeveloperError('cartesian is required');
  3633. }
  3634. if (typeof scalar !== 'number') {
  3635. throw new DeveloperError('scalar is required and must be a number.');
  3636. }
  3637. if (!defined(result)) {
  3638. throw new DeveloperError('result is required');
  3639. }
  3640. result.x = cartesian.x / scalar;
  3641. result.y = cartesian.y / scalar;
  3642. return result;
  3643. };
  3644. /**
  3645. * Negates the provided Cartesian.
  3646. *
  3647. * @param {Cartesian2} cartesian The Cartesian to be negated.
  3648. * @param {Cartesian2} result The object onto which to store the result.
  3649. * @returns {Cartesian2} The modified result parameter.
  3650. */
  3651. Cartesian2.negate = function(cartesian, result) {
  3652. if (!defined(cartesian)) {
  3653. throw new DeveloperError('cartesian is required');
  3654. }
  3655. if (!defined(result)) {
  3656. throw new DeveloperError('result is required');
  3657. }
  3658. result.x = -cartesian.x;
  3659. result.y = -cartesian.y;
  3660. return result;
  3661. };
  3662. /**
  3663. * Computes the absolute value of the provided Cartesian.
  3664. *
  3665. * @param {Cartesian2} cartesian The Cartesian whose absolute value is to be computed.
  3666. * @param {Cartesian2} result The object onto which to store the result.
  3667. * @returns {Cartesian2} The modified result parameter.
  3668. */
  3669. Cartesian2.abs = function(cartesian, result) {
  3670. if (!defined(cartesian)) {
  3671. throw new DeveloperError('cartesian is required');
  3672. }
  3673. if (!defined(result)) {
  3674. throw new DeveloperError('result is required');
  3675. }
  3676. result.x = Math.abs(cartesian.x);
  3677. result.y = Math.abs(cartesian.y);
  3678. return result;
  3679. };
  3680. var lerpScratch = new Cartesian2();
  3681. /**
  3682. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  3683. *
  3684. * @param {Cartesian2} start The value corresponding to t at 0.0.
  3685. * @param {Cartesian2} end The value corresponding to t at 1.0.
  3686. * @param {Number} t The point along t at which to interpolate.
  3687. * @param {Cartesian2} result The object onto which to store the result.
  3688. * @returns {Cartesian2} The modified result parameter.
  3689. */
  3690. Cartesian2.lerp = function(start, end, t, result) {
  3691. if (!defined(start)) {
  3692. throw new DeveloperError('start is required.');
  3693. }
  3694. if (!defined(end)) {
  3695. throw new DeveloperError('end is required.');
  3696. }
  3697. if (typeof t !== 'number') {
  3698. throw new DeveloperError('t is required and must be a number.');
  3699. }
  3700. if (!defined(result)) {
  3701. throw new DeveloperError('result is required.');
  3702. }
  3703. Cartesian2.multiplyByScalar(end, t, lerpScratch);
  3704. result = Cartesian2.multiplyByScalar(start, 1.0 - t, result);
  3705. return Cartesian2.add(lerpScratch, result, result);
  3706. };
  3707. var angleBetweenScratch = new Cartesian2();
  3708. var angleBetweenScratch2 = new Cartesian2();
  3709. /**
  3710. * Returns the angle, in radians, between the provided Cartesians.
  3711. *
  3712. * @param {Cartesian2} left The first Cartesian.
  3713. * @param {Cartesian2} right The second Cartesian.
  3714. * @returns {Number} The angle between the Cartesians.
  3715. */
  3716. Cartesian2.angleBetween = function(left, right) {
  3717. if (!defined(left)) {
  3718. throw new DeveloperError('left is required');
  3719. }
  3720. if (!defined(right)) {
  3721. throw new DeveloperError('right is required');
  3722. }
  3723. Cartesian2.normalize(left, angleBetweenScratch);
  3724. Cartesian2.normalize(right, angleBetweenScratch2);
  3725. return CesiumMath.acosClamped(Cartesian2.dot(angleBetweenScratch, angleBetweenScratch2));
  3726. };
  3727. var mostOrthogonalAxisScratch = new Cartesian2();
  3728. /**
  3729. * Returns the axis that is most orthogonal to the provided Cartesian.
  3730. *
  3731. * @param {Cartesian2} cartesian The Cartesian on which to find the most orthogonal axis.
  3732. * @param {Cartesian2} result The object onto which to store the result.
  3733. * @returns {Cartesian2} The most orthogonal axis.
  3734. */
  3735. Cartesian2.mostOrthogonalAxis = function(cartesian, result) {
  3736. if (!defined(cartesian)) {
  3737. throw new DeveloperError('cartesian is required.');
  3738. }
  3739. if (!defined(result)) {
  3740. throw new DeveloperError('result is required.');
  3741. }
  3742. var f = Cartesian2.normalize(cartesian, mostOrthogonalAxisScratch);
  3743. Cartesian2.abs(f, f);
  3744. if (f.x <= f.y) {
  3745. result = Cartesian2.clone(Cartesian2.UNIT_X, result);
  3746. } else {
  3747. result = Cartesian2.clone(Cartesian2.UNIT_Y, result);
  3748. }
  3749. return result;
  3750. };
  3751. /**
  3752. * Compares the provided Cartesians componentwise and returns
  3753. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3754. *
  3755. * @param {Cartesian2} [left] The first Cartesian.
  3756. * @param {Cartesian2} [right] The second Cartesian.
  3757. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  3758. */
  3759. Cartesian2.equals = function(left, right) {
  3760. return (left === right) ||
  3761. ((defined(left)) &&
  3762. (defined(right)) &&
  3763. (left.x === right.x) &&
  3764. (left.y === right.y));
  3765. };
  3766. /**
  3767. * @private
  3768. */
  3769. Cartesian2.equalsArray = function(cartesian, array, offset) {
  3770. return cartesian.x === array[offset] &&
  3771. cartesian.y === array[offset + 1];
  3772. };
  3773. /**
  3774. * Compares the provided Cartesians componentwise and returns
  3775. * <code>true</code> if they pass an absolute or relative tolerance test,
  3776. * <code>false</code> otherwise.
  3777. *
  3778. * @param {Cartesian2} [left] The first Cartesian.
  3779. * @param {Cartesian2} [right] The second Cartesian.
  3780. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  3781. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  3782. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  3783. */
  3784. Cartesian2.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  3785. return (left === right) ||
  3786. (defined(left) &&
  3787. defined(right) &&
  3788. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  3789. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon));
  3790. };
  3791. /**
  3792. * An immutable Cartesian2 instance initialized to (0.0, 0.0).
  3793. *
  3794. * @type {Cartesian2}
  3795. * @constant
  3796. */
  3797. Cartesian2.ZERO = freezeObject(new Cartesian2(0.0, 0.0));
  3798. /**
  3799. * An immutable Cartesian2 instance initialized to (1.0, 0.0).
  3800. *
  3801. * @type {Cartesian2}
  3802. * @constant
  3803. */
  3804. Cartesian2.UNIT_X = freezeObject(new Cartesian2(1.0, 0.0));
  3805. /**
  3806. * An immutable Cartesian2 instance initialized to (0.0, 1.0).
  3807. *
  3808. * @type {Cartesian2}
  3809. * @constant
  3810. */
  3811. Cartesian2.UNIT_Y = freezeObject(new Cartesian2(0.0, 1.0));
  3812. /**
  3813. * Duplicates this Cartesian2 instance.
  3814. *
  3815. * @param {Cartesian2} [result] The object onto which to store the result.
  3816. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided.
  3817. */
  3818. Cartesian2.prototype.clone = function(result) {
  3819. return Cartesian2.clone(this, result);
  3820. };
  3821. /**
  3822. * Compares this Cartesian against the provided Cartesian componentwise and returns
  3823. * <code>true</code> if they are equal, <code>false</code> otherwise.
  3824. *
  3825. * @param {Cartesian2} [right] The right hand side Cartesian.
  3826. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  3827. */
  3828. Cartesian2.prototype.equals = function(right) {
  3829. return Cartesian2.equals(this, right);
  3830. };
  3831. /**
  3832. * Compares this Cartesian against the provided Cartesian componentwise and returns
  3833. * <code>true</code> if they pass an absolute or relative tolerance test,
  3834. * <code>false</code> otherwise.
  3835. *
  3836. * @param {Cartesian2} [right] The right hand side Cartesian.
  3837. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  3838. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  3839. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  3840. */
  3841. Cartesian2.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  3842. return Cartesian2.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  3843. };
  3844. /**
  3845. * Creates a string representing this Cartesian in the format '(x, y)'.
  3846. *
  3847. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  3848. */
  3849. Cartesian2.prototype.toString = function() {
  3850. return '(' + this.x + ', ' + this.y + ')';
  3851. };
  3852. return Cartesian2;
  3853. });
  3854. /*global define*/
  3855. define('Core/GeographicProjection',[
  3856. './Cartesian3',
  3857. './Cartographic',
  3858. './defaultValue',
  3859. './defined',
  3860. './defineProperties',
  3861. './DeveloperError',
  3862. './Ellipsoid'
  3863. ], function(
  3864. Cartesian3,
  3865. Cartographic,
  3866. defaultValue,
  3867. defined,
  3868. defineProperties,
  3869. DeveloperError,
  3870. Ellipsoid) {
  3871. 'use strict';
  3872. /**
  3873. * A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
  3874. * them by the {@link Ellipsoid#maximumRadius}. This projection
  3875. * is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
  3876. * is also known as EPSG:4326.
  3877. *
  3878. * @alias GeographicProjection
  3879. * @constructor
  3880. *
  3881. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
  3882. *
  3883. * @see WebMercatorProjection
  3884. */
  3885. function GeographicProjection(ellipsoid) {
  3886. this._ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  3887. this._semimajorAxis = this._ellipsoid.maximumRadius;
  3888. this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
  3889. }
  3890. defineProperties(GeographicProjection.prototype, {
  3891. /**
  3892. * Gets the {@link Ellipsoid}.
  3893. *
  3894. * @memberof GeographicProjection.prototype
  3895. *
  3896. * @type {Ellipsoid}
  3897. * @readonly
  3898. */
  3899. ellipsoid : {
  3900. get : function() {
  3901. return this._ellipsoid;
  3902. }
  3903. }
  3904. });
  3905. /**
  3906. * Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
  3907. * X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
  3908. * ellipsoid. Z is the unmodified height.
  3909. *
  3910. * @param {Cartographic} cartographic The coordinates to project.
  3911. * @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
  3912. * undefined, a new instance is created and returned.
  3913. * @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
  3914. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3915. * created and returned.
  3916. */
  3917. GeographicProjection.prototype.project = function(cartographic, result) {
  3918. // Actually this is the special case of equidistant cylindrical called the plate carree
  3919. var semimajorAxis = this._semimajorAxis;
  3920. var x = cartographic.longitude * semimajorAxis;
  3921. var y = cartographic.latitude * semimajorAxis;
  3922. var z = cartographic.height;
  3923. if (!defined(result)) {
  3924. return new Cartesian3(x, y, z);
  3925. }
  3926. result.x = x;
  3927. result.y = y;
  3928. result.z = z;
  3929. return result;
  3930. };
  3931. /**
  3932. * Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
  3933. * coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
  3934. * divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
  3935. *
  3936. * @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
  3937. * @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
  3938. * undefined, a new instance is created and returned.
  3939. * @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
  3940. * coordinates are copied there and that instance is returned. Otherwise, a new instance is
  3941. * created and returned.
  3942. */
  3943. GeographicProjection.prototype.unproject = function(cartesian, result) {
  3944. if (!defined(cartesian)) {
  3945. throw new DeveloperError('cartesian is required');
  3946. }
  3947. var oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
  3948. var longitude = cartesian.x * oneOverEarthSemimajorAxis;
  3949. var latitude = cartesian.y * oneOverEarthSemimajorAxis;
  3950. var height = cartesian.z;
  3951. if (!defined(result)) {
  3952. return new Cartographic(longitude, latitude, height);
  3953. }
  3954. result.longitude = longitude;
  3955. result.latitude = latitude;
  3956. result.height = height;
  3957. return result;
  3958. };
  3959. return GeographicProjection;
  3960. });
  3961. /*global define*/
  3962. define('Core/Intersect',[
  3963. './freezeObject'
  3964. ], function(
  3965. freezeObject) {
  3966. 'use strict';
  3967. /**
  3968. * This enumerated type is used in determining where, relative to the frustum, an
  3969. * object is located. The object can either be fully contained within the frustum (INSIDE),
  3970. * partially inside the frustum and partially outside (INTERSECTING), or somwhere entirely
  3971. * outside of the frustum's 6 planes (OUTSIDE).
  3972. *
  3973. * @exports Intersect
  3974. */
  3975. var Intersect = {
  3976. /**
  3977. * Represents that an object is not contained within the frustum.
  3978. *
  3979. * @type {Number}
  3980. * @constant
  3981. */
  3982. OUTSIDE : -1,
  3983. /**
  3984. * Represents that an object intersects one of the frustum's planes.
  3985. *
  3986. * @type {Number}
  3987. * @constant
  3988. */
  3989. INTERSECTING : 0,
  3990. /**
  3991. * Represents that an object is fully within the frustum.
  3992. *
  3993. * @type {Number}
  3994. * @constant
  3995. */
  3996. INSIDE : 1
  3997. };
  3998. return freezeObject(Intersect);
  3999. });
  4000. /*global define*/
  4001. define('Core/Rectangle',[
  4002. './Cartographic',
  4003. './defaultValue',
  4004. './defined',
  4005. './defineProperties',
  4006. './DeveloperError',
  4007. './Ellipsoid',
  4008. './freezeObject',
  4009. './Math'
  4010. ], function(
  4011. Cartographic,
  4012. defaultValue,
  4013. defined,
  4014. defineProperties,
  4015. DeveloperError,
  4016. Ellipsoid,
  4017. freezeObject,
  4018. CesiumMath) {
  4019. 'use strict';
  4020. /**
  4021. * A two dimensional region specified as longitude and latitude coordinates.
  4022. *
  4023. * @alias Rectangle
  4024. * @constructor
  4025. *
  4026. * @param {Number} [west=0.0] The westernmost longitude, in radians, in the range [-Pi, Pi].
  4027. * @param {Number} [south=0.0] The southernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  4028. * @param {Number} [east=0.0] The easternmost longitude, in radians, in the range [-Pi, Pi].
  4029. * @param {Number} [north=0.0] The northernmost latitude, in radians, in the range [-Pi/2, Pi/2].
  4030. *
  4031. * @see Packable
  4032. */
  4033. function Rectangle(west, south, east, north) {
  4034. /**
  4035. * The westernmost longitude in radians in the range [-Pi, Pi].
  4036. *
  4037. * @type {Number}
  4038. * @default 0.0
  4039. */
  4040. this.west = defaultValue(west, 0.0);
  4041. /**
  4042. * The southernmost latitude in radians in the range [-Pi/2, Pi/2].
  4043. *
  4044. * @type {Number}
  4045. * @default 0.0
  4046. */
  4047. this.south = defaultValue(south, 0.0);
  4048. /**
  4049. * The easternmost longitude in radians in the range [-Pi, Pi].
  4050. *
  4051. * @type {Number}
  4052. * @default 0.0
  4053. */
  4054. this.east = defaultValue(east, 0.0);
  4055. /**
  4056. * The northernmost latitude in radians in the range [-Pi/2, Pi/2].
  4057. *
  4058. * @type {Number}
  4059. * @default 0.0
  4060. */
  4061. this.north = defaultValue(north, 0.0);
  4062. }
  4063. defineProperties(Rectangle.prototype, {
  4064. /**
  4065. * Gets the width of the rectangle in radians.
  4066. * @memberof Rectangle.prototype
  4067. * @type {Number}
  4068. */
  4069. width : {
  4070. get : function() {
  4071. return Rectangle.computeWidth(this);
  4072. }
  4073. },
  4074. /**
  4075. * Gets the height of the rectangle in radians.
  4076. * @memberof Rectangle.prototype
  4077. * @type {Number}
  4078. */
  4079. height : {
  4080. get : function() {
  4081. return Rectangle.computeHeight(this);
  4082. }
  4083. }
  4084. });
  4085. /**
  4086. * The number of elements used to pack the object into an array.
  4087. * @type {Number}
  4088. */
  4089. Rectangle.packedLength = 4;
  4090. /**
  4091. * Stores the provided instance into the provided array.
  4092. *
  4093. * @param {Rectangle} value The value to pack.
  4094. * @param {Number[]} array The array to pack into.
  4095. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4096. *
  4097. * @returns {Number[]} The array that was packed into
  4098. */
  4099. Rectangle.pack = function(value, array, startingIndex) {
  4100. if (!defined(value)) {
  4101. throw new DeveloperError('value is required');
  4102. }
  4103. if (!defined(array)) {
  4104. throw new DeveloperError('array is required');
  4105. }
  4106. startingIndex = defaultValue(startingIndex, 0);
  4107. array[startingIndex++] = value.west;
  4108. array[startingIndex++] = value.south;
  4109. array[startingIndex++] = value.east;
  4110. array[startingIndex] = value.north;
  4111. return array;
  4112. };
  4113. /**
  4114. * Retrieves an instance from a packed array.
  4115. *
  4116. * @param {Number[]} array The packed array.
  4117. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4118. * @param {Rectangle} [result] The object into which to store the result.
  4119. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  4120. */
  4121. Rectangle.unpack = function(array, startingIndex, result) {
  4122. if (!defined(array)) {
  4123. throw new DeveloperError('array is required');
  4124. }
  4125. startingIndex = defaultValue(startingIndex, 0);
  4126. if (!defined(result)) {
  4127. result = new Rectangle();
  4128. }
  4129. result.west = array[startingIndex++];
  4130. result.south = array[startingIndex++];
  4131. result.east = array[startingIndex++];
  4132. result.north = array[startingIndex];
  4133. return result;
  4134. };
  4135. /**
  4136. * Computes the width of a rectangle in radians.
  4137. * @param {Rectangle} rectangle The rectangle to compute the width of.
  4138. * @returns {Number} The width.
  4139. */
  4140. Rectangle.computeWidth = function(rectangle) {
  4141. if (!defined(rectangle)) {
  4142. throw new DeveloperError('rectangle is required.');
  4143. }
  4144. var east = rectangle.east;
  4145. var west = rectangle.west;
  4146. if (east < west) {
  4147. east += CesiumMath.TWO_PI;
  4148. }
  4149. return east - west;
  4150. };
  4151. /**
  4152. * Computes the height of a rectangle in radians.
  4153. * @param {Rectangle} rectangle The rectangle to compute the height of.
  4154. * @returns {Number} The height.
  4155. */
  4156. Rectangle.computeHeight = function(rectangle) {
  4157. if (!defined(rectangle)) {
  4158. throw new DeveloperError('rectangle is required.');
  4159. }
  4160. return rectangle.north - rectangle.south;
  4161. };
  4162. /**
  4163. * Creates an rectangle given the boundary longitude and latitude in degrees.
  4164. *
  4165. * @param {Number} [west=0.0] The westernmost longitude in degrees in the range [-180.0, 180.0].
  4166. * @param {Number} [south=0.0] The southernmost latitude in degrees in the range [-90.0, 90.0].
  4167. * @param {Number} [east=0.0] The easternmost longitude in degrees in the range [-180.0, 180.0].
  4168. * @param {Number} [north=0.0] The northernmost latitude in degrees in the range [-90.0, 90.0].
  4169. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4170. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4171. *
  4172. * @example
  4173. * var rectangle = Cesium.Rectangle.fromDegrees(0.0, 20.0, 10.0, 30.0);
  4174. */
  4175. Rectangle.fromDegrees = function(west, south, east, north, result) {
  4176. west = CesiumMath.toRadians(defaultValue(west, 0.0));
  4177. south = CesiumMath.toRadians(defaultValue(south, 0.0));
  4178. east = CesiumMath.toRadians(defaultValue(east, 0.0));
  4179. north = CesiumMath.toRadians(defaultValue(north, 0.0));
  4180. if (!defined(result)) {
  4181. return new Rectangle(west, south, east, north);
  4182. }
  4183. result.west = west;
  4184. result.south = south;
  4185. result.east = east;
  4186. result.north = north;
  4187. return result;
  4188. };
  4189. /**
  4190. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  4191. *
  4192. * @param {Cartographic[]} cartographics The list of Cartographic instances.
  4193. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4194. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4195. */
  4196. Rectangle.fromCartographicArray = function(cartographics, result) {
  4197. if (!defined(cartographics)) {
  4198. throw new DeveloperError('cartographics is required.');
  4199. }
  4200. var west = Number.MAX_VALUE;
  4201. var east = -Number.MAX_VALUE;
  4202. var westOverIDL = Number.MAX_VALUE;
  4203. var eastOverIDL = -Number.MAX_VALUE;
  4204. var south = Number.MAX_VALUE;
  4205. var north = -Number.MAX_VALUE;
  4206. for ( var i = 0, len = cartographics.length; i < len; i++) {
  4207. var position = cartographics[i];
  4208. west = Math.min(west, position.longitude);
  4209. east = Math.max(east, position.longitude);
  4210. south = Math.min(south, position.latitude);
  4211. north = Math.max(north, position.latitude);
  4212. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  4213. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  4214. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  4215. }
  4216. if(east - west > eastOverIDL - westOverIDL) {
  4217. west = westOverIDL;
  4218. east = eastOverIDL;
  4219. if (east > CesiumMath.PI) {
  4220. east = east - CesiumMath.TWO_PI;
  4221. }
  4222. if (west > CesiumMath.PI) {
  4223. west = west - CesiumMath.TWO_PI;
  4224. }
  4225. }
  4226. if (!defined(result)) {
  4227. return new Rectangle(west, south, east, north);
  4228. }
  4229. result.west = west;
  4230. result.south = south;
  4231. result.east = east;
  4232. result.north = north;
  4233. return result;
  4234. };
  4235. /**
  4236. * Creates the smallest possible Rectangle that encloses all positions in the provided array.
  4237. *
  4238. * @param {Cartesian[]} cartesians The list of Cartesian instances.
  4239. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid the cartesians are on.
  4240. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4241. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4242. */
  4243. Rectangle.fromCartesianArray = function(cartesians, ellipsoid, result) {
  4244. if (!defined(cartesians)) {
  4245. throw new DeveloperError('cartesians is required.');
  4246. }
  4247. var west = Number.MAX_VALUE;
  4248. var east = -Number.MAX_VALUE;
  4249. var westOverIDL = Number.MAX_VALUE;
  4250. var eastOverIDL = -Number.MAX_VALUE;
  4251. var south = Number.MAX_VALUE;
  4252. var north = -Number.MAX_VALUE;
  4253. for ( var i = 0, len = cartesians.length; i < len; i++) {
  4254. var position = ellipsoid.cartesianToCartographic(cartesians[i]);
  4255. west = Math.min(west, position.longitude);
  4256. east = Math.max(east, position.longitude);
  4257. south = Math.min(south, position.latitude);
  4258. north = Math.max(north, position.latitude);
  4259. var lonAdjusted = position.longitude >= 0 ? position.longitude : position.longitude + CesiumMath.TWO_PI;
  4260. westOverIDL = Math.min(westOverIDL, lonAdjusted);
  4261. eastOverIDL = Math.max(eastOverIDL, lonAdjusted);
  4262. }
  4263. if(east - west > eastOverIDL - westOverIDL) {
  4264. west = westOverIDL;
  4265. east = eastOverIDL;
  4266. if (east > CesiumMath.PI) {
  4267. east = east - CesiumMath.TWO_PI;
  4268. }
  4269. if (west > CesiumMath.PI) {
  4270. west = west - CesiumMath.TWO_PI;
  4271. }
  4272. }
  4273. if (!defined(result)) {
  4274. return new Rectangle(west, south, east, north);
  4275. }
  4276. result.west = west;
  4277. result.south = south;
  4278. result.east = east;
  4279. result.north = north;
  4280. return result;
  4281. };
  4282. /**
  4283. * Duplicates an Rectangle.
  4284. *
  4285. * @param {Rectangle} rectangle The rectangle to clone.
  4286. * @param {Rectangle} [result] The object onto which to store the result, or undefined if a new instance should be created.
  4287. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided. (Returns undefined if rectangle is undefined)
  4288. */
  4289. Rectangle.clone = function(rectangle, result) {
  4290. if (!defined(rectangle)) {
  4291. return undefined;
  4292. }
  4293. if (!defined(result)) {
  4294. return new Rectangle(rectangle.west, rectangle.south, rectangle.east, rectangle.north);
  4295. }
  4296. result.west = rectangle.west;
  4297. result.south = rectangle.south;
  4298. result.east = rectangle.east;
  4299. result.north = rectangle.north;
  4300. return result;
  4301. };
  4302. /**
  4303. * Duplicates this Rectangle.
  4304. *
  4305. * @param {Rectangle} [result] The object onto which to store the result.
  4306. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4307. */
  4308. Rectangle.prototype.clone = function(result) {
  4309. return Rectangle.clone(this, result);
  4310. };
  4311. /**
  4312. * Compares the provided Rectangle with this Rectangle componentwise and returns
  4313. * <code>true</code> if they are equal, <code>false</code> otherwise.
  4314. *
  4315. * @param {Rectangle} [other] The Rectangle to compare.
  4316. * @returns {Boolean} <code>true</code> if the Rectangles are equal, <code>false</code> otherwise.
  4317. */
  4318. Rectangle.prototype.equals = function(other) {
  4319. return Rectangle.equals(this, other);
  4320. };
  4321. /**
  4322. * Compares the provided rectangles and returns <code>true</code> if they are equal,
  4323. * <code>false</code> otherwise.
  4324. *
  4325. * @param {Rectangle} [left] The first Rectangle.
  4326. * @param {Rectangle} [right] The second Rectangle.
  4327. * @returns {Boolean} <code>true</code> if left and right are equal; otherwise <code>false</code>.
  4328. */
  4329. Rectangle.equals = function(left, right) {
  4330. return (left === right) ||
  4331. ((defined(left)) &&
  4332. (defined(right)) &&
  4333. (left.west === right.west) &&
  4334. (left.south === right.south) &&
  4335. (left.east === right.east) &&
  4336. (left.north === right.north));
  4337. };
  4338. /**
  4339. * Compares the provided Rectangle with this Rectangle componentwise and returns
  4340. * <code>true</code> if they are within the provided epsilon,
  4341. * <code>false</code> otherwise.
  4342. *
  4343. * @param {Rectangle} [other] The Rectangle to compare.
  4344. * @param {Number} epsilon The epsilon to use for equality testing.
  4345. * @returns {Boolean} <code>true</code> if the Rectangles are within the provided epsilon, <code>false</code> otherwise.
  4346. */
  4347. Rectangle.prototype.equalsEpsilon = function(other, epsilon) {
  4348. if (typeof epsilon !== 'number') {
  4349. throw new DeveloperError('epsilon is required and must be a number.');
  4350. }
  4351. return defined(other) &&
  4352. (Math.abs(this.west - other.west) <= epsilon) &&
  4353. (Math.abs(this.south - other.south) <= epsilon) &&
  4354. (Math.abs(this.east - other.east) <= epsilon) &&
  4355. (Math.abs(this.north - other.north) <= epsilon);
  4356. };
  4357. /**
  4358. * Checks an Rectangle's properties and throws if they are not in valid ranges.
  4359. *
  4360. * @param {Rectangle} rectangle The rectangle to validate
  4361. *
  4362. * @exception {DeveloperError} <code>north</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  4363. * @exception {DeveloperError} <code>south</code> must be in the interval [<code>-Pi/2</code>, <code>Pi/2</code>].
  4364. * @exception {DeveloperError} <code>east</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  4365. * @exception {DeveloperError} <code>west</code> must be in the interval [<code>-Pi</code>, <code>Pi</code>].
  4366. */
  4367. Rectangle.validate = function(rectangle) {
  4368. if (!defined(rectangle)) {
  4369. throw new DeveloperError('rectangle is required');
  4370. }
  4371. var north = rectangle.north;
  4372. if (typeof north !== 'number') {
  4373. throw new DeveloperError('north is required to be a number.');
  4374. }
  4375. if (north < -CesiumMath.PI_OVER_TWO || north > CesiumMath.PI_OVER_TWO) {
  4376. throw new DeveloperError('north must be in the interval [-Pi/2, Pi/2].');
  4377. }
  4378. var south = rectangle.south;
  4379. if (typeof south !== 'number') {
  4380. throw new DeveloperError('south is required to be a number.');
  4381. }
  4382. if (south < -CesiumMath.PI_OVER_TWO || south > CesiumMath.PI_OVER_TWO) {
  4383. throw new DeveloperError('south must be in the interval [-Pi/2, Pi/2].');
  4384. }
  4385. var west = rectangle.west;
  4386. if (typeof west !== 'number') {
  4387. throw new DeveloperError('west is required to be a number.');
  4388. }
  4389. if (west < -Math.PI || west > Math.PI) {
  4390. throw new DeveloperError('west must be in the interval [-Pi, Pi].');
  4391. }
  4392. var east = rectangle.east;
  4393. if (typeof east !== 'number') {
  4394. throw new DeveloperError('east is required to be a number.');
  4395. }
  4396. if (east < -Math.PI || east > Math.PI) {
  4397. throw new DeveloperError('east must be in the interval [-Pi, Pi].');
  4398. }
  4399. };
  4400. /**
  4401. * Computes the southwest corner of an rectangle.
  4402. *
  4403. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4404. * @param {Cartographic} [result] The object onto which to store the result.
  4405. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4406. */
  4407. Rectangle.southwest = function(rectangle, result) {
  4408. if (!defined(rectangle)) {
  4409. throw new DeveloperError('rectangle is required');
  4410. }
  4411. if (!defined(result)) {
  4412. return new Cartographic(rectangle.west, rectangle.south);
  4413. }
  4414. result.longitude = rectangle.west;
  4415. result.latitude = rectangle.south;
  4416. result.height = 0.0;
  4417. return result;
  4418. };
  4419. /**
  4420. * Computes the northwest corner of an rectangle.
  4421. *
  4422. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4423. * @param {Cartographic} [result] The object onto which to store the result.
  4424. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4425. */
  4426. Rectangle.northwest = function(rectangle, result) {
  4427. if (!defined(rectangle)) {
  4428. throw new DeveloperError('rectangle is required');
  4429. }
  4430. if (!defined(result)) {
  4431. return new Cartographic(rectangle.west, rectangle.north);
  4432. }
  4433. result.longitude = rectangle.west;
  4434. result.latitude = rectangle.north;
  4435. result.height = 0.0;
  4436. return result;
  4437. };
  4438. /**
  4439. * Computes the northeast corner of an rectangle.
  4440. *
  4441. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4442. * @param {Cartographic} [result] The object onto which to store the result.
  4443. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4444. */
  4445. Rectangle.northeast = function(rectangle, result) {
  4446. if (!defined(rectangle)) {
  4447. throw new DeveloperError('rectangle is required');
  4448. }
  4449. if (!defined(result)) {
  4450. return new Cartographic(rectangle.east, rectangle.north);
  4451. }
  4452. result.longitude = rectangle.east;
  4453. result.latitude = rectangle.north;
  4454. result.height = 0.0;
  4455. return result;
  4456. };
  4457. /**
  4458. * Computes the southeast corner of an rectangle.
  4459. *
  4460. * @param {Rectangle} rectangle The rectangle for which to find the corner
  4461. * @param {Cartographic} [result] The object onto which to store the result.
  4462. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4463. */
  4464. Rectangle.southeast = function(rectangle, result) {
  4465. if (!defined(rectangle)) {
  4466. throw new DeveloperError('rectangle is required');
  4467. }
  4468. if (!defined(result)) {
  4469. return new Cartographic(rectangle.east, rectangle.south);
  4470. }
  4471. result.longitude = rectangle.east;
  4472. result.latitude = rectangle.south;
  4473. result.height = 0.0;
  4474. return result;
  4475. };
  4476. /**
  4477. * Computes the center of an rectangle.
  4478. *
  4479. * @param {Rectangle} rectangle The rectangle for which to find the center
  4480. * @param {Cartographic} [result] The object onto which to store the result.
  4481. * @returns {Cartographic} The modified result parameter or a new Cartographic instance if none was provided.
  4482. */
  4483. Rectangle.center = function(rectangle, result) {
  4484. if (!defined(rectangle)) {
  4485. throw new DeveloperError('rectangle is required');
  4486. }
  4487. var east = rectangle.east;
  4488. var west = rectangle.west;
  4489. if (east < west) {
  4490. east += CesiumMath.TWO_PI;
  4491. }
  4492. var longitude = CesiumMath.negativePiToPi((west + east) * 0.5);
  4493. var latitude = (rectangle.south + rectangle.north) * 0.5;
  4494. if (!defined(result)) {
  4495. return new Cartographic(longitude, latitude);
  4496. }
  4497. result.longitude = longitude;
  4498. result.latitude = latitude;
  4499. result.height = 0.0;
  4500. return result;
  4501. };
  4502. /**
  4503. * Computes the intersection of two rectangles. This function assumes that the rectangle's coordinates are
  4504. * latitude and longitude in radians and produces a correct intersection, taking into account the fact that
  4505. * the same angle can be represented with multiple values as well as the wrapping of longitude at the
  4506. * anti-meridian. For a simple intersection that ignores these factors and can be used with projected
  4507. * coordinates, see {@link Rectangle.simpleIntersection}.
  4508. *
  4509. * @param {Rectangle} rectangle On rectangle to find an intersection
  4510. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  4511. * @param {Rectangle} [result] The object onto which to store the result.
  4512. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  4513. */
  4514. Rectangle.intersection = function(rectangle, otherRectangle, result) {
  4515. if (!defined(rectangle)) {
  4516. throw new DeveloperError('rectangle is required');
  4517. }
  4518. if (!defined(otherRectangle)) {
  4519. throw new DeveloperError('otherRectangle is required.');
  4520. }
  4521. var rectangleEast = rectangle.east;
  4522. var rectangleWest = rectangle.west;
  4523. var otherRectangleEast = otherRectangle.east;
  4524. var otherRectangleWest = otherRectangle.west;
  4525. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  4526. rectangleEast += CesiumMath.TWO_PI;
  4527. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  4528. otherRectangleEast += CesiumMath.TWO_PI;
  4529. }
  4530. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  4531. otherRectangleWest += CesiumMath.TWO_PI;
  4532. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  4533. rectangleWest += CesiumMath.TWO_PI;
  4534. }
  4535. var west = CesiumMath.negativePiToPi(Math.max(rectangleWest, otherRectangleWest));
  4536. var east = CesiumMath.negativePiToPi(Math.min(rectangleEast, otherRectangleEast));
  4537. if ((rectangle.west < rectangle.east || otherRectangle.west < otherRectangle.east) && east <= west) {
  4538. return undefined;
  4539. }
  4540. var south = Math.max(rectangle.south, otherRectangle.south);
  4541. var north = Math.min(rectangle.north, otherRectangle.north);
  4542. if (south >= north) {
  4543. return undefined;
  4544. }
  4545. if (!defined(result)) {
  4546. return new Rectangle(west, south, east, north);
  4547. }
  4548. result.west = west;
  4549. result.south = south;
  4550. result.east = east;
  4551. result.north = north;
  4552. return result;
  4553. };
  4554. /**
  4555. * Computes a simple intersection of two rectangles. Unlike {@link Rectangle.intersection}, this function
  4556. * does not attempt to put the angular coordinates into a consistent range or to account for crossing the
  4557. * anti-meridian. As such, it can be used for rectangles where the coordinates are not simply latitude
  4558. * and longitude (i.e. projected coordinates).
  4559. *
  4560. * @param {Rectangle} rectangle On rectangle to find an intersection
  4561. * @param {Rectangle} otherRectangle Another rectangle to find an intersection
  4562. * @param {Rectangle} [result] The object onto which to store the result.
  4563. * @returns {Rectangle|undefined} The modified result parameter, a new Rectangle instance if none was provided or undefined if there is no intersection.
  4564. */
  4565. Rectangle.simpleIntersection = function(rectangle, otherRectangle, result) {
  4566. if (!defined(rectangle)) {
  4567. throw new DeveloperError('rectangle is required');
  4568. }
  4569. if (!defined(otherRectangle)) {
  4570. throw new DeveloperError('otherRectangle is required.');
  4571. }
  4572. var west = Math.max(rectangle.west, otherRectangle.west);
  4573. var south = Math.max(rectangle.south, otherRectangle.south);
  4574. var east = Math.min(rectangle.east, otherRectangle.east);
  4575. var north = Math.min(rectangle.north, otherRectangle.north);
  4576. if (south >= north || west >= east) {
  4577. return undefined;
  4578. }
  4579. if (!defined(result)) {
  4580. return new Rectangle(west, south, east, north);
  4581. }
  4582. result.west = west;
  4583. result.south = south;
  4584. result.east = east;
  4585. result.north = north;
  4586. return result;
  4587. };
  4588. /**
  4589. * Computes a rectangle that is the union of two rectangles.
  4590. *
  4591. * @param {Rectangle} rectangle A rectangle to enclose in rectangle.
  4592. * @param {Rectangle} otherRectangle A rectangle to enclose in a rectangle.
  4593. * @param {Rectangle} [result] The object onto which to store the result.
  4594. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if none was provided.
  4595. */
  4596. Rectangle.union = function(rectangle, otherRectangle, result) {
  4597. if (!defined(rectangle)) {
  4598. throw new DeveloperError('rectangle is required');
  4599. }
  4600. if (!defined(otherRectangle)) {
  4601. throw new DeveloperError('otherRectangle is required.');
  4602. }
  4603. if (!defined(result)) {
  4604. result = new Rectangle();
  4605. }
  4606. var rectangleEast = rectangle.east;
  4607. var rectangleWest = rectangle.west;
  4608. var otherRectangleEast = otherRectangle.east;
  4609. var otherRectangleWest = otherRectangle.west;
  4610. if (rectangleEast < rectangleWest && otherRectangleEast > 0.0) {
  4611. rectangleEast += CesiumMath.TWO_PI;
  4612. } else if (otherRectangleEast < otherRectangleWest && rectangleEast > 0.0) {
  4613. otherRectangleEast += CesiumMath.TWO_PI;
  4614. }
  4615. if (rectangleEast < rectangleWest && otherRectangleWest < 0.0) {
  4616. otherRectangleWest += CesiumMath.TWO_PI;
  4617. } else if (otherRectangleEast < otherRectangleWest && rectangleWest < 0.0) {
  4618. rectangleWest += CesiumMath.TWO_PI;
  4619. }
  4620. var west = CesiumMath.convertLongitudeRange(Math.min(rectangleWest, otherRectangleWest));
  4621. var east = CesiumMath.convertLongitudeRange(Math.max(rectangleEast, otherRectangleEast));
  4622. result.west = west;
  4623. result.south = Math.min(rectangle.south, otherRectangle.south);
  4624. result.east = east;
  4625. result.north = Math.max(rectangle.north, otherRectangle.north);
  4626. return result;
  4627. };
  4628. /**
  4629. * Computes a rectangle by enlarging the provided rectangle until it contains the provided cartographic.
  4630. *
  4631. * @param {Rectangle} rectangle A rectangle to expand.
  4632. * @param {Cartographic} cartographic A cartographic to enclose in a rectangle.
  4633. * @param {Rectangle} [result] The object onto which to store the result.
  4634. * @returns {Rectangle} The modified result parameter or a new Rectangle instance if one was not provided.
  4635. */
  4636. Rectangle.expand = function(rectangle, cartographic, result) {
  4637. if (!defined(rectangle)) {
  4638. throw new DeveloperError('rectangle is required.');
  4639. }
  4640. if (!defined(cartographic)) {
  4641. throw new DeveloperError('cartographic is required.');
  4642. }
  4643. if (!defined(result)) {
  4644. result = new Rectangle();
  4645. }
  4646. result.west = Math.min(rectangle.west, cartographic.longitude);
  4647. result.south = Math.min(rectangle.south, cartographic.latitude);
  4648. result.east = Math.max(rectangle.east, cartographic.longitude);
  4649. result.north = Math.max(rectangle.north, cartographic.latitude);
  4650. return result;
  4651. };
  4652. /**
  4653. * Returns true if the cartographic is on or inside the rectangle, false otherwise.
  4654. *
  4655. * @param {Rectangle} rectangle The rectangle
  4656. * @param {Cartographic} cartographic The cartographic to test.
  4657. * @returns {Boolean} true if the provided cartographic is inside the rectangle, false otherwise.
  4658. */
  4659. Rectangle.contains = function(rectangle, cartographic) {
  4660. if (!defined(rectangle)) {
  4661. throw new DeveloperError('rectangle is required');
  4662. }
  4663. if (!defined(cartographic)) {
  4664. throw new DeveloperError('cartographic is required.');
  4665. }
  4666. var longitude = cartographic.longitude;
  4667. var latitude = cartographic.latitude;
  4668. var west = rectangle.west;
  4669. var east = rectangle.east;
  4670. if (east < west) {
  4671. east += CesiumMath.TWO_PI;
  4672. if (longitude < 0.0) {
  4673. longitude += CesiumMath.TWO_PI;
  4674. }
  4675. }
  4676. return (longitude > west || CesiumMath.equalsEpsilon(longitude, west, CesiumMath.EPSILON14)) &&
  4677. (longitude < east || CesiumMath.equalsEpsilon(longitude, east, CesiumMath.EPSILON14)) &&
  4678. latitude >= rectangle.south &&
  4679. latitude <= rectangle.north;
  4680. };
  4681. var subsampleLlaScratch = new Cartographic();
  4682. /**
  4683. * Samples an rectangle so that it includes a list of Cartesian points suitable for passing to
  4684. * {@link BoundingSphere#fromPoints}. Sampling is necessary to account
  4685. * for rectangles that cover the poles or cross the equator.
  4686. *
  4687. * @param {Rectangle} rectangle The rectangle to subsample.
  4688. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  4689. * @param {Number} [surfaceHeight=0.0] The height of the rectangle above the ellipsoid.
  4690. * @param {Cartesian3[]} [result] The array of Cartesians onto which to store the result.
  4691. * @returns {Cartesian3[]} The modified result parameter or a new Array of Cartesians instances if none was provided.
  4692. */
  4693. Rectangle.subsample = function(rectangle, ellipsoid, surfaceHeight, result) {
  4694. if (!defined(rectangle)) {
  4695. throw new DeveloperError('rectangle is required');
  4696. }
  4697. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  4698. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  4699. if (!defined(result)) {
  4700. result = [];
  4701. }
  4702. var length = 0;
  4703. var north = rectangle.north;
  4704. var south = rectangle.south;
  4705. var east = rectangle.east;
  4706. var west = rectangle.west;
  4707. var lla = subsampleLlaScratch;
  4708. lla.height = surfaceHeight;
  4709. lla.longitude = west;
  4710. lla.latitude = north;
  4711. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4712. length++;
  4713. lla.longitude = east;
  4714. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4715. length++;
  4716. lla.latitude = south;
  4717. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4718. length++;
  4719. lla.longitude = west;
  4720. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4721. length++;
  4722. if (north < 0.0) {
  4723. lla.latitude = north;
  4724. } else if (south > 0.0) {
  4725. lla.latitude = south;
  4726. } else {
  4727. lla.latitude = 0.0;
  4728. }
  4729. for ( var i = 1; i < 8; ++i) {
  4730. lla.longitude = -Math.PI + i * CesiumMath.PI_OVER_TWO;
  4731. if (Rectangle.contains(rectangle, lla)) {
  4732. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4733. length++;
  4734. }
  4735. }
  4736. if (lla.latitude === 0.0) {
  4737. lla.longitude = west;
  4738. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4739. length++;
  4740. lla.longitude = east;
  4741. result[length] = ellipsoid.cartographicToCartesian(lla, result[length]);
  4742. length++;
  4743. }
  4744. result.length = length;
  4745. return result;
  4746. };
  4747. /**
  4748. * The largest possible rectangle.
  4749. *
  4750. * @type {Rectangle}
  4751. * @constant
  4752. */
  4753. Rectangle.MAX_VALUE = freezeObject(new Rectangle(-Math.PI, -CesiumMath.PI_OVER_TWO, Math.PI, CesiumMath.PI_OVER_TWO));
  4754. return Rectangle;
  4755. });
  4756. /*global define*/
  4757. define('Core/BoundingRectangle',[
  4758. './Cartesian2',
  4759. './Cartographic',
  4760. './defaultValue',
  4761. './defined',
  4762. './DeveloperError',
  4763. './GeographicProjection',
  4764. './Intersect',
  4765. './Rectangle'
  4766. ], function(
  4767. Cartesian2,
  4768. Cartographic,
  4769. defaultValue,
  4770. defined,
  4771. DeveloperError,
  4772. GeographicProjection,
  4773. Intersect,
  4774. Rectangle) {
  4775. 'use strict';
  4776. /**
  4777. * A bounding rectangle given by a corner, width and height.
  4778. * @alias BoundingRectangle
  4779. * @constructor
  4780. *
  4781. * @param {Number} [x=0.0] The x coordinate of the rectangle.
  4782. * @param {Number} [y=0.0] The y coordinate of the rectangle.
  4783. * @param {Number} [width=0.0] The width of the rectangle.
  4784. * @param {Number} [height=0.0] The height of the rectangle.
  4785. *
  4786. * @see BoundingSphere
  4787. * @see Packable
  4788. */
  4789. function BoundingRectangle(x, y, width, height) {
  4790. /**
  4791. * The x coordinate of the rectangle.
  4792. * @type {Number}
  4793. * @default 0.0
  4794. */
  4795. this.x = defaultValue(x, 0.0);
  4796. /**
  4797. * The y coordinate of the rectangle.
  4798. * @type {Number}
  4799. * @default 0.0
  4800. */
  4801. this.y = defaultValue(y, 0.0);
  4802. /**
  4803. * The width of the rectangle.
  4804. * @type {Number}
  4805. * @default 0.0
  4806. */
  4807. this.width = defaultValue(width, 0.0);
  4808. /**
  4809. * The height of the rectangle.
  4810. * @type {Number}
  4811. * @default 0.0
  4812. */
  4813. this.height = defaultValue(height, 0.0);
  4814. }
  4815. /**
  4816. * The number of elements used to pack the object into an array.
  4817. * @type {Number}
  4818. */
  4819. BoundingRectangle.packedLength = 4;
  4820. /**
  4821. * Stores the provided instance into the provided array.
  4822. *
  4823. * @param {BoundingRectangle} value The value to pack.
  4824. * @param {Number[]} array The array to pack into.
  4825. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  4826. *
  4827. * @returns {Number[]} The array that was packed into
  4828. */
  4829. BoundingRectangle.pack = function(value, array, startingIndex) {
  4830. if (!defined(value)) {
  4831. throw new DeveloperError('value is required');
  4832. }
  4833. if (!defined(array)) {
  4834. throw new DeveloperError('array is required');
  4835. }
  4836. startingIndex = defaultValue(startingIndex, 0);
  4837. array[startingIndex++] = value.x;
  4838. array[startingIndex++] = value.y;
  4839. array[startingIndex++] = value.width;
  4840. array[startingIndex] = value.height;
  4841. return array;
  4842. };
  4843. /**
  4844. * Retrieves an instance from a packed array.
  4845. *
  4846. * @param {Number[]} array The packed array.
  4847. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  4848. * @param {BoundingRectangle} [result] The object into which to store the result.
  4849. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4850. */
  4851. BoundingRectangle.unpack = function(array, startingIndex, result) {
  4852. if (!defined(array)) {
  4853. throw new DeveloperError('array is required');
  4854. }
  4855. startingIndex = defaultValue(startingIndex, 0);
  4856. if (!defined(result)) {
  4857. result = new BoundingRectangle();
  4858. }
  4859. result.x = array[startingIndex++];
  4860. result.y = array[startingIndex++];
  4861. result.width = array[startingIndex++];
  4862. result.height = array[startingIndex];
  4863. return result;
  4864. };
  4865. /**
  4866. * Computes a bounding rectangle enclosing the list of 2D points.
  4867. * The rectangle is oriented with the corner at the bottom left.
  4868. *
  4869. * @param {Cartesian2[]} positions List of points that the bounding rectangle will enclose. Each point must have <code>x</code> and <code>y</code> properties.
  4870. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4871. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4872. */
  4873. BoundingRectangle.fromPoints = function(positions, result) {
  4874. if (!defined(result)) {
  4875. result = new BoundingRectangle();
  4876. }
  4877. if (!defined(positions) || positions.length === 0) {
  4878. result.x = 0;
  4879. result.y = 0;
  4880. result.width = 0;
  4881. result.height = 0;
  4882. return result;
  4883. }
  4884. var length = positions.length;
  4885. var minimumX = positions[0].x;
  4886. var minimumY = positions[0].y;
  4887. var maximumX = positions[0].x;
  4888. var maximumY = positions[0].y;
  4889. for ( var i = 1; i < length; i++) {
  4890. var p = positions[i];
  4891. var x = p.x;
  4892. var y = p.y;
  4893. minimumX = Math.min(x, minimumX);
  4894. maximumX = Math.max(x, maximumX);
  4895. minimumY = Math.min(y, minimumY);
  4896. maximumY = Math.max(y, maximumY);
  4897. }
  4898. result.x = minimumX;
  4899. result.y = minimumY;
  4900. result.width = maximumX - minimumX;
  4901. result.height = maximumY - minimumY;
  4902. return result;
  4903. };
  4904. var defaultProjection = new GeographicProjection();
  4905. var fromRectangleLowerLeft = new Cartographic();
  4906. var fromRectangleUpperRight = new Cartographic();
  4907. /**
  4908. * Computes a bounding rectangle from an rectangle.
  4909. *
  4910. * @param {Rectangle} rectangle The valid rectangle used to create a bounding rectangle.
  4911. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  4912. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4913. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4914. */
  4915. BoundingRectangle.fromRectangle = function(rectangle, projection, result) {
  4916. if (!defined(result)) {
  4917. result = new BoundingRectangle();
  4918. }
  4919. if (!defined(rectangle)) {
  4920. result.x = 0;
  4921. result.y = 0;
  4922. result.width = 0;
  4923. result.height = 0;
  4924. return result;
  4925. }
  4926. projection = defaultValue(projection, defaultProjection);
  4927. var lowerLeft = projection.project(Rectangle.southwest(rectangle, fromRectangleLowerLeft));
  4928. var upperRight = projection.project(Rectangle.northeast(rectangle, fromRectangleUpperRight));
  4929. Cartesian2.subtract(upperRight, lowerLeft, upperRight);
  4930. result.x = lowerLeft.x;
  4931. result.y = lowerLeft.y;
  4932. result.width = upperRight.x;
  4933. result.height = upperRight.y;
  4934. return result;
  4935. };
  4936. /**
  4937. * Duplicates a BoundingRectangle instance.
  4938. *
  4939. * @param {BoundingRectangle} rectangle The bounding rectangle to duplicate.
  4940. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4941. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided. (Returns undefined if rectangle is undefined)
  4942. */
  4943. BoundingRectangle.clone = function(rectangle, result) {
  4944. if (!defined(rectangle)) {
  4945. return undefined;
  4946. }
  4947. if (!defined(result)) {
  4948. return new BoundingRectangle(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
  4949. }
  4950. result.x = rectangle.x;
  4951. result.y = rectangle.y;
  4952. result.width = rectangle.width;
  4953. result.height = rectangle.height;
  4954. return result;
  4955. };
  4956. /**
  4957. * Computes a bounding rectangle that is the union of the left and right bounding rectangles.
  4958. *
  4959. * @param {BoundingRectangle} left A rectangle to enclose in bounding rectangle.
  4960. * @param {BoundingRectangle} right A rectangle to enclose in a bounding rectangle.
  4961. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4962. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4963. */
  4964. BoundingRectangle.union = function(left, right, result) {
  4965. if (!defined(left)) {
  4966. throw new DeveloperError('left is required.');
  4967. }
  4968. if (!defined(right)) {
  4969. throw new DeveloperError('right is required.');
  4970. }
  4971. if (!defined(result)) {
  4972. result = new BoundingRectangle();
  4973. }
  4974. var lowerLeftX = Math.min(left.x, right.x);
  4975. var lowerLeftY = Math.min(left.y, right.y);
  4976. var upperRightX = Math.max(left.x + left.width, right.x + right.width);
  4977. var upperRightY = Math.max(left.y + left.height, right.y + right.height);
  4978. result.x = lowerLeftX;
  4979. result.y = lowerLeftY;
  4980. result.width = upperRightX - lowerLeftX;
  4981. result.height = upperRightY - lowerLeftY;
  4982. return result;
  4983. };
  4984. /**
  4985. * Computes a bounding rectangle by enlarging the provided rectangle until it contains the provided point.
  4986. *
  4987. * @param {BoundingRectangle} rectangle A rectangle to expand.
  4988. * @param {Cartesian2} point A point to enclose in a bounding rectangle.
  4989. * @param {BoundingRectangle} [result] The object onto which to store the result.
  4990. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  4991. */
  4992. BoundingRectangle.expand = function(rectangle, point, result) {
  4993. if (!defined(rectangle)) {
  4994. throw new DeveloperError('rectangle is required.');
  4995. }
  4996. if (!defined(point)) {
  4997. throw new DeveloperError('point is required.');
  4998. }
  4999. result = BoundingRectangle.clone(rectangle, result);
  5000. var width = point.x - result.x;
  5001. var height = point.y - result.y;
  5002. if (width > result.width) {
  5003. result.width = width;
  5004. } else if (width < 0) {
  5005. result.width -= width;
  5006. result.x = point.x;
  5007. }
  5008. if (height > result.height) {
  5009. result.height = height;
  5010. } else if (height < 0) {
  5011. result.height -= height;
  5012. result.y = point.y;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Determines if two rectangles intersect.
  5018. *
  5019. * @param {BoundingRectangle} left A rectangle to check for intersection.
  5020. * @param {BoundingRectangle} right The other rectangle to check for intersection.
  5021. * @returns {Intersect} <code>Intersect.INTESECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
  5022. */
  5023. BoundingRectangle.intersect = function(left, right) {
  5024. if (!defined(left)) {
  5025. throw new DeveloperError('left is required.');
  5026. }
  5027. if (!defined(right)) {
  5028. throw new DeveloperError('right is required.');
  5029. }
  5030. var leftX = left.x;
  5031. var leftY = left.y;
  5032. var rightX = right.x;
  5033. var rightY = right.y;
  5034. if (!(leftX > rightX + right.width ||
  5035. leftX + left.width < rightX ||
  5036. leftY + left.height < rightY ||
  5037. leftY > rightY + right.height)) {
  5038. return Intersect.INTERSECTING;
  5039. }
  5040. return Intersect.OUTSIDE;
  5041. };
  5042. /**
  5043. * Compares the provided BoundingRectangles componentwise and returns
  5044. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5045. *
  5046. * @param {BoundingRectangle} [left] The first BoundingRectangle.
  5047. * @param {BoundingRectangle} [right] The second BoundingRectangle.
  5048. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  5049. */
  5050. BoundingRectangle.equals = function(left, right) {
  5051. return (left === right) ||
  5052. ((defined(left)) &&
  5053. (defined(right)) &&
  5054. (left.x === right.x) &&
  5055. (left.y === right.y) &&
  5056. (left.width === right.width) &&
  5057. (left.height === right.height));
  5058. };
  5059. /**
  5060. * Duplicates this BoundingRectangle instance.
  5061. *
  5062. * @param {BoundingRectangle} [result] The object onto which to store the result.
  5063. * @returns {BoundingRectangle} The modified result parameter or a new BoundingRectangle instance if one was not provided.
  5064. */
  5065. BoundingRectangle.prototype.clone = function(result) {
  5066. return BoundingRectangle.clone(this, result);
  5067. };
  5068. /**
  5069. * Determines if this rectangle intersects with another.
  5070. *
  5071. * @param {BoundingRectangle} right A rectangle to check for intersection.
  5072. * @returns {Intersect} <code>Intersect.INTESECTING</code> if the rectangles intersect, <code>Intersect.OUTSIDE</code> otherwise.
  5073. */
  5074. BoundingRectangle.prototype.intersect = function(right) {
  5075. return BoundingRectangle.intersect(this, right);
  5076. };
  5077. /**
  5078. * Compares this BoundingRectangle against the provided BoundingRectangle componentwise and returns
  5079. * <code>true</code> if they are equal, <code>false</code> otherwise.
  5080. *
  5081. * @param {BoundingRectangle} [right] The right hand side BoundingRectangle.
  5082. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  5083. */
  5084. BoundingRectangle.prototype.equals = function(right) {
  5085. return BoundingRectangle.equals(this, right);
  5086. };
  5087. return BoundingRectangle;
  5088. });
  5089. /*global define*/
  5090. define('Core/Interval',[
  5091. './defaultValue'
  5092. ], function(
  5093. defaultValue) {
  5094. 'use strict';
  5095. /**
  5096. * Represents the closed interval [start, stop].
  5097. * @alias Interval
  5098. * @constructor
  5099. *
  5100. * @param {Number} [start=0.0] The beginning of the interval.
  5101. * @param {Number} [stop=0.0] The end of the interval.
  5102. */
  5103. function Interval(start, stop) {
  5104. /**
  5105. * The beginning of the interval.
  5106. * @type {Number}
  5107. * @default 0.0
  5108. */
  5109. this.start = defaultValue(start, 0.0);
  5110. /**
  5111. * The end of the interval.
  5112. * @type {Number}
  5113. * @default 0.0
  5114. */
  5115. this.stop = defaultValue(stop, 0.0);
  5116. }
  5117. return Interval;
  5118. });
  5119. /*global define*/
  5120. define('Core/Matrix3',[
  5121. './Cartesian3',
  5122. './defaultValue',
  5123. './defined',
  5124. './defineProperties',
  5125. './DeveloperError',
  5126. './freezeObject',
  5127. './Math'
  5128. ], function(
  5129. Cartesian3,
  5130. defaultValue,
  5131. defined,
  5132. defineProperties,
  5133. DeveloperError,
  5134. freezeObject,
  5135. CesiumMath) {
  5136. 'use strict';
  5137. /**
  5138. * A 3x3 matrix, indexable as a column-major order array.
  5139. * Constructor parameters are in row-major order for code readability.
  5140. * @alias Matrix3
  5141. * @constructor
  5142. *
  5143. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  5144. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  5145. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  5146. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  5147. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  5148. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  5149. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  5150. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  5151. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  5152. *
  5153. * @see Matrix3.fromColumnMajorArray
  5154. * @see Matrix3.fromRowMajorArray
  5155. * @see Matrix3.fromQuaternion
  5156. * @see Matrix3.fromScale
  5157. * @see Matrix3.fromUniformScale
  5158. * @see Matrix2
  5159. * @see Matrix4
  5160. */
  5161. function Matrix3(column0Row0, column1Row0, column2Row0,
  5162. column0Row1, column1Row1, column2Row1,
  5163. column0Row2, column1Row2, column2Row2) {
  5164. this[0] = defaultValue(column0Row0, 0.0);
  5165. this[1] = defaultValue(column0Row1, 0.0);
  5166. this[2] = defaultValue(column0Row2, 0.0);
  5167. this[3] = defaultValue(column1Row0, 0.0);
  5168. this[4] = defaultValue(column1Row1, 0.0);
  5169. this[5] = defaultValue(column1Row2, 0.0);
  5170. this[6] = defaultValue(column2Row0, 0.0);
  5171. this[7] = defaultValue(column2Row1, 0.0);
  5172. this[8] = defaultValue(column2Row2, 0.0);
  5173. }
  5174. /**
  5175. * The number of elements used to pack the object into an array.
  5176. * @type {Number}
  5177. */
  5178. Matrix3.packedLength = 9;
  5179. /**
  5180. * Stores the provided instance into the provided array.
  5181. *
  5182. * @param {Matrix3} value The value to pack.
  5183. * @param {Number[]} array The array to pack into.
  5184. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  5185. *
  5186. * @returns {Number[]} The array that was packed into
  5187. */
  5188. Matrix3.pack = function(value, array, startingIndex) {
  5189. if (!defined(value)) {
  5190. throw new DeveloperError('value is required');
  5191. }
  5192. if (!defined(array)) {
  5193. throw new DeveloperError('array is required');
  5194. }
  5195. startingIndex = defaultValue(startingIndex, 0);
  5196. array[startingIndex++] = value[0];
  5197. array[startingIndex++] = value[1];
  5198. array[startingIndex++] = value[2];
  5199. array[startingIndex++] = value[3];
  5200. array[startingIndex++] = value[4];
  5201. array[startingIndex++] = value[5];
  5202. array[startingIndex++] = value[6];
  5203. array[startingIndex++] = value[7];
  5204. array[startingIndex++] = value[8];
  5205. return array;
  5206. };
  5207. /**
  5208. * Retrieves an instance from a packed array.
  5209. *
  5210. * @param {Number[]} array The packed array.
  5211. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  5212. * @param {Matrix3} [result] The object into which to store the result.
  5213. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  5214. */
  5215. Matrix3.unpack = function(array, startingIndex, result) {
  5216. if (!defined(array)) {
  5217. throw new DeveloperError('array is required');
  5218. }
  5219. startingIndex = defaultValue(startingIndex, 0);
  5220. if (!defined(result)) {
  5221. result = new Matrix3();
  5222. }
  5223. result[0] = array[startingIndex++];
  5224. result[1] = array[startingIndex++];
  5225. result[2] = array[startingIndex++];
  5226. result[3] = array[startingIndex++];
  5227. result[4] = array[startingIndex++];
  5228. result[5] = array[startingIndex++];
  5229. result[6] = array[startingIndex++];
  5230. result[7] = array[startingIndex++];
  5231. result[8] = array[startingIndex++];
  5232. return result;
  5233. };
  5234. /**
  5235. * Duplicates a Matrix3 instance.
  5236. *
  5237. * @param {Matrix3} matrix The matrix to duplicate.
  5238. * @param {Matrix3} [result] The object onto which to store the result.
  5239. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided. (Returns undefined if matrix is undefined)
  5240. */
  5241. Matrix3.clone = function(values, result) {
  5242. if (!defined(values)) {
  5243. return undefined;
  5244. }
  5245. if (!defined(result)) {
  5246. return new Matrix3(values[0], values[3], values[6],
  5247. values[1], values[4], values[7],
  5248. values[2], values[5], values[8]);
  5249. }
  5250. result[0] = values[0];
  5251. result[1] = values[1];
  5252. result[2] = values[2];
  5253. result[3] = values[3];
  5254. result[4] = values[4];
  5255. result[5] = values[5];
  5256. result[6] = values[6];
  5257. result[7] = values[7];
  5258. result[8] = values[8];
  5259. return result;
  5260. };
  5261. /**
  5262. * Creates a Matrix3 from 9 consecutive elements in an array.
  5263. *
  5264. * @param {Number[]} array The array whose 9 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  5265. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  5266. * @param {Matrix3} [result] The object onto which to store the result.
  5267. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  5268. *
  5269. * @example
  5270. * // Create the Matrix3:
  5271. * // [1.0, 2.0, 3.0]
  5272. * // [1.0, 2.0, 3.0]
  5273. * // [1.0, 2.0, 3.0]
  5274. *
  5275. * var v = [1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  5276. * var m = Cesium.Matrix3.fromArray(v);
  5277. *
  5278. * // Create same Matrix3 with using an offset into an array
  5279. * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0];
  5280. * var m2 = Cesium.Matrix3.fromArray(v2, 2);
  5281. */
  5282. Matrix3.fromArray = function(array, startingIndex, result) {
  5283. if (!defined(array)) {
  5284. throw new DeveloperError('array is required');
  5285. }
  5286. startingIndex = defaultValue(startingIndex, 0);
  5287. if (!defined(result)) {
  5288. result = new Matrix3();
  5289. }
  5290. result[0] = array[startingIndex];
  5291. result[1] = array[startingIndex + 1];
  5292. result[2] = array[startingIndex + 2];
  5293. result[3] = array[startingIndex + 3];
  5294. result[4] = array[startingIndex + 4];
  5295. result[5] = array[startingIndex + 5];
  5296. result[6] = array[startingIndex + 6];
  5297. result[7] = array[startingIndex + 7];
  5298. result[8] = array[startingIndex + 8];
  5299. return result;
  5300. };
  5301. /**
  5302. * Creates a Matrix3 instance from a column-major order array.
  5303. *
  5304. * @param {Number[]} values The column-major order array.
  5305. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5306. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5307. */
  5308. Matrix3.fromColumnMajorArray = function(values, result) {
  5309. if (!defined(values)) {
  5310. throw new DeveloperError('values parameter is required');
  5311. }
  5312. return Matrix3.clone(values, result);
  5313. };
  5314. /**
  5315. * Creates a Matrix3 instance from a row-major order array.
  5316. * The resulting matrix will be in column-major order.
  5317. *
  5318. * @param {Number[]} values The row-major order array.
  5319. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5320. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5321. */
  5322. Matrix3.fromRowMajorArray = function(values, result) {
  5323. if (!defined(values)) {
  5324. throw new DeveloperError('values is required.');
  5325. }
  5326. if (!defined(result)) {
  5327. return new Matrix3(values[0], values[1], values[2],
  5328. values[3], values[4], values[5],
  5329. values[6], values[7], values[8]);
  5330. }
  5331. result[0] = values[0];
  5332. result[1] = values[3];
  5333. result[2] = values[6];
  5334. result[3] = values[1];
  5335. result[4] = values[4];
  5336. result[5] = values[7];
  5337. result[6] = values[2];
  5338. result[7] = values[5];
  5339. result[8] = values[8];
  5340. return result;
  5341. };
  5342. /**
  5343. * Computes a 3x3 rotation matrix from the provided quaternion.
  5344. *
  5345. * @param {Quaternion} quaternion the quaternion to use.
  5346. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5347. * @returns {Matrix3} The 3x3 rotation matrix from this quaternion.
  5348. */
  5349. Matrix3.fromQuaternion = function(quaternion, result) {
  5350. if (!defined(quaternion)) {
  5351. throw new DeveloperError('quaternion is required');
  5352. }
  5353. var x2 = quaternion.x * quaternion.x;
  5354. var xy = quaternion.x * quaternion.y;
  5355. var xz = quaternion.x * quaternion.z;
  5356. var xw = quaternion.x * quaternion.w;
  5357. var y2 = quaternion.y * quaternion.y;
  5358. var yz = quaternion.y * quaternion.z;
  5359. var yw = quaternion.y * quaternion.w;
  5360. var z2 = quaternion.z * quaternion.z;
  5361. var zw = quaternion.z * quaternion.w;
  5362. var w2 = quaternion.w * quaternion.w;
  5363. var m00 = x2 - y2 - z2 + w2;
  5364. var m01 = 2.0 * (xy - zw);
  5365. var m02 = 2.0 * (xz + yw);
  5366. var m10 = 2.0 * (xy + zw);
  5367. var m11 = -x2 + y2 - z2 + w2;
  5368. var m12 = 2.0 * (yz - xw);
  5369. var m20 = 2.0 * (xz - yw);
  5370. var m21 = 2.0 * (yz + xw);
  5371. var m22 = -x2 - y2 + z2 + w2;
  5372. if (!defined(result)) {
  5373. return new Matrix3(m00, m01, m02,
  5374. m10, m11, m12,
  5375. m20, m21, m22);
  5376. }
  5377. result[0] = m00;
  5378. result[1] = m10;
  5379. result[2] = m20;
  5380. result[3] = m01;
  5381. result[4] = m11;
  5382. result[5] = m21;
  5383. result[6] = m02;
  5384. result[7] = m12;
  5385. result[8] = m22;
  5386. return result;
  5387. };
  5388. /**
  5389. * Computes a 3x3 rotation matrix from the provided headingPitchRoll. (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  5390. *
  5391. * @param {HeadingPitchRoll} headingPitchRoll the headingPitchRoll to use.
  5392. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5393. * @returns {Matrix3} The 3x3 rotation matrix from this headingPitchRoll.
  5394. */
  5395. Matrix3.fromHeadingPitchRoll = function(headingPitchRoll, result) {
  5396. if (!defined(headingPitchRoll)) {
  5397. throw new DeveloperError('headingPitchRoll is required');
  5398. }
  5399. var cosTheta = Math.cos(-headingPitchRoll.pitch);
  5400. var cosPsi = Math.cos(-headingPitchRoll.heading);
  5401. var cosPhi = Math.cos(headingPitchRoll.roll);
  5402. var sinTheta = Math.sin(-headingPitchRoll.pitch);
  5403. var sinPsi = Math.sin(-headingPitchRoll.heading);
  5404. var sinPhi = Math.sin(headingPitchRoll.roll);
  5405. var m00 = cosTheta * cosPsi;
  5406. var m01 = -cosPhi * sinPsi + sinPhi * sinTheta * cosPsi;
  5407. var m02 = sinPhi * sinPsi + cosPhi * sinTheta * cosPsi;
  5408. var m10 = cosTheta * sinPsi;
  5409. var m11 = cosPhi * cosPsi + sinPhi * sinTheta * sinPsi;
  5410. var m12 = -sinTheta * cosPhi + cosPhi * sinTheta * sinPsi;
  5411. var m20 = -sinTheta;
  5412. var m21 = sinPhi * cosTheta;
  5413. var m22 = cosPhi * cosTheta;
  5414. if (!defined(result)) {
  5415. return new Matrix3(m00, m01, m02,
  5416. m10, m11, m12,
  5417. m20, m21, m22);
  5418. }
  5419. result[0] = m00;
  5420. result[1] = m10;
  5421. result[2] = m20;
  5422. result[3] = m01;
  5423. result[4] = m11;
  5424. result[5] = m21;
  5425. result[6] = m02;
  5426. result[7] = m12;
  5427. result[8] = m22;
  5428. return result;
  5429. };
  5430. /**
  5431. * Computes a Matrix3 instance representing a non-uniform scale.
  5432. *
  5433. * @param {Cartesian3} scale The x, y, and z scale factors.
  5434. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5435. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5436. *
  5437. * @example
  5438. * // Creates
  5439. * // [7.0, 0.0, 0.0]
  5440. * // [0.0, 8.0, 0.0]
  5441. * // [0.0, 0.0, 9.0]
  5442. * var m = Cesium.Matrix3.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5443. */
  5444. Matrix3.fromScale = function(scale, result) {
  5445. if (!defined(scale)) {
  5446. throw new DeveloperError('scale is required.');
  5447. }
  5448. if (!defined(result)) {
  5449. return new Matrix3(
  5450. scale.x, 0.0, 0.0,
  5451. 0.0, scale.y, 0.0,
  5452. 0.0, 0.0, scale.z);
  5453. }
  5454. result[0] = scale.x;
  5455. result[1] = 0.0;
  5456. result[2] = 0.0;
  5457. result[3] = 0.0;
  5458. result[4] = scale.y;
  5459. result[5] = 0.0;
  5460. result[6] = 0.0;
  5461. result[7] = 0.0;
  5462. result[8] = scale.z;
  5463. return result;
  5464. };
  5465. /**
  5466. * Computes a Matrix3 instance representing a uniform scale.
  5467. *
  5468. * @param {Number} scale The uniform scale factor.
  5469. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5470. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5471. *
  5472. * @example
  5473. * // Creates
  5474. * // [2.0, 0.0, 0.0]
  5475. * // [0.0, 2.0, 0.0]
  5476. * // [0.0, 0.0, 2.0]
  5477. * var m = Cesium.Matrix3.fromUniformScale(2.0);
  5478. */
  5479. Matrix3.fromUniformScale = function(scale, result) {
  5480. if (typeof scale !== 'number') {
  5481. throw new DeveloperError('scale is required.');
  5482. }
  5483. if (!defined(result)) {
  5484. return new Matrix3(
  5485. scale, 0.0, 0.0,
  5486. 0.0, scale, 0.0,
  5487. 0.0, 0.0, scale);
  5488. }
  5489. result[0] = scale;
  5490. result[1] = 0.0;
  5491. result[2] = 0.0;
  5492. result[3] = 0.0;
  5493. result[4] = scale;
  5494. result[5] = 0.0;
  5495. result[6] = 0.0;
  5496. result[7] = 0.0;
  5497. result[8] = scale;
  5498. return result;
  5499. };
  5500. /**
  5501. * Computes a Matrix3 instance representing the cross product equivalent matrix of a Cartesian3 vector.
  5502. *
  5503. * @param {Cartesian3} the vector on the left hand side of the cross product operation.
  5504. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5505. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5506. *
  5507. * @example
  5508. * // Creates
  5509. * // [0.0, -9.0, 8.0]
  5510. * // [9.0, 0.0, -7.0]
  5511. * // [-8.0, 7.0, 0.0]
  5512. * var m = Cesium.Matrix3.fromCrossProduct(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  5513. */
  5514. Matrix3.fromCrossProduct = function(vector, result) {
  5515. if (!defined(vector)) {
  5516. throw new DeveloperError('vector is required.');
  5517. }
  5518. if (!defined(result)) {
  5519. return new Matrix3(
  5520. 0.0, -vector.z, vector.y,
  5521. vector.z, 0.0, -vector.x,
  5522. -vector.y, vector.x, 0.0);
  5523. }
  5524. result[0] = 0.0;
  5525. result[1] = vector.z;
  5526. result[2] = -vector.y;
  5527. result[3] = -vector.z;
  5528. result[4] = 0.0;
  5529. result[5] = vector.x;
  5530. result[6] = vector.y;
  5531. result[7] = -vector.x;
  5532. result[8] = 0.0;
  5533. return result;
  5534. };
  5535. /**
  5536. * Creates a rotation matrix around the x-axis.
  5537. *
  5538. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5539. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5540. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5541. *
  5542. * @example
  5543. * // Rotate a point 45 degrees counterclockwise around the x-axis.
  5544. * var p = new Cesium.Cartesian3(5, 6, 7);
  5545. * var m = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(45.0));
  5546. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5547. */
  5548. Matrix3.fromRotationX = function(angle, result) {
  5549. if (!defined(angle)) {
  5550. throw new DeveloperError('angle is required.');
  5551. }
  5552. var cosAngle = Math.cos(angle);
  5553. var sinAngle = Math.sin(angle);
  5554. if (!defined(result)) {
  5555. return new Matrix3(
  5556. 1.0, 0.0, 0.0,
  5557. 0.0, cosAngle, -sinAngle,
  5558. 0.0, sinAngle, cosAngle);
  5559. }
  5560. result[0] = 1.0;
  5561. result[1] = 0.0;
  5562. result[2] = 0.0;
  5563. result[3] = 0.0;
  5564. result[4] = cosAngle;
  5565. result[5] = sinAngle;
  5566. result[6] = 0.0;
  5567. result[7] = -sinAngle;
  5568. result[8] = cosAngle;
  5569. return result;
  5570. };
  5571. /**
  5572. * Creates a rotation matrix around the y-axis.
  5573. *
  5574. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5575. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5576. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5577. *
  5578. * @example
  5579. * // Rotate a point 45 degrees counterclockwise around the y-axis.
  5580. * var p = new Cesium.Cartesian3(5, 6, 7);
  5581. * var m = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(45.0));
  5582. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5583. */
  5584. Matrix3.fromRotationY = function(angle, result) {
  5585. if (!defined(angle)) {
  5586. throw new DeveloperError('angle is required.');
  5587. }
  5588. var cosAngle = Math.cos(angle);
  5589. var sinAngle = Math.sin(angle);
  5590. if (!defined(result)) {
  5591. return new Matrix3(
  5592. cosAngle, 0.0, sinAngle,
  5593. 0.0, 1.0, 0.0,
  5594. -sinAngle, 0.0, cosAngle);
  5595. }
  5596. result[0] = cosAngle;
  5597. result[1] = 0.0;
  5598. result[2] = -sinAngle;
  5599. result[3] = 0.0;
  5600. result[4] = 1.0;
  5601. result[5] = 0.0;
  5602. result[6] = sinAngle;
  5603. result[7] = 0.0;
  5604. result[8] = cosAngle;
  5605. return result;
  5606. };
  5607. /**
  5608. * Creates a rotation matrix around the z-axis.
  5609. *
  5610. * @param {Number} angle The angle, in radians, of the rotation. Positive angles are counterclockwise.
  5611. * @param {Matrix3} [result] The object in which the result will be stored, if undefined a new instance will be created.
  5612. * @returns {Matrix3} The modified result parameter, or a new Matrix3 instance if one was not provided.
  5613. *
  5614. * @example
  5615. * // Rotate a point 45 degrees counterclockwise around the z-axis.
  5616. * var p = new Cesium.Cartesian3(5, 6, 7);
  5617. * var m = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(45.0));
  5618. * var rotated = Cesium.Matrix3.multiplyByVector(m, p, new Cesium.Cartesian3());
  5619. */
  5620. Matrix3.fromRotationZ = function(angle, result) {
  5621. if (!defined(angle)) {
  5622. throw new DeveloperError('angle is required.');
  5623. }
  5624. var cosAngle = Math.cos(angle);
  5625. var sinAngle = Math.sin(angle);
  5626. if (!defined(result)) {
  5627. return new Matrix3(
  5628. cosAngle, -sinAngle, 0.0,
  5629. sinAngle, cosAngle, 0.0,
  5630. 0.0, 0.0, 1.0);
  5631. }
  5632. result[0] = cosAngle;
  5633. result[1] = sinAngle;
  5634. result[2] = 0.0;
  5635. result[3] = -sinAngle;
  5636. result[4] = cosAngle;
  5637. result[5] = 0.0;
  5638. result[6] = 0.0;
  5639. result[7] = 0.0;
  5640. result[8] = 1.0;
  5641. return result;
  5642. };
  5643. /**
  5644. * Creates an Array from the provided Matrix3 instance.
  5645. * The array will be in column-major order.
  5646. *
  5647. * @param {Matrix3} matrix The matrix to use..
  5648. * @param {Number[]} [result] The Array onto which to store the result.
  5649. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  5650. */
  5651. Matrix3.toArray = function(matrix, result) {
  5652. if (!defined(matrix)) {
  5653. throw new DeveloperError('matrix is required');
  5654. }
  5655. if (!defined(result)) {
  5656. return [matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8]];
  5657. }
  5658. result[0] = matrix[0];
  5659. result[1] = matrix[1];
  5660. result[2] = matrix[2];
  5661. result[3] = matrix[3];
  5662. result[4] = matrix[4];
  5663. result[5] = matrix[5];
  5664. result[6] = matrix[6];
  5665. result[7] = matrix[7];
  5666. result[8] = matrix[8];
  5667. return result;
  5668. };
  5669. /**
  5670. * Computes the array index of the element at the provided row and column.
  5671. *
  5672. * @param {Number} row The zero-based index of the row.
  5673. * @param {Number} column The zero-based index of the column.
  5674. * @returns {Number} The index of the element at the provided row and column.
  5675. *
  5676. * @exception {DeveloperError} row must be 0, 1, or 2.
  5677. * @exception {DeveloperError} column must be 0, 1, or 2.
  5678. *
  5679. * @example
  5680. * var myMatrix = new Cesium.Matrix3();
  5681. * var column1Row0Index = Cesium.Matrix3.getElementIndex(1, 0);
  5682. * var column1Row0 = myMatrix[column1Row0Index]
  5683. * myMatrix[column1Row0Index] = 10.0;
  5684. */
  5685. Matrix3.getElementIndex = function(column, row) {
  5686. if (typeof row !== 'number' || row < 0 || row > 2) {
  5687. throw new DeveloperError('row must be 0, 1, or 2.');
  5688. }
  5689. if (typeof column !== 'number' || column < 0 || column > 2) {
  5690. throw new DeveloperError('column must be 0, 1, or 2.');
  5691. }
  5692. return column * 3 + row;
  5693. };
  5694. /**
  5695. * Retrieves a copy of the matrix column at the provided index as a Cartesian3 instance.
  5696. *
  5697. * @param {Matrix3} matrix The matrix to use.
  5698. * @param {Number} index The zero-based index of the column to retrieve.
  5699. * @param {Cartesian3} result The object onto which to store the result.
  5700. * @returns {Cartesian3} The modified result parameter.
  5701. *
  5702. * @exception {DeveloperError} index must be 0, 1, or 2.
  5703. */
  5704. Matrix3.getColumn = function(matrix, index, result) {
  5705. if (!defined(matrix)) {
  5706. throw new DeveloperError('matrix is required.');
  5707. }
  5708. if (typeof index !== 'number' || index < 0 || index > 2) {
  5709. throw new DeveloperError('index must be 0, 1, or 2.');
  5710. }
  5711. if (!defined(result)) {
  5712. throw new DeveloperError('result is required');
  5713. }
  5714. var startIndex = index * 3;
  5715. var x = matrix[startIndex];
  5716. var y = matrix[startIndex + 1];
  5717. var z = matrix[startIndex + 2];
  5718. result.x = x;
  5719. result.y = y;
  5720. result.z = z;
  5721. return result;
  5722. };
  5723. /**
  5724. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian3 instance.
  5725. *
  5726. * @param {Matrix3} matrix The matrix to use.
  5727. * @param {Number} index The zero-based index of the column to set.
  5728. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified column.
  5729. * @param {Matrix3} result The object onto which to store the result.
  5730. * @returns {Matrix3} The modified result parameter.
  5731. *
  5732. * @exception {DeveloperError} index must be 0, 1, or 2.
  5733. */
  5734. Matrix3.setColumn = function(matrix, index, cartesian, result) {
  5735. if (!defined(matrix)) {
  5736. throw new DeveloperError('matrix is required');
  5737. }
  5738. if (!defined(cartesian)) {
  5739. throw new DeveloperError('cartesian is required');
  5740. }
  5741. if (typeof index !== 'number' || index < 0 || index > 2) {
  5742. throw new DeveloperError('index must be 0, 1, or 2.');
  5743. }
  5744. if (!defined(result)) {
  5745. throw new DeveloperError('result is required');
  5746. }
  5747. result = Matrix3.clone(matrix, result);
  5748. var startIndex = index * 3;
  5749. result[startIndex] = cartesian.x;
  5750. result[startIndex + 1] = cartesian.y;
  5751. result[startIndex + 2] = cartesian.z;
  5752. return result;
  5753. };
  5754. /**
  5755. * Retrieves a copy of the matrix row at the provided index as a Cartesian3 instance.
  5756. *
  5757. * @param {Matrix3} matrix The matrix to use.
  5758. * @param {Number} index The zero-based index of the row to retrieve.
  5759. * @param {Cartesian3} result The object onto which to store the result.
  5760. * @returns {Cartesian3} The modified result parameter.
  5761. *
  5762. * @exception {DeveloperError} index must be 0, 1, or 2.
  5763. */
  5764. Matrix3.getRow = function(matrix, index, result) {
  5765. if (!defined(matrix)) {
  5766. throw new DeveloperError('matrix is required.');
  5767. }
  5768. if (typeof index !== 'number' || index < 0 || index > 2) {
  5769. throw new DeveloperError('index must be 0, 1, or 2.');
  5770. }
  5771. if (!defined(result)) {
  5772. throw new DeveloperError('result is required');
  5773. }
  5774. var x = matrix[index];
  5775. var y = matrix[index + 3];
  5776. var z = matrix[index + 6];
  5777. result.x = x;
  5778. result.y = y;
  5779. result.z = z;
  5780. return result;
  5781. };
  5782. /**
  5783. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian3 instance.
  5784. *
  5785. * @param {Matrix3} matrix The matrix to use.
  5786. * @param {Number} index The zero-based index of the row to set.
  5787. * @param {Cartesian3} cartesian The Cartesian whose values will be assigned to the specified row.
  5788. * @param {Matrix3} result The object onto which to store the result.
  5789. * @returns {Matrix3} The modified result parameter.
  5790. *
  5791. * @exception {DeveloperError} index must be 0, 1, or 2.
  5792. */
  5793. Matrix3.setRow = function(matrix, index, cartesian, result) {
  5794. if (!defined(matrix)) {
  5795. throw new DeveloperError('matrix is required');
  5796. }
  5797. if (!defined(cartesian)) {
  5798. throw new DeveloperError('cartesian is required');
  5799. }
  5800. if (typeof index !== 'number' || index < 0 || index > 2) {
  5801. throw new DeveloperError('index must be 0, 1, or 2.');
  5802. }
  5803. if (!defined(result)) {
  5804. throw new DeveloperError('result is required');
  5805. }
  5806. result = Matrix3.clone(matrix, result);
  5807. result[index] = cartesian.x;
  5808. result[index + 3] = cartesian.y;
  5809. result[index + 6] = cartesian.z;
  5810. return result;
  5811. };
  5812. var scratchColumn = new Cartesian3();
  5813. /**
  5814. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  5815. *
  5816. * @param {Matrix3} matrix The matrix.
  5817. * @param {Cartesian3} result The object onto which to store the result.
  5818. * @returns {Cartesian3} The modified result parameter.
  5819. */
  5820. Matrix3.getScale = function(matrix, result) {
  5821. if (!defined(matrix)) {
  5822. throw new DeveloperError('matrix is required.');
  5823. }
  5824. if (!defined(result)) {
  5825. throw new DeveloperError('result is required');
  5826. }
  5827. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  5828. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[3], matrix[4], matrix[5], scratchColumn));
  5829. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[6], matrix[7], matrix[8], scratchColumn));
  5830. return result;
  5831. };
  5832. var scratchScale = new Cartesian3();
  5833. /**
  5834. * Computes the maximum scale assuming the matrix is an affine transformation.
  5835. * The maximum scale is the maximum length of the column vectors.
  5836. *
  5837. * @param {Matrix3} matrix The matrix.
  5838. * @returns {Number} The maximum scale.
  5839. */
  5840. Matrix3.getMaximumScale = function(matrix) {
  5841. Matrix3.getScale(matrix, scratchScale);
  5842. return Cartesian3.maximumComponent(scratchScale);
  5843. };
  5844. /**
  5845. * Computes the product of two matrices.
  5846. *
  5847. * @param {Matrix3} left The first matrix.
  5848. * @param {Matrix3} right The second matrix.
  5849. * @param {Matrix3} result The object onto which to store the result.
  5850. * @returns {Matrix3} The modified result parameter.
  5851. */
  5852. Matrix3.multiply = function(left, right, result) {
  5853. if (!defined(left)) {
  5854. throw new DeveloperError('left is required');
  5855. }
  5856. if (!defined(right)) {
  5857. throw new DeveloperError('right is required');
  5858. }
  5859. if (!defined(result)) {
  5860. throw new DeveloperError('result is required');
  5861. }
  5862. var column0Row0 = left[0] * right[0] + left[3] * right[1] + left[6] * right[2];
  5863. var column0Row1 = left[1] * right[0] + left[4] * right[1] + left[7] * right[2];
  5864. var column0Row2 = left[2] * right[0] + left[5] * right[1] + left[8] * right[2];
  5865. var column1Row0 = left[0] * right[3] + left[3] * right[4] + left[6] * right[5];
  5866. var column1Row1 = left[1] * right[3] + left[4] * right[4] + left[7] * right[5];
  5867. var column1Row2 = left[2] * right[3] + left[5] * right[4] + left[8] * right[5];
  5868. var column2Row0 = left[0] * right[6] + left[3] * right[7] + left[6] * right[8];
  5869. var column2Row1 = left[1] * right[6] + left[4] * right[7] + left[7] * right[8];
  5870. var column2Row2 = left[2] * right[6] + left[5] * right[7] + left[8] * right[8];
  5871. result[0] = column0Row0;
  5872. result[1] = column0Row1;
  5873. result[2] = column0Row2;
  5874. result[3] = column1Row0;
  5875. result[4] = column1Row1;
  5876. result[5] = column1Row2;
  5877. result[6] = column2Row0;
  5878. result[7] = column2Row1;
  5879. result[8] = column2Row2;
  5880. return result;
  5881. };
  5882. /**
  5883. * Computes the sum of two matrices.
  5884. *
  5885. * @param {Matrix3} left The first matrix.
  5886. * @param {Matrix3} right The second matrix.
  5887. * @param {Matrix3} result The object onto which to store the result.
  5888. * @returns {Matrix3} The modified result parameter.
  5889. */
  5890. Matrix3.add = function(left, right, result) {
  5891. if (!defined(left)) {
  5892. throw new DeveloperError('left is required');
  5893. }
  5894. if (!defined(right)) {
  5895. throw new DeveloperError('right is required');
  5896. }
  5897. if (!defined(result)) {
  5898. throw new DeveloperError('result is required');
  5899. }
  5900. result[0] = left[0] + right[0];
  5901. result[1] = left[1] + right[1];
  5902. result[2] = left[2] + right[2];
  5903. result[3] = left[3] + right[3];
  5904. result[4] = left[4] + right[4];
  5905. result[5] = left[5] + right[5];
  5906. result[6] = left[6] + right[6];
  5907. result[7] = left[7] + right[7];
  5908. result[8] = left[8] + right[8];
  5909. return result;
  5910. };
  5911. /**
  5912. * Computes the difference of two matrices.
  5913. *
  5914. * @param {Matrix3} left The first matrix.
  5915. * @param {Matrix3} right The second matrix.
  5916. * @param {Matrix3} result The object onto which to store the result.
  5917. * @returns {Matrix3} The modified result parameter.
  5918. */
  5919. Matrix3.subtract = function(left, right, result) {
  5920. if (!defined(left)) {
  5921. throw new DeveloperError('left is required');
  5922. }
  5923. if (!defined(right)) {
  5924. throw new DeveloperError('right is required');
  5925. }
  5926. if (!defined(result)) {
  5927. throw new DeveloperError('result is required');
  5928. }
  5929. result[0] = left[0] - right[0];
  5930. result[1] = left[1] - right[1];
  5931. result[2] = left[2] - right[2];
  5932. result[3] = left[3] - right[3];
  5933. result[4] = left[4] - right[4];
  5934. result[5] = left[5] - right[5];
  5935. result[6] = left[6] - right[6];
  5936. result[7] = left[7] - right[7];
  5937. result[8] = left[8] - right[8];
  5938. return result;
  5939. };
  5940. /**
  5941. * Computes the product of a matrix and a column vector.
  5942. *
  5943. * @param {Matrix3} matrix The matrix.
  5944. * @param {Cartesian3} cartesian The column.
  5945. * @param {Cartesian3} result The object onto which to store the result.
  5946. * @returns {Cartesian3} The modified result parameter.
  5947. */
  5948. Matrix3.multiplyByVector = function(matrix, cartesian, result) {
  5949. if (!defined(matrix)) {
  5950. throw new DeveloperError('matrix is required');
  5951. }
  5952. if (!defined(cartesian)) {
  5953. throw new DeveloperError('cartesian is required');
  5954. }
  5955. if (!defined(result)) {
  5956. throw new DeveloperError('result is required');
  5957. }
  5958. var vX = cartesian.x;
  5959. var vY = cartesian.y;
  5960. var vZ = cartesian.z;
  5961. var x = matrix[0] * vX + matrix[3] * vY + matrix[6] * vZ;
  5962. var y = matrix[1] * vX + matrix[4] * vY + matrix[7] * vZ;
  5963. var z = matrix[2] * vX + matrix[5] * vY + matrix[8] * vZ;
  5964. result.x = x;
  5965. result.y = y;
  5966. result.z = z;
  5967. return result;
  5968. };
  5969. /**
  5970. * Computes the product of a matrix and a scalar.
  5971. *
  5972. * @param {Matrix3} matrix The matrix.
  5973. * @param {Number} scalar The number to multiply by.
  5974. * @param {Matrix3} result The object onto which to store the result.
  5975. * @returns {Matrix3} The modified result parameter.
  5976. */
  5977. Matrix3.multiplyByScalar = function(matrix, scalar, result) {
  5978. if (!defined(matrix)) {
  5979. throw new DeveloperError('matrix is required');
  5980. }
  5981. if (typeof scalar !== 'number') {
  5982. throw new DeveloperError('scalar must be a number');
  5983. }
  5984. if (!defined(result)) {
  5985. throw new DeveloperError('result is required');
  5986. }
  5987. result[0] = matrix[0] * scalar;
  5988. result[1] = matrix[1] * scalar;
  5989. result[2] = matrix[2] * scalar;
  5990. result[3] = matrix[3] * scalar;
  5991. result[4] = matrix[4] * scalar;
  5992. result[5] = matrix[5] * scalar;
  5993. result[6] = matrix[6] * scalar;
  5994. result[7] = matrix[7] * scalar;
  5995. result[8] = matrix[8] * scalar;
  5996. return result;
  5997. };
  5998. /**
  5999. * Computes the product of a matrix times a (non-uniform) scale, as if the scale were a scale matrix.
  6000. *
  6001. * @param {Matrix3} matrix The matrix on the left-hand side.
  6002. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  6003. * @param {Matrix3} result The object onto which to store the result.
  6004. * @returns {Matrix3} The modified result parameter.
  6005. *
  6006. *
  6007. * @example
  6008. * // Instead of Cesium.Matrix3.multiply(m, Cesium.Matrix3.fromScale(scale), m);
  6009. * Cesium.Matrix3.multiplyByScale(m, scale, m);
  6010. *
  6011. * @see Matrix3.fromScale
  6012. * @see Matrix3.multiplyByUniformScale
  6013. */
  6014. Matrix3.multiplyByScale = function(matrix, scale, result) {
  6015. if (!defined(matrix)) {
  6016. throw new DeveloperError('matrix is required');
  6017. }
  6018. if (!defined(scale)) {
  6019. throw new DeveloperError('scale is required');
  6020. }
  6021. if (!defined(result)) {
  6022. throw new DeveloperError('result is required');
  6023. }
  6024. result[0] = matrix[0] * scale.x;
  6025. result[1] = matrix[1] * scale.x;
  6026. result[2] = matrix[2] * scale.x;
  6027. result[3] = matrix[3] * scale.y;
  6028. result[4] = matrix[4] * scale.y;
  6029. result[5] = matrix[5] * scale.y;
  6030. result[6] = matrix[6] * scale.z;
  6031. result[7] = matrix[7] * scale.z;
  6032. result[8] = matrix[8] * scale.z;
  6033. return result;
  6034. };
  6035. /**
  6036. * Creates a negated copy of the provided matrix.
  6037. *
  6038. * @param {Matrix3} matrix The matrix to negate.
  6039. * @param {Matrix3} result The object onto which to store the result.
  6040. * @returns {Matrix3} The modified result parameter.
  6041. */
  6042. Matrix3.negate = function(matrix, result) {
  6043. if (!defined(matrix)) {
  6044. throw new DeveloperError('matrix is required');
  6045. }
  6046. if (!defined(result)) {
  6047. throw new DeveloperError('result is required');
  6048. }
  6049. result[0] = -matrix[0];
  6050. result[1] = -matrix[1];
  6051. result[2] = -matrix[2];
  6052. result[3] = -matrix[3];
  6053. result[4] = -matrix[4];
  6054. result[5] = -matrix[5];
  6055. result[6] = -matrix[6];
  6056. result[7] = -matrix[7];
  6057. result[8] = -matrix[8];
  6058. return result;
  6059. };
  6060. /**
  6061. * Computes the transpose of the provided matrix.
  6062. *
  6063. * @param {Matrix3} matrix The matrix to transpose.
  6064. * @param {Matrix3} result The object onto which to store the result.
  6065. * @returns {Matrix3} The modified result parameter.
  6066. */
  6067. Matrix3.transpose = function(matrix, result) {
  6068. if (!defined(matrix)) {
  6069. throw new DeveloperError('matrix is required');
  6070. }
  6071. if (!defined(result)) {
  6072. throw new DeveloperError('result is required');
  6073. }
  6074. var column0Row0 = matrix[0];
  6075. var column0Row1 = matrix[3];
  6076. var column0Row2 = matrix[6];
  6077. var column1Row0 = matrix[1];
  6078. var column1Row1 = matrix[4];
  6079. var column1Row2 = matrix[7];
  6080. var column2Row0 = matrix[2];
  6081. var column2Row1 = matrix[5];
  6082. var column2Row2 = matrix[8];
  6083. result[0] = column0Row0;
  6084. result[1] = column0Row1;
  6085. result[2] = column0Row2;
  6086. result[3] = column1Row0;
  6087. result[4] = column1Row1;
  6088. result[5] = column1Row2;
  6089. result[6] = column2Row0;
  6090. result[7] = column2Row1;
  6091. result[8] = column2Row2;
  6092. return result;
  6093. };
  6094. function computeFrobeniusNorm(matrix) {
  6095. var norm = 0.0;
  6096. for (var i = 0; i < 9; ++i) {
  6097. var temp = matrix[i];
  6098. norm += temp * temp;
  6099. }
  6100. return Math.sqrt(norm);
  6101. }
  6102. var rowVal = [1, 0, 0];
  6103. var colVal = [2, 2, 1];
  6104. function offDiagonalFrobeniusNorm(matrix) {
  6105. // Computes the "off-diagonal" Frobenius norm.
  6106. // Assumes matrix is symmetric.
  6107. var norm = 0.0;
  6108. for (var i = 0; i < 3; ++i) {
  6109. var temp = matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])];
  6110. norm += 2.0 * temp * temp;
  6111. }
  6112. return Math.sqrt(norm);
  6113. }
  6114. function shurDecomposition(matrix, result) {
  6115. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  6116. // section 8.4.2 The 2by2 Symmetric Schur Decomposition.
  6117. //
  6118. // The routine takes a matrix, which is assumed to be symmetric, and
  6119. // finds the largest off-diagonal term, and then creates
  6120. // a matrix (result) which can be used to help reduce it
  6121. var tolerance = CesiumMath.EPSILON15;
  6122. var maxDiagonal = 0.0;
  6123. var rotAxis = 1;
  6124. // find pivot (rotAxis) based on max diagonal of matrix
  6125. for (var i = 0; i < 3; ++i) {
  6126. var temp = Math.abs(matrix[Matrix3.getElementIndex(colVal[i], rowVal[i])]);
  6127. if (temp > maxDiagonal) {
  6128. rotAxis = i;
  6129. maxDiagonal = temp;
  6130. }
  6131. }
  6132. var c = 1.0;
  6133. var s = 0.0;
  6134. var p = rowVal[rotAxis];
  6135. var q = colVal[rotAxis];
  6136. if (Math.abs(matrix[Matrix3.getElementIndex(q, p)]) > tolerance) {
  6137. var qq = matrix[Matrix3.getElementIndex(q, q)];
  6138. var pp = matrix[Matrix3.getElementIndex(p, p)];
  6139. var qp = matrix[Matrix3.getElementIndex(q, p)];
  6140. var tau = (qq - pp) / 2.0 / qp;
  6141. var t;
  6142. if (tau < 0.0) {
  6143. t = -1.0 / (-tau + Math.sqrt(1.0 + tau * tau));
  6144. } else {
  6145. t = 1.0 / (tau + Math.sqrt(1.0 + tau * tau));
  6146. }
  6147. c = 1.0 / Math.sqrt(1.0 + t * t);
  6148. s = t * c;
  6149. }
  6150. result = Matrix3.clone(Matrix3.IDENTITY, result);
  6151. result[Matrix3.getElementIndex(p, p)] = result[Matrix3.getElementIndex(q, q)] = c;
  6152. result[Matrix3.getElementIndex(q, p)] = s;
  6153. result[Matrix3.getElementIndex(p, q)] = -s;
  6154. return result;
  6155. }
  6156. var jMatrix = new Matrix3();
  6157. var jMatrixTranspose = new Matrix3();
  6158. /**
  6159. * Computes the eigenvectors and eigenvalues of a symmetric matrix.
  6160. * <p>
  6161. * Returns a diagonal matrix and unitary matrix such that:
  6162. * <code>matrix = unitary matrix * diagonal matrix * transpose(unitary matrix)</code>
  6163. * </p>
  6164. * <p>
  6165. * The values along the diagonal of the diagonal matrix are the eigenvalues. The columns
  6166. * of the unitary matrix are the corresponding eigenvectors.
  6167. * </p>
  6168. *
  6169. * @param {Matrix3} matrix The matrix to decompose into diagonal and unitary matrix. Expected to be symmetric.
  6170. * @param {Object} [result] An object with unitary and diagonal properties which are matrices onto which to store the result.
  6171. * @returns {Object} An object with unitary and diagonal properties which are the unitary and diagonal matrices, respectively.
  6172. *
  6173. * @example
  6174. * var a = //... symetric matrix
  6175. * var result = {
  6176. * unitary : new Cesium.Matrix3(),
  6177. * diagonal : new Cesium.Matrix3()
  6178. * };
  6179. * Cesium.Matrix3.computeEigenDecomposition(a, result);
  6180. *
  6181. * var unitaryTranspose = Cesium.Matrix3.transpose(result.unitary, new Cesium.Matrix3());
  6182. * var b = Cesium.Matrix3.multiply(result.unitary, result.diagonal, new Cesium.Matrix3());
  6183. * Cesium.Matrix3.multiply(b, unitaryTranspose, b); // b is now equal to a
  6184. *
  6185. * var lambda = Cesium.Matrix3.getColumn(result.diagonal, 0, new Cesium.Cartesian3()).x; // first eigenvalue
  6186. * var v = Cesium.Matrix3.getColumn(result.unitary, 0, new Cesium.Cartesian3()); // first eigenvector
  6187. * var c = Cesium.Cartesian3.multiplyByScalar(v, lambda, new Cesium.Cartesian3()); // equal to Cesium.Matrix3.multiplyByVector(a, v)
  6188. */
  6189. Matrix3.computeEigenDecomposition = function(matrix, result) {
  6190. if (!defined(matrix)) {
  6191. throw new DeveloperError('matrix is required.');
  6192. }
  6193. // This routine was created based upon Matrix Computations, 3rd ed., by Golub and Van Loan,
  6194. // section 8.4.3 The Classical Jacobi Algorithm
  6195. var tolerance = CesiumMath.EPSILON20;
  6196. var maxSweeps = 10;
  6197. var count = 0;
  6198. var sweep = 0;
  6199. if (!defined(result)) {
  6200. result = {};
  6201. }
  6202. var unitaryMatrix = result.unitary = Matrix3.clone(Matrix3.IDENTITY, result.unitary);
  6203. var diagMatrix = result.diagonal = Matrix3.clone(matrix, result.diagonal);
  6204. var epsilon = tolerance * computeFrobeniusNorm(diagMatrix);
  6205. while (sweep < maxSweeps && offDiagonalFrobeniusNorm(diagMatrix) > epsilon) {
  6206. shurDecomposition(diagMatrix, jMatrix);
  6207. Matrix3.transpose(jMatrix, jMatrixTranspose);
  6208. Matrix3.multiply(diagMatrix, jMatrix, diagMatrix);
  6209. Matrix3.multiply(jMatrixTranspose, diagMatrix, diagMatrix);
  6210. Matrix3.multiply(unitaryMatrix, jMatrix, unitaryMatrix);
  6211. if (++count > 2) {
  6212. ++sweep;
  6213. count = 0;
  6214. }
  6215. }
  6216. return result;
  6217. };
  6218. /**
  6219. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  6220. *
  6221. * @param {Matrix3} matrix The matrix with signed elements.
  6222. * @param {Matrix3} result The object onto which to store the result.
  6223. * @returns {Matrix3} The modified result parameter.
  6224. */
  6225. Matrix3.abs = function(matrix, result) {
  6226. if (!defined(matrix)) {
  6227. throw new DeveloperError('matrix is required');
  6228. }
  6229. if (!defined(result)) {
  6230. throw new DeveloperError('result is required');
  6231. }
  6232. result[0] = Math.abs(matrix[0]);
  6233. result[1] = Math.abs(matrix[1]);
  6234. result[2] = Math.abs(matrix[2]);
  6235. result[3] = Math.abs(matrix[3]);
  6236. result[4] = Math.abs(matrix[4]);
  6237. result[5] = Math.abs(matrix[5]);
  6238. result[6] = Math.abs(matrix[6]);
  6239. result[7] = Math.abs(matrix[7]);
  6240. result[8] = Math.abs(matrix[8]);
  6241. return result;
  6242. };
  6243. /**
  6244. * Computes the determinant of the provided matrix.
  6245. *
  6246. * @param {Matrix3} matrix The matrix to use.
  6247. * @returns {Number} The value of the determinant of the matrix.
  6248. */
  6249. Matrix3.determinant = function(matrix) {
  6250. if (!defined(matrix)) {
  6251. throw new DeveloperError('matrix is required');
  6252. }
  6253. var m11 = matrix[0];
  6254. var m21 = matrix[3];
  6255. var m31 = matrix[6];
  6256. var m12 = matrix[1];
  6257. var m22 = matrix[4];
  6258. var m32 = matrix[7];
  6259. var m13 = matrix[2];
  6260. var m23 = matrix[5];
  6261. var m33 = matrix[8];
  6262. return m11 * (m22 * m33 - m23 * m32) + m12 * (m23 * m31 - m21 * m33) + m13 * (m21 * m32 - m22 * m31);
  6263. };
  6264. /**
  6265. * Computes the inverse of the provided matrix.
  6266. *
  6267. * @param {Matrix3} matrix The matrix to invert.
  6268. * @param {Matrix3} result The object onto which to store the result.
  6269. * @returns {Matrix3} The modified result parameter.
  6270. *
  6271. * @exception {DeveloperError} matrix is not invertible.
  6272. */
  6273. Matrix3.inverse = function(matrix, result) {
  6274. if (!defined(matrix)) {
  6275. throw new DeveloperError('matrix is required');
  6276. }
  6277. if (!defined(result)) {
  6278. throw new DeveloperError('result is required');
  6279. }
  6280. var m11 = matrix[0];
  6281. var m21 = matrix[1];
  6282. var m31 = matrix[2];
  6283. var m12 = matrix[3];
  6284. var m22 = matrix[4];
  6285. var m32 = matrix[5];
  6286. var m13 = matrix[6];
  6287. var m23 = matrix[7];
  6288. var m33 = matrix[8];
  6289. var determinant = Matrix3.determinant(matrix);
  6290. if (Math.abs(determinant) <= CesiumMath.EPSILON15) {
  6291. throw new DeveloperError('matrix is not invertible');
  6292. }
  6293. result[0] = m22 * m33 - m23 * m32;
  6294. result[1] = m23 * m31 - m21 * m33;
  6295. result[2] = m21 * m32 - m22 * m31;
  6296. result[3] = m13 * m32 - m12 * m33;
  6297. result[4] = m11 * m33 - m13 * m31;
  6298. result[5] = m12 * m31 - m11 * m32;
  6299. result[6] = m12 * m23 - m13 * m22;
  6300. result[7] = m13 * m21 - m11 * m23;
  6301. result[8] = m11 * m22 - m12 * m21;
  6302. var scale = 1.0 / determinant;
  6303. return Matrix3.multiplyByScalar(result, scale, result);
  6304. };
  6305. /**
  6306. * Compares the provided matrices componentwise and returns
  6307. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6308. *
  6309. * @param {Matrix3} [left] The first matrix.
  6310. * @param {Matrix3} [right] The second matrix.
  6311. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  6312. */
  6313. Matrix3.equals = function(left, right) {
  6314. return (left === right) ||
  6315. (defined(left) &&
  6316. defined(right) &&
  6317. left[0] === right[0] &&
  6318. left[1] === right[1] &&
  6319. left[2] === right[2] &&
  6320. left[3] === right[3] &&
  6321. left[4] === right[4] &&
  6322. left[5] === right[5] &&
  6323. left[6] === right[6] &&
  6324. left[7] === right[7] &&
  6325. left[8] === right[8]);
  6326. };
  6327. /**
  6328. * Compares the provided matrices componentwise and returns
  6329. * <code>true</code> if they are within the provided epsilon,
  6330. * <code>false</code> otherwise.
  6331. *
  6332. * @param {Matrix3} [left] The first matrix.
  6333. * @param {Matrix3} [right] The second matrix.
  6334. * @param {Number} epsilon The epsilon to use for equality testing.
  6335. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  6336. */
  6337. Matrix3.equalsEpsilon = function(left, right, epsilon) {
  6338. if (typeof epsilon !== 'number') {
  6339. throw new DeveloperError('epsilon must be a number');
  6340. }
  6341. return (left === right) ||
  6342. (defined(left) &&
  6343. defined(right) &&
  6344. Math.abs(left[0] - right[0]) <= epsilon &&
  6345. Math.abs(left[1] - right[1]) <= epsilon &&
  6346. Math.abs(left[2] - right[2]) <= epsilon &&
  6347. Math.abs(left[3] - right[3]) <= epsilon &&
  6348. Math.abs(left[4] - right[4]) <= epsilon &&
  6349. Math.abs(left[5] - right[5]) <= epsilon &&
  6350. Math.abs(left[6] - right[6]) <= epsilon &&
  6351. Math.abs(left[7] - right[7]) <= epsilon &&
  6352. Math.abs(left[8] - right[8]) <= epsilon);
  6353. };
  6354. /**
  6355. * An immutable Matrix3 instance initialized to the identity matrix.
  6356. *
  6357. * @type {Matrix3}
  6358. * @constant
  6359. */
  6360. Matrix3.IDENTITY = freezeObject(new Matrix3(1.0, 0.0, 0.0,
  6361. 0.0, 1.0, 0.0,
  6362. 0.0, 0.0, 1.0));
  6363. /**
  6364. * An immutable Matrix3 instance initialized to the zero matrix.
  6365. *
  6366. * @type {Matrix3}
  6367. * @constant
  6368. */
  6369. Matrix3.ZERO = freezeObject(new Matrix3(0.0, 0.0, 0.0,
  6370. 0.0, 0.0, 0.0,
  6371. 0.0, 0.0, 0.0));
  6372. /**
  6373. * The index into Matrix3 for column 0, row 0.
  6374. *
  6375. * @type {Number}
  6376. * @constant
  6377. */
  6378. Matrix3.COLUMN0ROW0 = 0;
  6379. /**
  6380. * The index into Matrix3 for column 0, row 1.
  6381. *
  6382. * @type {Number}
  6383. * @constant
  6384. */
  6385. Matrix3.COLUMN0ROW1 = 1;
  6386. /**
  6387. * The index into Matrix3 for column 0, row 2.
  6388. *
  6389. * @type {Number}
  6390. * @constant
  6391. */
  6392. Matrix3.COLUMN0ROW2 = 2;
  6393. /**
  6394. * The index into Matrix3 for column 1, row 0.
  6395. *
  6396. * @type {Number}
  6397. * @constant
  6398. */
  6399. Matrix3.COLUMN1ROW0 = 3;
  6400. /**
  6401. * The index into Matrix3 for column 1, row 1.
  6402. *
  6403. * @type {Number}
  6404. * @constant
  6405. */
  6406. Matrix3.COLUMN1ROW1 = 4;
  6407. /**
  6408. * The index into Matrix3 for column 1, row 2.
  6409. *
  6410. * @type {Number}
  6411. * @constant
  6412. */
  6413. Matrix3.COLUMN1ROW2 = 5;
  6414. /**
  6415. * The index into Matrix3 for column 2, row 0.
  6416. *
  6417. * @type {Number}
  6418. * @constant
  6419. */
  6420. Matrix3.COLUMN2ROW0 = 6;
  6421. /**
  6422. * The index into Matrix3 for column 2, row 1.
  6423. *
  6424. * @type {Number}
  6425. * @constant
  6426. */
  6427. Matrix3.COLUMN2ROW1 = 7;
  6428. /**
  6429. * The index into Matrix3 for column 2, row 2.
  6430. *
  6431. * @type {Number}
  6432. * @constant
  6433. */
  6434. Matrix3.COLUMN2ROW2 = 8;
  6435. defineProperties(Matrix3.prototype, {
  6436. /**
  6437. * Gets the number of items in the collection.
  6438. * @memberof Matrix3.prototype
  6439. *
  6440. * @type {Number}
  6441. */
  6442. length : {
  6443. get : function() {
  6444. return Matrix3.packedLength;
  6445. }
  6446. }
  6447. });
  6448. /**
  6449. * Duplicates the provided Matrix3 instance.
  6450. *
  6451. * @param {Matrix3} [result] The object onto which to store the result.
  6452. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if one was not provided.
  6453. */
  6454. Matrix3.prototype.clone = function(result) {
  6455. return Matrix3.clone(this, result);
  6456. };
  6457. /**
  6458. * Compares this matrix to the provided matrix componentwise and returns
  6459. * <code>true</code> if they are equal, <code>false</code> otherwise.
  6460. *
  6461. * @param {Matrix3} [right] The right hand side matrix.
  6462. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  6463. */
  6464. Matrix3.prototype.equals = function(right) {
  6465. return Matrix3.equals(this, right);
  6466. };
  6467. /**
  6468. * @private
  6469. */
  6470. Matrix3.equalsArray = function(matrix, array, offset) {
  6471. return matrix[0] === array[offset] &&
  6472. matrix[1] === array[offset + 1] &&
  6473. matrix[2] === array[offset + 2] &&
  6474. matrix[3] === array[offset + 3] &&
  6475. matrix[4] === array[offset + 4] &&
  6476. matrix[5] === array[offset + 5] &&
  6477. matrix[6] === array[offset + 6] &&
  6478. matrix[7] === array[offset + 7] &&
  6479. matrix[8] === array[offset + 8];
  6480. };
  6481. /**
  6482. * Compares this matrix to the provided matrix componentwise and returns
  6483. * <code>true</code> if they are within the provided epsilon,
  6484. * <code>false</code> otherwise.
  6485. *
  6486. * @param {Matrix3} [right] The right hand side matrix.
  6487. * @param {Number} epsilon The epsilon to use for equality testing.
  6488. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  6489. */
  6490. Matrix3.prototype.equalsEpsilon = function(right, epsilon) {
  6491. return Matrix3.equalsEpsilon(this, right, epsilon);
  6492. };
  6493. /**
  6494. * Creates a string representing this Matrix with each row being
  6495. * on a separate line and in the format '(column0, column1, column2)'.
  6496. *
  6497. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2)'.
  6498. */
  6499. Matrix3.prototype.toString = function() {
  6500. return '(' + this[0] + ', ' + this[3] + ', ' + this[6] + ')\n' +
  6501. '(' + this[1] + ', ' + this[4] + ', ' + this[7] + ')\n' +
  6502. '(' + this[2] + ', ' + this[5] + ', ' + this[8] + ')';
  6503. };
  6504. return Matrix3;
  6505. });
  6506. /*global define*/
  6507. define('Core/Cartesian4',[
  6508. './defaultValue',
  6509. './defined',
  6510. './DeveloperError',
  6511. './freezeObject',
  6512. './Math'
  6513. ], function(
  6514. defaultValue,
  6515. defined,
  6516. DeveloperError,
  6517. freezeObject,
  6518. CesiumMath) {
  6519. 'use strict';
  6520. /**
  6521. * A 4D Cartesian point.
  6522. * @alias Cartesian4
  6523. * @constructor
  6524. *
  6525. * @param {Number} [x=0.0] The X component.
  6526. * @param {Number} [y=0.0] The Y component.
  6527. * @param {Number} [z=0.0] The Z component.
  6528. * @param {Number} [w=0.0] The W component.
  6529. *
  6530. * @see Cartesian2
  6531. * @see Cartesian3
  6532. * @see Packable
  6533. */
  6534. function Cartesian4(x, y, z, w) {
  6535. /**
  6536. * The X component.
  6537. * @type {Number}
  6538. * @default 0.0
  6539. */
  6540. this.x = defaultValue(x, 0.0);
  6541. /**
  6542. * The Y component.
  6543. * @type {Number}
  6544. * @default 0.0
  6545. */
  6546. this.y = defaultValue(y, 0.0);
  6547. /**
  6548. * The Z component.
  6549. * @type {Number}
  6550. * @default 0.0
  6551. */
  6552. this.z = defaultValue(z, 0.0);
  6553. /**
  6554. * The W component.
  6555. * @type {Number}
  6556. * @default 0.0
  6557. */
  6558. this.w = defaultValue(w, 0.0);
  6559. }
  6560. /**
  6561. * Creates a Cartesian4 instance from x, y, z and w coordinates.
  6562. *
  6563. * @param {Number} x The x coordinate.
  6564. * @param {Number} y The y coordinate.
  6565. * @param {Number} z The z coordinate.
  6566. * @param {Number} w The w coordinate.
  6567. * @param {Cartesian4} [result] The object onto which to store the result.
  6568. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6569. */
  6570. Cartesian4.fromElements = function(x, y, z, w, result) {
  6571. if (!defined(result)) {
  6572. return new Cartesian4(x, y, z, w);
  6573. }
  6574. result.x = x;
  6575. result.y = y;
  6576. result.z = z;
  6577. result.w = w;
  6578. return result;
  6579. };
  6580. /**
  6581. * Creates a Cartesian4 instance from a {@link Color}. <code>red</code>, <code>green</code>, <code>blue</code>,
  6582. * and <code>alpha</code> map to <code>x</code>, <code>y</code>, <code>z</code>, and <code>w</code>, respectively.
  6583. *
  6584. * @param {Color} color The source color.
  6585. * @param {Cartesian4} [result] The object onto which to store the result.
  6586. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6587. */
  6588. Cartesian4.fromColor = function(color, result) {
  6589. if (!defined(color)) {
  6590. throw new DeveloperError('color is required');
  6591. }
  6592. if (!defined(result)) {
  6593. return new Cartesian4(color.red, color.green, color.blue, color.alpha);
  6594. }
  6595. result.x = color.red;
  6596. result.y = color.green;
  6597. result.z = color.blue;
  6598. result.w = color.alpha;
  6599. return result;
  6600. };
  6601. /**
  6602. * Duplicates a Cartesian4 instance.
  6603. *
  6604. * @param {Cartesian4} cartesian The Cartesian to duplicate.
  6605. * @param {Cartesian4} [result] The object onto which to store the result.
  6606. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided. (Returns undefined if cartesian is undefined)
  6607. */
  6608. Cartesian4.clone = function(cartesian, result) {
  6609. if (!defined(cartesian)) {
  6610. return undefined;
  6611. }
  6612. if (!defined(result)) {
  6613. return new Cartesian4(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6614. }
  6615. result.x = cartesian.x;
  6616. result.y = cartesian.y;
  6617. result.z = cartesian.z;
  6618. result.w = cartesian.w;
  6619. return result;
  6620. };
  6621. /**
  6622. * The number of elements used to pack the object into an array.
  6623. * @type {Number}
  6624. */
  6625. Cartesian4.packedLength = 4;
  6626. /**
  6627. * Stores the provided instance into the provided array.
  6628. *
  6629. * @param {Cartesian4} value The value to pack.
  6630. * @param {Number[]} array The array to pack into.
  6631. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  6632. *
  6633. * @returns {Number[]} The array that was packed into
  6634. */
  6635. Cartesian4.pack = function(value, array, startingIndex) {
  6636. if (!defined(value)) {
  6637. throw new DeveloperError('value is required');
  6638. }
  6639. if (!defined(array)) {
  6640. throw new DeveloperError('array is required');
  6641. }
  6642. startingIndex = defaultValue(startingIndex, 0);
  6643. array[startingIndex++] = value.x;
  6644. array[startingIndex++] = value.y;
  6645. array[startingIndex++] = value.z;
  6646. array[startingIndex] = value.w;
  6647. return array;
  6648. };
  6649. /**
  6650. * Retrieves an instance from a packed array.
  6651. *
  6652. * @param {Number[]} array The packed array.
  6653. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  6654. * @param {Cartesian4} [result] The object into which to store the result.
  6655. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6656. */
  6657. Cartesian4.unpack = function(array, startingIndex, result) {
  6658. if (!defined(array)) {
  6659. throw new DeveloperError('array is required');
  6660. }
  6661. startingIndex = defaultValue(startingIndex, 0);
  6662. if (!defined(result)) {
  6663. result = new Cartesian4();
  6664. }
  6665. result.x = array[startingIndex++];
  6666. result.y = array[startingIndex++];
  6667. result.z = array[startingIndex++];
  6668. result.w = array[startingIndex];
  6669. return result;
  6670. };
  6671. /**
  6672. * Flattens an array of Cartesian4s into and array of components.
  6673. *
  6674. * @param {Cartesian4[]} array The array of cartesians to pack.
  6675. * @param {Number[]} result The array onto which to store the result.
  6676. * @returns {Number[]} The packed array.
  6677. */
  6678. Cartesian4.packArray = function(array, result) {
  6679. if (!defined(array)) {
  6680. throw new DeveloperError('array is required');
  6681. }
  6682. var length = array.length;
  6683. if (!defined(result)) {
  6684. result = new Array(length * 4);
  6685. } else {
  6686. result.length = length * 4;
  6687. }
  6688. for (var i = 0; i < length; ++i) {
  6689. Cartesian4.pack(array[i], result, i * 4);
  6690. }
  6691. return result;
  6692. };
  6693. /**
  6694. * Unpacks an array of cartesian components into and array of Cartesian4s.
  6695. *
  6696. * @param {Number[]} array The array of components to unpack.
  6697. * @param {Cartesian4[]} result The array onto which to store the result.
  6698. * @returns {Cartesian4[]} The unpacked array.
  6699. */
  6700. Cartesian4.unpackArray = function(array, result) {
  6701. if (!defined(array)) {
  6702. throw new DeveloperError('array is required');
  6703. }
  6704. var length = array.length;
  6705. if (!defined(result)) {
  6706. result = new Array(length / 4);
  6707. } else {
  6708. result.length = length / 4;
  6709. }
  6710. for (var i = 0; i < length; i += 4) {
  6711. var index = i / 4;
  6712. result[index] = Cartesian4.unpack(array, i, result[index]);
  6713. }
  6714. return result;
  6715. };
  6716. /**
  6717. * Creates a Cartesian4 from four consecutive elements in an array.
  6718. * @function
  6719. *
  6720. * @param {Number[]} array The array whose four consecutive elements correspond to the x, y, z, and w components, respectively.
  6721. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to the x component.
  6722. * @param {Cartesian4} [result] The object onto which to store the result.
  6723. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  6724. *
  6725. * @example
  6726. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0)
  6727. * var v = [1.0, 2.0, 3.0, 4.0];
  6728. * var p = Cesium.Cartesian4.fromArray(v);
  6729. *
  6730. * // Create a Cartesian4 with (1.0, 2.0, 3.0, 4.0) using an offset into an array
  6731. * var v2 = [0.0, 0.0, 1.0, 2.0, 3.0, 4.0];
  6732. * var p2 = Cesium.Cartesian4.fromArray(v2, 2);
  6733. */
  6734. Cartesian4.fromArray = Cartesian4.unpack;
  6735. /**
  6736. * Computes the value of the maximum component for the supplied Cartesian.
  6737. *
  6738. * @param {Cartesian4} cartesian The cartesian to use.
  6739. * @returns {Number} The value of the maximum component.
  6740. */
  6741. Cartesian4.maximumComponent = function(cartesian) {
  6742. if (!defined(cartesian)) {
  6743. throw new DeveloperError('cartesian is required');
  6744. }
  6745. return Math.max(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6746. };
  6747. /**
  6748. * Computes the value of the minimum component for the supplied Cartesian.
  6749. *
  6750. * @param {Cartesian4} cartesian The cartesian to use.
  6751. * @returns {Number} The value of the minimum component.
  6752. */
  6753. Cartesian4.minimumComponent = function(cartesian) {
  6754. if (!defined(cartesian)) {
  6755. throw new DeveloperError('cartesian is required');
  6756. }
  6757. return Math.min(cartesian.x, cartesian.y, cartesian.z, cartesian.w);
  6758. };
  6759. /**
  6760. * Compares two Cartesians and computes a Cartesian which contains the minimum components of the supplied Cartesians.
  6761. *
  6762. * @param {Cartesian4} first A cartesian to compare.
  6763. * @param {Cartesian4} second A cartesian to compare.
  6764. * @param {Cartesian4} result The object into which to store the result.
  6765. * @returns {Cartesian4} A cartesian with the minimum components.
  6766. */
  6767. Cartesian4.minimumByComponent = function(first, second, result) {
  6768. if (!defined(first)) {
  6769. throw new DeveloperError('first is required.');
  6770. }
  6771. if (!defined(second)) {
  6772. throw new DeveloperError('second is required.');
  6773. }
  6774. if (!defined(result)) {
  6775. throw new DeveloperError('result is required.');
  6776. }
  6777. result.x = Math.min(first.x, second.x);
  6778. result.y = Math.min(first.y, second.y);
  6779. result.z = Math.min(first.z, second.z);
  6780. result.w = Math.min(first.w, second.w);
  6781. return result;
  6782. };
  6783. /**
  6784. * Compares two Cartesians and computes a Cartesian which contains the maximum components of the supplied Cartesians.
  6785. *
  6786. * @param {Cartesian4} first A cartesian to compare.
  6787. * @param {Cartesian4} second A cartesian to compare.
  6788. * @param {Cartesian4} result The object into which to store the result.
  6789. * @returns {Cartesian4} A cartesian with the maximum components.
  6790. */
  6791. Cartesian4.maximumByComponent = function(first, second, result) {
  6792. if (!defined(first)) {
  6793. throw new DeveloperError('first is required.');
  6794. }
  6795. if (!defined(second)) {
  6796. throw new DeveloperError('second is required.');
  6797. }
  6798. if (!defined(result)) {
  6799. throw new DeveloperError('result is required.');
  6800. }
  6801. result.x = Math.max(first.x, second.x);
  6802. result.y = Math.max(first.y, second.y);
  6803. result.z = Math.max(first.z, second.z);
  6804. result.w = Math.max(first.w, second.w);
  6805. return result;
  6806. };
  6807. /**
  6808. * Computes the provided Cartesian's squared magnitude.
  6809. *
  6810. * @param {Cartesian4} cartesian The Cartesian instance whose squared magnitude is to be computed.
  6811. * @returns {Number} The squared magnitude.
  6812. */
  6813. Cartesian4.magnitudeSquared = function(cartesian) {
  6814. if (!defined(cartesian)) {
  6815. throw new DeveloperError('cartesian is required');
  6816. }
  6817. return cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian.z * cartesian.z + cartesian.w * cartesian.w;
  6818. };
  6819. /**
  6820. * Computes the Cartesian's magnitude (length).
  6821. *
  6822. * @param {Cartesian4} cartesian The Cartesian instance whose magnitude is to be computed.
  6823. * @returns {Number} The magnitude.
  6824. */
  6825. Cartesian4.magnitude = function(cartesian) {
  6826. return Math.sqrt(Cartesian4.magnitudeSquared(cartesian));
  6827. };
  6828. var distanceScratch = new Cartesian4();
  6829. /**
  6830. * Computes the 4-space distance between two points.
  6831. *
  6832. * @param {Cartesian4} left The first point to compute the distance from.
  6833. * @param {Cartesian4} right The second point to compute the distance to.
  6834. * @returns {Number} The distance between two points.
  6835. *
  6836. * @example
  6837. * // Returns 1.0
  6838. * var d = Cesium.Cartesian4.distance(
  6839. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6840. * new Cesium.Cartesian4(2.0, 0.0, 0.0, 0.0));
  6841. */
  6842. Cartesian4.distance = function(left, right) {
  6843. if (!defined(left) || !defined(right)) {
  6844. throw new DeveloperError('left and right are required.');
  6845. }
  6846. Cartesian4.subtract(left, right, distanceScratch);
  6847. return Cartesian4.magnitude(distanceScratch);
  6848. };
  6849. /**
  6850. * Computes the squared distance between two points. Comparing squared distances
  6851. * using this function is more efficient than comparing distances using {@link Cartesian4#distance}.
  6852. *
  6853. * @param {Cartesian4} left The first point to compute the distance from.
  6854. * @param {Cartesian4} right The second point to compute the distance to.
  6855. * @returns {Number} The distance between two points.
  6856. *
  6857. * @example
  6858. * // Returns 4.0, not 2.0
  6859. * var d = Cesium.Cartesian4.distance(
  6860. * new Cesium.Cartesian4(1.0, 0.0, 0.0, 0.0),
  6861. * new Cesium.Cartesian4(3.0, 0.0, 0.0, 0.0));
  6862. */
  6863. Cartesian4.distanceSquared = function(left, right) {
  6864. if (!defined(left) || !defined(right)) {
  6865. throw new DeveloperError('left and right are required.');
  6866. }
  6867. Cartesian4.subtract(left, right, distanceScratch);
  6868. return Cartesian4.magnitudeSquared(distanceScratch);
  6869. };
  6870. /**
  6871. * Computes the normalized form of the supplied Cartesian.
  6872. *
  6873. * @param {Cartesian4} cartesian The Cartesian to be normalized.
  6874. * @param {Cartesian4} result The object onto which to store the result.
  6875. * @returns {Cartesian4} The modified result parameter.
  6876. */
  6877. Cartesian4.normalize = function(cartesian, result) {
  6878. if (!defined(cartesian)) {
  6879. throw new DeveloperError('cartesian is required');
  6880. }
  6881. if (!defined(result)) {
  6882. throw new DeveloperError('result is required');
  6883. }
  6884. var magnitude = Cartesian4.magnitude(cartesian);
  6885. result.x = cartesian.x / magnitude;
  6886. result.y = cartesian.y / magnitude;
  6887. result.z = cartesian.z / magnitude;
  6888. result.w = cartesian.w / magnitude;
  6889. if (isNaN(result.x) || isNaN(result.y) || isNaN(result.z) || isNaN(result.w)) {
  6890. throw new DeveloperError('normalized result is not a number');
  6891. }
  6892. return result;
  6893. };
  6894. /**
  6895. * Computes the dot (scalar) product of two Cartesians.
  6896. *
  6897. * @param {Cartesian4} left The first Cartesian.
  6898. * @param {Cartesian4} right The second Cartesian.
  6899. * @returns {Number} The dot product.
  6900. */
  6901. Cartesian4.dot = function(left, right) {
  6902. if (!defined(left)) {
  6903. throw new DeveloperError('left is required');
  6904. }
  6905. if (!defined(right)) {
  6906. throw new DeveloperError('right is required');
  6907. }
  6908. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  6909. };
  6910. /**
  6911. * Computes the componentwise product of two Cartesians.
  6912. *
  6913. * @param {Cartesian4} left The first Cartesian.
  6914. * @param {Cartesian4} right The second Cartesian.
  6915. * @param {Cartesian4} result The object onto which to store the result.
  6916. * @returns {Cartesian4} The modified result parameter.
  6917. */
  6918. Cartesian4.multiplyComponents = function(left, right, result) {
  6919. if (!defined(left)) {
  6920. throw new DeveloperError('left is required');
  6921. }
  6922. if (!defined(right)) {
  6923. throw new DeveloperError('right is required');
  6924. }
  6925. if (!defined(result)) {
  6926. throw new DeveloperError('result is required');
  6927. }
  6928. result.x = left.x * right.x;
  6929. result.y = left.y * right.y;
  6930. result.z = left.z * right.z;
  6931. result.w = left.w * right.w;
  6932. return result;
  6933. };
  6934. /**
  6935. * Computes the componentwise quotient of two Cartesians.
  6936. *
  6937. * @param {Cartesian4} left The first Cartesian.
  6938. * @param {Cartesian4} right The second Cartesian.
  6939. * @param {Cartesian4} result The object onto which to store the result.
  6940. * @returns {Cartesian4} The modified result parameter.
  6941. */
  6942. Cartesian4.divideComponents = function(left, right, result) {
  6943. if (!defined(left)) {
  6944. throw new DeveloperError('left is required');
  6945. }
  6946. if (!defined(right)) {
  6947. throw new DeveloperError('right is required');
  6948. }
  6949. if (!defined(result)) {
  6950. throw new DeveloperError('result is required');
  6951. }
  6952. result.x = left.x / right.x;
  6953. result.y = left.y / right.y;
  6954. result.z = left.z / right.z;
  6955. result.w = left.w / right.w;
  6956. return result;
  6957. };
  6958. /**
  6959. * Computes the componentwise sum of two Cartesians.
  6960. *
  6961. * @param {Cartesian4} left The first Cartesian.
  6962. * @param {Cartesian4} right The second Cartesian.
  6963. * @param {Cartesian4} result The object onto which to store the result.
  6964. * @returns {Cartesian4} The modified result parameter.
  6965. */
  6966. Cartesian4.add = function(left, right, result) {
  6967. if (!defined(left)) {
  6968. throw new DeveloperError('left is required');
  6969. }
  6970. if (!defined(right)) {
  6971. throw new DeveloperError('right is required');
  6972. }
  6973. if (!defined(result)) {
  6974. throw new DeveloperError('result is required');
  6975. }
  6976. result.x = left.x + right.x;
  6977. result.y = left.y + right.y;
  6978. result.z = left.z + right.z;
  6979. result.w = left.w + right.w;
  6980. return result;
  6981. };
  6982. /**
  6983. * Computes the componentwise difference of two Cartesians.
  6984. *
  6985. * @param {Cartesian4} left The first Cartesian.
  6986. * @param {Cartesian4} right The second Cartesian.
  6987. * @param {Cartesian4} result The object onto which to store the result.
  6988. * @returns {Cartesian4} The modified result parameter.
  6989. */
  6990. Cartesian4.subtract = function(left, right, result) {
  6991. if (!defined(left)) {
  6992. throw new DeveloperError('left is required');
  6993. }
  6994. if (!defined(right)) {
  6995. throw new DeveloperError('right is required');
  6996. }
  6997. if (!defined(result)) {
  6998. throw new DeveloperError('result is required');
  6999. }
  7000. result.x = left.x - right.x;
  7001. result.y = left.y - right.y;
  7002. result.z = left.z - right.z;
  7003. result.w = left.w - right.w;
  7004. return result;
  7005. };
  7006. /**
  7007. * Multiplies the provided Cartesian componentwise by the provided scalar.
  7008. *
  7009. * @param {Cartesian4} cartesian The Cartesian to be scaled.
  7010. * @param {Number} scalar The scalar to multiply with.
  7011. * @param {Cartesian4} result The object onto which to store the result.
  7012. * @returns {Cartesian4} The modified result parameter.
  7013. */
  7014. Cartesian4.multiplyByScalar = function(cartesian, scalar, result) {
  7015. if (!defined(cartesian)) {
  7016. throw new DeveloperError('cartesian is required');
  7017. }
  7018. if (typeof scalar !== 'number') {
  7019. throw new DeveloperError('scalar is required and must be a number.');
  7020. }
  7021. if (!defined(result)) {
  7022. throw new DeveloperError('result is required');
  7023. }
  7024. result.x = cartesian.x * scalar;
  7025. result.y = cartesian.y * scalar;
  7026. result.z = cartesian.z * scalar;
  7027. result.w = cartesian.w * scalar;
  7028. return result;
  7029. };
  7030. /**
  7031. * Divides the provided Cartesian componentwise by the provided scalar.
  7032. *
  7033. * @param {Cartesian4} cartesian The Cartesian to be divided.
  7034. * @param {Number} scalar The scalar to divide by.
  7035. * @param {Cartesian4} result The object onto which to store the result.
  7036. * @returns {Cartesian4} The modified result parameter.
  7037. */
  7038. Cartesian4.divideByScalar = function(cartesian, scalar, result) {
  7039. if (!defined(cartesian)) {
  7040. throw new DeveloperError('cartesian is required');
  7041. }
  7042. if (typeof scalar !== 'number') {
  7043. throw new DeveloperError('scalar is required and must be a number.');
  7044. }
  7045. if (!defined(result)) {
  7046. throw new DeveloperError('result is required');
  7047. }
  7048. result.x = cartesian.x / scalar;
  7049. result.y = cartesian.y / scalar;
  7050. result.z = cartesian.z / scalar;
  7051. result.w = cartesian.w / scalar;
  7052. return result;
  7053. };
  7054. /**
  7055. * Negates the provided Cartesian.
  7056. *
  7057. * @param {Cartesian4} cartesian The Cartesian to be negated.
  7058. * @param {Cartesian4} result The object onto which to store the result.
  7059. * @returns {Cartesian4} The modified result parameter.
  7060. */
  7061. Cartesian4.negate = function(cartesian, result) {
  7062. if (!defined(cartesian)) {
  7063. throw new DeveloperError('cartesian is required');
  7064. }
  7065. if (!defined(result)) {
  7066. throw new DeveloperError('result is required');
  7067. }
  7068. result.x = -cartesian.x;
  7069. result.y = -cartesian.y;
  7070. result.z = -cartesian.z;
  7071. result.w = -cartesian.w;
  7072. return result;
  7073. };
  7074. /**
  7075. * Computes the absolute value of the provided Cartesian.
  7076. *
  7077. * @param {Cartesian4} cartesian The Cartesian whose absolute value is to be computed.
  7078. * @param {Cartesian4} result The object onto which to store the result.
  7079. * @returns {Cartesian4} The modified result parameter.
  7080. */
  7081. Cartesian4.abs = function(cartesian, result) {
  7082. if (!defined(cartesian)) {
  7083. throw new DeveloperError('cartesian is required');
  7084. }
  7085. if (!defined(result)) {
  7086. throw new DeveloperError('result is required');
  7087. }
  7088. result.x = Math.abs(cartesian.x);
  7089. result.y = Math.abs(cartesian.y);
  7090. result.z = Math.abs(cartesian.z);
  7091. result.w = Math.abs(cartesian.w);
  7092. return result;
  7093. };
  7094. var lerpScratch = new Cartesian4();
  7095. /**
  7096. * Computes the linear interpolation or extrapolation at t using the provided cartesians.
  7097. *
  7098. * @param {Cartesian4} start The value corresponding to t at 0.0.
  7099. * @param {Cartesian4}end The value corresponding to t at 1.0.
  7100. * @param {Number} t The point along t at which to interpolate.
  7101. * @param {Cartesian4} result The object onto which to store the result.
  7102. * @returns {Cartesian4} The modified result parameter.
  7103. */
  7104. Cartesian4.lerp = function(start, end, t, result) {
  7105. if (!defined(start)) {
  7106. throw new DeveloperError('start is required.');
  7107. }
  7108. if (!defined(end)) {
  7109. throw new DeveloperError('end is required.');
  7110. }
  7111. if (typeof t !== 'number') {
  7112. throw new DeveloperError('t is required and must be a number.');
  7113. }
  7114. if (!defined(result)) {
  7115. throw new DeveloperError('result is required.');
  7116. }
  7117. Cartesian4.multiplyByScalar(end, t, lerpScratch);
  7118. result = Cartesian4.multiplyByScalar(start, 1.0 - t, result);
  7119. return Cartesian4.add(lerpScratch, result, result);
  7120. };
  7121. var mostOrthogonalAxisScratch = new Cartesian4();
  7122. /**
  7123. * Returns the axis that is most orthogonal to the provided Cartesian.
  7124. *
  7125. * @param {Cartesian4} cartesian The Cartesian on which to find the most orthogonal axis.
  7126. * @param {Cartesian4} result The object onto which to store the result.
  7127. * @returns {Cartesian4} The most orthogonal axis.
  7128. */
  7129. Cartesian4.mostOrthogonalAxis = function(cartesian, result) {
  7130. if (!defined(cartesian)) {
  7131. throw new DeveloperError('cartesian is required.');
  7132. }
  7133. if (!defined(result)) {
  7134. throw new DeveloperError('result is required.');
  7135. }
  7136. var f = Cartesian4.normalize(cartesian, mostOrthogonalAxisScratch);
  7137. Cartesian4.abs(f, f);
  7138. if (f.x <= f.y) {
  7139. if (f.x <= f.z) {
  7140. if (f.x <= f.w) {
  7141. result = Cartesian4.clone(Cartesian4.UNIT_X, result);
  7142. } else {
  7143. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7144. }
  7145. } else if (f.z <= f.w) {
  7146. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  7147. } else {
  7148. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7149. }
  7150. } else if (f.y <= f.z) {
  7151. if (f.y <= f.w) {
  7152. result = Cartesian4.clone(Cartesian4.UNIT_Y, result);
  7153. } else {
  7154. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7155. }
  7156. } else if (f.z <= f.w) {
  7157. result = Cartesian4.clone(Cartesian4.UNIT_Z, result);
  7158. } else {
  7159. result = Cartesian4.clone(Cartesian4.UNIT_W, result);
  7160. }
  7161. return result;
  7162. };
  7163. /**
  7164. * Compares the provided Cartesians componentwise and returns
  7165. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7166. *
  7167. * @param {Cartesian4} [left] The first Cartesian.
  7168. * @param {Cartesian4} [right] The second Cartesian.
  7169. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  7170. */
  7171. Cartesian4.equals = function(left, right) {
  7172. return (left === right) ||
  7173. ((defined(left)) &&
  7174. (defined(right)) &&
  7175. (left.x === right.x) &&
  7176. (left.y === right.y) &&
  7177. (left.z === right.z) &&
  7178. (left.w === right.w));
  7179. };
  7180. /**
  7181. * @private
  7182. */
  7183. Cartesian4.equalsArray = function(cartesian, array, offset) {
  7184. return cartesian.x === array[offset] &&
  7185. cartesian.y === array[offset + 1] &&
  7186. cartesian.z === array[offset + 2] &&
  7187. cartesian.w === array[offset + 3];
  7188. };
  7189. /**
  7190. * Compares the provided Cartesians componentwise and returns
  7191. * <code>true</code> if they pass an absolute or relative tolerance test,
  7192. * <code>false</code> otherwise.
  7193. *
  7194. * @param {Cartesian4} [left] The first Cartesian.
  7195. * @param {Cartesian4} [right] The second Cartesian.
  7196. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  7197. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  7198. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  7199. */
  7200. Cartesian4.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  7201. return (left === right) ||
  7202. (defined(left) &&
  7203. defined(right) &&
  7204. CesiumMath.equalsEpsilon(left.x, right.x, relativeEpsilon, absoluteEpsilon) &&
  7205. CesiumMath.equalsEpsilon(left.y, right.y, relativeEpsilon, absoluteEpsilon) &&
  7206. CesiumMath.equalsEpsilon(left.z, right.z, relativeEpsilon, absoluteEpsilon) &&
  7207. CesiumMath.equalsEpsilon(left.w, right.w, relativeEpsilon, absoluteEpsilon));
  7208. };
  7209. /**
  7210. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 0.0).
  7211. *
  7212. * @type {Cartesian4}
  7213. * @constant
  7214. */
  7215. Cartesian4.ZERO = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 0.0));
  7216. /**
  7217. * An immutable Cartesian4 instance initialized to (1.0, 0.0, 0.0, 0.0).
  7218. *
  7219. * @type {Cartesian4}
  7220. * @constant
  7221. */
  7222. Cartesian4.UNIT_X = freezeObject(new Cartesian4(1.0, 0.0, 0.0, 0.0));
  7223. /**
  7224. * An immutable Cartesian4 instance initialized to (0.0, 1.0, 0.0, 0.0).
  7225. *
  7226. * @type {Cartesian4}
  7227. * @constant
  7228. */
  7229. Cartesian4.UNIT_Y = freezeObject(new Cartesian4(0.0, 1.0, 0.0, 0.0));
  7230. /**
  7231. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 1.0, 0.0).
  7232. *
  7233. * @type {Cartesian4}
  7234. * @constant
  7235. */
  7236. Cartesian4.UNIT_Z = freezeObject(new Cartesian4(0.0, 0.0, 1.0, 0.0));
  7237. /**
  7238. * An immutable Cartesian4 instance initialized to (0.0, 0.0, 0.0, 1.0).
  7239. *
  7240. * @type {Cartesian4}
  7241. * @constant
  7242. */
  7243. Cartesian4.UNIT_W = freezeObject(new Cartesian4(0.0, 0.0, 0.0, 1.0));
  7244. /**
  7245. * Duplicates this Cartesian4 instance.
  7246. *
  7247. * @param {Cartesian4} [result] The object onto which to store the result.
  7248. * @returns {Cartesian4} The modified result parameter or a new Cartesian4 instance if one was not provided.
  7249. */
  7250. Cartesian4.prototype.clone = function(result) {
  7251. return Cartesian4.clone(this, result);
  7252. };
  7253. /**
  7254. * Compares this Cartesian against the provided Cartesian componentwise and returns
  7255. * <code>true</code> if they are equal, <code>false</code> otherwise.
  7256. *
  7257. * @param {Cartesian4} [right] The right hand side Cartesian.
  7258. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  7259. */
  7260. Cartesian4.prototype.equals = function(right) {
  7261. return Cartesian4.equals(this, right);
  7262. };
  7263. /**
  7264. * Compares this Cartesian against the provided Cartesian componentwise and returns
  7265. * <code>true</code> if they pass an absolute or relative tolerance test,
  7266. * <code>false</code> otherwise.
  7267. *
  7268. * @param {Cartesian4} [right] The right hand side Cartesian.
  7269. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  7270. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  7271. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  7272. */
  7273. Cartesian4.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  7274. return Cartesian4.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  7275. };
  7276. /**
  7277. * Creates a string representing this Cartesian in the format '(x, y)'.
  7278. *
  7279. * @returns {String} A string representing the provided Cartesian in the format '(x, y)'.
  7280. */
  7281. Cartesian4.prototype.toString = function() {
  7282. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  7283. };
  7284. return Cartesian4;
  7285. });
  7286. /*global define*/
  7287. define('Core/RuntimeError',[
  7288. './defined'
  7289. ], function(
  7290. defined) {
  7291. 'use strict';
  7292. /**
  7293. * Constructs an exception object that is thrown due to an error that can occur at runtime, e.g.,
  7294. * out of memory, could not compile shader, etc. If a function may throw this
  7295. * exception, the calling code should be prepared to catch it.
  7296. * <br /><br />
  7297. * On the other hand, a {@link DeveloperError} indicates an exception due
  7298. * to a developer error, e.g., invalid argument, that usually indicates a bug in the
  7299. * calling code.
  7300. *
  7301. * @alias RuntimeError
  7302. * @constructor
  7303. * @extends Error
  7304. *
  7305. * @param {String} [message] The error message for this exception.
  7306. *
  7307. * @see DeveloperError
  7308. */
  7309. function RuntimeError(message) {
  7310. /**
  7311. * 'RuntimeError' indicating that this exception was thrown due to a runtime error.
  7312. * @type {String}
  7313. * @readonly
  7314. */
  7315. this.name = 'RuntimeError';
  7316. /**
  7317. * The explanation for why this exception was thrown.
  7318. * @type {String}
  7319. * @readonly
  7320. */
  7321. this.message = message;
  7322. //Browsers such as IE don't have a stack property until you actually throw the error.
  7323. var stack;
  7324. try {
  7325. throw new Error();
  7326. } catch (e) {
  7327. stack = e.stack;
  7328. }
  7329. /**
  7330. * The stack trace of this exception, if available.
  7331. * @type {String}
  7332. * @readonly
  7333. */
  7334. this.stack = stack;
  7335. }
  7336. if (defined(Object.create)) {
  7337. RuntimeError.prototype = Object.create(Error.prototype);
  7338. RuntimeError.prototype.constructor = RuntimeError;
  7339. }
  7340. RuntimeError.prototype.toString = function() {
  7341. var str = this.name + ': ' + this.message;
  7342. if (defined(this.stack)) {
  7343. str += '\n' + this.stack.toString();
  7344. }
  7345. return str;
  7346. };
  7347. return RuntimeError;
  7348. });
  7349. /*global define*/
  7350. define('Core/Matrix4',[
  7351. './Cartesian3',
  7352. './Cartesian4',
  7353. './defaultValue',
  7354. './defined',
  7355. './defineProperties',
  7356. './DeveloperError',
  7357. './freezeObject',
  7358. './Math',
  7359. './Matrix3',
  7360. './RuntimeError'
  7361. ], function(
  7362. Cartesian3,
  7363. Cartesian4,
  7364. defaultValue,
  7365. defined,
  7366. defineProperties,
  7367. DeveloperError,
  7368. freezeObject,
  7369. CesiumMath,
  7370. Matrix3,
  7371. RuntimeError) {
  7372. 'use strict';
  7373. /**
  7374. * A 4x4 matrix, indexable as a column-major order array.
  7375. * Constructor parameters are in row-major order for code readability.
  7376. * @alias Matrix4
  7377. * @constructor
  7378. *
  7379. * @param {Number} [column0Row0=0.0] The value for column 0, row 0.
  7380. * @param {Number} [column1Row0=0.0] The value for column 1, row 0.
  7381. * @param {Number} [column2Row0=0.0] The value for column 2, row 0.
  7382. * @param {Number} [column3Row0=0.0] The value for column 3, row 0.
  7383. * @param {Number} [column0Row1=0.0] The value for column 0, row 1.
  7384. * @param {Number} [column1Row1=0.0] The value for column 1, row 1.
  7385. * @param {Number} [column2Row1=0.0] The value for column 2, row 1.
  7386. * @param {Number} [column3Row1=0.0] The value for column 3, row 1.
  7387. * @param {Number} [column0Row2=0.0] The value for column 0, row 2.
  7388. * @param {Number} [column1Row2=0.0] The value for column 1, row 2.
  7389. * @param {Number} [column2Row2=0.0] The value for column 2, row 2.
  7390. * @param {Number} [column3Row2=0.0] The value for column 3, row 2.
  7391. * @param {Number} [column0Row3=0.0] The value for column 0, row 3.
  7392. * @param {Number} [column1Row3=0.0] The value for column 1, row 3.
  7393. * @param {Number} [column2Row3=0.0] The value for column 2, row 3.
  7394. * @param {Number} [column3Row3=0.0] The value for column 3, row 3.
  7395. *
  7396. * @see Matrix4.fromColumnMajorArray
  7397. * @see Matrix4.fromRowMajorArray
  7398. * @see Matrix4.fromRotationTranslation
  7399. * @see Matrix4.fromTranslationRotationScale
  7400. * @see Matrix4.fromTranslationQuaternionRotationScale
  7401. * @see Matrix4.fromTranslation
  7402. * @see Matrix4.fromScale
  7403. * @see Matrix4.fromUniformScale
  7404. * @see Matrix4.fromCamera
  7405. * @see Matrix4.computePerspectiveFieldOfView
  7406. * @see Matrix4.computeOrthographicOffCenter
  7407. * @see Matrix4.computePerspectiveOffCenter
  7408. * @see Matrix4.computeInfinitePerspectiveOffCenter
  7409. * @see Matrix4.computeViewportTransformation
  7410. * @see Matrix4.computeView
  7411. * @see Matrix2
  7412. * @see Matrix3
  7413. * @see Packable
  7414. */
  7415. function Matrix4(column0Row0, column1Row0, column2Row0, column3Row0,
  7416. column0Row1, column1Row1, column2Row1, column3Row1,
  7417. column0Row2, column1Row2, column2Row2, column3Row2,
  7418. column0Row3, column1Row3, column2Row3, column3Row3) {
  7419. this[0] = defaultValue(column0Row0, 0.0);
  7420. this[1] = defaultValue(column0Row1, 0.0);
  7421. this[2] = defaultValue(column0Row2, 0.0);
  7422. this[3] = defaultValue(column0Row3, 0.0);
  7423. this[4] = defaultValue(column1Row0, 0.0);
  7424. this[5] = defaultValue(column1Row1, 0.0);
  7425. this[6] = defaultValue(column1Row2, 0.0);
  7426. this[7] = defaultValue(column1Row3, 0.0);
  7427. this[8] = defaultValue(column2Row0, 0.0);
  7428. this[9] = defaultValue(column2Row1, 0.0);
  7429. this[10] = defaultValue(column2Row2, 0.0);
  7430. this[11] = defaultValue(column2Row3, 0.0);
  7431. this[12] = defaultValue(column3Row0, 0.0);
  7432. this[13] = defaultValue(column3Row1, 0.0);
  7433. this[14] = defaultValue(column3Row2, 0.0);
  7434. this[15] = defaultValue(column3Row3, 0.0);
  7435. }
  7436. /**
  7437. * The number of elements used to pack the object into an array.
  7438. * @type {Number}
  7439. */
  7440. Matrix4.packedLength = 16;
  7441. /**
  7442. * Stores the provided instance into the provided array.
  7443. *
  7444. * @param {Matrix4} value The value to pack.
  7445. * @param {Number[]} array The array to pack into.
  7446. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  7447. *
  7448. * @returns {Number[]} The array that was packed into
  7449. */
  7450. Matrix4.pack = function(value, array, startingIndex) {
  7451. if (!defined(value)) {
  7452. throw new DeveloperError('value is required');
  7453. }
  7454. if (!defined(array)) {
  7455. throw new DeveloperError('array is required');
  7456. }
  7457. startingIndex = defaultValue(startingIndex, 0);
  7458. array[startingIndex++] = value[0];
  7459. array[startingIndex++] = value[1];
  7460. array[startingIndex++] = value[2];
  7461. array[startingIndex++] = value[3];
  7462. array[startingIndex++] = value[4];
  7463. array[startingIndex++] = value[5];
  7464. array[startingIndex++] = value[6];
  7465. array[startingIndex++] = value[7];
  7466. array[startingIndex++] = value[8];
  7467. array[startingIndex++] = value[9];
  7468. array[startingIndex++] = value[10];
  7469. array[startingIndex++] = value[11];
  7470. array[startingIndex++] = value[12];
  7471. array[startingIndex++] = value[13];
  7472. array[startingIndex++] = value[14];
  7473. array[startingIndex] = value[15];
  7474. return array;
  7475. };
  7476. /**
  7477. * Retrieves an instance from a packed array.
  7478. *
  7479. * @param {Number[]} array The packed array.
  7480. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  7481. * @param {Matrix4} [result] The object into which to store the result.
  7482. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  7483. */
  7484. Matrix4.unpack = function(array, startingIndex, result) {
  7485. if (!defined(array)) {
  7486. throw new DeveloperError('array is required');
  7487. }
  7488. startingIndex = defaultValue(startingIndex, 0);
  7489. if (!defined(result)) {
  7490. result = new Matrix4();
  7491. }
  7492. result[0] = array[startingIndex++];
  7493. result[1] = array[startingIndex++];
  7494. result[2] = array[startingIndex++];
  7495. result[3] = array[startingIndex++];
  7496. result[4] = array[startingIndex++];
  7497. result[5] = array[startingIndex++];
  7498. result[6] = array[startingIndex++];
  7499. result[7] = array[startingIndex++];
  7500. result[8] = array[startingIndex++];
  7501. result[9] = array[startingIndex++];
  7502. result[10] = array[startingIndex++];
  7503. result[11] = array[startingIndex++];
  7504. result[12] = array[startingIndex++];
  7505. result[13] = array[startingIndex++];
  7506. result[14] = array[startingIndex++];
  7507. result[15] = array[startingIndex];
  7508. return result;
  7509. };
  7510. /**
  7511. * Duplicates a Matrix4 instance.
  7512. *
  7513. * @param {Matrix4} matrix The matrix to duplicate.
  7514. * @param {Matrix4} [result] The object onto which to store the result.
  7515. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. (Returns undefined if matrix is undefined)
  7516. */
  7517. Matrix4.clone = function(matrix, result) {
  7518. if (!defined(matrix)) {
  7519. return undefined;
  7520. }
  7521. if (!defined(result)) {
  7522. return new Matrix4(matrix[0], matrix[4], matrix[8], matrix[12],
  7523. matrix[1], matrix[5], matrix[9], matrix[13],
  7524. matrix[2], matrix[6], matrix[10], matrix[14],
  7525. matrix[3], matrix[7], matrix[11], matrix[15]);
  7526. }
  7527. result[0] = matrix[0];
  7528. result[1] = matrix[1];
  7529. result[2] = matrix[2];
  7530. result[3] = matrix[3];
  7531. result[4] = matrix[4];
  7532. result[5] = matrix[5];
  7533. result[6] = matrix[6];
  7534. result[7] = matrix[7];
  7535. result[8] = matrix[8];
  7536. result[9] = matrix[9];
  7537. result[10] = matrix[10];
  7538. result[11] = matrix[11];
  7539. result[12] = matrix[12];
  7540. result[13] = matrix[13];
  7541. result[14] = matrix[14];
  7542. result[15] = matrix[15];
  7543. return result;
  7544. };
  7545. /**
  7546. * Creates a Matrix4 from 16 consecutive elements in an array.
  7547. * @function
  7548. *
  7549. * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order.
  7550. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix.
  7551. * @param {Matrix4} [result] The object onto which to store the result.
  7552. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  7553. *
  7554. * @example
  7555. * // Create the Matrix4:
  7556. * // [1.0, 2.0, 3.0, 4.0]
  7557. * // [1.0, 2.0, 3.0, 4.0]
  7558. * // [1.0, 2.0, 3.0, 4.0]
  7559. * // [1.0, 2.0, 3.0, 4.0]
  7560. *
  7561. * 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];
  7562. * var m = Cesium.Matrix4.fromArray(v);
  7563. *
  7564. * // Create same Matrix4 with using an offset into an array
  7565. * 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];
  7566. * var m2 = Cesium.Matrix4.fromArray(v2, 2);
  7567. */
  7568. Matrix4.fromArray = Matrix4.unpack;
  7569. /**
  7570. * Computes a Matrix4 instance from a column-major order array.
  7571. *
  7572. * @param {Number[]} values The column-major order array.
  7573. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7574. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7575. */
  7576. Matrix4.fromColumnMajorArray = function(values, result) {
  7577. if (!defined(values)) {
  7578. throw new DeveloperError('values is required');
  7579. }
  7580. return Matrix4.clone(values, result);
  7581. };
  7582. /**
  7583. * Computes a Matrix4 instance from a row-major order array.
  7584. * The resulting matrix will be in column-major order.
  7585. *
  7586. * @param {Number[]} values The row-major order array.
  7587. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7588. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7589. */
  7590. Matrix4.fromRowMajorArray = function(values, result) {
  7591. if (!defined(values)) {
  7592. throw new DeveloperError('values is required.');
  7593. }
  7594. if (!defined(result)) {
  7595. return new Matrix4(values[0], values[1], values[2], values[3],
  7596. values[4], values[5], values[6], values[7],
  7597. values[8], values[9], values[10], values[11],
  7598. values[12], values[13], values[14], values[15]);
  7599. }
  7600. result[0] = values[0];
  7601. result[1] = values[4];
  7602. result[2] = values[8];
  7603. result[3] = values[12];
  7604. result[4] = values[1];
  7605. result[5] = values[5];
  7606. result[6] = values[9];
  7607. result[7] = values[13];
  7608. result[8] = values[2];
  7609. result[9] = values[6];
  7610. result[10] = values[10];
  7611. result[11] = values[14];
  7612. result[12] = values[3];
  7613. result[13] = values[7];
  7614. result[14] = values[11];
  7615. result[15] = values[15];
  7616. return result;
  7617. };
  7618. /**
  7619. * Computes a Matrix4 instance from a Matrix3 representing the rotation
  7620. * and a Cartesian3 representing the translation.
  7621. *
  7622. * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation.
  7623. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation.
  7624. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7625. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7626. */
  7627. Matrix4.fromRotationTranslation = function(rotation, translation, result) {
  7628. if (!defined(rotation)) {
  7629. throw new DeveloperError('rotation is required.');
  7630. }
  7631. translation = defaultValue(translation, Cartesian3.ZERO);
  7632. if (!defined(result)) {
  7633. return new Matrix4(rotation[0], rotation[3], rotation[6], translation.x,
  7634. rotation[1], rotation[4], rotation[7], translation.y,
  7635. rotation[2], rotation[5], rotation[8], translation.z,
  7636. 0.0, 0.0, 0.0, 1.0);
  7637. }
  7638. result[0] = rotation[0];
  7639. result[1] = rotation[1];
  7640. result[2] = rotation[2];
  7641. result[3] = 0.0;
  7642. result[4] = rotation[3];
  7643. result[5] = rotation[4];
  7644. result[6] = rotation[5];
  7645. result[7] = 0.0;
  7646. result[8] = rotation[6];
  7647. result[9] = rotation[7];
  7648. result[10] = rotation[8];
  7649. result[11] = 0.0;
  7650. result[12] = translation.x;
  7651. result[13] = translation.y;
  7652. result[14] = translation.z;
  7653. result[15] = 1.0;
  7654. return result;
  7655. };
  7656. /**
  7657. * Computes a Matrix4 instance from a translation, rotation, and scale (TRS)
  7658. * representation with the rotation represented as a quaternion.
  7659. *
  7660. * @param {Cartesian3} translation The translation transformation.
  7661. * @param {Quaternion} rotation The rotation transformation.
  7662. * @param {Cartesian3} scale The non-uniform scale transformation.
  7663. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7664. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7665. *
  7666. * @example
  7667. * var result = Cesium.Matrix4.fromTranslationQuaternionRotationScale(
  7668. * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation
  7669. * Cesium.Quaternion.IDENTITY, // rotation
  7670. * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale
  7671. * result);
  7672. */
  7673. Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) {
  7674. if (!defined(translation)) {
  7675. throw new DeveloperError('translation is required.');
  7676. }
  7677. if (!defined(rotation)) {
  7678. throw new DeveloperError('rotation is required.');
  7679. }
  7680. if (!defined(scale)) {
  7681. throw new DeveloperError('scale is required.');
  7682. }
  7683. if (!defined(result)) {
  7684. result = new Matrix4();
  7685. }
  7686. var scaleX = scale.x;
  7687. var scaleY = scale.y;
  7688. var scaleZ = scale.z;
  7689. var x2 = rotation.x * rotation.x;
  7690. var xy = rotation.x * rotation.y;
  7691. var xz = rotation.x * rotation.z;
  7692. var xw = rotation.x * rotation.w;
  7693. var y2 = rotation.y * rotation.y;
  7694. var yz = rotation.y * rotation.z;
  7695. var yw = rotation.y * rotation.w;
  7696. var z2 = rotation.z * rotation.z;
  7697. var zw = rotation.z * rotation.w;
  7698. var w2 = rotation.w * rotation.w;
  7699. var m00 = x2 - y2 - z2 + w2;
  7700. var m01 = 2.0 * (xy - zw);
  7701. var m02 = 2.0 * (xz + yw);
  7702. var m10 = 2.0 * (xy + zw);
  7703. var m11 = -x2 + y2 - z2 + w2;
  7704. var m12 = 2.0 * (yz - xw);
  7705. var m20 = 2.0 * (xz - yw);
  7706. var m21 = 2.0 * (yz + xw);
  7707. var m22 = -x2 - y2 + z2 + w2;
  7708. result[0] = m00 * scaleX;
  7709. result[1] = m10 * scaleX;
  7710. result[2] = m20 * scaleX;
  7711. result[3] = 0.0;
  7712. result[4] = m01 * scaleY;
  7713. result[5] = m11 * scaleY;
  7714. result[6] = m21 * scaleY;
  7715. result[7] = 0.0;
  7716. result[8] = m02 * scaleZ;
  7717. result[9] = m12 * scaleZ;
  7718. result[10] = m22 * scaleZ;
  7719. result[11] = 0.0;
  7720. result[12] = translation.x;
  7721. result[13] = translation.y;
  7722. result[14] = translation.z;
  7723. result[15] = 1.0;
  7724. return result;
  7725. };
  7726. /**
  7727. * Creates a Matrix4 instance from a {@link TranslationRotationScale} instance.
  7728. *
  7729. * @param {TranslationRotationScale} translationRotationScale The instance.
  7730. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7731. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7732. */
  7733. Matrix4.fromTranslationRotationScale = function(translationRotationScale, result) {
  7734. if (!defined(translationRotationScale)) {
  7735. throw new DeveloperError('translationRotationScale is required.');
  7736. }
  7737. return Matrix4.fromTranslationQuaternionRotationScale(translationRotationScale.translation, translationRotationScale.rotation, translationRotationScale.scale, result);
  7738. };
  7739. /**
  7740. * Creates a Matrix4 instance from a Cartesian3 representing the translation.
  7741. *
  7742. * @param {Cartesian3} translation The upper right portion of the matrix representing the translation.
  7743. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7744. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7745. *
  7746. * @see Matrix4.multiplyByTranslation
  7747. */
  7748. Matrix4.fromTranslation = function(translation, result) {
  7749. if (!defined(translation)) {
  7750. throw new DeveloperError('translation is required.');
  7751. }
  7752. return Matrix4.fromRotationTranslation(Matrix3.IDENTITY, translation, result);
  7753. };
  7754. /**
  7755. * Computes a Matrix4 instance representing a non-uniform scale.
  7756. *
  7757. * @param {Cartesian3} scale The x, y, and z scale factors.
  7758. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7759. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7760. *
  7761. * @example
  7762. * // Creates
  7763. * // [7.0, 0.0, 0.0, 0.0]
  7764. * // [0.0, 8.0, 0.0, 0.0]
  7765. * // [0.0, 0.0, 9.0, 0.0]
  7766. * // [0.0, 0.0, 0.0, 1.0]
  7767. * var m = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(7.0, 8.0, 9.0));
  7768. */
  7769. Matrix4.fromScale = function(scale, result) {
  7770. if (!defined(scale)) {
  7771. throw new DeveloperError('scale is required.');
  7772. }
  7773. if (!defined(result)) {
  7774. return new Matrix4(
  7775. scale.x, 0.0, 0.0, 0.0,
  7776. 0.0, scale.y, 0.0, 0.0,
  7777. 0.0, 0.0, scale.z, 0.0,
  7778. 0.0, 0.0, 0.0, 1.0);
  7779. }
  7780. result[0] = scale.x;
  7781. result[1] = 0.0;
  7782. result[2] = 0.0;
  7783. result[3] = 0.0;
  7784. result[4] = 0.0;
  7785. result[5] = scale.y;
  7786. result[6] = 0.0;
  7787. result[7] = 0.0;
  7788. result[8] = 0.0;
  7789. result[9] = 0.0;
  7790. result[10] = scale.z;
  7791. result[11] = 0.0;
  7792. result[12] = 0.0;
  7793. result[13] = 0.0;
  7794. result[14] = 0.0;
  7795. result[15] = 1.0;
  7796. return result;
  7797. };
  7798. /**
  7799. * Computes a Matrix4 instance representing a uniform scale.
  7800. *
  7801. * @param {Number} scale The uniform scale factor.
  7802. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7803. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7804. *
  7805. * @example
  7806. * // Creates
  7807. * // [2.0, 0.0, 0.0, 0.0]
  7808. * // [0.0, 2.0, 0.0, 0.0]
  7809. * // [0.0, 0.0, 2.0, 0.0]
  7810. * // [0.0, 0.0, 0.0, 1.0]
  7811. * var m = Cesium.Matrix4.fromUniformScale(2.0);
  7812. */
  7813. Matrix4.fromUniformScale = function(scale, result) {
  7814. if (typeof scale !== 'number') {
  7815. throw new DeveloperError('scale is required.');
  7816. }
  7817. if (!defined(result)) {
  7818. return new Matrix4(scale, 0.0, 0.0, 0.0,
  7819. 0.0, scale, 0.0, 0.0,
  7820. 0.0, 0.0, scale, 0.0,
  7821. 0.0, 0.0, 0.0, 1.0);
  7822. }
  7823. result[0] = scale;
  7824. result[1] = 0.0;
  7825. result[2] = 0.0;
  7826. result[3] = 0.0;
  7827. result[4] = 0.0;
  7828. result[5] = scale;
  7829. result[6] = 0.0;
  7830. result[7] = 0.0;
  7831. result[8] = 0.0;
  7832. result[9] = 0.0;
  7833. result[10] = scale;
  7834. result[11] = 0.0;
  7835. result[12] = 0.0;
  7836. result[13] = 0.0;
  7837. result[14] = 0.0;
  7838. result[15] = 1.0;
  7839. return result;
  7840. };
  7841. var fromCameraF = new Cartesian3();
  7842. var fromCameraR = new Cartesian3();
  7843. var fromCameraU = new Cartesian3();
  7844. /**
  7845. * Computes a Matrix4 instance from a Camera.
  7846. *
  7847. * @param {Camera} camera The camera to use.
  7848. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created.
  7849. * @returns {Matrix4} The modified result parameter, or a new Matrix4 instance if one was not provided.
  7850. */
  7851. Matrix4.fromCamera = function(camera, result) {
  7852. if (!defined(camera)) {
  7853. throw new DeveloperError('camera is required.');
  7854. }
  7855. var position = camera.position;
  7856. var direction = camera.direction;
  7857. var up = camera.up;
  7858. if (!defined(position)) {
  7859. throw new DeveloperError('camera.position is required.');
  7860. }
  7861. if (!defined(direction)) {
  7862. throw new DeveloperError('camera.direction is required.');
  7863. }
  7864. if (!defined(up)) {
  7865. throw new DeveloperError('camera.up is required.');
  7866. }
  7867. Cartesian3.normalize(direction, fromCameraF);
  7868. Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraR), fromCameraR);
  7869. Cartesian3.normalize(Cartesian3.cross(fromCameraR, fromCameraF, fromCameraU), fromCameraU);
  7870. var sX = fromCameraR.x;
  7871. var sY = fromCameraR.y;
  7872. var sZ = fromCameraR.z;
  7873. var fX = fromCameraF.x;
  7874. var fY = fromCameraF.y;
  7875. var fZ = fromCameraF.z;
  7876. var uX = fromCameraU.x;
  7877. var uY = fromCameraU.y;
  7878. var uZ = fromCameraU.z;
  7879. var positionX = position.x;
  7880. var positionY = position.y;
  7881. var positionZ = position.z;
  7882. var t0 = sX * -positionX + sY * -positionY+ sZ * -positionZ;
  7883. var t1 = uX * -positionX + uY * -positionY+ uZ * -positionZ;
  7884. var t2 = fX * positionX + fY * positionY + fZ * positionZ;
  7885. // The code below this comment is an optimized
  7886. // version of the commented lines.
  7887. // Rather that create two matrices and then multiply,
  7888. // we just bake in the multiplcation as part of creation.
  7889. // var rotation = new Matrix4(
  7890. // sX, sY, sZ, 0.0,
  7891. // uX, uY, uZ, 0.0,
  7892. // -fX, -fY, -fZ, 0.0,
  7893. // 0.0, 0.0, 0.0, 1.0);
  7894. // var translation = new Matrix4(
  7895. // 1.0, 0.0, 0.0, -position.x,
  7896. // 0.0, 1.0, 0.0, -position.y,
  7897. // 0.0, 0.0, 1.0, -position.z,
  7898. // 0.0, 0.0, 0.0, 1.0);
  7899. // return rotation.multiply(translation);
  7900. if (!defined(result)) {
  7901. return new Matrix4(
  7902. sX, sY, sZ, t0,
  7903. uX, uY, uZ, t1,
  7904. -fX, -fY, -fZ, t2,
  7905. 0.0, 0.0, 0.0, 1.0);
  7906. }
  7907. result[0] = sX;
  7908. result[1] = uX;
  7909. result[2] = -fX;
  7910. result[3] = 0.0;
  7911. result[4] = sY;
  7912. result[5] = uY;
  7913. result[6] = -fY;
  7914. result[7] = 0.0;
  7915. result[8] = sZ;
  7916. result[9] = uZ;
  7917. result[10] = -fZ;
  7918. result[11] = 0.0;
  7919. result[12] = t0;
  7920. result[13] = t1;
  7921. result[14] = t2;
  7922. result[15] = 1.0;
  7923. return result;
  7924. };
  7925. /**
  7926. * Computes a Matrix4 instance representing a perspective transformation matrix.
  7927. *
  7928. * @param {Number} fovY The field of view along the Y axis in radians.
  7929. * @param {Number} aspectRatio The aspect ratio.
  7930. * @param {Number} near The distance to the near plane in meters.
  7931. * @param {Number} far The distance to the far plane in meters.
  7932. * @param {Matrix4} result The object in which the result will be stored.
  7933. * @returns {Matrix4} The modified result parameter.
  7934. *
  7935. * @exception {DeveloperError} fovY must be in (0, PI].
  7936. * @exception {DeveloperError} aspectRatio must be greater than zero.
  7937. * @exception {DeveloperError} near must be greater than zero.
  7938. * @exception {DeveloperError} far must be greater than zero.
  7939. */
  7940. Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) {
  7941. if (fovY <= 0.0 || fovY > Math.PI) {
  7942. throw new DeveloperError('fovY must be in (0, PI].');
  7943. }
  7944. if (aspectRatio <= 0.0) {
  7945. throw new DeveloperError('aspectRatio must be greater than zero.');
  7946. }
  7947. if (near <= 0.0) {
  7948. throw new DeveloperError('near must be greater than zero.');
  7949. }
  7950. if (far <= 0.0) {
  7951. throw new DeveloperError('far must be greater than zero.');
  7952. }
  7953. if (!defined(result)) {
  7954. throw new DeveloperError('result is required');
  7955. }
  7956. var bottom = Math.tan(fovY * 0.5);
  7957. var column1Row1 = 1.0 / bottom;
  7958. var column0Row0 = column1Row1 / aspectRatio;
  7959. var column2Row2 = (far + near) / (near - far);
  7960. var column3Row2 = (2.0 * far * near) / (near - far);
  7961. result[0] = column0Row0;
  7962. result[1] = 0.0;
  7963. result[2] = 0.0;
  7964. result[3] = 0.0;
  7965. result[4] = 0.0;
  7966. result[5] = column1Row1;
  7967. result[6] = 0.0;
  7968. result[7] = 0.0;
  7969. result[8] = 0.0;
  7970. result[9] = 0.0;
  7971. result[10] = column2Row2;
  7972. result[11] = -1.0;
  7973. result[12] = 0.0;
  7974. result[13] = 0.0;
  7975. result[14] = column3Row2;
  7976. result[15] = 0.0;
  7977. return result;
  7978. };
  7979. /**
  7980. * Computes a Matrix4 instance representing an orthographic transformation matrix.
  7981. *
  7982. * @param {Number} left The number of meters to the left of the camera that will be in view.
  7983. * @param {Number} right The number of meters to the right of the camera that will be in view.
  7984. * @param {Number} bottom The number of meters below of the camera that will be in view.
  7985. * @param {Number} top The number of meters above of the camera that will be in view.
  7986. * @param {Number} near The distance to the near plane in meters.
  7987. * @param {Number} far The distance to the far plane in meters.
  7988. * @param {Matrix4} result The object in which the result will be stored.
  7989. * @returns {Matrix4} The modified result parameter.
  7990. */
  7991. Matrix4.computeOrthographicOffCenter = function(left, right, bottom, top, near, far, result) {
  7992. if (!defined(left)) {
  7993. throw new DeveloperError('left is required.');
  7994. }
  7995. if (!defined(right)) {
  7996. throw new DeveloperError('right is required.');
  7997. }
  7998. if (!defined(bottom)) {
  7999. throw new DeveloperError('bottom is required.');
  8000. }
  8001. if (!defined(top)) {
  8002. throw new DeveloperError('top is required.');
  8003. }
  8004. if (!defined(near)) {
  8005. throw new DeveloperError('near is required.');
  8006. }
  8007. if (!defined(far)) {
  8008. throw new DeveloperError('far is required.');
  8009. }
  8010. if (!defined(result)) {
  8011. throw new DeveloperError('result is required');
  8012. }
  8013. var a = 1.0 / (right - left);
  8014. var b = 1.0 / (top - bottom);
  8015. var c = 1.0 / (far - near);
  8016. var tx = -(right + left) * a;
  8017. var ty = -(top + bottom) * b;
  8018. var tz = -(far + near) * c;
  8019. a *= 2.0;
  8020. b *= 2.0;
  8021. c *= -2.0;
  8022. result[0] = a;
  8023. result[1] = 0.0;
  8024. result[2] = 0.0;
  8025. result[3] = 0.0;
  8026. result[4] = 0.0;
  8027. result[5] = b;
  8028. result[6] = 0.0;
  8029. result[7] = 0.0;
  8030. result[8] = 0.0;
  8031. result[9] = 0.0;
  8032. result[10] = c;
  8033. result[11] = 0.0;
  8034. result[12] = tx;
  8035. result[13] = ty;
  8036. result[14] = tz;
  8037. result[15] = 1.0;
  8038. return result;
  8039. };
  8040. /**
  8041. * Computes a Matrix4 instance representing an off center perspective transformation.
  8042. *
  8043. * @param {Number} left The number of meters to the left of the camera that will be in view.
  8044. * @param {Number} right The number of meters to the right of the camera that will be in view.
  8045. * @param {Number} bottom The number of meters below of the camera that will be in view.
  8046. * @param {Number} top The number of meters above of the camera that will be in view.
  8047. * @param {Number} near The distance to the near plane in meters.
  8048. * @param {Number} far The distance to the far plane in meters.
  8049. * @param {Matrix4} result The object in which the result will be stored.
  8050. * @returns {Matrix4} The modified result parameter.
  8051. */
  8052. Matrix4.computePerspectiveOffCenter = function(left, right, bottom, top, near, far, result) {
  8053. if (!defined(left)) {
  8054. throw new DeveloperError('left is required.');
  8055. }
  8056. if (!defined(right)) {
  8057. throw new DeveloperError('right is required.');
  8058. }
  8059. if (!defined(bottom)) {
  8060. throw new DeveloperError('bottom is required.');
  8061. }
  8062. if (!defined(top)) {
  8063. throw new DeveloperError('top is required.');
  8064. }
  8065. if (!defined(near)) {
  8066. throw new DeveloperError('near is required.');
  8067. }
  8068. if (!defined(far)) {
  8069. throw new DeveloperError('far is required.');
  8070. }
  8071. if (!defined(result)) {
  8072. throw new DeveloperError('result is required');
  8073. }
  8074. var column0Row0 = 2.0 * near / (right - left);
  8075. var column1Row1 = 2.0 * near / (top - bottom);
  8076. var column2Row0 = (right + left) / (right - left);
  8077. var column2Row1 = (top + bottom) / (top - bottom);
  8078. var column2Row2 = -(far + near) / (far - near);
  8079. var column2Row3 = -1.0;
  8080. var column3Row2 = -2.0 * far * near / (far - near);
  8081. result[0] = column0Row0;
  8082. result[1] = 0.0;
  8083. result[2] = 0.0;
  8084. result[3] = 0.0;
  8085. result[4] = 0.0;
  8086. result[5] = column1Row1;
  8087. result[6] = 0.0;
  8088. result[7] = 0.0;
  8089. result[8] = column2Row0;
  8090. result[9] = column2Row1;
  8091. result[10] = column2Row2;
  8092. result[11] = column2Row3;
  8093. result[12] = 0.0;
  8094. result[13] = 0.0;
  8095. result[14] = column3Row2;
  8096. result[15] = 0.0;
  8097. return result;
  8098. };
  8099. /**
  8100. * Computes a Matrix4 instance representing an infinite off center perspective transformation.
  8101. *
  8102. * @param {Number} left The number of meters to the left of the camera that will be in view.
  8103. * @param {Number} right The number of meters to the right of the camera that will be in view.
  8104. * @param {Number} bottom The number of meters below of the camera that will be in view.
  8105. * @param {Number} top The number of meters above of the camera that will be in view.
  8106. * @param {Number} near The distance to the near plane in meters.
  8107. * @param {Matrix4} result The object in which the result will be stored.
  8108. * @returns {Matrix4} The modified result parameter.
  8109. */
  8110. Matrix4.computeInfinitePerspectiveOffCenter = function(left, right, bottom, top, near, result) {
  8111. if (!defined(left)) {
  8112. throw new DeveloperError('left is required.');
  8113. }
  8114. if (!defined(right)) {
  8115. throw new DeveloperError('right is required.');
  8116. }
  8117. if (!defined(bottom)) {
  8118. throw new DeveloperError('bottom is required.');
  8119. }
  8120. if (!defined(top)) {
  8121. throw new DeveloperError('top is required.');
  8122. }
  8123. if (!defined(near)) {
  8124. throw new DeveloperError('near is required.');
  8125. }
  8126. if (!defined(result)) {
  8127. throw new DeveloperError('result is required');
  8128. }
  8129. var column0Row0 = 2.0 * near / (right - left);
  8130. var column1Row1 = 2.0 * near / (top - bottom);
  8131. var column2Row0 = (right + left) / (right - left);
  8132. var column2Row1 = (top + bottom) / (top - bottom);
  8133. var column2Row2 = -1.0;
  8134. var column2Row3 = -1.0;
  8135. var column3Row2 = -2.0 * near;
  8136. result[0] = column0Row0;
  8137. result[1] = 0.0;
  8138. result[2] = 0.0;
  8139. result[3] = 0.0;
  8140. result[4] = 0.0;
  8141. result[5] = column1Row1;
  8142. result[6] = 0.0;
  8143. result[7] = 0.0;
  8144. result[8] = column2Row0;
  8145. result[9] = column2Row1;
  8146. result[10] = column2Row2;
  8147. result[11] = column2Row3;
  8148. result[12] = 0.0;
  8149. result[13] = 0.0;
  8150. result[14] = column3Row2;
  8151. result[15] = 0.0;
  8152. return result;
  8153. };
  8154. /**
  8155. * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates.
  8156. *
  8157. * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1.
  8158. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates.
  8159. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates.
  8160. * @param {Matrix4} result The object in which the result will be stored.
  8161. * @returns {Matrix4} The modified result parameter.
  8162. *
  8163. * @example
  8164. * // Create viewport transformation using an explicit viewport and depth range.
  8165. * var m = Cesium.Matrix4.computeViewportTransformation({
  8166. * x : 0.0,
  8167. * y : 0.0,
  8168. * width : 1024.0,
  8169. * height : 768.0
  8170. * }, 0.0, 1.0, new Cesium.Matrix4());
  8171. */
  8172. Matrix4.computeViewportTransformation = function(viewport, nearDepthRange, farDepthRange, result) {
  8173. if (!defined(result)) {
  8174. throw new DeveloperError('result is required');
  8175. }
  8176. viewport = defaultValue(viewport, defaultValue.EMPTY_OBJECT);
  8177. var x = defaultValue(viewport.x, 0.0);
  8178. var y = defaultValue(viewport.y, 0.0);
  8179. var width = defaultValue(viewport.width, 0.0);
  8180. var height = defaultValue(viewport.height, 0.0);
  8181. nearDepthRange = defaultValue(nearDepthRange, 0.0);
  8182. farDepthRange = defaultValue(farDepthRange, 1.0);
  8183. var halfWidth = width * 0.5;
  8184. var halfHeight = height * 0.5;
  8185. var halfDepth = (farDepthRange - nearDepthRange) * 0.5;
  8186. var column0Row0 = halfWidth;
  8187. var column1Row1 = halfHeight;
  8188. var column2Row2 = halfDepth;
  8189. var column3Row0 = x + halfWidth;
  8190. var column3Row1 = y + halfHeight;
  8191. var column3Row2 = nearDepthRange + halfDepth;
  8192. var column3Row3 = 1.0;
  8193. result[0] = column0Row0;
  8194. result[1] = 0.0;
  8195. result[2] = 0.0;
  8196. result[3] = 0.0;
  8197. result[4] = 0.0;
  8198. result[5] = column1Row1;
  8199. result[6] = 0.0;
  8200. result[7] = 0.0;
  8201. result[8] = 0.0;
  8202. result[9] = 0.0;
  8203. result[10] = column2Row2;
  8204. result[11] = 0.0;
  8205. result[12] = column3Row0;
  8206. result[13] = column3Row1;
  8207. result[14] = column3Row2;
  8208. result[15] = column3Row3;
  8209. return result;
  8210. };
  8211. /**
  8212. * Computes a Matrix4 instance that transforms from world space to view space.
  8213. *
  8214. * @param {Cartesian3} position The position of the camera.
  8215. * @param {Cartesian3} direction The forward direction.
  8216. * @param {Cartesian3} up The up direction.
  8217. * @param {Cartesian3} right The right direction.
  8218. * @param {Matrix4} result The object in which the result will be stored.
  8219. * @returns {Matrix4} The modified result parameter.
  8220. */
  8221. Matrix4.computeView = function(position, direction, up, right, result) {
  8222. if (!defined(position)) {
  8223. throw new DeveloperError('position is required');
  8224. }
  8225. if (!defined(direction)) {
  8226. throw new DeveloperError('direction is required');
  8227. }
  8228. if (!defined(up)) {
  8229. throw new DeveloperError('up is required');
  8230. }
  8231. if (!defined(right)) {
  8232. throw new DeveloperError('right is required');
  8233. }
  8234. if (!defined(result)) {
  8235. throw new DeveloperError('result is required');
  8236. }
  8237. result[0] = right.x;
  8238. result[1] = up.x;
  8239. result[2] = -direction.x;
  8240. result[3] = 0.0;
  8241. result[4] = right.y;
  8242. result[5] = up.y;
  8243. result[6] = -direction.y;
  8244. result[7] = 0.0;
  8245. result[8] = right.z;
  8246. result[9] = up.z;
  8247. result[10] = -direction.z;
  8248. result[11] = 0.0;
  8249. result[12] = -Cartesian3.dot(right, position);
  8250. result[13] = -Cartesian3.dot(up, position);
  8251. result[14] = Cartesian3.dot(direction, position);
  8252. result[15] = 1.0;
  8253. return result;
  8254. };
  8255. /**
  8256. * Computes an Array from the provided Matrix4 instance.
  8257. * The array will be in column-major order.
  8258. *
  8259. * @param {Matrix4} matrix The matrix to use..
  8260. * @param {Number[]} [result] The Array onto which to store the result.
  8261. * @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
  8262. *
  8263. * @example
  8264. * //create an array from an instance of Matrix4
  8265. * // m = [10.0, 14.0, 18.0, 22.0]
  8266. * // [11.0, 15.0, 19.0, 23.0]
  8267. * // [12.0, 16.0, 20.0, 24.0]
  8268. * // [13.0, 17.0, 21.0, 25.0]
  8269. * var a = Cesium.Matrix4.toArray(m);
  8270. *
  8271. * // m remains the same
  8272. * //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]
  8273. */
  8274. Matrix4.toArray = function(matrix, result) {
  8275. if (!defined(matrix)) {
  8276. throw new DeveloperError('matrix is required');
  8277. }
  8278. if (!defined(result)) {
  8279. return [matrix[0], matrix[1], matrix[2], matrix[3],
  8280. matrix[4], matrix[5], matrix[6], matrix[7],
  8281. matrix[8], matrix[9], matrix[10], matrix[11],
  8282. matrix[12], matrix[13], matrix[14], matrix[15]];
  8283. }
  8284. result[0] = matrix[0];
  8285. result[1] = matrix[1];
  8286. result[2] = matrix[2];
  8287. result[3] = matrix[3];
  8288. result[4] = matrix[4];
  8289. result[5] = matrix[5];
  8290. result[6] = matrix[6];
  8291. result[7] = matrix[7];
  8292. result[8] = matrix[8];
  8293. result[9] = matrix[9];
  8294. result[10] = matrix[10];
  8295. result[11] = matrix[11];
  8296. result[12] = matrix[12];
  8297. result[13] = matrix[13];
  8298. result[14] = matrix[14];
  8299. result[15] = matrix[15];
  8300. return result;
  8301. };
  8302. /**
  8303. * Computes the array index of the element at the provided row and column.
  8304. *
  8305. * @param {Number} row The zero-based index of the row.
  8306. * @param {Number} column The zero-based index of the column.
  8307. * @returns {Number} The index of the element at the provided row and column.
  8308. *
  8309. * @exception {DeveloperError} row must be 0, 1, 2, or 3.
  8310. * @exception {DeveloperError} column must be 0, 1, 2, or 3.
  8311. *
  8312. * @example
  8313. * var myMatrix = new Cesium.Matrix4();
  8314. * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0);
  8315. * var column1Row0 = myMatrix[column1Row0Index];
  8316. * myMatrix[column1Row0Index] = 10.0;
  8317. */
  8318. Matrix4.getElementIndex = function(column, row) {
  8319. if (typeof row !== 'number' || row < 0 || row > 3) {
  8320. throw new DeveloperError('row must be 0, 1, 2, or 3.');
  8321. }
  8322. if (typeof column !== 'number' || column < 0 || column > 3) {
  8323. throw new DeveloperError('column must be 0, 1, 2, or 3.');
  8324. }
  8325. return column * 4 + row;
  8326. };
  8327. /**
  8328. * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance.
  8329. *
  8330. * @param {Matrix4} matrix The matrix to use.
  8331. * @param {Number} index The zero-based index of the column to retrieve.
  8332. * @param {Cartesian4} result The object onto which to store the result.
  8333. * @returns {Cartesian4} The modified result parameter.
  8334. *
  8335. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8336. *
  8337. * @example
  8338. * //returns a Cartesian4 instance with values from the specified column
  8339. * // m = [10.0, 11.0, 12.0, 13.0]
  8340. * // [14.0, 15.0, 16.0, 17.0]
  8341. * // [18.0, 19.0, 20.0, 21.0]
  8342. * // [22.0, 23.0, 24.0, 25.0]
  8343. *
  8344. * //Example 1: Creates an instance of Cartesian
  8345. * var a = Cesium.Matrix4.getColumn(m, 2, new Cesium.Cartesian4());
  8346. *
  8347. * @example
  8348. * //Example 2: Sets values for Cartesian instance
  8349. * var a = new Cesium.Cartesian4();
  8350. * Cesium.Matrix4.getColumn(m, 2, a);
  8351. *
  8352. * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0;
  8353. */
  8354. Matrix4.getColumn = function(matrix, index, result) {
  8355. if (!defined(matrix)) {
  8356. throw new DeveloperError('matrix is required.');
  8357. }
  8358. if (typeof index !== 'number' || index < 0 || index > 3) {
  8359. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8360. }
  8361. if (!defined(result)) {
  8362. throw new DeveloperError('result is required');
  8363. }
  8364. var startIndex = index * 4;
  8365. var x = matrix[startIndex];
  8366. var y = matrix[startIndex + 1];
  8367. var z = matrix[startIndex + 2];
  8368. var w = matrix[startIndex + 3];
  8369. result.x = x;
  8370. result.y = y;
  8371. result.z = z;
  8372. result.w = w;
  8373. return result;
  8374. };
  8375. /**
  8376. * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance.
  8377. *
  8378. * @param {Matrix4} matrix The matrix to use.
  8379. * @param {Number} index The zero-based index of the column to set.
  8380. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column.
  8381. * @param {Matrix4} result The object onto which to store the result.
  8382. * @returns {Matrix4} The modified result parameter.
  8383. *
  8384. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8385. *
  8386. * @example
  8387. * //creates a new Matrix4 instance with new column values from the Cartesian4 instance
  8388. * // m = [10.0, 11.0, 12.0, 13.0]
  8389. * // [14.0, 15.0, 16.0, 17.0]
  8390. * // [18.0, 19.0, 20.0, 21.0]
  8391. * // [22.0, 23.0, 24.0, 25.0]
  8392. *
  8393. * var a = Cesium.Matrix4.setColumn(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  8394. *
  8395. * // m remains the same
  8396. * // a = [10.0, 11.0, 99.0, 13.0]
  8397. * // [14.0, 15.0, 98.0, 17.0]
  8398. * // [18.0, 19.0, 97.0, 21.0]
  8399. * // [22.0, 23.0, 96.0, 25.0]
  8400. */
  8401. Matrix4.setColumn = function(matrix, index, cartesian, result) {
  8402. if (!defined(matrix)) {
  8403. throw new DeveloperError('matrix is required');
  8404. }
  8405. if (!defined(cartesian)) {
  8406. throw new DeveloperError('cartesian is required');
  8407. }
  8408. if (typeof index !== 'number' || index < 0 || index > 3) {
  8409. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8410. }
  8411. if (!defined(result)) {
  8412. throw new DeveloperError('result is required');
  8413. }
  8414. result = Matrix4.clone(matrix, result);
  8415. var startIndex = index * 4;
  8416. result[startIndex] = cartesian.x;
  8417. result[startIndex + 1] = cartesian.y;
  8418. result[startIndex + 2] = cartesian.z;
  8419. result[startIndex + 3] = cartesian.w;
  8420. return result;
  8421. };
  8422. /**
  8423. * Computes a new matrix that replaces the translation in the rightmost column of the provided
  8424. * matrix with the provided translation. This assumes the matrix is an affine transformation
  8425. *
  8426. * @param {Matrix4} matrix The matrix to use.
  8427. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix.
  8428. * @param {Cartesian4} result The object onto which to store the result.
  8429. * @returns {Matrix4} The modified result parameter.
  8430. */
  8431. Matrix4.setTranslation = function(matrix, translation, result) {
  8432. if (!defined(matrix)) {
  8433. throw new DeveloperError('matrix is required');
  8434. }
  8435. if (!defined(translation)) {
  8436. throw new DeveloperError('translation is required');
  8437. }
  8438. if (!defined(result)) {
  8439. throw new DeveloperError('result is required');
  8440. }
  8441. result[0] = matrix[0];
  8442. result[1] = matrix[1];
  8443. result[2] = matrix[2];
  8444. result[3] = matrix[3];
  8445. result[4] = matrix[4];
  8446. result[5] = matrix[5];
  8447. result[6] = matrix[6];
  8448. result[7] = matrix[7];
  8449. result[8] = matrix[8];
  8450. result[9] = matrix[9];
  8451. result[10] = matrix[10];
  8452. result[11] = matrix[11];
  8453. result[12] = translation.x;
  8454. result[13] = translation.y;
  8455. result[14] = translation.z;
  8456. result[15] = matrix[15];
  8457. return result;
  8458. };
  8459. /**
  8460. * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance.
  8461. *
  8462. * @param {Matrix4} matrix The matrix to use.
  8463. * @param {Number} index The zero-based index of the row to retrieve.
  8464. * @param {Cartesian4} result The object onto which to store the result.
  8465. * @returns {Cartesian4} The modified result parameter.
  8466. *
  8467. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8468. *
  8469. * @example
  8470. * //returns a Cartesian4 instance with values from the specified column
  8471. * // m = [10.0, 11.0, 12.0, 13.0]
  8472. * // [14.0, 15.0, 16.0, 17.0]
  8473. * // [18.0, 19.0, 20.0, 21.0]
  8474. * // [22.0, 23.0, 24.0, 25.0]
  8475. *
  8476. * //Example 1: Returns an instance of Cartesian
  8477. * var a = Cesium.Matrix4.getRow(m, 2, new Cesium.Cartesian4());
  8478. *
  8479. * @example
  8480. * //Example 2: Sets values for a Cartesian instance
  8481. * var a = new Cesium.Cartesian4();
  8482. * Cesium.Matrix4.getRow(m, 2, a);
  8483. *
  8484. * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0;
  8485. */
  8486. Matrix4.getRow = function(matrix, index, result) {
  8487. if (!defined(matrix)) {
  8488. throw new DeveloperError('matrix is required.');
  8489. }
  8490. if (typeof index !== 'number' || index < 0 || index > 3) {
  8491. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8492. }
  8493. if (!defined(result)) {
  8494. throw new DeveloperError('result is required');
  8495. }
  8496. var x = matrix[index];
  8497. var y = matrix[index + 4];
  8498. var z = matrix[index + 8];
  8499. var w = matrix[index + 12];
  8500. result.x = x;
  8501. result.y = y;
  8502. result.z = z;
  8503. result.w = w;
  8504. return result;
  8505. };
  8506. /**
  8507. * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance.
  8508. *
  8509. * @param {Matrix4} matrix The matrix to use.
  8510. * @param {Number} index The zero-based index of the row to set.
  8511. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row.
  8512. * @param {Matrix4} result The object onto which to store the result.
  8513. * @returns {Matrix4} The modified result parameter.
  8514. *
  8515. * @exception {DeveloperError} index must be 0, 1, 2, or 3.
  8516. *
  8517. * @example
  8518. * //create a new Matrix4 instance with new row values from the Cartesian4 instance
  8519. * // m = [10.0, 11.0, 12.0, 13.0]
  8520. * // [14.0, 15.0, 16.0, 17.0]
  8521. * // [18.0, 19.0, 20.0, 21.0]
  8522. * // [22.0, 23.0, 24.0, 25.0]
  8523. *
  8524. * var a = Cesium.Matrix4.setRow(m, 2, new Cesium.Cartesian4(99.0, 98.0, 97.0, 96.0), new Cesium.Matrix4());
  8525. *
  8526. * // m remains the same
  8527. * // a = [10.0, 11.0, 12.0, 13.0]
  8528. * // [14.0, 15.0, 16.0, 17.0]
  8529. * // [99.0, 98.0, 97.0, 96.0]
  8530. * // [22.0, 23.0, 24.0, 25.0]
  8531. */
  8532. Matrix4.setRow = function(matrix, index, cartesian, result) {
  8533. if (!defined(matrix)) {
  8534. throw new DeveloperError('matrix is required');
  8535. }
  8536. if (!defined(cartesian)) {
  8537. throw new DeveloperError('cartesian is required');
  8538. }
  8539. if (typeof index !== 'number' || index < 0 || index > 3) {
  8540. throw new DeveloperError('index must be 0, 1, 2, or 3.');
  8541. }
  8542. if (!defined(result)) {
  8543. throw new DeveloperError('result is required');
  8544. }
  8545. result = Matrix4.clone(matrix, result);
  8546. result[index] = cartesian.x;
  8547. result[index + 4] = cartesian.y;
  8548. result[index + 8] = cartesian.z;
  8549. result[index + 12] = cartesian.w;
  8550. return result;
  8551. };
  8552. var scratchColumn = new Cartesian3();
  8553. /**
  8554. * Extracts the non-uniform scale assuming the matrix is an affine transformation.
  8555. *
  8556. * @param {Matrix4} matrix The matrix.
  8557. * @param {Cartesian3} result The object onto which to store the result.
  8558. * @returns {Cartesian3} The modified result parameter
  8559. */
  8560. Matrix4.getScale = function(matrix, result) {
  8561. if (!defined(matrix)) {
  8562. throw new DeveloperError('matrix is required.');
  8563. }
  8564. if (!defined(result)) {
  8565. throw new DeveloperError('result is required');
  8566. }
  8567. result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn));
  8568. result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn));
  8569. result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn));
  8570. return result;
  8571. };
  8572. var scratchScale = new Cartesian3();
  8573. /**
  8574. * Computes the maximum scale assuming the matrix is an affine transformation.
  8575. * The maximum scale is the maximum length of the column vectors in the upper-left
  8576. * 3x3 matrix.
  8577. *
  8578. * @param {Matrix4} matrix The matrix.
  8579. * @returns {Number} The maximum scale.
  8580. */
  8581. Matrix4.getMaximumScale = function(matrix) {
  8582. Matrix4.getScale(matrix, scratchScale);
  8583. return Cartesian3.maximumComponent(scratchScale);
  8584. };
  8585. /**
  8586. * Computes the product of two matrices.
  8587. *
  8588. * @param {Matrix4} left The first matrix.
  8589. * @param {Matrix4} right The second matrix.
  8590. * @param {Matrix4} result The object onto which to store the result.
  8591. * @returns {Matrix4} The modified result parameter.
  8592. */
  8593. Matrix4.multiply = function(left, right, result) {
  8594. if (!defined(left)) {
  8595. throw new DeveloperError('left is required');
  8596. }
  8597. if (!defined(right)) {
  8598. throw new DeveloperError('right is required');
  8599. }
  8600. if (!defined(result)) {
  8601. throw new DeveloperError('result is required');
  8602. }
  8603. var left0 = left[0];
  8604. var left1 = left[1];
  8605. var left2 = left[2];
  8606. var left3 = left[3];
  8607. var left4 = left[4];
  8608. var left5 = left[5];
  8609. var left6 = left[6];
  8610. var left7 = left[7];
  8611. var left8 = left[8];
  8612. var left9 = left[9];
  8613. var left10 = left[10];
  8614. var left11 = left[11];
  8615. var left12 = left[12];
  8616. var left13 = left[13];
  8617. var left14 = left[14];
  8618. var left15 = left[15];
  8619. var right0 = right[0];
  8620. var right1 = right[1];
  8621. var right2 = right[2];
  8622. var right3 = right[3];
  8623. var right4 = right[4];
  8624. var right5 = right[5];
  8625. var right6 = right[6];
  8626. var right7 = right[7];
  8627. var right8 = right[8];
  8628. var right9 = right[9];
  8629. var right10 = right[10];
  8630. var right11 = right[11];
  8631. var right12 = right[12];
  8632. var right13 = right[13];
  8633. var right14 = right[14];
  8634. var right15 = right[15];
  8635. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2 + left12 * right3;
  8636. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2 + left13 * right3;
  8637. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2 + left14 * right3;
  8638. var column0Row3 = left3 * right0 + left7 * right1 + left11 * right2 + left15 * right3;
  8639. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6 + left12 * right7;
  8640. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6 + left13 * right7;
  8641. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6 + left14 * right7;
  8642. var column1Row3 = left3 * right4 + left7 * right5 + left11 * right6 + left15 * right7;
  8643. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10 + left12 * right11;
  8644. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10 + left13 * right11;
  8645. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10 + left14 * right11;
  8646. var column2Row3 = left3 * right8 + left7 * right9 + left11 * right10 + left15 * right11;
  8647. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12 * right15;
  8648. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13 * right15;
  8649. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14 * right15;
  8650. var column3Row3 = left3 * right12 + left7 * right13 + left11 * right14 + left15 * right15;
  8651. result[0] = column0Row0;
  8652. result[1] = column0Row1;
  8653. result[2] = column0Row2;
  8654. result[3] = column0Row3;
  8655. result[4] = column1Row0;
  8656. result[5] = column1Row1;
  8657. result[6] = column1Row2;
  8658. result[7] = column1Row3;
  8659. result[8] = column2Row0;
  8660. result[9] = column2Row1;
  8661. result[10] = column2Row2;
  8662. result[11] = column2Row3;
  8663. result[12] = column3Row0;
  8664. result[13] = column3Row1;
  8665. result[14] = column3Row2;
  8666. result[15] = column3Row3;
  8667. return result;
  8668. };
  8669. /**
  8670. * Computes the sum of two matrices.
  8671. *
  8672. * @param {Matrix4} left The first matrix.
  8673. * @param {Matrix4} right The second matrix.
  8674. * @param {Matrix4} result The object onto which to store the result.
  8675. * @returns {Matrix4} The modified result parameter.
  8676. */
  8677. Matrix4.add = function(left, right, result) {
  8678. if (!defined(left)) {
  8679. throw new DeveloperError('left is required');
  8680. }
  8681. if (!defined(right)) {
  8682. throw new DeveloperError('right is required');
  8683. }
  8684. if (!defined(result)) {
  8685. throw new DeveloperError('result is required');
  8686. }
  8687. result[0] = left[0] + right[0];
  8688. result[1] = left[1] + right[1];
  8689. result[2] = left[2] + right[2];
  8690. result[3] = left[3] + right[3];
  8691. result[4] = left[4] + right[4];
  8692. result[5] = left[5] + right[5];
  8693. result[6] = left[6] + right[6];
  8694. result[7] = left[7] + right[7];
  8695. result[8] = left[8] + right[8];
  8696. result[9] = left[9] + right[9];
  8697. result[10] = left[10] + right[10];
  8698. result[11] = left[11] + right[11];
  8699. result[12] = left[12] + right[12];
  8700. result[13] = left[13] + right[13];
  8701. result[14] = left[14] + right[14];
  8702. result[15] = left[15] + right[15];
  8703. return result;
  8704. };
  8705. /**
  8706. * Computes the difference of two matrices.
  8707. *
  8708. * @param {Matrix4} left The first matrix.
  8709. * @param {Matrix4} right The second matrix.
  8710. * @param {Matrix4} result The object onto which to store the result.
  8711. * @returns {Matrix4} The modified result parameter.
  8712. */
  8713. Matrix4.subtract = function(left, right, result) {
  8714. if (!defined(left)) {
  8715. throw new DeveloperError('left is required');
  8716. }
  8717. if (!defined(right)) {
  8718. throw new DeveloperError('right is required');
  8719. }
  8720. if (!defined(result)) {
  8721. throw new DeveloperError('result is required');
  8722. }
  8723. result[0] = left[0] - right[0];
  8724. result[1] = left[1] - right[1];
  8725. result[2] = left[2] - right[2];
  8726. result[3] = left[3] - right[3];
  8727. result[4] = left[4] - right[4];
  8728. result[5] = left[5] - right[5];
  8729. result[6] = left[6] - right[6];
  8730. result[7] = left[7] - right[7];
  8731. result[8] = left[8] - right[8];
  8732. result[9] = left[9] - right[9];
  8733. result[10] = left[10] - right[10];
  8734. result[11] = left[11] - right[11];
  8735. result[12] = left[12] - right[12];
  8736. result[13] = left[13] - right[13];
  8737. result[14] = left[14] - right[14];
  8738. result[15] = left[15] - right[15];
  8739. return result;
  8740. };
  8741. /**
  8742. * Computes the product of two matrices assuming the matrices are
  8743. * affine transformation matrices, where the upper left 3x3 elements
  8744. * are a rotation matrix, and the upper three elements in the fourth
  8745. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  8746. * The matrix is not verified to be in the proper form.
  8747. * This method is faster than computing the product for general 4x4
  8748. * matrices using {@link Matrix4.multiply}.
  8749. *
  8750. * @param {Matrix4} left The first matrix.
  8751. * @param {Matrix4} right The second matrix.
  8752. * @param {Matrix4} result The object onto which to store the result.
  8753. * @returns {Matrix4} The modified result parameter.
  8754. *
  8755. * @example
  8756. * 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);
  8757. * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0));
  8758. * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2, new Cesium.Matrix4());
  8759. */
  8760. Matrix4.multiplyTransformation = function(left, right, result) {
  8761. if (!defined(left)) {
  8762. throw new DeveloperError('left is required');
  8763. }
  8764. if (!defined(right)) {
  8765. throw new DeveloperError('right is required');
  8766. }
  8767. if (!defined(result)) {
  8768. throw new DeveloperError('result is required');
  8769. }
  8770. var left0 = left[0];
  8771. var left1 = left[1];
  8772. var left2 = left[2];
  8773. var left4 = left[4];
  8774. var left5 = left[5];
  8775. var left6 = left[6];
  8776. var left8 = left[8];
  8777. var left9 = left[9];
  8778. var left10 = left[10];
  8779. var left12 = left[12];
  8780. var left13 = left[13];
  8781. var left14 = left[14];
  8782. var right0 = right[0];
  8783. var right1 = right[1];
  8784. var right2 = right[2];
  8785. var right4 = right[4];
  8786. var right5 = right[5];
  8787. var right6 = right[6];
  8788. var right8 = right[8];
  8789. var right9 = right[9];
  8790. var right10 = right[10];
  8791. var right12 = right[12];
  8792. var right13 = right[13];
  8793. var right14 = right[14];
  8794. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8795. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8796. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8797. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8798. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8799. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8800. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8801. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8802. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8803. var column3Row0 = left0 * right12 + left4 * right13 + left8 * right14 + left12;
  8804. var column3Row1 = left1 * right12 + left5 * right13 + left9 * right14 + left13;
  8805. var column3Row2 = left2 * right12 + left6 * right13 + left10 * right14 + left14;
  8806. result[0] = column0Row0;
  8807. result[1] = column0Row1;
  8808. result[2] = column0Row2;
  8809. result[3] = 0.0;
  8810. result[4] = column1Row0;
  8811. result[5] = column1Row1;
  8812. result[6] = column1Row2;
  8813. result[7] = 0.0;
  8814. result[8] = column2Row0;
  8815. result[9] = column2Row1;
  8816. result[10] = column2Row2;
  8817. result[11] = 0.0;
  8818. result[12] = column3Row0;
  8819. result[13] = column3Row1;
  8820. result[14] = column3Row2;
  8821. result[15] = 1.0;
  8822. return result;
  8823. };
  8824. /**
  8825. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8826. * by a 3x3 rotation matrix. This is an optimization
  8827. * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations.
  8828. *
  8829. * @param {Matrix4} matrix The matrix on the left-hand side.
  8830. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side.
  8831. * @param {Matrix4} result The object onto which to store the result.
  8832. * @returns {Matrix4} The modified result parameter.
  8833. *
  8834. * @example
  8835. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m);
  8836. * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m);
  8837. */
  8838. Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) {
  8839. if (!defined(matrix)) {
  8840. throw new DeveloperError('matrix is required');
  8841. }
  8842. if (!defined(rotation)) {
  8843. throw new DeveloperError('rotation is required');
  8844. }
  8845. if (!defined(result)) {
  8846. throw new DeveloperError('result is required');
  8847. }
  8848. var left0 = matrix[0];
  8849. var left1 = matrix[1];
  8850. var left2 = matrix[2];
  8851. var left4 = matrix[4];
  8852. var left5 = matrix[5];
  8853. var left6 = matrix[6];
  8854. var left8 = matrix[8];
  8855. var left9 = matrix[9];
  8856. var left10 = matrix[10];
  8857. var right0 = rotation[0];
  8858. var right1 = rotation[1];
  8859. var right2 = rotation[2];
  8860. var right4 = rotation[3];
  8861. var right5 = rotation[4];
  8862. var right6 = rotation[5];
  8863. var right8 = rotation[6];
  8864. var right9 = rotation[7];
  8865. var right10 = rotation[8];
  8866. var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2;
  8867. var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2;
  8868. var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2;
  8869. var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6;
  8870. var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6;
  8871. var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6;
  8872. var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10;
  8873. var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10;
  8874. var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10;
  8875. result[0] = column0Row0;
  8876. result[1] = column0Row1;
  8877. result[2] = column0Row2;
  8878. result[3] = 0.0;
  8879. result[4] = column1Row0;
  8880. result[5] = column1Row1;
  8881. result[6] = column1Row2;
  8882. result[7] = 0.0;
  8883. result[8] = column2Row0;
  8884. result[9] = column2Row1;
  8885. result[10] = column2Row2;
  8886. result[11] = 0.0;
  8887. result[12] = matrix[12];
  8888. result[13] = matrix[13];
  8889. result[14] = matrix[14];
  8890. result[15] = matrix[15];
  8891. return result;
  8892. };
  8893. /**
  8894. * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8895. * by an implicit translation matrix defined by a {@link Cartesian3}. This is an optimization
  8896. * for <code>Matrix4.multiply(m, Matrix4.fromTranslation(position), m);</code> with less allocations and arithmetic operations.
  8897. *
  8898. * @param {Matrix4} matrix The matrix on the left-hand side.
  8899. * @param {Cartesian3} translation The translation on the right-hand side.
  8900. * @param {Matrix4} result The object onto which to store the result.
  8901. * @returns {Matrix4} The modified result parameter.
  8902. *
  8903. * @example
  8904. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m);
  8905. * Cesium.Matrix4.multiplyByTranslation(m, position, m);
  8906. */
  8907. Matrix4.multiplyByTranslation = function(matrix, translation, result) {
  8908. if (!defined(matrix)) {
  8909. throw new DeveloperError('matrix is required');
  8910. }
  8911. if (!defined(translation)) {
  8912. throw new DeveloperError('translation is required');
  8913. }
  8914. if (!defined(result)) {
  8915. throw new DeveloperError('result is required');
  8916. }
  8917. var x = translation.x;
  8918. var y = translation.y;
  8919. var z = translation.z;
  8920. var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12];
  8921. var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13];
  8922. var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14];
  8923. result[0] = matrix[0];
  8924. result[1] = matrix[1];
  8925. result[2] = matrix[2];
  8926. result[3] = matrix[3];
  8927. result[4] = matrix[4];
  8928. result[5] = matrix[5];
  8929. result[6] = matrix[6];
  8930. result[7] = matrix[7];
  8931. result[8] = matrix[8];
  8932. result[9] = matrix[9];
  8933. result[10] = matrix[10];
  8934. result[11] = matrix[11];
  8935. result[12] = tx;
  8936. result[13] = ty;
  8937. result[14] = tz;
  8938. result[15] = matrix[15];
  8939. return result;
  8940. };
  8941. var uniformScaleScratch = new Cartesian3();
  8942. /**
  8943. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8944. * by an implicit uniform scale matrix. This is an optimization
  8945. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8946. * <code>m</code> must be an affine matrix.
  8947. * This function performs fewer allocations and arithmetic operations.
  8948. *
  8949. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8950. * @param {Number} scale The uniform scale on the right-hand side.
  8951. * @param {Matrix4} result The object onto which to store the result.
  8952. * @returns {Matrix4} The modified result parameter.
  8953. *
  8954. *
  8955. * @example
  8956. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m);
  8957. * Cesium.Matrix4.multiplyByUniformScale(m, scale, m);
  8958. *
  8959. * @see Matrix4.fromUniformScale
  8960. * @see Matrix4.multiplyByScale
  8961. */
  8962. Matrix4.multiplyByUniformScale = function(matrix, scale, result) {
  8963. if (!defined(matrix)) {
  8964. throw new DeveloperError('matrix is required');
  8965. }
  8966. if (typeof scale !== 'number') {
  8967. throw new DeveloperError('scale is required');
  8968. }
  8969. if (!defined(result)) {
  8970. throw new DeveloperError('result is required');
  8971. }
  8972. uniformScaleScratch.x = scale;
  8973. uniformScaleScratch.y = scale;
  8974. uniformScaleScratch.z = scale;
  8975. return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result);
  8976. };
  8977. /**
  8978. * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>)
  8979. * by an implicit non-uniform scale matrix. This is an optimization
  8980. * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where
  8981. * <code>m</code> must be an affine matrix.
  8982. * This function performs fewer allocations and arithmetic operations.
  8983. *
  8984. * @param {Matrix4} matrix The affine matrix on the left-hand side.
  8985. * @param {Cartesian3} scale The non-uniform scale on the right-hand side.
  8986. * @param {Matrix4} result The object onto which to store the result.
  8987. * @returns {Matrix4} The modified result parameter.
  8988. *
  8989. *
  8990. * @example
  8991. * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m);
  8992. * Cesium.Matrix4.multiplyByScale(m, scale, m);
  8993. *
  8994. * @see Matrix4.fromScale
  8995. * @see Matrix4.multiplyByUniformScale
  8996. */
  8997. Matrix4.multiplyByScale = function(matrix, scale, result) {
  8998. if (!defined(matrix)) {
  8999. throw new DeveloperError('matrix is required');
  9000. }
  9001. if (!defined(scale)) {
  9002. throw new DeveloperError('scale is required');
  9003. }
  9004. if (!defined(result)) {
  9005. throw new DeveloperError('result is required');
  9006. }
  9007. var scaleX = scale.x;
  9008. var scaleY = scale.y;
  9009. var scaleZ = scale.z;
  9010. // Faster than Cartesian3.equals
  9011. if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) {
  9012. return Matrix4.clone(matrix, result);
  9013. }
  9014. result[0] = scaleX * matrix[0];
  9015. result[1] = scaleX * matrix[1];
  9016. result[2] = scaleX * matrix[2];
  9017. result[3] = 0.0;
  9018. result[4] = scaleY * matrix[4];
  9019. result[5] = scaleY * matrix[5];
  9020. result[6] = scaleY * matrix[6];
  9021. result[7] = 0.0;
  9022. result[8] = scaleZ * matrix[8];
  9023. result[9] = scaleZ * matrix[9];
  9024. result[10] = scaleZ * matrix[10];
  9025. result[11] = 0.0;
  9026. result[12] = matrix[12];
  9027. result[13] = matrix[13];
  9028. result[14] = matrix[14];
  9029. result[15] = 1.0;
  9030. return result;
  9031. };
  9032. /**
  9033. * Computes the product of a matrix and a column vector.
  9034. *
  9035. * @param {Matrix4} matrix The matrix.
  9036. * @param {Cartesian4} cartesian The vector.
  9037. * @param {Cartesian4} result The object onto which to store the result.
  9038. * @returns {Cartesian4} The modified result parameter.
  9039. */
  9040. Matrix4.multiplyByVector = function(matrix, cartesian, result) {
  9041. if (!defined(matrix)) {
  9042. throw new DeveloperError('matrix is required');
  9043. }
  9044. if (!defined(cartesian)) {
  9045. throw new DeveloperError('cartesian is required');
  9046. }
  9047. if (!defined(result)) {
  9048. throw new DeveloperError('result is required');
  9049. }
  9050. var vX = cartesian.x;
  9051. var vY = cartesian.y;
  9052. var vZ = cartesian.z;
  9053. var vW = cartesian.w;
  9054. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12] * vW;
  9055. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13] * vW;
  9056. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14] * vW;
  9057. var w = matrix[3] * vX + matrix[7] * vY + matrix[11] * vZ + matrix[15] * vW;
  9058. result.x = x;
  9059. result.y = y;
  9060. result.z = z;
  9061. result.w = w;
  9062. return result;
  9063. };
  9064. /**
  9065. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  9066. * with a {@link Cartesian4} with a <code>w</code> component of zero.
  9067. *
  9068. * @param {Matrix4} matrix The matrix.
  9069. * @param {Cartesian3} cartesian The point.
  9070. * @param {Cartesian3} result The object onto which to store the result.
  9071. * @returns {Cartesian3} The modified result parameter.
  9072. *
  9073. * @example
  9074. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9075. * var result = Cesium.Matrix4.multiplyByPointAsVector(matrix, p, new Cesium.Cartesian3());
  9076. * // A shortcut for
  9077. * // Cartesian3 p = ...
  9078. * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result);
  9079. */
  9080. Matrix4.multiplyByPointAsVector = function(matrix, cartesian, result) {
  9081. if (!defined(matrix)) {
  9082. throw new DeveloperError('matrix is required');
  9083. }
  9084. if (!defined(cartesian)) {
  9085. throw new DeveloperError('cartesian is required');
  9086. }
  9087. if (!defined(result)) {
  9088. throw new DeveloperError('result is required');
  9089. }
  9090. var vX = cartesian.x;
  9091. var vY = cartesian.y;
  9092. var vZ = cartesian.z;
  9093. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ;
  9094. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ;
  9095. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ;
  9096. result.x = x;
  9097. result.y = y;
  9098. result.z = z;
  9099. return result;
  9100. };
  9101. /**
  9102. * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector}
  9103. * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}.
  9104. *
  9105. * @param {Matrix4} matrix The matrix.
  9106. * @param {Cartesian3} cartesian The point.
  9107. * @param {Cartesian3} result The object onto which to store the result.
  9108. * @returns {Cartesian3} The modified result parameter.
  9109. *
  9110. * @example
  9111. * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  9112. * var result = Cesium.Matrix4.multiplyByPoint(matrix, p, new Cesium.Cartesian3());
  9113. */
  9114. Matrix4.multiplyByPoint = function(matrix, cartesian, result) {
  9115. if (!defined(matrix)) {
  9116. throw new DeveloperError('matrix is required');
  9117. }
  9118. if (!defined(cartesian)) {
  9119. throw new DeveloperError('cartesian is required');
  9120. }
  9121. if (!defined(result)) {
  9122. throw new DeveloperError('result is required');
  9123. }
  9124. var vX = cartesian.x;
  9125. var vY = cartesian.y;
  9126. var vZ = cartesian.z;
  9127. var x = matrix[0] * vX + matrix[4] * vY + matrix[8] * vZ + matrix[12];
  9128. var y = matrix[1] * vX + matrix[5] * vY + matrix[9] * vZ + matrix[13];
  9129. var z = matrix[2] * vX + matrix[6] * vY + matrix[10] * vZ + matrix[14];
  9130. result.x = x;
  9131. result.y = y;
  9132. result.z = z;
  9133. return result;
  9134. };
  9135. /**
  9136. * Computes the product of a matrix and a scalar.
  9137. *
  9138. * @param {Matrix4} matrix The matrix.
  9139. * @param {Number} scalar The number to multiply by.
  9140. * @param {Matrix4} result The object onto which to store the result.
  9141. * @returns {Matrix4} The modified result parameter.
  9142. *
  9143. * @example
  9144. * //create a Matrix4 instance which is a scaled version of the supplied Matrix4
  9145. * // m = [10.0, 11.0, 12.0, 13.0]
  9146. * // [14.0, 15.0, 16.0, 17.0]
  9147. * // [18.0, 19.0, 20.0, 21.0]
  9148. * // [22.0, 23.0, 24.0, 25.0]
  9149. *
  9150. * var a = Cesium.Matrix4.multiplyByScalar(m, -2, new Cesium.Matrix4());
  9151. *
  9152. * // m remains the same
  9153. * // a = [-20.0, -22.0, -24.0, -26.0]
  9154. * // [-28.0, -30.0, -32.0, -34.0]
  9155. * // [-36.0, -38.0, -40.0, -42.0]
  9156. * // [-44.0, -46.0, -48.0, -50.0]
  9157. */
  9158. Matrix4.multiplyByScalar = function(matrix, scalar, result) {
  9159. if (!defined(matrix)) {
  9160. throw new DeveloperError('matrix is required');
  9161. }
  9162. if (typeof scalar !== 'number') {
  9163. throw new DeveloperError('scalar must be a number');
  9164. }
  9165. if (!defined(result)) {
  9166. throw new DeveloperError('result is required');
  9167. }
  9168. result[0] = matrix[0] * scalar;
  9169. result[1] = matrix[1] * scalar;
  9170. result[2] = matrix[2] * scalar;
  9171. result[3] = matrix[3] * scalar;
  9172. result[4] = matrix[4] * scalar;
  9173. result[5] = matrix[5] * scalar;
  9174. result[6] = matrix[6] * scalar;
  9175. result[7] = matrix[7] * scalar;
  9176. result[8] = matrix[8] * scalar;
  9177. result[9] = matrix[9] * scalar;
  9178. result[10] = matrix[10] * scalar;
  9179. result[11] = matrix[11] * scalar;
  9180. result[12] = matrix[12] * scalar;
  9181. result[13] = matrix[13] * scalar;
  9182. result[14] = matrix[14] * scalar;
  9183. result[15] = matrix[15] * scalar;
  9184. return result;
  9185. };
  9186. /**
  9187. * Computes a negated copy of the provided matrix.
  9188. *
  9189. * @param {Matrix4} matrix The matrix to negate.
  9190. * @param {Matrix4} result The object onto which to store the result.
  9191. * @returns {Matrix4} The modified result parameter.
  9192. *
  9193. * @example
  9194. * //create a new Matrix4 instance which is a negation of a Matrix4
  9195. * // m = [10.0, 11.0, 12.0, 13.0]
  9196. * // [14.0, 15.0, 16.0, 17.0]
  9197. * // [18.0, 19.0, 20.0, 21.0]
  9198. * // [22.0, 23.0, 24.0, 25.0]
  9199. *
  9200. * var a = Cesium.Matrix4.negate(m, new Cesium.Matrix4());
  9201. *
  9202. * // m remains the same
  9203. * // a = [-10.0, -11.0, -12.0, -13.0]
  9204. * // [-14.0, -15.0, -16.0, -17.0]
  9205. * // [-18.0, -19.0, -20.0, -21.0]
  9206. * // [-22.0, -23.0, -24.0, -25.0]
  9207. */
  9208. Matrix4.negate = function(matrix, result) {
  9209. if (!defined(matrix)) {
  9210. throw new DeveloperError('matrix is required');
  9211. }
  9212. if (!defined(result)) {
  9213. throw new DeveloperError('result is required');
  9214. }
  9215. result[0] = -matrix[0];
  9216. result[1] = -matrix[1];
  9217. result[2] = -matrix[2];
  9218. result[3] = -matrix[3];
  9219. result[4] = -matrix[4];
  9220. result[5] = -matrix[5];
  9221. result[6] = -matrix[6];
  9222. result[7] = -matrix[7];
  9223. result[8] = -matrix[8];
  9224. result[9] = -matrix[9];
  9225. result[10] = -matrix[10];
  9226. result[11] = -matrix[11];
  9227. result[12] = -matrix[12];
  9228. result[13] = -matrix[13];
  9229. result[14] = -matrix[14];
  9230. result[15] = -matrix[15];
  9231. return result;
  9232. };
  9233. /**
  9234. * Computes the transpose of the provided matrix.
  9235. *
  9236. * @param {Matrix4} matrix The matrix to transpose.
  9237. * @param {Matrix4} result The object onto which to store the result.
  9238. * @returns {Matrix4} The modified result parameter.
  9239. *
  9240. * @example
  9241. * //returns transpose of a Matrix4
  9242. * // m = [10.0, 11.0, 12.0, 13.0]
  9243. * // [14.0, 15.0, 16.0, 17.0]
  9244. * // [18.0, 19.0, 20.0, 21.0]
  9245. * // [22.0, 23.0, 24.0, 25.0]
  9246. *
  9247. * var a = Cesium.Matrix4.transpose(m, new Cesium.Matrix4());
  9248. *
  9249. * // m remains the same
  9250. * // a = [10.0, 14.0, 18.0, 22.0]
  9251. * // [11.0, 15.0, 19.0, 23.0]
  9252. * // [12.0, 16.0, 20.0, 24.0]
  9253. * // [13.0, 17.0, 21.0, 25.0]
  9254. */
  9255. Matrix4.transpose = function(matrix, result) {
  9256. if (!defined(matrix)) {
  9257. throw new DeveloperError('matrix is required');
  9258. }
  9259. if (!defined(result)) {
  9260. throw new DeveloperError('result is required');
  9261. }
  9262. var matrix1 = matrix[1];
  9263. var matrix2 = matrix[2];
  9264. var matrix3 = matrix[3];
  9265. var matrix6 = matrix[6];
  9266. var matrix7 = matrix[7];
  9267. var matrix11 = matrix[11];
  9268. result[0] = matrix[0];
  9269. result[1] = matrix[4];
  9270. result[2] = matrix[8];
  9271. result[3] = matrix[12];
  9272. result[4] = matrix1;
  9273. result[5] = matrix[5];
  9274. result[6] = matrix[9];
  9275. result[7] = matrix[13];
  9276. result[8] = matrix2;
  9277. result[9] = matrix6;
  9278. result[10] = matrix[10];
  9279. result[11] = matrix[14];
  9280. result[12] = matrix3;
  9281. result[13] = matrix7;
  9282. result[14] = matrix11;
  9283. result[15] = matrix[15];
  9284. return result;
  9285. };
  9286. /**
  9287. * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements.
  9288. *
  9289. * @param {Matrix4} matrix The matrix with signed elements.
  9290. * @param {Matrix4} result The object onto which to store the result.
  9291. * @returns {Matrix4} The modified result parameter.
  9292. */
  9293. Matrix4.abs = function(matrix, result) {
  9294. if (!defined(matrix)) {
  9295. throw new DeveloperError('matrix is required');
  9296. }
  9297. if (!defined(result)) {
  9298. throw new DeveloperError('result is required');
  9299. }
  9300. result[0] = Math.abs(matrix[0]);
  9301. result[1] = Math.abs(matrix[1]);
  9302. result[2] = Math.abs(matrix[2]);
  9303. result[3] = Math.abs(matrix[3]);
  9304. result[4] = Math.abs(matrix[4]);
  9305. result[5] = Math.abs(matrix[5]);
  9306. result[6] = Math.abs(matrix[6]);
  9307. result[7] = Math.abs(matrix[7]);
  9308. result[8] = Math.abs(matrix[8]);
  9309. result[9] = Math.abs(matrix[9]);
  9310. result[10] = Math.abs(matrix[10]);
  9311. result[11] = Math.abs(matrix[11]);
  9312. result[12] = Math.abs(matrix[12]);
  9313. result[13] = Math.abs(matrix[13]);
  9314. result[14] = Math.abs(matrix[14]);
  9315. result[15] = Math.abs(matrix[15]);
  9316. return result;
  9317. };
  9318. /**
  9319. * Compares the provided matrices componentwise and returns
  9320. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9321. *
  9322. * @param {Matrix4} [left] The first matrix.
  9323. * @param {Matrix4} [right] The second matrix.
  9324. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  9325. *
  9326. * @example
  9327. * //compares two Matrix4 instances
  9328. *
  9329. * // a = [10.0, 14.0, 18.0, 22.0]
  9330. * // [11.0, 15.0, 19.0, 23.0]
  9331. * // [12.0, 16.0, 20.0, 24.0]
  9332. * // [13.0, 17.0, 21.0, 25.0]
  9333. *
  9334. * // b = [10.0, 14.0, 18.0, 22.0]
  9335. * // [11.0, 15.0, 19.0, 23.0]
  9336. * // [12.0, 16.0, 20.0, 24.0]
  9337. * // [13.0, 17.0, 21.0, 25.0]
  9338. *
  9339. * if(Cesium.Matrix4.equals(a,b)) {
  9340. * console.log("Both matrices are equal");
  9341. * } else {
  9342. * console.log("They are not equal");
  9343. * }
  9344. *
  9345. * //Prints "Both matrices are equal" on the console
  9346. */
  9347. Matrix4.equals = function(left, right) {
  9348. // Given that most matrices will be transformation matrices, the elements
  9349. // are tested in order such that the test is likely to fail as early
  9350. // as possible. I _think_ this is just as friendly to the L1 cache
  9351. // as testing in index order. It is certainty faster in practice.
  9352. return (left === right) ||
  9353. (defined(left) &&
  9354. defined(right) &&
  9355. // Translation
  9356. left[12] === right[12] &&
  9357. left[13] === right[13] &&
  9358. left[14] === right[14] &&
  9359. // Rotation/scale
  9360. left[0] === right[0] &&
  9361. left[1] === right[1] &&
  9362. left[2] === right[2] &&
  9363. left[4] === right[4] &&
  9364. left[5] === right[5] &&
  9365. left[6] === right[6] &&
  9366. left[8] === right[8] &&
  9367. left[9] === right[9] &&
  9368. left[10] === right[10] &&
  9369. // Bottom row
  9370. left[3] === right[3] &&
  9371. left[7] === right[7] &&
  9372. left[11] === right[11] &&
  9373. left[15] === right[15]);
  9374. };
  9375. /**
  9376. * Compares the provided matrices componentwise and returns
  9377. * <code>true</code> if they are within the provided epsilon,
  9378. * <code>false</code> otherwise.
  9379. *
  9380. * @param {Matrix4} [left] The first matrix.
  9381. * @param {Matrix4} [right] The second matrix.
  9382. * @param {Number} epsilon The epsilon to use for equality testing.
  9383. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  9384. *
  9385. * @example
  9386. * //compares two Matrix4 instances
  9387. *
  9388. * // a = [10.5, 14.5, 18.5, 22.5]
  9389. * // [11.5, 15.5, 19.5, 23.5]
  9390. * // [12.5, 16.5, 20.5, 24.5]
  9391. * // [13.5, 17.5, 21.5, 25.5]
  9392. *
  9393. * // b = [10.0, 14.0, 18.0, 22.0]
  9394. * // [11.0, 15.0, 19.0, 23.0]
  9395. * // [12.0, 16.0, 20.0, 24.0]
  9396. * // [13.0, 17.0, 21.0, 25.0]
  9397. *
  9398. * if(Cesium.Matrix4.equalsEpsilon(a,b,0.1)){
  9399. * console.log("Difference between both the matrices is less than 0.1");
  9400. * } else {
  9401. * console.log("Difference between both the matrices is not less than 0.1");
  9402. * }
  9403. *
  9404. * //Prints "Difference between both the matrices is not less than 0.1" on the console
  9405. */
  9406. Matrix4.equalsEpsilon = function(left, right, epsilon) {
  9407. if (typeof epsilon !== 'number') {
  9408. throw new DeveloperError('epsilon must be a number');
  9409. }
  9410. return (left === right) ||
  9411. (defined(left) &&
  9412. defined(right) &&
  9413. Math.abs(left[0] - right[0]) <= epsilon &&
  9414. Math.abs(left[1] - right[1]) <= epsilon &&
  9415. Math.abs(left[2] - right[2]) <= epsilon &&
  9416. Math.abs(left[3] - right[3]) <= epsilon &&
  9417. Math.abs(left[4] - right[4]) <= epsilon &&
  9418. Math.abs(left[5] - right[5]) <= epsilon &&
  9419. Math.abs(left[6] - right[6]) <= epsilon &&
  9420. Math.abs(left[7] - right[7]) <= epsilon &&
  9421. Math.abs(left[8] - right[8]) <= epsilon &&
  9422. Math.abs(left[9] - right[9]) <= epsilon &&
  9423. Math.abs(left[10] - right[10]) <= epsilon &&
  9424. Math.abs(left[11] - right[11]) <= epsilon &&
  9425. Math.abs(left[12] - right[12]) <= epsilon &&
  9426. Math.abs(left[13] - right[13]) <= epsilon &&
  9427. Math.abs(left[14] - right[14]) <= epsilon &&
  9428. Math.abs(left[15] - right[15]) <= epsilon);
  9429. };
  9430. /**
  9431. * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix.
  9432. *
  9433. * @param {Matrix4} matrix The matrix to use.
  9434. * @param {Cartesian3} result The object onto which to store the result.
  9435. * @returns {Cartesian3} The modified result parameter.
  9436. */
  9437. Matrix4.getTranslation = function(matrix, result) {
  9438. if (!defined(matrix)) {
  9439. throw new DeveloperError('matrix is required');
  9440. }
  9441. if (!defined(result)) {
  9442. throw new DeveloperError('result is required');
  9443. }
  9444. result.x = matrix[12];
  9445. result.y = matrix[13];
  9446. result.z = matrix[14];
  9447. return result;
  9448. };
  9449. /**
  9450. * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix.
  9451. *
  9452. * @param {Matrix4} matrix The matrix to use.
  9453. * @param {Matrix3} result The object onto which to store the result.
  9454. * @returns {Matrix3} The modified result parameter.
  9455. *
  9456. * @example
  9457. * // returns a Matrix3 instance from a Matrix4 instance
  9458. *
  9459. * // m = [10.0, 14.0, 18.0, 22.0]
  9460. * // [11.0, 15.0, 19.0, 23.0]
  9461. * // [12.0, 16.0, 20.0, 24.0]
  9462. * // [13.0, 17.0, 21.0, 25.0]
  9463. *
  9464. * var b = new Cesium.Matrix3();
  9465. * Cesium.Matrix4.getRotation(m,b);
  9466. *
  9467. * // b = [10.0, 14.0, 18.0]
  9468. * // [11.0, 15.0, 19.0]
  9469. * // [12.0, 16.0, 20.0]
  9470. */
  9471. Matrix4.getRotation = function(matrix, result) {
  9472. if (!defined(matrix)) {
  9473. throw new DeveloperError('matrix is required');
  9474. }
  9475. if (!defined(result)) {
  9476. throw new DeveloperError('result is required');
  9477. }
  9478. result[0] = matrix[0];
  9479. result[1] = matrix[1];
  9480. result[2] = matrix[2];
  9481. result[3] = matrix[4];
  9482. result[4] = matrix[5];
  9483. result[5] = matrix[6];
  9484. result[6] = matrix[8];
  9485. result[7] = matrix[9];
  9486. result[8] = matrix[10];
  9487. return result;
  9488. };
  9489. var scratchInverseRotation = new Matrix3();
  9490. var scratchMatrix3Zero = new Matrix3();
  9491. var scratchBottomRow = new Cartesian4();
  9492. var scratchExpectedBottomRow = new Cartesian4(0.0, 0.0, 0.0, 1.0);
  9493. /**
  9494. * Computes the inverse of the provided matrix using Cramers Rule.
  9495. * If the determinant is zero, the matrix can not be inverted, and an exception is thrown.
  9496. * If the matrix is an affine transformation matrix, it is more efficient
  9497. * to invert it with {@link Matrix4.inverseTransformation}.
  9498. *
  9499. * @param {Matrix4} matrix The matrix to invert.
  9500. * @param {Matrix4} result The object onto which to store the result.
  9501. * @returns {Matrix4} The modified result parameter.
  9502. *
  9503. * @exception {RuntimeError} matrix is not invertible because its determinate is zero.
  9504. */
  9505. Matrix4.inverse = function(matrix, result) {
  9506. if (!defined(matrix)) {
  9507. throw new DeveloperError('matrix is required');
  9508. }
  9509. if (!defined(result)) {
  9510. throw new DeveloperError('result is required');
  9511. }
  9512. // Special case for a zero scale matrix that can occur, for example,
  9513. // when a model's node has a [0, 0, 0] scale.
  9514. if (Matrix3.equalsEpsilon(Matrix4.getRotation(matrix, scratchInverseRotation), scratchMatrix3Zero, CesiumMath.EPSILON7) &&
  9515. Cartesian4.equals(Matrix4.getRow(matrix, 3, scratchBottomRow), scratchExpectedBottomRow)) {
  9516. result[0] = 0.0;
  9517. result[1] = 0.0;
  9518. result[2] = 0.0;
  9519. result[3] = 0.0;
  9520. result[4] = 0.0;
  9521. result[5] = 0.0;
  9522. result[6] = 0.0;
  9523. result[7] = 0.0;
  9524. result[8] = 0.0;
  9525. result[9] = 0.0;
  9526. result[10] = 0.0;
  9527. result[11] = 0.0;
  9528. result[12] = -matrix[12];
  9529. result[13] = -matrix[13];
  9530. result[14] = -matrix[14];
  9531. result[15] = 1.0;
  9532. return result;
  9533. }
  9534. //
  9535. // Ported from:
  9536. // ftp://download.intel.com/design/PentiumIII/sml/24504301.pdf
  9537. //
  9538. var src0 = matrix[0];
  9539. var src1 = matrix[4];
  9540. var src2 = matrix[8];
  9541. var src3 = matrix[12];
  9542. var src4 = matrix[1];
  9543. var src5 = matrix[5];
  9544. var src6 = matrix[9];
  9545. var src7 = matrix[13];
  9546. var src8 = matrix[2];
  9547. var src9 = matrix[6];
  9548. var src10 = matrix[10];
  9549. var src11 = matrix[14];
  9550. var src12 = matrix[3];
  9551. var src13 = matrix[7];
  9552. var src14 = matrix[11];
  9553. var src15 = matrix[15];
  9554. // calculate pairs for first 8 elements (cofactors)
  9555. var tmp0 = src10 * src15;
  9556. var tmp1 = src11 * src14;
  9557. var tmp2 = src9 * src15;
  9558. var tmp3 = src11 * src13;
  9559. var tmp4 = src9 * src14;
  9560. var tmp5 = src10 * src13;
  9561. var tmp6 = src8 * src15;
  9562. var tmp7 = src11 * src12;
  9563. var tmp8 = src8 * src14;
  9564. var tmp9 = src10 * src12;
  9565. var tmp10 = src8 * src13;
  9566. var tmp11 = src9 * src12;
  9567. // calculate first 8 elements (cofactors)
  9568. var dst0 = (tmp0 * src5 + tmp3 * src6 + tmp4 * src7) - (tmp1 * src5 + tmp2 * src6 + tmp5 * src7);
  9569. var dst1 = (tmp1 * src4 + tmp6 * src6 + tmp9 * src7) - (tmp0 * src4 + tmp7 * src6 + tmp8 * src7);
  9570. var dst2 = (tmp2 * src4 + tmp7 * src5 + tmp10 * src7) - (tmp3 * src4 + tmp6 * src5 + tmp11 * src7);
  9571. var dst3 = (tmp5 * src4 + tmp8 * src5 + tmp11 * src6) - (tmp4 * src4 + tmp9 * src5 + tmp10 * src6);
  9572. var dst4 = (tmp1 * src1 + tmp2 * src2 + tmp5 * src3) - (tmp0 * src1 + tmp3 * src2 + tmp4 * src3);
  9573. var dst5 = (tmp0 * src0 + tmp7 * src2 + tmp8 * src3) - (tmp1 * src0 + tmp6 * src2 + tmp9 * src3);
  9574. var dst6 = (tmp3 * src0 + tmp6 * src1 + tmp11 * src3) - (tmp2 * src0 + tmp7 * src1 + tmp10 * src3);
  9575. var dst7 = (tmp4 * src0 + tmp9 * src1 + tmp10 * src2) - (tmp5 * src0 + tmp8 * src1 + tmp11 * src2);
  9576. // calculate pairs for second 8 elements (cofactors)
  9577. tmp0 = src2 * src7;
  9578. tmp1 = src3 * src6;
  9579. tmp2 = src1 * src7;
  9580. tmp3 = src3 * src5;
  9581. tmp4 = src1 * src6;
  9582. tmp5 = src2 * src5;
  9583. tmp6 = src0 * src7;
  9584. tmp7 = src3 * src4;
  9585. tmp8 = src0 * src6;
  9586. tmp9 = src2 * src4;
  9587. tmp10 = src0 * src5;
  9588. tmp11 = src1 * src4;
  9589. // calculate second 8 elements (cofactors)
  9590. var dst8 = (tmp0 * src13 + tmp3 * src14 + tmp4 * src15) - (tmp1 * src13 + tmp2 * src14 + tmp5 * src15);
  9591. var dst9 = (tmp1 * src12 + tmp6 * src14 + tmp9 * src15) - (tmp0 * src12 + tmp7 * src14 + tmp8 * src15);
  9592. var dst10 = (tmp2 * src12 + tmp7 * src13 + tmp10 * src15) - (tmp3 * src12 + tmp6 * src13 + tmp11 * src15);
  9593. var dst11 = (tmp5 * src12 + tmp8 * src13 + tmp11 * src14) - (tmp4 * src12 + tmp9 * src13 + tmp10 * src14);
  9594. var dst12 = (tmp2 * src10 + tmp5 * src11 + tmp1 * src9) - (tmp4 * src11 + tmp0 * src9 + tmp3 * src10);
  9595. var dst13 = (tmp8 * src11 + tmp0 * src8 + tmp7 * src10) - (tmp6 * src10 + tmp9 * src11 + tmp1 * src8);
  9596. var dst14 = (tmp6 * src9 + tmp11 * src11 + tmp3 * src8) - (tmp10 * src11 + tmp2 * src8 + tmp7 * src9);
  9597. var dst15 = (tmp10 * src10 + tmp4 * src8 + tmp9 * src9) - (tmp8 * src9 + tmp11 * src10 + tmp5 * src8);
  9598. // calculate determinant
  9599. var det = src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;
  9600. if (Math.abs(det) < CesiumMath.EPSILON20) {
  9601. throw new RuntimeError('matrix is not invertible because its determinate is zero.');
  9602. }
  9603. // calculate matrix inverse
  9604. det = 1.0 / det;
  9605. result[0] = dst0 * det;
  9606. result[1] = dst1 * det;
  9607. result[2] = dst2 * det;
  9608. result[3] = dst3 * det;
  9609. result[4] = dst4 * det;
  9610. result[5] = dst5 * det;
  9611. result[6] = dst6 * det;
  9612. result[7] = dst7 * det;
  9613. result[8] = dst8 * det;
  9614. result[9] = dst9 * det;
  9615. result[10] = dst10 * det;
  9616. result[11] = dst11 * det;
  9617. result[12] = dst12 * det;
  9618. result[13] = dst13 * det;
  9619. result[14] = dst14 * det;
  9620. result[15] = dst15 * det;
  9621. return result;
  9622. };
  9623. /**
  9624. * Computes the inverse of the provided matrix assuming it is
  9625. * an affine transformation matrix, where the upper left 3x3 elements
  9626. * are a rotation matrix, and the upper three elements in the fourth
  9627. * column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  9628. * The matrix is not verified to be in the proper form.
  9629. * This method is faster than computing the inverse for a general 4x4
  9630. * matrix using {@link Matrix4.inverse}.
  9631. *
  9632. * @param {Matrix4} matrix The matrix to invert.
  9633. * @param {Matrix4} result The object onto which to store the result.
  9634. * @returns {Matrix4} The modified result parameter.
  9635. */
  9636. Matrix4.inverseTransformation = function(matrix, result) {
  9637. if (!defined(matrix)) {
  9638. throw new DeveloperError('matrix is required');
  9639. }
  9640. if (!defined(result)) {
  9641. throw new DeveloperError('result is required');
  9642. }
  9643. //This function is an optimized version of the below 4 lines.
  9644. //var rT = Matrix3.transpose(Matrix4.getRotation(matrix));
  9645. //var rTN = Matrix3.negate(rT);
  9646. //var rTT = Matrix3.multiplyByVector(rTN, Matrix4.getTranslation(matrix));
  9647. //return Matrix4.fromRotationTranslation(rT, rTT, result);
  9648. var matrix0 = matrix[0];
  9649. var matrix1 = matrix[1];
  9650. var matrix2 = matrix[2];
  9651. var matrix4 = matrix[4];
  9652. var matrix5 = matrix[5];
  9653. var matrix6 = matrix[6];
  9654. var matrix8 = matrix[8];
  9655. var matrix9 = matrix[9];
  9656. var matrix10 = matrix[10];
  9657. var vX = matrix[12];
  9658. var vY = matrix[13];
  9659. var vZ = matrix[14];
  9660. var x = -matrix0 * vX - matrix1 * vY - matrix2 * vZ;
  9661. var y = -matrix4 * vX - matrix5 * vY - matrix6 * vZ;
  9662. var z = -matrix8 * vX - matrix9 * vY - matrix10 * vZ;
  9663. result[0] = matrix0;
  9664. result[1] = matrix4;
  9665. result[2] = matrix8;
  9666. result[3] = 0.0;
  9667. result[4] = matrix1;
  9668. result[5] = matrix5;
  9669. result[6] = matrix9;
  9670. result[7] = 0.0;
  9671. result[8] = matrix2;
  9672. result[9] = matrix6;
  9673. result[10] = matrix10;
  9674. result[11] = 0.0;
  9675. result[12] = x;
  9676. result[13] = y;
  9677. result[14] = z;
  9678. result[15] = 1.0;
  9679. return result;
  9680. };
  9681. /**
  9682. * An immutable Matrix4 instance initialized to the identity matrix.
  9683. *
  9684. * @type {Matrix4}
  9685. * @constant
  9686. */
  9687. Matrix4.IDENTITY = freezeObject(new Matrix4(1.0, 0.0, 0.0, 0.0,
  9688. 0.0, 1.0, 0.0, 0.0,
  9689. 0.0, 0.0, 1.0, 0.0,
  9690. 0.0, 0.0, 0.0, 1.0));
  9691. /**
  9692. * An immutable Matrix4 instance initialized to the zero matrix.
  9693. *
  9694. * @type {Matrix4}
  9695. * @constant
  9696. */
  9697. Matrix4.ZERO = freezeObject(new Matrix4(0.0, 0.0, 0.0, 0.0,
  9698. 0.0, 0.0, 0.0, 0.0,
  9699. 0.0, 0.0, 0.0, 0.0,
  9700. 0.0, 0.0, 0.0, 0.0));
  9701. /**
  9702. * The index into Matrix4 for column 0, row 0.
  9703. *
  9704. * @type {Number}
  9705. * @constant
  9706. */
  9707. Matrix4.COLUMN0ROW0 = 0;
  9708. /**
  9709. * The index into Matrix4 for column 0, row 1.
  9710. *
  9711. * @type {Number}
  9712. * @constant
  9713. */
  9714. Matrix4.COLUMN0ROW1 = 1;
  9715. /**
  9716. * The index into Matrix4 for column 0, row 2.
  9717. *
  9718. * @type {Number}
  9719. * @constant
  9720. */
  9721. Matrix4.COLUMN0ROW2 = 2;
  9722. /**
  9723. * The index into Matrix4 for column 0, row 3.
  9724. *
  9725. * @type {Number}
  9726. * @constant
  9727. */
  9728. Matrix4.COLUMN0ROW3 = 3;
  9729. /**
  9730. * The index into Matrix4 for column 1, row 0.
  9731. *
  9732. * @type {Number}
  9733. * @constant
  9734. */
  9735. Matrix4.COLUMN1ROW0 = 4;
  9736. /**
  9737. * The index into Matrix4 for column 1, row 1.
  9738. *
  9739. * @type {Number}
  9740. * @constant
  9741. */
  9742. Matrix4.COLUMN1ROW1 = 5;
  9743. /**
  9744. * The index into Matrix4 for column 1, row 2.
  9745. *
  9746. * @type {Number}
  9747. * @constant
  9748. */
  9749. Matrix4.COLUMN1ROW2 = 6;
  9750. /**
  9751. * The index into Matrix4 for column 1, row 3.
  9752. *
  9753. * @type {Number}
  9754. * @constant
  9755. */
  9756. Matrix4.COLUMN1ROW3 = 7;
  9757. /**
  9758. * The index into Matrix4 for column 2, row 0.
  9759. *
  9760. * @type {Number}
  9761. * @constant
  9762. */
  9763. Matrix4.COLUMN2ROW0 = 8;
  9764. /**
  9765. * The index into Matrix4 for column 2, row 1.
  9766. *
  9767. * @type {Number}
  9768. * @constant
  9769. */
  9770. Matrix4.COLUMN2ROW1 = 9;
  9771. /**
  9772. * The index into Matrix4 for column 2, row 2.
  9773. *
  9774. * @type {Number}
  9775. * @constant
  9776. */
  9777. Matrix4.COLUMN2ROW2 = 10;
  9778. /**
  9779. * The index into Matrix4 for column 2, row 3.
  9780. *
  9781. * @type {Number}
  9782. * @constant
  9783. */
  9784. Matrix4.COLUMN2ROW3 = 11;
  9785. /**
  9786. * The index into Matrix4 for column 3, row 0.
  9787. *
  9788. * @type {Number}
  9789. * @constant
  9790. */
  9791. Matrix4.COLUMN3ROW0 = 12;
  9792. /**
  9793. * The index into Matrix4 for column 3, row 1.
  9794. *
  9795. * @type {Number}
  9796. * @constant
  9797. */
  9798. Matrix4.COLUMN3ROW1 = 13;
  9799. /**
  9800. * The index into Matrix4 for column 3, row 2.
  9801. *
  9802. * @type {Number}
  9803. * @constant
  9804. */
  9805. Matrix4.COLUMN3ROW2 = 14;
  9806. /**
  9807. * The index into Matrix4 for column 3, row 3.
  9808. *
  9809. * @type {Number}
  9810. * @constant
  9811. */
  9812. Matrix4.COLUMN3ROW3 = 15;
  9813. defineProperties(Matrix4.prototype, {
  9814. /**
  9815. * Gets the number of items in the collection.
  9816. * @memberof Matrix4.prototype
  9817. *
  9818. * @type {Number}
  9819. */
  9820. length : {
  9821. get : function() {
  9822. return Matrix4.packedLength;
  9823. }
  9824. }
  9825. });
  9826. /**
  9827. * Duplicates the provided Matrix4 instance.
  9828. *
  9829. * @param {Matrix4} [result] The object onto which to store the result.
  9830. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided.
  9831. */
  9832. Matrix4.prototype.clone = function(result) {
  9833. return Matrix4.clone(this, result);
  9834. };
  9835. /**
  9836. * Compares this matrix to the provided matrix componentwise and returns
  9837. * <code>true</code> if they are equal, <code>false</code> otherwise.
  9838. *
  9839. * @param {Matrix4} [right] The right hand side matrix.
  9840. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  9841. */
  9842. Matrix4.prototype.equals = function(right) {
  9843. return Matrix4.equals(this, right);
  9844. };
  9845. /**
  9846. * @private
  9847. */
  9848. Matrix4.equalsArray = function(matrix, array, offset) {
  9849. return matrix[0] === array[offset] &&
  9850. matrix[1] === array[offset + 1] &&
  9851. matrix[2] === array[offset + 2] &&
  9852. matrix[3] === array[offset + 3] &&
  9853. matrix[4] === array[offset + 4] &&
  9854. matrix[5] === array[offset + 5] &&
  9855. matrix[6] === array[offset + 6] &&
  9856. matrix[7] === array[offset + 7] &&
  9857. matrix[8] === array[offset + 8] &&
  9858. matrix[9] === array[offset + 9] &&
  9859. matrix[10] === array[offset + 10] &&
  9860. matrix[11] === array[offset + 11] &&
  9861. matrix[12] === array[offset + 12] &&
  9862. matrix[13] === array[offset + 13] &&
  9863. matrix[14] === array[offset + 14] &&
  9864. matrix[15] === array[offset + 15];
  9865. };
  9866. /**
  9867. * Compares this matrix to the provided matrix componentwise and returns
  9868. * <code>true</code> if they are within the provided epsilon,
  9869. * <code>false</code> otherwise.
  9870. *
  9871. * @param {Matrix4} [right] The right hand side matrix.
  9872. * @param {Number} epsilon The epsilon to use for equality testing.
  9873. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  9874. */
  9875. Matrix4.prototype.equalsEpsilon = function(right, epsilon) {
  9876. return Matrix4.equalsEpsilon(this, right, epsilon);
  9877. };
  9878. /**
  9879. * Computes a string representing this Matrix with each row being
  9880. * on a separate line and in the format '(column0, column1, column2, column3)'.
  9881. *
  9882. * @returns {String} A string representing the provided Matrix with each row being on a separate line and in the format '(column0, column1, column2, column3)'.
  9883. */
  9884. Matrix4.prototype.toString = function() {
  9885. return '(' + this[0] + ', ' + this[4] + ', ' + this[8] + ', ' + this[12] +')\n' +
  9886. '(' + this[1] + ', ' + this[5] + ', ' + this[9] + ', ' + this[13] +')\n' +
  9887. '(' + this[2] + ', ' + this[6] + ', ' + this[10] + ', ' + this[14] +')\n' +
  9888. '(' + this[3] + ', ' + this[7] + ', ' + this[11] + ', ' + this[15] +')';
  9889. };
  9890. return Matrix4;
  9891. });
  9892. /*global define*/
  9893. define('Core/BoundingSphere',[
  9894. './Cartesian3',
  9895. './Cartographic',
  9896. './defaultValue',
  9897. './defined',
  9898. './DeveloperError',
  9899. './Ellipsoid',
  9900. './GeographicProjection',
  9901. './Intersect',
  9902. './Interval',
  9903. './Matrix3',
  9904. './Matrix4',
  9905. './Rectangle'
  9906. ], function(
  9907. Cartesian3,
  9908. Cartographic,
  9909. defaultValue,
  9910. defined,
  9911. DeveloperError,
  9912. Ellipsoid,
  9913. GeographicProjection,
  9914. Intersect,
  9915. Interval,
  9916. Matrix3,
  9917. Matrix4,
  9918. Rectangle) {
  9919. 'use strict';
  9920. /**
  9921. * A bounding sphere with a center and a radius.
  9922. * @alias BoundingSphere
  9923. * @constructor
  9924. *
  9925. * @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
  9926. * @param {Number} [radius=0.0] The radius of the bounding sphere.
  9927. *
  9928. * @see AxisAlignedBoundingBox
  9929. * @see BoundingRectangle
  9930. * @see Packable
  9931. */
  9932. function BoundingSphere(center, radius) {
  9933. /**
  9934. * The center point of the sphere.
  9935. * @type {Cartesian3}
  9936. * @default {@link Cartesian3.ZERO}
  9937. */
  9938. this.center = Cartesian3.clone(defaultValue(center, Cartesian3.ZERO));
  9939. /**
  9940. * The radius of the sphere.
  9941. * @type {Number}
  9942. * @default 0.0
  9943. */
  9944. this.radius = defaultValue(radius, 0.0);
  9945. }
  9946. var fromPointsXMin = new Cartesian3();
  9947. var fromPointsYMin = new Cartesian3();
  9948. var fromPointsZMin = new Cartesian3();
  9949. var fromPointsXMax = new Cartesian3();
  9950. var fromPointsYMax = new Cartesian3();
  9951. var fromPointsZMax = new Cartesian3();
  9952. var fromPointsCurrentPos = new Cartesian3();
  9953. var fromPointsScratch = new Cartesian3();
  9954. var fromPointsRitterCenter = new Cartesian3();
  9955. var fromPointsMinBoxPt = new Cartesian3();
  9956. var fromPointsMaxBoxPt = new Cartesian3();
  9957. var fromPointsNaiveCenterScratch = new Cartesian3();
  9958. /**
  9959. * Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
  9960. * The bounding sphere is computed by running two algorithms, a naive algorithm and
  9961. * Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
  9962. *
  9963. * @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.
  9964. * @param {BoundingSphere} [result] The object onto which to store the result.
  9965. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  9966. *
  9967. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  9968. */
  9969. BoundingSphere.fromPoints = function(positions, result) {
  9970. if (!defined(result)) {
  9971. result = new BoundingSphere();
  9972. }
  9973. if (!defined(positions) || positions.length === 0) {
  9974. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  9975. result.radius = 0.0;
  9976. return result;
  9977. }
  9978. var currentPos = Cartesian3.clone(positions[0], fromPointsCurrentPos);
  9979. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  9980. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  9981. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  9982. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  9983. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  9984. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  9985. var numPositions = positions.length;
  9986. for (var i = 1; i < numPositions; i++) {
  9987. Cartesian3.clone(positions[i], currentPos);
  9988. var x = currentPos.x;
  9989. var y = currentPos.y;
  9990. var z = currentPos.z;
  9991. // Store points containing the the smallest and largest components
  9992. if (x < xMin.x) {
  9993. Cartesian3.clone(currentPos, xMin);
  9994. }
  9995. if (x > xMax.x) {
  9996. Cartesian3.clone(currentPos, xMax);
  9997. }
  9998. if (y < yMin.y) {
  9999. Cartesian3.clone(currentPos, yMin);
  10000. }
  10001. if (y > yMax.y) {
  10002. Cartesian3.clone(currentPos, yMax);
  10003. }
  10004. if (z < zMin.z) {
  10005. Cartesian3.clone(currentPos, zMin);
  10006. }
  10007. if (z > zMax.z) {
  10008. Cartesian3.clone(currentPos, zMax);
  10009. }
  10010. }
  10011. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10012. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10013. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10014. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10015. // Set the diameter endpoints to the largest span.
  10016. var diameter1 = xMin;
  10017. var diameter2 = xMax;
  10018. var maxSpan = xSpan;
  10019. if (ySpan > maxSpan) {
  10020. maxSpan = ySpan;
  10021. diameter1 = yMin;
  10022. diameter2 = yMax;
  10023. }
  10024. if (zSpan > maxSpan) {
  10025. maxSpan = zSpan;
  10026. diameter1 = zMin;
  10027. diameter2 = zMax;
  10028. }
  10029. // Calculate the center of the initial sphere found by Ritter's algorithm
  10030. var ritterCenter = fromPointsRitterCenter;
  10031. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10032. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10033. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10034. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10035. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10036. var ritterRadius = Math.sqrt(radiusSquared);
  10037. // Find the center of the sphere found using the Naive method.
  10038. var minBoxPt = fromPointsMinBoxPt;
  10039. minBoxPt.x = xMin.x;
  10040. minBoxPt.y = yMin.y;
  10041. minBoxPt.z = zMin.z;
  10042. var maxBoxPt = fromPointsMaxBoxPt;
  10043. maxBoxPt.x = xMax.x;
  10044. maxBoxPt.y = yMax.y;
  10045. maxBoxPt.z = zMax.z;
  10046. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10047. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10048. var naiveRadius = 0;
  10049. for (i = 0; i < numPositions; i++) {
  10050. Cartesian3.clone(positions[i], currentPos);
  10051. // Find the furthest point from the naive center to calculate the naive radius.
  10052. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10053. if (r > naiveRadius) {
  10054. naiveRadius = r;
  10055. }
  10056. // Make adjustments to the Ritter Sphere to include all points.
  10057. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10058. if (oldCenterToPointSquared > radiusSquared) {
  10059. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10060. // Calculate new radius to include the point that lies outside
  10061. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10062. radiusSquared = ritterRadius * ritterRadius;
  10063. // Calculate center of new Ritter sphere
  10064. var oldToNew = oldCenterToPoint - ritterRadius;
  10065. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10066. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10067. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10068. }
  10069. }
  10070. if (ritterRadius < naiveRadius) {
  10071. Cartesian3.clone(ritterCenter, result.center);
  10072. result.radius = ritterRadius;
  10073. } else {
  10074. Cartesian3.clone(naiveCenter, result.center);
  10075. result.radius = naiveRadius;
  10076. }
  10077. return result;
  10078. };
  10079. var defaultProjection = new GeographicProjection();
  10080. var fromRectangle2DLowerLeft = new Cartesian3();
  10081. var fromRectangle2DUpperRight = new Cartesian3();
  10082. var fromRectangle2DSouthwest = new Cartographic();
  10083. var fromRectangle2DNortheast = new Cartographic();
  10084. /**
  10085. * Computes a bounding sphere from an rectangle projected in 2D.
  10086. *
  10087. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10088. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10089. * @param {BoundingSphere} [result] The object onto which to store the result.
  10090. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10091. */
  10092. BoundingSphere.fromRectangle2D = function(rectangle, projection, result) {
  10093. return BoundingSphere.fromRectangleWithHeights2D(rectangle, projection, 0.0, 0.0, result);
  10094. };
  10095. /**
  10096. * Computes a bounding sphere from an rectangle projected in 2D. The bounding sphere accounts for the
  10097. * object's minimum and maximum heights over the rectangle.
  10098. *
  10099. * @param {Rectangle} rectangle The rectangle around which to create a bounding sphere.
  10100. * @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
  10101. * @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
  10102. * @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
  10103. * @param {BoundingSphere} [result] The object onto which to store the result.
  10104. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10105. */
  10106. BoundingSphere.fromRectangleWithHeights2D = function(rectangle, projection, minimumHeight, maximumHeight, result) {
  10107. if (!defined(result)) {
  10108. result = new BoundingSphere();
  10109. }
  10110. if (!defined(rectangle)) {
  10111. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10112. result.radius = 0.0;
  10113. return result;
  10114. }
  10115. projection = defaultValue(projection, defaultProjection);
  10116. Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
  10117. fromRectangle2DSouthwest.height = minimumHeight;
  10118. Rectangle.northeast(rectangle, fromRectangle2DNortheast);
  10119. fromRectangle2DNortheast.height = maximumHeight;
  10120. var lowerLeft = projection.project(fromRectangle2DSouthwest, fromRectangle2DLowerLeft);
  10121. var upperRight = projection.project(fromRectangle2DNortheast, fromRectangle2DUpperRight);
  10122. var width = upperRight.x - lowerLeft.x;
  10123. var height = upperRight.y - lowerLeft.y;
  10124. var elevation = upperRight.z - lowerLeft.z;
  10125. result.radius = Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
  10126. var center = result.center;
  10127. center.x = lowerLeft.x + width * 0.5;
  10128. center.y = lowerLeft.y + height * 0.5;
  10129. center.z = lowerLeft.z + elevation * 0.5;
  10130. return result;
  10131. };
  10132. var fromRectangle3DScratch = [];
  10133. /**
  10134. * Computes a bounding sphere from an rectangle in 3D. The bounding sphere is created using a subsample of points
  10135. * on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
  10136. *
  10137. * @param {Rectangle} rectangle The valid rectangle used to create a bounding sphere.
  10138. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
  10139. * @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
  10140. * @param {BoundingSphere} [result] The object onto which to store the result.
  10141. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10142. */
  10143. BoundingSphere.fromRectangle3D = function(rectangle, ellipsoid, surfaceHeight, result) {
  10144. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  10145. surfaceHeight = defaultValue(surfaceHeight, 0.0);
  10146. var positions;
  10147. if (defined(rectangle)) {
  10148. positions = Rectangle.subsample(rectangle, ellipsoid, surfaceHeight, fromRectangle3DScratch);
  10149. }
  10150. return BoundingSphere.fromPoints(positions, result);
  10151. };
  10152. /**
  10153. * Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
  10154. * stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
  10155. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10156. * ensure a tight fit.
  10157. *
  10158. * @param {Number[]} positions An array of points that the bounding sphere will enclose. Each point
  10159. * is formed from three elements in the array in the order X, Y, Z.
  10160. * @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
  10161. * origin of the coordinate system. This is useful when the positions are to be used for
  10162. * relative-to-center (RTC) rendering.
  10163. * @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
  10164. * be higher. Regardless of the value of this parameter, the X coordinate of the first position
  10165. * is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
  10166. * 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
  10167. * the stride is 5, however, two array elements are skipped and the next position begins at array
  10168. * index 5.
  10169. * @param {BoundingSphere} [result] The object onto which to store the result.
  10170. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10171. *
  10172. * @example
  10173. * // Compute the bounding sphere from 3 positions, each specified relative to a center.
  10174. * // In addition to the X, Y, and Z coordinates, the points array contains two additional
  10175. * // elements per point which are ignored for the purpose of computing the bounding sphere.
  10176. * var center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
  10177. * var points = [1.0, 2.0, 3.0, 0.1, 0.2,
  10178. * 4.0, 5.0, 6.0, 0.1, 0.2,
  10179. * 7.0, 8.0, 9.0, 0.1, 0.2];
  10180. * var sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
  10181. *
  10182. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10183. */
  10184. BoundingSphere.fromVertices = function(positions, center, stride, result) {
  10185. if (!defined(result)) {
  10186. result = new BoundingSphere();
  10187. }
  10188. if (!defined(positions) || positions.length === 0) {
  10189. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10190. result.radius = 0.0;
  10191. return result;
  10192. }
  10193. center = defaultValue(center, Cartesian3.ZERO);
  10194. stride = defaultValue(stride, 3);
  10195. if (stride < 3) {
  10196. throw new DeveloperError('stride must be 3 or greater.');
  10197. }
  10198. var currentPos = fromPointsCurrentPos;
  10199. currentPos.x = positions[0] + center.x;
  10200. currentPos.y = positions[1] + center.y;
  10201. currentPos.z = positions[2] + center.z;
  10202. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10203. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10204. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10205. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10206. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10207. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10208. var numElements = positions.length;
  10209. for (var i = 0; i < numElements; i += stride) {
  10210. var x = positions[i] + center.x;
  10211. var y = positions[i + 1] + center.y;
  10212. var z = positions[i + 2] + center.z;
  10213. currentPos.x = x;
  10214. currentPos.y = y;
  10215. currentPos.z = z;
  10216. // Store points containing the the smallest and largest components
  10217. if (x < xMin.x) {
  10218. Cartesian3.clone(currentPos, xMin);
  10219. }
  10220. if (x > xMax.x) {
  10221. Cartesian3.clone(currentPos, xMax);
  10222. }
  10223. if (y < yMin.y) {
  10224. Cartesian3.clone(currentPos, yMin);
  10225. }
  10226. if (y > yMax.y) {
  10227. Cartesian3.clone(currentPos, yMax);
  10228. }
  10229. if (z < zMin.z) {
  10230. Cartesian3.clone(currentPos, zMin);
  10231. }
  10232. if (z > zMax.z) {
  10233. Cartesian3.clone(currentPos, zMax);
  10234. }
  10235. }
  10236. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10237. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10238. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10239. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10240. // Set the diameter endpoints to the largest span.
  10241. var diameter1 = xMin;
  10242. var diameter2 = xMax;
  10243. var maxSpan = xSpan;
  10244. if (ySpan > maxSpan) {
  10245. maxSpan = ySpan;
  10246. diameter1 = yMin;
  10247. diameter2 = yMax;
  10248. }
  10249. if (zSpan > maxSpan) {
  10250. maxSpan = zSpan;
  10251. diameter1 = zMin;
  10252. diameter2 = zMax;
  10253. }
  10254. // Calculate the center of the initial sphere found by Ritter's algorithm
  10255. var ritterCenter = fromPointsRitterCenter;
  10256. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10257. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10258. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10259. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10260. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10261. var ritterRadius = Math.sqrt(radiusSquared);
  10262. // Find the center of the sphere found using the Naive method.
  10263. var minBoxPt = fromPointsMinBoxPt;
  10264. minBoxPt.x = xMin.x;
  10265. minBoxPt.y = yMin.y;
  10266. minBoxPt.z = zMin.z;
  10267. var maxBoxPt = fromPointsMaxBoxPt;
  10268. maxBoxPt.x = xMax.x;
  10269. maxBoxPt.y = yMax.y;
  10270. maxBoxPt.z = zMax.z;
  10271. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10272. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10273. var naiveRadius = 0;
  10274. for (i = 0; i < numElements; i += stride) {
  10275. currentPos.x = positions[i] + center.x;
  10276. currentPos.y = positions[i + 1] + center.y;
  10277. currentPos.z = positions[i + 2] + center.z;
  10278. // Find the furthest point from the naive center to calculate the naive radius.
  10279. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10280. if (r > naiveRadius) {
  10281. naiveRadius = r;
  10282. }
  10283. // Make adjustments to the Ritter Sphere to include all points.
  10284. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10285. if (oldCenterToPointSquared > radiusSquared) {
  10286. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10287. // Calculate new radius to include the point that lies outside
  10288. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10289. radiusSquared = ritterRadius * ritterRadius;
  10290. // Calculate center of new Ritter sphere
  10291. var oldToNew = oldCenterToPoint - ritterRadius;
  10292. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10293. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10294. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10295. }
  10296. }
  10297. if (ritterRadius < naiveRadius) {
  10298. Cartesian3.clone(ritterCenter, result.center);
  10299. result.radius = ritterRadius;
  10300. } else {
  10301. Cartesian3.clone(naiveCenter, result.center);
  10302. result.radius = naiveRadius;
  10303. }
  10304. return result;
  10305. };
  10306. /**
  10307. * Computes a tight-fitting bounding sphere enclosing a list of {@link EncodedCartesian3}s, where the points are
  10308. * stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
  10309. * algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
  10310. * ensure a tight fit.
  10311. *
  10312. * @param {Number[]} positionsHigh An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10313. * is formed from three elements in the array in the order X, Y, Z.
  10314. * @param {Number[]} positionsLow An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
  10315. * is formed from three elements in the array in the order X, Y, Z.
  10316. * @param {BoundingSphere} [result] The object onto which to store the result.
  10317. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10318. *
  10319. * @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
  10320. */
  10321. BoundingSphere.fromEncodedCartesianVertices = function(positionsHigh, positionsLow, result) {
  10322. if (!defined(result)) {
  10323. result = new BoundingSphere();
  10324. }
  10325. if (!defined(positionsHigh) || !defined(positionsLow) || positionsHigh.length !== positionsLow.length || positionsHigh.length === 0) {
  10326. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10327. result.radius = 0.0;
  10328. return result;
  10329. }
  10330. var currentPos = fromPointsCurrentPos;
  10331. currentPos.x = positionsHigh[0] + positionsLow[0];
  10332. currentPos.y = positionsHigh[1] + positionsLow[1];
  10333. currentPos.z = positionsHigh[2] + positionsLow[2];
  10334. var xMin = Cartesian3.clone(currentPos, fromPointsXMin);
  10335. var yMin = Cartesian3.clone(currentPos, fromPointsYMin);
  10336. var zMin = Cartesian3.clone(currentPos, fromPointsZMin);
  10337. var xMax = Cartesian3.clone(currentPos, fromPointsXMax);
  10338. var yMax = Cartesian3.clone(currentPos, fromPointsYMax);
  10339. var zMax = Cartesian3.clone(currentPos, fromPointsZMax);
  10340. var numElements = positionsHigh.length;
  10341. for (var i = 0; i < numElements; i += 3) {
  10342. var x = positionsHigh[i] + positionsLow[i];
  10343. var y = positionsHigh[i + 1] + positionsLow[i + 1];
  10344. var z = positionsHigh[i + 2] + positionsLow[i + 2];
  10345. currentPos.x = x;
  10346. currentPos.y = y;
  10347. currentPos.z = z;
  10348. // Store points containing the the smallest and largest components
  10349. if (x < xMin.x) {
  10350. Cartesian3.clone(currentPos, xMin);
  10351. }
  10352. if (x > xMax.x) {
  10353. Cartesian3.clone(currentPos, xMax);
  10354. }
  10355. if (y < yMin.y) {
  10356. Cartesian3.clone(currentPos, yMin);
  10357. }
  10358. if (y > yMax.y) {
  10359. Cartesian3.clone(currentPos, yMax);
  10360. }
  10361. if (z < zMin.z) {
  10362. Cartesian3.clone(currentPos, zMin);
  10363. }
  10364. if (z > zMax.z) {
  10365. Cartesian3.clone(currentPos, zMax);
  10366. }
  10367. }
  10368. // Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
  10369. var xSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(xMax, xMin, fromPointsScratch));
  10370. var ySpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(yMax, yMin, fromPointsScratch));
  10371. var zSpan = Cartesian3.magnitudeSquared(Cartesian3.subtract(zMax, zMin, fromPointsScratch));
  10372. // Set the diameter endpoints to the largest span.
  10373. var diameter1 = xMin;
  10374. var diameter2 = xMax;
  10375. var maxSpan = xSpan;
  10376. if (ySpan > maxSpan) {
  10377. maxSpan = ySpan;
  10378. diameter1 = yMin;
  10379. diameter2 = yMax;
  10380. }
  10381. if (zSpan > maxSpan) {
  10382. maxSpan = zSpan;
  10383. diameter1 = zMin;
  10384. diameter2 = zMax;
  10385. }
  10386. // Calculate the center of the initial sphere found by Ritter's algorithm
  10387. var ritterCenter = fromPointsRitterCenter;
  10388. ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
  10389. ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
  10390. ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
  10391. // Calculate the radius of the initial sphere found by Ritter's algorithm
  10392. var radiusSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch));
  10393. var ritterRadius = Math.sqrt(radiusSquared);
  10394. // Find the center of the sphere found using the Naive method.
  10395. var minBoxPt = fromPointsMinBoxPt;
  10396. minBoxPt.x = xMin.x;
  10397. minBoxPt.y = yMin.y;
  10398. minBoxPt.z = zMin.z;
  10399. var maxBoxPt = fromPointsMaxBoxPt;
  10400. maxBoxPt.x = xMax.x;
  10401. maxBoxPt.y = yMax.y;
  10402. maxBoxPt.z = zMax.z;
  10403. var naiveCenter = Cartesian3.multiplyByScalar(Cartesian3.add(minBoxPt, maxBoxPt, fromPointsScratch), 0.5, fromPointsNaiveCenterScratch);
  10404. // Begin 2nd pass to find naive radius and modify the ritter sphere.
  10405. var naiveRadius = 0;
  10406. for (i = 0; i < numElements; i += 3) {
  10407. currentPos.x = positionsHigh[i] + positionsLow[i];
  10408. currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
  10409. currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
  10410. // Find the furthest point from the naive center to calculate the naive radius.
  10411. var r = Cartesian3.magnitude(Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch));
  10412. if (r > naiveRadius) {
  10413. naiveRadius = r;
  10414. }
  10415. // Make adjustments to the Ritter Sphere to include all points.
  10416. var oldCenterToPointSquared = Cartesian3.magnitudeSquared(Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch));
  10417. if (oldCenterToPointSquared > radiusSquared) {
  10418. var oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
  10419. // Calculate new radius to include the point that lies outside
  10420. ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
  10421. radiusSquared = ritterRadius * ritterRadius;
  10422. // Calculate center of new Ritter sphere
  10423. var oldToNew = oldCenterToPoint - ritterRadius;
  10424. ritterCenter.x = (ritterRadius * ritterCenter.x + oldToNew * currentPos.x) / oldCenterToPoint;
  10425. ritterCenter.y = (ritterRadius * ritterCenter.y + oldToNew * currentPos.y) / oldCenterToPoint;
  10426. ritterCenter.z = (ritterRadius * ritterCenter.z + oldToNew * currentPos.z) / oldCenterToPoint;
  10427. }
  10428. }
  10429. if (ritterRadius < naiveRadius) {
  10430. Cartesian3.clone(ritterCenter, result.center);
  10431. result.radius = ritterRadius;
  10432. } else {
  10433. Cartesian3.clone(naiveCenter, result.center);
  10434. result.radius = naiveRadius;
  10435. }
  10436. return result;
  10437. };
  10438. /**
  10439. * Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
  10440. * tighly and fully encompases the box.
  10441. *
  10442. * @param {Cartesian3} [corner] The minimum height over the rectangle.
  10443. * @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
  10444. * @param {BoundingSphere} [result] The object onto which to store the result.
  10445. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10446. *
  10447. * @example
  10448. * // Create a bounding sphere around the unit cube
  10449. * var sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
  10450. */
  10451. BoundingSphere.fromCornerPoints = function(corner, oppositeCorner, result) {
  10452. if (!defined(corner) || !defined(oppositeCorner)) {
  10453. throw new DeveloperError('corner and oppositeCorner are required.');
  10454. }
  10455. if (!defined(result)) {
  10456. result = new BoundingSphere();
  10457. }
  10458. var center = result.center;
  10459. Cartesian3.add(corner, oppositeCorner, center);
  10460. Cartesian3.multiplyByScalar(center, 0.5, center);
  10461. result.radius = Cartesian3.distance(center, oppositeCorner);
  10462. return result;
  10463. };
  10464. /**
  10465. * Creates a bounding sphere encompassing an ellipsoid.
  10466. *
  10467. * @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
  10468. * @param {BoundingSphere} [result] The object onto which to store the result.
  10469. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10470. *
  10471. * @example
  10472. * var boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
  10473. */
  10474. BoundingSphere.fromEllipsoid = function(ellipsoid, result) {
  10475. if (!defined(ellipsoid)) {
  10476. throw new DeveloperError('ellipsoid is required.');
  10477. }
  10478. if (!defined(result)) {
  10479. result = new BoundingSphere();
  10480. }
  10481. Cartesian3.clone(Cartesian3.ZERO, result.center);
  10482. result.radius = ellipsoid.maximumRadius;
  10483. return result;
  10484. };
  10485. var fromBoundingSpheresScratch = new Cartesian3();
  10486. /**
  10487. * Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
  10488. *
  10489. * @param {BoundingSphere[]} boundingSpheres The array of bounding spheres.
  10490. * @param {BoundingSphere} [result] The object onto which to store the result.
  10491. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10492. */
  10493. BoundingSphere.fromBoundingSpheres = function(boundingSpheres, result) {
  10494. if (!defined(result)) {
  10495. result = new BoundingSphere();
  10496. }
  10497. if (!defined(boundingSpheres) || boundingSpheres.length === 0) {
  10498. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  10499. result.radius = 0.0;
  10500. return result;
  10501. }
  10502. var length = boundingSpheres.length;
  10503. if (length === 1) {
  10504. return BoundingSphere.clone(boundingSpheres[0], result);
  10505. }
  10506. if (length === 2) {
  10507. return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
  10508. }
  10509. var positions = [];
  10510. for (var i = 0; i < length; i++) {
  10511. positions.push(boundingSpheres[i].center);
  10512. }
  10513. result = BoundingSphere.fromPoints(positions, result);
  10514. var center = result.center;
  10515. var radius = result.radius;
  10516. for (i = 0; i < length; i++) {
  10517. var tmp = boundingSpheres[i];
  10518. radius = Math.max(radius, Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) + tmp.radius);
  10519. }
  10520. result.radius = radius;
  10521. return result;
  10522. };
  10523. var fromOrientedBoundingBoxScratchU = new Cartesian3();
  10524. var fromOrientedBoundingBoxScratchV = new Cartesian3();
  10525. var fromOrientedBoundingBoxScratchW = new Cartesian3();
  10526. /**
  10527. * Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
  10528. *
  10529. * @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
  10530. * @param {BoundingSphere} [result] The object onto which to store the result.
  10531. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10532. */
  10533. BoundingSphere.fromOrientedBoundingBox = function(orientedBoundingBox, result) {
  10534. if (!defined(result)) {
  10535. result = new BoundingSphere();
  10536. }
  10537. var halfAxes = orientedBoundingBox.halfAxes;
  10538. var u = Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
  10539. var v = Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
  10540. var w = Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
  10541. var uHalf = Cartesian3.magnitude(u);
  10542. var vHalf = Cartesian3.magnitude(v);
  10543. var wHalf = Cartesian3.magnitude(w);
  10544. result.center = Cartesian3.clone(orientedBoundingBox.center, result.center);
  10545. result.radius = Math.max(uHalf, vHalf, wHalf);
  10546. return result;
  10547. };
  10548. /**
  10549. * Duplicates a BoundingSphere instance.
  10550. *
  10551. * @param {BoundingSphere} sphere The bounding sphere to duplicate.
  10552. * @param {BoundingSphere} [result] The object onto which to store the result.
  10553. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
  10554. */
  10555. BoundingSphere.clone = function(sphere, result) {
  10556. if (!defined(sphere)) {
  10557. return undefined;
  10558. }
  10559. if (!defined(result)) {
  10560. return new BoundingSphere(sphere.center, sphere.radius);
  10561. }
  10562. result.center = Cartesian3.clone(sphere.center, result.center);
  10563. result.radius = sphere.radius;
  10564. return result;
  10565. };
  10566. /**
  10567. * The number of elements used to pack the object into an array.
  10568. * @type {Number}
  10569. */
  10570. BoundingSphere.packedLength = 4;
  10571. /**
  10572. * Stores the provided instance into the provided array.
  10573. *
  10574. * @param {BoundingSphere} value The value to pack.
  10575. * @param {Number[]} array The array to pack into.
  10576. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  10577. *
  10578. * @returns {Number[]} The array that was packed into
  10579. */
  10580. BoundingSphere.pack = function(value, array, startingIndex) {
  10581. if (!defined(value)) {
  10582. throw new DeveloperError('value is required');
  10583. }
  10584. if (!defined(array)) {
  10585. throw new DeveloperError('array is required');
  10586. }
  10587. startingIndex = defaultValue(startingIndex, 0);
  10588. var center = value.center;
  10589. array[startingIndex++] = center.x;
  10590. array[startingIndex++] = center.y;
  10591. array[startingIndex++] = center.z;
  10592. array[startingIndex] = value.radius;
  10593. return array;
  10594. };
  10595. /**
  10596. * Retrieves an instance from a packed array.
  10597. *
  10598. * @param {Number[]} array The packed array.
  10599. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  10600. * @param {BoundingSphere} [result] The object into which to store the result.
  10601. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
  10602. */
  10603. BoundingSphere.unpack = function(array, startingIndex, result) {
  10604. if (!defined(array)) {
  10605. throw new DeveloperError('array is required');
  10606. }
  10607. startingIndex = defaultValue(startingIndex, 0);
  10608. if (!defined(result)) {
  10609. result = new BoundingSphere();
  10610. }
  10611. var center = result.center;
  10612. center.x = array[startingIndex++];
  10613. center.y = array[startingIndex++];
  10614. center.z = array[startingIndex++];
  10615. result.radius = array[startingIndex];
  10616. return result;
  10617. };
  10618. var unionScratch = new Cartesian3();
  10619. var unionScratchCenter = new Cartesian3();
  10620. /**
  10621. * Computes a bounding sphere that contains both the left and right bounding spheres.
  10622. *
  10623. * @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
  10624. * @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
  10625. * @param {BoundingSphere} [result] The object onto which to store the result.
  10626. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10627. */
  10628. BoundingSphere.union = function(left, right, result) {
  10629. if (!defined(left)) {
  10630. throw new DeveloperError('left is required.');
  10631. }
  10632. if (!defined(right)) {
  10633. throw new DeveloperError('right is required.');
  10634. }
  10635. if (!defined(result)) {
  10636. result = new BoundingSphere();
  10637. }
  10638. var leftCenter = left.center;
  10639. var leftRadius = left.radius;
  10640. var rightCenter = right.center;
  10641. var rightRadius = right.radius;
  10642. var toRightCenter = Cartesian3.subtract(rightCenter, leftCenter, unionScratch);
  10643. var centerSeparation = Cartesian3.magnitude(toRightCenter);
  10644. if (leftRadius >= (centerSeparation + rightRadius)) {
  10645. // Left sphere wins.
  10646. left.clone(result);
  10647. return result;
  10648. }
  10649. if (rightRadius >= (centerSeparation + leftRadius)) {
  10650. // Right sphere wins.
  10651. right.clone(result);
  10652. return result;
  10653. }
  10654. // There are two tangent points, one on far side of each sphere.
  10655. var halfDistanceBetweenTangentPoints = (leftRadius + centerSeparation + rightRadius) * 0.5;
  10656. // Compute the center point halfway between the two tangent points.
  10657. var center = Cartesian3.multiplyByScalar(toRightCenter,
  10658. (-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation, unionScratchCenter);
  10659. Cartesian3.add(center, leftCenter, center);
  10660. Cartesian3.clone(center, result.center);
  10661. result.radius = halfDistanceBetweenTangentPoints;
  10662. return result;
  10663. };
  10664. var expandScratch = new Cartesian3();
  10665. /**
  10666. * Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
  10667. *
  10668. * @param {BoundingSphere} sphere A sphere to expand.
  10669. * @param {Cartesian3} point A point to enclose in a bounding sphere.
  10670. * @param {BoundingSphere} [result] The object onto which to store the result.
  10671. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10672. */
  10673. BoundingSphere.expand = function(sphere, point, result) {
  10674. if (!defined(sphere)) {
  10675. throw new DeveloperError('sphere is required.');
  10676. }
  10677. if (!defined(point)) {
  10678. throw new DeveloperError('point is required.');
  10679. }
  10680. result = BoundingSphere.clone(sphere, result);
  10681. var radius = Cartesian3.magnitude(Cartesian3.subtract(point, result.center, expandScratch));
  10682. if (radius > result.radius) {
  10683. result.radius = radius;
  10684. }
  10685. return result;
  10686. };
  10687. /**
  10688. * Determines which side of a plane a sphere is located.
  10689. *
  10690. * @param {BoundingSphere} sphere The bounding sphere to test.
  10691. * @param {Plane} plane The plane to test against.
  10692. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10693. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10694. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10695. * intersects the plane.
  10696. */
  10697. BoundingSphere.intersectPlane = function(sphere, plane) {
  10698. if (!defined(sphere)) {
  10699. throw new DeveloperError('sphere is required.');
  10700. }
  10701. if (!defined(plane)) {
  10702. throw new DeveloperError('plane is required.');
  10703. }
  10704. var center = sphere.center;
  10705. var radius = sphere.radius;
  10706. var normal = plane.normal;
  10707. var distanceToPlane = Cartesian3.dot(normal, center) + plane.distance;
  10708. if (distanceToPlane < -radius) {
  10709. // The center point is negative side of the plane normal
  10710. return Intersect.OUTSIDE;
  10711. } else if (distanceToPlane < radius) {
  10712. // The center point is positive side of the plane, but radius extends beyond it; partial overlap
  10713. return Intersect.INTERSECTING;
  10714. }
  10715. return Intersect.INSIDE;
  10716. };
  10717. /**
  10718. * Applies a 4x4 affine transformation matrix to a bounding sphere.
  10719. *
  10720. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10721. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10722. * @param {BoundingSphere} [result] The object onto which to store the result.
  10723. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10724. */
  10725. BoundingSphere.transform = function(sphere, transform, result) {
  10726. if (!defined(sphere)) {
  10727. throw new DeveloperError('sphere is required.');
  10728. }
  10729. if (!defined(transform)) {
  10730. throw new DeveloperError('transform is required.');
  10731. }
  10732. if (!defined(result)) {
  10733. result = new BoundingSphere();
  10734. }
  10735. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10736. result.radius = Matrix4.getMaximumScale(transform) * sphere.radius;
  10737. return result;
  10738. };
  10739. var distanceSquaredToScratch = new Cartesian3();
  10740. /**
  10741. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10742. *
  10743. * @param {BoundingSphere} sphere The sphere.
  10744. * @param {Cartesian3} cartesian The point
  10745. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10746. *
  10747. * @example
  10748. * // Sort bounding spheres from back to front
  10749. * spheres.sort(function(a, b) {
  10750. * return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
  10751. * });
  10752. */
  10753. BoundingSphere.distanceSquaredTo = function(sphere, cartesian) {
  10754. if (!defined(sphere)) {
  10755. throw new DeveloperError('sphere is required.');
  10756. }
  10757. if (!defined(cartesian)) {
  10758. throw new DeveloperError('cartesian is required.');
  10759. }
  10760. var diff = Cartesian3.subtract(sphere.center, cartesian, distanceSquaredToScratch);
  10761. return Cartesian3.magnitudeSquared(diff) - sphere.radius * sphere.radius;
  10762. };
  10763. /**
  10764. * Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
  10765. * The transformation matrix is not verified to have a uniform scale of 1.
  10766. * This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
  10767. *
  10768. * @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
  10769. * @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
  10770. * @param {BoundingSphere} [result] The object onto which to store the result.
  10771. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10772. *
  10773. * @example
  10774. * var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
  10775. * var boundingSphere = new Cesium.BoundingSphere();
  10776. * var newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
  10777. */
  10778. BoundingSphere.transformWithoutScale = function(sphere, transform, result) {
  10779. if (!defined(sphere)) {
  10780. throw new DeveloperError('sphere is required.');
  10781. }
  10782. if (!defined(transform)) {
  10783. throw new DeveloperError('transform is required.');
  10784. }
  10785. if (!defined(result)) {
  10786. result = new BoundingSphere();
  10787. }
  10788. result.center = Matrix4.multiplyByPoint(transform, sphere.center, result.center);
  10789. result.radius = sphere.radius;
  10790. return result;
  10791. };
  10792. var scratchCartesian3 = new Cartesian3();
  10793. /**
  10794. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10795. * plus/minus the radius of the bounding sphere.
  10796. * <br>
  10797. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10798. * closest and farthest planes from position that intersect the bounding sphere.
  10799. *
  10800. * @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
  10801. * @param {Cartesian3} position The position to calculate the distance from.
  10802. * @param {Cartesian3} direction The direction from position.
  10803. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10804. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10805. */
  10806. BoundingSphere.computePlaneDistances = function(sphere, position, direction, result) {
  10807. if (!defined(sphere)) {
  10808. throw new DeveloperError('sphere is required.');
  10809. }
  10810. if (!defined(position)) {
  10811. throw new DeveloperError('position is required.');
  10812. }
  10813. if (!defined(direction)) {
  10814. throw new DeveloperError('direction is required.');
  10815. }
  10816. if (!defined(result)) {
  10817. result = new Interval();
  10818. }
  10819. var toCenter = Cartesian3.subtract(sphere.center, position, scratchCartesian3);
  10820. var mag = Cartesian3.dot(direction, toCenter);
  10821. result.start = mag - sphere.radius;
  10822. result.stop = mag + sphere.radius;
  10823. return result;
  10824. };
  10825. var projectTo2DNormalScratch = new Cartesian3();
  10826. var projectTo2DEastScratch = new Cartesian3();
  10827. var projectTo2DNorthScratch = new Cartesian3();
  10828. var projectTo2DWestScratch = new Cartesian3();
  10829. var projectTo2DSouthScratch = new Cartesian3();
  10830. var projectTo2DCartographicScratch = new Cartographic();
  10831. var projectTo2DPositionsScratch = new Array(8);
  10832. for (var n = 0; n < 8; ++n) {
  10833. projectTo2DPositionsScratch[n] = new Cartesian3();
  10834. }
  10835. var projectTo2DProjection = new GeographicProjection();
  10836. /**
  10837. * Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
  10838. *
  10839. * @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
  10840. * @param {Object} [projection=GeographicProjection] The projection to 2D.
  10841. * @param {BoundingSphere} [result] The object onto which to store the result.
  10842. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  10843. */
  10844. BoundingSphere.projectTo2D = function(sphere, projection, result) {
  10845. if (!defined(sphere)) {
  10846. throw new DeveloperError('sphere is required.');
  10847. }
  10848. projection = defaultValue(projection, projectTo2DProjection);
  10849. var ellipsoid = projection.ellipsoid;
  10850. var center = sphere.center;
  10851. var radius = sphere.radius;
  10852. var normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
  10853. var east = Cartesian3.cross(Cartesian3.UNIT_Z, normal, projectTo2DEastScratch);
  10854. Cartesian3.normalize(east, east);
  10855. var north = Cartesian3.cross(normal, east, projectTo2DNorthScratch);
  10856. Cartesian3.normalize(north, north);
  10857. Cartesian3.multiplyByScalar(normal, radius, normal);
  10858. Cartesian3.multiplyByScalar(north, radius, north);
  10859. Cartesian3.multiplyByScalar(east, radius, east);
  10860. var south = Cartesian3.negate(north, projectTo2DSouthScratch);
  10861. var west = Cartesian3.negate(east, projectTo2DWestScratch);
  10862. var positions = projectTo2DPositionsScratch;
  10863. // top NE corner
  10864. var corner = positions[0];
  10865. Cartesian3.add(normal, north, corner);
  10866. Cartesian3.add(corner, east, corner);
  10867. // top NW corner
  10868. corner = positions[1];
  10869. Cartesian3.add(normal, north, corner);
  10870. Cartesian3.add(corner, west, corner);
  10871. // top SW corner
  10872. corner = positions[2];
  10873. Cartesian3.add(normal, south, corner);
  10874. Cartesian3.add(corner, west, corner);
  10875. // top SE corner
  10876. corner = positions[3];
  10877. Cartesian3.add(normal, south, corner);
  10878. Cartesian3.add(corner, east, corner);
  10879. Cartesian3.negate(normal, normal);
  10880. // bottom NE corner
  10881. corner = positions[4];
  10882. Cartesian3.add(normal, north, corner);
  10883. Cartesian3.add(corner, east, corner);
  10884. // bottom NW corner
  10885. corner = positions[5];
  10886. Cartesian3.add(normal, north, corner);
  10887. Cartesian3.add(corner, west, corner);
  10888. // bottom SW corner
  10889. corner = positions[6];
  10890. Cartesian3.add(normal, south, corner);
  10891. Cartesian3.add(corner, west, corner);
  10892. // bottom SE corner
  10893. corner = positions[7];
  10894. Cartesian3.add(normal, south, corner);
  10895. Cartesian3.add(corner, east, corner);
  10896. var length = positions.length;
  10897. for (var i = 0; i < length; ++i) {
  10898. var position = positions[i];
  10899. Cartesian3.add(center, position, position);
  10900. var cartographic = ellipsoid.cartesianToCartographic(position, projectTo2DCartographicScratch);
  10901. projection.project(cartographic, position);
  10902. }
  10903. result = BoundingSphere.fromPoints(positions, result);
  10904. // swizzle center components
  10905. center = result.center;
  10906. var x = center.x;
  10907. var y = center.y;
  10908. var z = center.z;
  10909. center.x = z;
  10910. center.y = x;
  10911. center.z = y;
  10912. return result;
  10913. };
  10914. /**
  10915. * Determines whether or not a sphere is hidden from view by the occluder.
  10916. *
  10917. * @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
  10918. * @param {Occluder} occluder The occluder.
  10919. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10920. */
  10921. BoundingSphere.isOccluded = function(sphere, occluder) {
  10922. if (!defined(sphere)) {
  10923. throw new DeveloperError('sphere is required.');
  10924. }
  10925. if (!defined(occluder)) {
  10926. throw new DeveloperError('occluder is required.');
  10927. }
  10928. return !occluder.isBoundingSphereVisible(sphere);
  10929. };
  10930. /**
  10931. * Compares the provided BoundingSphere componentwise and returns
  10932. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10933. *
  10934. * @param {BoundingSphere} [left] The first BoundingSphere.
  10935. * @param {BoundingSphere} [right] The second BoundingSphere.
  10936. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  10937. */
  10938. BoundingSphere.equals = function(left, right) {
  10939. return (left === right) ||
  10940. ((defined(left)) &&
  10941. (defined(right)) &&
  10942. Cartesian3.equals(left.center, right.center) &&
  10943. left.radius === right.radius);
  10944. };
  10945. /**
  10946. * Determines which side of a plane the sphere is located.
  10947. *
  10948. * @param {Plane} plane The plane to test against.
  10949. * @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
  10950. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
  10951. * on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
  10952. * intersects the plane.
  10953. */
  10954. BoundingSphere.prototype.intersectPlane = function(plane) {
  10955. return BoundingSphere.intersectPlane(this, plane);
  10956. };
  10957. /**
  10958. * Computes the estimated distance squared from the closest point on a bounding sphere to a point.
  10959. *
  10960. * @param {Cartesian3} cartesian The point
  10961. * @returns {Number} The estimated distance squared from the bounding sphere to the point.
  10962. *
  10963. * @example
  10964. * // Sort bounding spheres from back to front
  10965. * spheres.sort(function(a, b) {
  10966. * return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
  10967. * });
  10968. */
  10969. BoundingSphere.prototype.distanceSquaredTo = function(cartesian) {
  10970. return BoundingSphere.distanceSquaredTo(this, cartesian);
  10971. };
  10972. /**
  10973. * The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
  10974. * plus/minus the radius of the bounding sphere.
  10975. * <br>
  10976. * If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
  10977. * closest and farthest planes from position that intersect the bounding sphere.
  10978. *
  10979. * @param {Cartesian3} position The position to calculate the distance from.
  10980. * @param {Cartesian3} direction The direction from position.
  10981. * @param {Interval} [result] A Interval to store the nearest and farthest distances.
  10982. * @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
  10983. */
  10984. BoundingSphere.prototype.computePlaneDistances = function(position, direction, result) {
  10985. return BoundingSphere.computePlaneDistances(this, position, direction, result);
  10986. };
  10987. /**
  10988. * Determines whether or not a sphere is hidden from view by the occluder.
  10989. *
  10990. * @param {Occluder} occluder The occluder.
  10991. * @returns {Boolean} <code>true</code> if the sphere is not visible; otherwise <code>false</code>.
  10992. */
  10993. BoundingSphere.prototype.isOccluded = function(occluder) {
  10994. return BoundingSphere.isOccluded(this, occluder);
  10995. };
  10996. /**
  10997. * Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
  10998. * <code>true</code> if they are equal, <code>false</code> otherwise.
  10999. *
  11000. * @param {BoundingSphere} [right] The right hand side BoundingSphere.
  11001. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  11002. */
  11003. BoundingSphere.prototype.equals = function(right) {
  11004. return BoundingSphere.equals(this, right);
  11005. };
  11006. /**
  11007. * Duplicates this BoundingSphere instance.
  11008. *
  11009. * @param {BoundingSphere} [result] The object onto which to store the result.
  11010. * @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
  11011. */
  11012. BoundingSphere.prototype.clone = function(result) {
  11013. return BoundingSphere.clone(this, result);
  11014. };
  11015. return BoundingSphere;
  11016. });
  11017. /*global define*/
  11018. define('Core/Fullscreen',[
  11019. './defined',
  11020. './defineProperties'
  11021. ], function(
  11022. defined,
  11023. defineProperties) {
  11024. 'use strict';
  11025. var _supportsFullscreen;
  11026. var _names = {
  11027. requestFullscreen : undefined,
  11028. exitFullscreen : undefined,
  11029. fullscreenEnabled : undefined,
  11030. fullscreenElement : undefined,
  11031. fullscreenchange : undefined,
  11032. fullscreenerror : undefined
  11033. };
  11034. /**
  11035. * Browser-independent functions for working with the standard fullscreen API.
  11036. *
  11037. * @exports Fullscreen
  11038. *
  11039. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  11040. */
  11041. var Fullscreen = {};
  11042. defineProperties(Fullscreen, {
  11043. /**
  11044. * The element that is currently fullscreen, if any. To simply check if the
  11045. * browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
  11046. * @memberof Fullscreen
  11047. * @type {Object}
  11048. * @readonly
  11049. */
  11050. element : {
  11051. get : function() {
  11052. if (!Fullscreen.supportsFullscreen()) {
  11053. return undefined;
  11054. }
  11055. return document[_names.fullscreenElement];
  11056. }
  11057. },
  11058. /**
  11059. * The name of the event on the document that is fired when fullscreen is
  11060. * entered or exited. This event name is intended for use with addEventListener.
  11061. * In your event handler, to determine if the browser is in fullscreen mode or not,
  11062. * use {@link Fullscreen#fullscreen}.
  11063. * @memberof Fullscreen
  11064. * @type {String}
  11065. * @readonly
  11066. */
  11067. changeEventName : {
  11068. get : function() {
  11069. if (!Fullscreen.supportsFullscreen()) {
  11070. return undefined;
  11071. }
  11072. return _names.fullscreenchange;
  11073. }
  11074. },
  11075. /**
  11076. * The name of the event that is fired when a fullscreen error
  11077. * occurs. This event name is intended for use with addEventListener.
  11078. * @memberof Fullscreen
  11079. * @type {String}
  11080. * @readonly
  11081. */
  11082. errorEventName : {
  11083. get : function() {
  11084. if (!Fullscreen.supportsFullscreen()) {
  11085. return undefined;
  11086. }
  11087. return _names.fullscreenerror;
  11088. }
  11089. },
  11090. /**
  11091. * Determine whether the browser will allow an element to be made fullscreen, or not.
  11092. * For example, by default, iframes cannot go fullscreen unless the containing page
  11093. * adds an "allowfullscreen" attribute (or prefixed equivalent).
  11094. * @memberof Fullscreen
  11095. * @type {Boolean}
  11096. * @readonly
  11097. */
  11098. enabled : {
  11099. get : function() {
  11100. if (!Fullscreen.supportsFullscreen()) {
  11101. return undefined;
  11102. }
  11103. return document[_names.fullscreenEnabled];
  11104. }
  11105. },
  11106. /**
  11107. * Determines if the browser is currently in fullscreen mode.
  11108. * @memberof Fullscreen
  11109. * @type {Boolean}
  11110. * @readonly
  11111. */
  11112. fullscreen : {
  11113. get : function() {
  11114. if (!Fullscreen.supportsFullscreen()) {
  11115. return undefined;
  11116. }
  11117. return Fullscreen.element !== null;
  11118. }
  11119. }
  11120. });
  11121. /**
  11122. * Detects whether the browser supports the standard fullscreen API.
  11123. *
  11124. * @returns {Boolean} <code>true</code> if the browser supports the standard fullscreen API,
  11125. * <code>false</code> otherwise.
  11126. */
  11127. Fullscreen.supportsFullscreen = function() {
  11128. if (defined(_supportsFullscreen)) {
  11129. return _supportsFullscreen;
  11130. }
  11131. _supportsFullscreen = false;
  11132. var body = document.body;
  11133. if (typeof body.requestFullscreen === 'function') {
  11134. // go with the unprefixed, standard set of names
  11135. _names.requestFullscreen = 'requestFullscreen';
  11136. _names.exitFullscreen = 'exitFullscreen';
  11137. _names.fullscreenEnabled = 'fullscreenEnabled';
  11138. _names.fullscreenElement = 'fullscreenElement';
  11139. _names.fullscreenchange = 'fullscreenchange';
  11140. _names.fullscreenerror = 'fullscreenerror';
  11141. _supportsFullscreen = true;
  11142. return _supportsFullscreen;
  11143. }
  11144. //check for the correct combination of prefix plus the various names that browsers use
  11145. var prefixes = ['webkit', 'moz', 'o', 'ms', 'khtml'];
  11146. var name;
  11147. for (var i = 0, len = prefixes.length; i < len; ++i) {
  11148. var prefix = prefixes[i];
  11149. // casing of Fullscreen differs across browsers
  11150. name = prefix + 'RequestFullscreen';
  11151. if (typeof body[name] === 'function') {
  11152. _names.requestFullscreen = name;
  11153. _supportsFullscreen = true;
  11154. } else {
  11155. name = prefix + 'RequestFullScreen';
  11156. if (typeof body[name] === 'function') {
  11157. _names.requestFullscreen = name;
  11158. _supportsFullscreen = true;
  11159. }
  11160. }
  11161. // disagreement about whether it's "exit" as per spec, or "cancel"
  11162. name = prefix + 'ExitFullscreen';
  11163. if (typeof document[name] === 'function') {
  11164. _names.exitFullscreen = name;
  11165. } else {
  11166. name = prefix + 'CancelFullScreen';
  11167. if (typeof document[name] === 'function') {
  11168. _names.exitFullscreen = name;
  11169. }
  11170. }
  11171. // casing of Fullscreen differs across browsers
  11172. name = prefix + 'FullscreenEnabled';
  11173. if (document[name] !== undefined) {
  11174. _names.fullscreenEnabled = name;
  11175. } else {
  11176. name = prefix + 'FullScreenEnabled';
  11177. if (document[name] !== undefined) {
  11178. _names.fullscreenEnabled = name;
  11179. }
  11180. }
  11181. // casing of Fullscreen differs across browsers
  11182. name = prefix + 'FullscreenElement';
  11183. if (document[name] !== undefined) {
  11184. _names.fullscreenElement = name;
  11185. } else {
  11186. name = prefix + 'FullScreenElement';
  11187. if (document[name] !== undefined) {
  11188. _names.fullscreenElement = name;
  11189. }
  11190. }
  11191. // thankfully, event names are all lowercase per spec
  11192. name = prefix + 'fullscreenchange';
  11193. // event names do not have 'on' in the front, but the property on the document does
  11194. if (document['on' + name] !== undefined) {
  11195. //except on IE
  11196. if (prefix === 'ms') {
  11197. name = 'MSFullscreenChange';
  11198. }
  11199. _names.fullscreenchange = name;
  11200. }
  11201. name = prefix + 'fullscreenerror';
  11202. if (document['on' + name] !== undefined) {
  11203. //except on IE
  11204. if (prefix === 'ms') {
  11205. name = 'MSFullscreenError';
  11206. }
  11207. _names.fullscreenerror = name;
  11208. }
  11209. }
  11210. return _supportsFullscreen;
  11211. };
  11212. /**
  11213. * Asynchronously requests the browser to enter fullscreen mode on the given element.
  11214. * If fullscreen mode is not supported by the browser, does nothing.
  11215. *
  11216. * @param {Object} element The HTML element which will be placed into fullscreen mode.
  11217. * @param {HMDVRDevice} [vrDevice] The VR device.
  11218. *
  11219. * @example
  11220. * // Put the entire page into fullscreen.
  11221. * Cesium.Fullscreen.requestFullscreen(document.body)
  11222. *
  11223. * // Place only the Cesium canvas into fullscreen.
  11224. * Cesium.Fullscreen.requestFullscreen(scene.canvas)
  11225. */
  11226. Fullscreen.requestFullscreen = function(element, vrDevice) {
  11227. if (!Fullscreen.supportsFullscreen()) {
  11228. return;
  11229. }
  11230. element[_names.requestFullscreen]({ vrDisplay: vrDevice });
  11231. };
  11232. /**
  11233. * Asynchronously exits fullscreen mode. If the browser is not currently
  11234. * in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
  11235. */
  11236. Fullscreen.exitFullscreen = function() {
  11237. if (!Fullscreen.supportsFullscreen()) {
  11238. return;
  11239. }
  11240. document[_names.exitFullscreen]();
  11241. };
  11242. return Fullscreen;
  11243. });
  11244. /*global define*/
  11245. define('Core/FeatureDetection',[
  11246. './defaultValue',
  11247. './defined',
  11248. './Fullscreen'
  11249. ], function(
  11250. defaultValue,
  11251. defined,
  11252. Fullscreen) {
  11253. 'use strict';
  11254. var theNavigator;
  11255. if (typeof navigator !== 'undefined') {
  11256. theNavigator = navigator;
  11257. } else {
  11258. theNavigator = {};
  11259. }
  11260. function extractVersion(versionString) {
  11261. var parts = versionString.split('.');
  11262. for (var i = 0, len = parts.length; i < len; ++i) {
  11263. parts[i] = parseInt(parts[i], 10);
  11264. }
  11265. return parts;
  11266. }
  11267. var isChromeResult;
  11268. var chromeVersionResult;
  11269. function isChrome() {
  11270. if (!defined(isChromeResult)) {
  11271. isChromeResult = false;
  11272. // Edge contains Chrome in the user agent too
  11273. if (!isEdge()) {
  11274. var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11275. if (fields !== null) {
  11276. isChromeResult = true;
  11277. chromeVersionResult = extractVersion(fields[1]);
  11278. }
  11279. }
  11280. }
  11281. return isChromeResult;
  11282. }
  11283. function chromeVersion() {
  11284. return isChrome() && chromeVersionResult;
  11285. }
  11286. var isSafariResult;
  11287. var safariVersionResult;
  11288. function isSafari() {
  11289. if (!defined(isSafariResult)) {
  11290. isSafariResult = false;
  11291. // Chrome and Edge contain Safari in the user agent too
  11292. if (!isChrome() && !isEdge() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) {
  11293. var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11294. if (fields !== null) {
  11295. isSafariResult = true;
  11296. safariVersionResult = extractVersion(fields[1]);
  11297. }
  11298. }
  11299. }
  11300. return isSafariResult;
  11301. }
  11302. function safariVersion() {
  11303. return isSafari() && safariVersionResult;
  11304. }
  11305. var isWebkitResult;
  11306. var webkitVersionResult;
  11307. function isWebkit() {
  11308. if (!defined(isWebkitResult)) {
  11309. isWebkitResult = false;
  11310. var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent);
  11311. if (fields !== null) {
  11312. isWebkitResult = true;
  11313. webkitVersionResult = extractVersion(fields[1]);
  11314. webkitVersionResult.isNightly = !!fields[2];
  11315. }
  11316. }
  11317. return isWebkitResult;
  11318. }
  11319. function webkitVersion() {
  11320. return isWebkit() && webkitVersionResult;
  11321. }
  11322. var isInternetExplorerResult;
  11323. var internetExplorerVersionResult;
  11324. function isInternetExplorer() {
  11325. if (!defined(isInternetExplorerResult)) {
  11326. isInternetExplorerResult = false;
  11327. var fields;
  11328. if (theNavigator.appName === 'Microsoft Internet Explorer') {
  11329. fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  11330. if (fields !== null) {
  11331. isInternetExplorerResult = true;
  11332. internetExplorerVersionResult = extractVersion(fields[1]);
  11333. }
  11334. } else if (theNavigator.appName === 'Netscape') {
  11335. fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
  11336. if (fields !== null) {
  11337. isInternetExplorerResult = true;
  11338. internetExplorerVersionResult = extractVersion(fields[1]);
  11339. }
  11340. }
  11341. }
  11342. return isInternetExplorerResult;
  11343. }
  11344. function internetExplorerVersion() {
  11345. return isInternetExplorer() && internetExplorerVersionResult;
  11346. }
  11347. var isEdgeResult;
  11348. var edgeVersionResult;
  11349. function isEdge() {
  11350. if (!defined(isEdgeResult)) {
  11351. isEdgeResult = false;
  11352. var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent);
  11353. if (fields !== null) {
  11354. isEdgeResult = true;
  11355. edgeVersionResult = extractVersion(fields[1]);
  11356. }
  11357. }
  11358. return isEdgeResult;
  11359. }
  11360. function edgeVersion() {
  11361. return isEdge() && edgeVersionResult;
  11362. }
  11363. var isFirefoxResult;
  11364. var firefoxVersionResult;
  11365. function isFirefox() {
  11366. if (!defined(isFirefoxResult)) {
  11367. isFirefoxResult = false;
  11368. var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
  11369. if (fields !== null) {
  11370. isFirefoxResult = true;
  11371. firefoxVersionResult = extractVersion(fields[1]);
  11372. }
  11373. }
  11374. return isFirefoxResult;
  11375. }
  11376. var isWindowsResult;
  11377. function isWindows() {
  11378. if (!defined(isWindowsResult)) {
  11379. isWindowsResult = /Windows/i.test(theNavigator.appVersion);
  11380. }
  11381. return isWindowsResult;
  11382. }
  11383. function firefoxVersion() {
  11384. return isFirefox() && firefoxVersionResult;
  11385. }
  11386. var hasPointerEvents;
  11387. function supportsPointerEvents() {
  11388. if (!defined(hasPointerEvents)) {
  11389. //While navigator.pointerEnabled is deprecated in the W3C specification
  11390. //we still need to use it if it exists in order to support browsers
  11391. //that rely on it, such as the Windows WebBrowser control which defines
  11392. //PointerEvent but sets navigator.pointerEnabled to false.
  11393. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
  11394. }
  11395. return hasPointerEvents;
  11396. }
  11397. var imageRenderingValueResult;
  11398. var supportsImageRenderingPixelatedResult;
  11399. function supportsImageRenderingPixelated() {
  11400. if (!defined(supportsImageRenderingPixelatedResult)) {
  11401. var canvas = document.createElement('canvas');
  11402. canvas.setAttribute('style',
  11403. 'image-rendering: -moz-crisp-edges;' +
  11404. 'image-rendering: pixelated;');
  11405. //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
  11406. var tmp = canvas.style.imageRendering;
  11407. supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== '';
  11408. if (supportsImageRenderingPixelatedResult) {
  11409. imageRenderingValueResult = tmp;
  11410. }
  11411. }
  11412. return supportsImageRenderingPixelatedResult;
  11413. }
  11414. function imageRenderingValue() {
  11415. return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined;
  11416. }
  11417. /**
  11418. * A set of functions to detect whether the current browser supports
  11419. * various features.
  11420. *
  11421. * @exports FeatureDetection
  11422. */
  11423. var FeatureDetection = {
  11424. isChrome : isChrome,
  11425. chromeVersion : chromeVersion,
  11426. isSafari : isSafari,
  11427. safariVersion : safariVersion,
  11428. isWebkit : isWebkit,
  11429. webkitVersion : webkitVersion,
  11430. isInternetExplorer : isInternetExplorer,
  11431. internetExplorerVersion : internetExplorerVersion,
  11432. isEdge : isEdge,
  11433. edgeVersion : edgeVersion,
  11434. isFirefox : isFirefox,
  11435. firefoxVersion : firefoxVersion,
  11436. isWindows : isWindows,
  11437. hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3),
  11438. supportsPointerEvents : supportsPointerEvents,
  11439. supportsImageRenderingPixelated: supportsImageRenderingPixelated,
  11440. imageRenderingValue: imageRenderingValue
  11441. };
  11442. /**
  11443. * Detects whether the current browser supports the full screen standard.
  11444. *
  11445. * @returns {Boolean} true if the browser supports the full screen standard, false if not.
  11446. *
  11447. * @see Fullscreen
  11448. * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
  11449. */
  11450. FeatureDetection.supportsFullscreen = function() {
  11451. return Fullscreen.supportsFullscreen();
  11452. };
  11453. /**
  11454. * Detects whether the current browser supports typed arrays.
  11455. *
  11456. * @returns {Boolean} true if the browser supports typed arrays, false if not.
  11457. *
  11458. * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification}
  11459. */
  11460. FeatureDetection.supportsTypedArrays = function() {
  11461. return typeof ArrayBuffer !== 'undefined';
  11462. };
  11463. /**
  11464. * Detects whether the current browser supports Web Workers.
  11465. *
  11466. * @returns {Boolean} true if the browsers supports Web Workers, false if not.
  11467. *
  11468. * @see {@link http://www.w3.org/TR/workers/}
  11469. */
  11470. FeatureDetection.supportsWebWorkers = function() {
  11471. return typeof Worker !== 'undefined';
  11472. };
  11473. return FeatureDetection;
  11474. });
  11475. /*global define*/
  11476. define('Core/WebGLConstants',[
  11477. './freezeObject'
  11478. ], function(
  11479. freezeObject) {
  11480. 'use strict';
  11481. /**
  11482. * Enum containing WebGL Constant values by name.
  11483. * for use without an active WebGL context, or in cases where certain constants are unavailable using the WebGL context
  11484. * (For example, in [Safari 9]{@link https://github.com/AnalyticalGraphicsInc/cesium/issues/2989}).
  11485. *
  11486. * These match the constants from the [WebGL 1.0]{@link https://www.khronos.org/registry/webgl/specs/latest/1.0/}
  11487. * and [WebGL 2.0]{@link https://www.khronos.org/registry/webgl/specs/latest/2.0/}
  11488. * specifications.
  11489. *
  11490. * @exports WebGLConstants
  11491. */
  11492. var WebGLConstants = {
  11493. DEPTH_BUFFER_BIT : 0x00000100,
  11494. STENCIL_BUFFER_BIT : 0x00000400,
  11495. COLOR_BUFFER_BIT : 0x00004000,
  11496. POINTS : 0x0000,
  11497. LINES : 0x0001,
  11498. LINE_LOOP : 0x0002,
  11499. LINE_STRIP : 0x0003,
  11500. TRIANGLES : 0x0004,
  11501. TRIANGLE_STRIP : 0x0005,
  11502. TRIANGLE_FAN : 0x0006,
  11503. ZERO : 0,
  11504. ONE : 1,
  11505. SRC_COLOR : 0x0300,
  11506. ONE_MINUS_SRC_COLOR : 0x0301,
  11507. SRC_ALPHA : 0x0302,
  11508. ONE_MINUS_SRC_ALPHA : 0x0303,
  11509. DST_ALPHA : 0x0304,
  11510. ONE_MINUS_DST_ALPHA : 0x0305,
  11511. DST_COLOR : 0x0306,
  11512. ONE_MINUS_DST_COLOR : 0x0307,
  11513. SRC_ALPHA_SATURATE : 0x0308,
  11514. FUNC_ADD : 0x8006,
  11515. BLEND_EQUATION : 0x8009,
  11516. BLEND_EQUATION_RGB : 0x8009, // same as BLEND_EQUATION
  11517. BLEND_EQUATION_ALPHA : 0x883D,
  11518. FUNC_SUBTRACT : 0x800A,
  11519. FUNC_REVERSE_SUBTRACT : 0x800B,
  11520. BLEND_DST_RGB : 0x80C8,
  11521. BLEND_SRC_RGB : 0x80C9,
  11522. BLEND_DST_ALPHA : 0x80CA,
  11523. BLEND_SRC_ALPHA : 0x80CB,
  11524. CONSTANT_COLOR : 0x8001,
  11525. ONE_MINUS_CONSTANT_COLOR : 0x8002,
  11526. CONSTANT_ALPHA : 0x8003,
  11527. ONE_MINUS_CONSTANT_ALPHA : 0x8004,
  11528. BLEND_COLOR : 0x8005,
  11529. ARRAY_BUFFER : 0x8892,
  11530. ELEMENT_ARRAY_BUFFER : 0x8893,
  11531. ARRAY_BUFFER_BINDING : 0x8894,
  11532. ELEMENT_ARRAY_BUFFER_BINDING : 0x8895,
  11533. STREAM_DRAW : 0x88E0,
  11534. STATIC_DRAW : 0x88E4,
  11535. DYNAMIC_DRAW : 0x88E8,
  11536. BUFFER_SIZE : 0x8764,
  11537. BUFFER_USAGE : 0x8765,
  11538. CURRENT_VERTEX_ATTRIB : 0x8626,
  11539. FRONT : 0x0404,
  11540. BACK : 0x0405,
  11541. FRONT_AND_BACK : 0x0408,
  11542. CULL_FACE : 0x0B44,
  11543. BLEND : 0x0BE2,
  11544. DITHER : 0x0BD0,
  11545. STENCIL_TEST : 0x0B90,
  11546. DEPTH_TEST : 0x0B71,
  11547. SCISSOR_TEST : 0x0C11,
  11548. POLYGON_OFFSET_FILL : 0x8037,
  11549. SAMPLE_ALPHA_TO_COVERAGE : 0x809E,
  11550. SAMPLE_COVERAGE : 0x80A0,
  11551. NO_ERROR : 0,
  11552. INVALID_ENUM : 0x0500,
  11553. INVALID_VALUE : 0x0501,
  11554. INVALID_OPERATION : 0x0502,
  11555. OUT_OF_MEMORY : 0x0505,
  11556. CW : 0x0900,
  11557. CCW : 0x0901,
  11558. LINE_WIDTH : 0x0B21,
  11559. ALIASED_POINT_SIZE_RANGE : 0x846D,
  11560. ALIASED_LINE_WIDTH_RANGE : 0x846E,
  11561. CULL_FACE_MODE : 0x0B45,
  11562. FRONT_FACE : 0x0B46,
  11563. DEPTH_RANGE : 0x0B70,
  11564. DEPTH_WRITEMASK : 0x0B72,
  11565. DEPTH_CLEAR_VALUE : 0x0B73,
  11566. DEPTH_FUNC : 0x0B74,
  11567. STENCIL_CLEAR_VALUE : 0x0B91,
  11568. STENCIL_FUNC : 0x0B92,
  11569. STENCIL_FAIL : 0x0B94,
  11570. STENCIL_PASS_DEPTH_FAIL : 0x0B95,
  11571. STENCIL_PASS_DEPTH_PASS : 0x0B96,
  11572. STENCIL_REF : 0x0B97,
  11573. STENCIL_VALUE_MASK : 0x0B93,
  11574. STENCIL_WRITEMASK : 0x0B98,
  11575. STENCIL_BACK_FUNC : 0x8800,
  11576. STENCIL_BACK_FAIL : 0x8801,
  11577. STENCIL_BACK_PASS_DEPTH_FAIL : 0x8802,
  11578. STENCIL_BACK_PASS_DEPTH_PASS : 0x8803,
  11579. STENCIL_BACK_REF : 0x8CA3,
  11580. STENCIL_BACK_VALUE_MASK : 0x8CA4,
  11581. STENCIL_BACK_WRITEMASK : 0x8CA5,
  11582. VIEWPORT : 0x0BA2,
  11583. SCISSOR_BOX : 0x0C10,
  11584. COLOR_CLEAR_VALUE : 0x0C22,
  11585. COLOR_WRITEMASK : 0x0C23,
  11586. UNPACK_ALIGNMENT : 0x0CF5,
  11587. PACK_ALIGNMENT : 0x0D05,
  11588. MAX_TEXTURE_SIZE : 0x0D33,
  11589. MAX_VIEWPORT_DIMS : 0x0D3A,
  11590. SUBPIXEL_BITS : 0x0D50,
  11591. RED_BITS : 0x0D52,
  11592. GREEN_BITS : 0x0D53,
  11593. BLUE_BITS : 0x0D54,
  11594. ALPHA_BITS : 0x0D55,
  11595. DEPTH_BITS : 0x0D56,
  11596. STENCIL_BITS : 0x0D57,
  11597. POLYGON_OFFSET_UNITS : 0x2A00,
  11598. POLYGON_OFFSET_FACTOR : 0x8038,
  11599. TEXTURE_BINDING_2D : 0x8069,
  11600. SAMPLE_BUFFERS : 0x80A8,
  11601. SAMPLES : 0x80A9,
  11602. SAMPLE_COVERAGE_VALUE : 0x80AA,
  11603. SAMPLE_COVERAGE_INVERT : 0x80AB,
  11604. COMPRESSED_TEXTURE_FORMATS : 0x86A3,
  11605. DONT_CARE : 0x1100,
  11606. FASTEST : 0x1101,
  11607. NICEST : 0x1102,
  11608. GENERATE_MIPMAP_HINT : 0x8192,
  11609. BYTE : 0x1400,
  11610. UNSIGNED_BYTE : 0x1401,
  11611. SHORT : 0x1402,
  11612. UNSIGNED_SHORT : 0x1403,
  11613. INT : 0x1404,
  11614. UNSIGNED_INT : 0x1405,
  11615. FLOAT : 0x1406,
  11616. DEPTH_COMPONENT : 0x1902,
  11617. ALPHA : 0x1906,
  11618. RGB : 0x1907,
  11619. RGBA : 0x1908,
  11620. LUMINANCE : 0x1909,
  11621. LUMINANCE_ALPHA : 0x190A,
  11622. UNSIGNED_SHORT_4_4_4_4 : 0x8033,
  11623. UNSIGNED_SHORT_5_5_5_1 : 0x8034,
  11624. UNSIGNED_SHORT_5_6_5 : 0x8363,
  11625. FRAGMENT_SHADER : 0x8B30,
  11626. VERTEX_SHADER : 0x8B31,
  11627. MAX_VERTEX_ATTRIBS : 0x8869,
  11628. MAX_VERTEX_UNIFORM_VECTORS : 0x8DFB,
  11629. MAX_VARYING_VECTORS : 0x8DFC,
  11630. MAX_COMBINED_TEXTURE_IMAGE_UNITS : 0x8B4D,
  11631. MAX_VERTEX_TEXTURE_IMAGE_UNITS : 0x8B4C,
  11632. MAX_TEXTURE_IMAGE_UNITS : 0x8872,
  11633. MAX_FRAGMENT_UNIFORM_VECTORS : 0x8DFD,
  11634. SHADER_TYPE : 0x8B4F,
  11635. DELETE_STATUS : 0x8B80,
  11636. LINK_STATUS : 0x8B82,
  11637. VALIDATE_STATUS : 0x8B83,
  11638. ATTACHED_SHADERS : 0x8B85,
  11639. ACTIVE_UNIFORMS : 0x8B86,
  11640. ACTIVE_ATTRIBUTES : 0x8B89,
  11641. SHADING_LANGUAGE_VERSION : 0x8B8C,
  11642. CURRENT_PROGRAM : 0x8B8D,
  11643. NEVER : 0x0200,
  11644. LESS : 0x0201,
  11645. EQUAL : 0x0202,
  11646. LEQUAL : 0x0203,
  11647. GREATER : 0x0204,
  11648. NOTEQUAL : 0x0205,
  11649. GEQUAL : 0x0206,
  11650. ALWAYS : 0x0207,
  11651. KEEP : 0x1E00,
  11652. REPLACE : 0x1E01,
  11653. INCR : 0x1E02,
  11654. DECR : 0x1E03,
  11655. INVERT : 0x150A,
  11656. INCR_WRAP : 0x8507,
  11657. DECR_WRAP : 0x8508,
  11658. VENDOR : 0x1F00,
  11659. RENDERER : 0x1F01,
  11660. VERSION : 0x1F02,
  11661. NEAREST : 0x2600,
  11662. LINEAR : 0x2601,
  11663. NEAREST_MIPMAP_NEAREST : 0x2700,
  11664. LINEAR_MIPMAP_NEAREST : 0x2701,
  11665. NEAREST_MIPMAP_LINEAR : 0x2702,
  11666. LINEAR_MIPMAP_LINEAR : 0x2703,
  11667. TEXTURE_MAG_FILTER : 0x2800,
  11668. TEXTURE_MIN_FILTER : 0x2801,
  11669. TEXTURE_WRAP_S : 0x2802,
  11670. TEXTURE_WRAP_T : 0x2803,
  11671. TEXTURE_2D : 0x0DE1,
  11672. TEXTURE : 0x1702,
  11673. TEXTURE_CUBE_MAP : 0x8513,
  11674. TEXTURE_BINDING_CUBE_MAP : 0x8514,
  11675. TEXTURE_CUBE_MAP_POSITIVE_X : 0x8515,
  11676. TEXTURE_CUBE_MAP_NEGATIVE_X : 0x8516,
  11677. TEXTURE_CUBE_MAP_POSITIVE_Y : 0x8517,
  11678. TEXTURE_CUBE_MAP_NEGATIVE_Y : 0x8518,
  11679. TEXTURE_CUBE_MAP_POSITIVE_Z : 0x8519,
  11680. TEXTURE_CUBE_MAP_NEGATIVE_Z : 0x851A,
  11681. MAX_CUBE_MAP_TEXTURE_SIZE : 0x851C,
  11682. TEXTURE0 : 0x84C0,
  11683. TEXTURE1 : 0x84C1,
  11684. TEXTURE2 : 0x84C2,
  11685. TEXTURE3 : 0x84C3,
  11686. TEXTURE4 : 0x84C4,
  11687. TEXTURE5 : 0x84C5,
  11688. TEXTURE6 : 0x84C6,
  11689. TEXTURE7 : 0x84C7,
  11690. TEXTURE8 : 0x84C8,
  11691. TEXTURE9 : 0x84C9,
  11692. TEXTURE10 : 0x84CA,
  11693. TEXTURE11 : 0x84CB,
  11694. TEXTURE12 : 0x84CC,
  11695. TEXTURE13 : 0x84CD,
  11696. TEXTURE14 : 0x84CE,
  11697. TEXTURE15 : 0x84CF,
  11698. TEXTURE16 : 0x84D0,
  11699. TEXTURE17 : 0x84D1,
  11700. TEXTURE18 : 0x84D2,
  11701. TEXTURE19 : 0x84D3,
  11702. TEXTURE20 : 0x84D4,
  11703. TEXTURE21 : 0x84D5,
  11704. TEXTURE22 : 0x84D6,
  11705. TEXTURE23 : 0x84D7,
  11706. TEXTURE24 : 0x84D8,
  11707. TEXTURE25 : 0x84D9,
  11708. TEXTURE26 : 0x84DA,
  11709. TEXTURE27 : 0x84DB,
  11710. TEXTURE28 : 0x84DC,
  11711. TEXTURE29 : 0x84DD,
  11712. TEXTURE30 : 0x84DE,
  11713. TEXTURE31 : 0x84DF,
  11714. ACTIVE_TEXTURE : 0x84E0,
  11715. REPEAT : 0x2901,
  11716. CLAMP_TO_EDGE : 0x812F,
  11717. MIRRORED_REPEAT : 0x8370,
  11718. FLOAT_VEC2 : 0x8B50,
  11719. FLOAT_VEC3 : 0x8B51,
  11720. FLOAT_VEC4 : 0x8B52,
  11721. INT_VEC2 : 0x8B53,
  11722. INT_VEC3 : 0x8B54,
  11723. INT_VEC4 : 0x8B55,
  11724. BOOL : 0x8B56,
  11725. BOOL_VEC2 : 0x8B57,
  11726. BOOL_VEC3 : 0x8B58,
  11727. BOOL_VEC4 : 0x8B59,
  11728. FLOAT_MAT2 : 0x8B5A,
  11729. FLOAT_MAT3 : 0x8B5B,
  11730. FLOAT_MAT4 : 0x8B5C,
  11731. SAMPLER_2D : 0x8B5E,
  11732. SAMPLER_CUBE : 0x8B60,
  11733. VERTEX_ATTRIB_ARRAY_ENABLED : 0x8622,
  11734. VERTEX_ATTRIB_ARRAY_SIZE : 0x8623,
  11735. VERTEX_ATTRIB_ARRAY_STRIDE : 0x8624,
  11736. VERTEX_ATTRIB_ARRAY_TYPE : 0x8625,
  11737. VERTEX_ATTRIB_ARRAY_NORMALIZED : 0x886A,
  11738. VERTEX_ATTRIB_ARRAY_POINTER : 0x8645,
  11739. VERTEX_ATTRIB_ARRAY_BUFFER_BINDING : 0x889F,
  11740. IMPLEMENTATION_COLOR_READ_TYPE : 0x8B9A,
  11741. IMPLEMENTATION_COLOR_READ_FORMAT : 0x8B9B,
  11742. COMPILE_STATUS : 0x8B81,
  11743. LOW_FLOAT : 0x8DF0,
  11744. MEDIUM_FLOAT : 0x8DF1,
  11745. HIGH_FLOAT : 0x8DF2,
  11746. LOW_INT : 0x8DF3,
  11747. MEDIUM_INT : 0x8DF4,
  11748. HIGH_INT : 0x8DF5,
  11749. FRAMEBUFFER : 0x8D40,
  11750. RENDERBUFFER : 0x8D41,
  11751. RGBA4 : 0x8056,
  11752. RGB5_A1 : 0x8057,
  11753. RGB565 : 0x8D62,
  11754. DEPTH_COMPONENT16 : 0x81A5,
  11755. STENCIL_INDEX : 0x1901,
  11756. STENCIL_INDEX8 : 0x8D48,
  11757. DEPTH_STENCIL : 0x84F9,
  11758. RENDERBUFFER_WIDTH : 0x8D42,
  11759. RENDERBUFFER_HEIGHT : 0x8D43,
  11760. RENDERBUFFER_INTERNAL_FORMAT : 0x8D44,
  11761. RENDERBUFFER_RED_SIZE : 0x8D50,
  11762. RENDERBUFFER_GREEN_SIZE : 0x8D51,
  11763. RENDERBUFFER_BLUE_SIZE : 0x8D52,
  11764. RENDERBUFFER_ALPHA_SIZE : 0x8D53,
  11765. RENDERBUFFER_DEPTH_SIZE : 0x8D54,
  11766. RENDERBUFFER_STENCIL_SIZE : 0x8D55,
  11767. FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE : 0x8CD0,
  11768. FRAMEBUFFER_ATTACHMENT_OBJECT_NAME : 0x8CD1,
  11769. FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL : 0x8CD2,
  11770. FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE : 0x8CD3,
  11771. COLOR_ATTACHMENT0 : 0x8CE0,
  11772. DEPTH_ATTACHMENT : 0x8D00,
  11773. STENCIL_ATTACHMENT : 0x8D20,
  11774. DEPTH_STENCIL_ATTACHMENT : 0x821A,
  11775. NONE : 0,
  11776. FRAMEBUFFER_COMPLETE : 0x8CD5,
  11777. FRAMEBUFFER_INCOMPLETE_ATTACHMENT : 0x8CD6,
  11778. FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT : 0x8CD7,
  11779. FRAMEBUFFER_INCOMPLETE_DIMENSIONS : 0x8CD9,
  11780. FRAMEBUFFER_UNSUPPORTED : 0x8CDD,
  11781. FRAMEBUFFER_BINDING : 0x8CA6,
  11782. RENDERBUFFER_BINDING : 0x8CA7,
  11783. MAX_RENDERBUFFER_SIZE : 0x84E8,
  11784. INVALID_FRAMEBUFFER_OPERATION : 0x0506,
  11785. UNPACK_FLIP_Y_WEBGL : 0x9240,
  11786. UNPACK_PREMULTIPLY_ALPHA_WEBGL : 0x9241,
  11787. CONTEXT_LOST_WEBGL : 0x9242,
  11788. UNPACK_COLORSPACE_CONVERSION_WEBGL : 0x9243,
  11789. BROWSER_DEFAULT_WEBGL : 0x9244,
  11790. // Desktop OpenGL
  11791. DOUBLE : 0x140A,
  11792. // WebGL 2
  11793. READ_BUFFER : 0x0C02,
  11794. UNPACK_ROW_LENGTH : 0x0CF2,
  11795. UNPACK_SKIP_ROWS : 0x0CF3,
  11796. UNPACK_SKIP_PIXELS : 0x0CF4,
  11797. PACK_ROW_LENGTH : 0x0D02,
  11798. PACK_SKIP_ROWS : 0x0D03,
  11799. PACK_SKIP_PIXELS : 0x0D04,
  11800. COLOR : 0x1800,
  11801. DEPTH : 0x1801,
  11802. STENCIL : 0x1802,
  11803. RED : 0x1903,
  11804. RGB8 : 0x8051,
  11805. RGBA8 : 0x8058,
  11806. RGB10_A2 : 0x8059,
  11807. TEXTURE_BINDING_3D : 0x806A,
  11808. UNPACK_SKIP_IMAGES : 0x806D,
  11809. UNPACK_IMAGE_HEIGHT : 0x806E,
  11810. TEXTURE_3D : 0x806F,
  11811. TEXTURE_WRAP_R : 0x8072,
  11812. MAX_3D_TEXTURE_SIZE : 0x8073,
  11813. UNSIGNED_INT_2_10_10_10_REV : 0x8368,
  11814. MAX_ELEMENTS_VERTICES : 0x80E8,
  11815. MAX_ELEMENTS_INDICES : 0x80E9,
  11816. TEXTURE_MIN_LOD : 0x813A,
  11817. TEXTURE_MAX_LOD : 0x813B,
  11818. TEXTURE_BASE_LEVEL : 0x813C,
  11819. TEXTURE_MAX_LEVEL : 0x813D,
  11820. MIN : 0x8007,
  11821. MAX : 0x8008,
  11822. DEPTH_COMPONENT24 : 0x81A6,
  11823. MAX_TEXTURE_LOD_BIAS : 0x84FD,
  11824. TEXTURE_COMPARE_MODE : 0x884C,
  11825. TEXTURE_COMPARE_FUNC : 0x884D,
  11826. CURRENT_QUERY : 0x8865,
  11827. QUERY_RESULT : 0x8866,
  11828. QUERY_RESULT_AVAILABLE : 0x8867,
  11829. STREAM_READ : 0x88E1,
  11830. STREAM_COPY : 0x88E2,
  11831. STATIC_READ : 0x88E5,
  11832. STATIC_COPY : 0x88E6,
  11833. DYNAMIC_READ : 0x88E9,
  11834. DYNAMIC_COPY : 0x88EA,
  11835. MAX_DRAW_BUFFERS : 0x8824,
  11836. DRAW_BUFFER0 : 0x8825,
  11837. DRAW_BUFFER1 : 0x8826,
  11838. DRAW_BUFFER2 : 0x8827,
  11839. DRAW_BUFFER3 : 0x8828,
  11840. DRAW_BUFFER4 : 0x8829,
  11841. DRAW_BUFFER5 : 0x882A,
  11842. DRAW_BUFFER6 : 0x882B,
  11843. DRAW_BUFFER7 : 0x882C,
  11844. DRAW_BUFFER8 : 0x882D,
  11845. DRAW_BUFFER9 : 0x882E,
  11846. DRAW_BUFFER10 : 0x882F,
  11847. DRAW_BUFFER11 : 0x8830,
  11848. DRAW_BUFFER12 : 0x8831,
  11849. DRAW_BUFFER13 : 0x8832,
  11850. DRAW_BUFFER14 : 0x8833,
  11851. DRAW_BUFFER15 : 0x8834,
  11852. MAX_FRAGMENT_UNIFORM_COMPONENTS : 0x8B49,
  11853. MAX_VERTEX_UNIFORM_COMPONENTS : 0x8B4A,
  11854. SAMPLER_3D : 0x8B5F,
  11855. SAMPLER_2D_SHADOW : 0x8B62,
  11856. FRAGMENT_SHADER_DERIVATIVE_HINT : 0x8B8B,
  11857. PIXEL_PACK_BUFFER : 0x88EB,
  11858. PIXEL_UNPACK_BUFFER : 0x88EC,
  11859. PIXEL_PACK_BUFFER_BINDING : 0x88ED,
  11860. PIXEL_UNPACK_BUFFER_BINDING : 0x88EF,
  11861. FLOAT_MAT2x3 : 0x8B65,
  11862. FLOAT_MAT2x4 : 0x8B66,
  11863. FLOAT_MAT3x2 : 0x8B67,
  11864. FLOAT_MAT3x4 : 0x8B68,
  11865. FLOAT_MAT4x2 : 0x8B69,
  11866. FLOAT_MAT4x3 : 0x8B6A,
  11867. SRGB : 0x8C40,
  11868. SRGB8 : 0x8C41,
  11869. SRGB8_ALPHA8 : 0x8C43,
  11870. COMPARE_REF_TO_TEXTURE : 0x884E,
  11871. RGBA32F : 0x8814,
  11872. RGB32F : 0x8815,
  11873. RGBA16F : 0x881A,
  11874. RGB16F : 0x881B,
  11875. VERTEX_ATTRIB_ARRAY_INTEGER : 0x88FD,
  11876. MAX_ARRAY_TEXTURE_LAYERS : 0x88FF,
  11877. MIN_PROGRAM_TEXEL_OFFSET : 0x8904,
  11878. MAX_PROGRAM_TEXEL_OFFSET : 0x8905,
  11879. MAX_VARYING_COMPONENTS : 0x8B4B,
  11880. TEXTURE_2D_ARRAY : 0x8C1A,
  11881. TEXTURE_BINDING_2D_ARRAY : 0x8C1D,
  11882. R11F_G11F_B10F : 0x8C3A,
  11883. UNSIGNED_INT_10F_11F_11F_REV : 0x8C3B,
  11884. RGB9_E5 : 0x8C3D,
  11885. UNSIGNED_INT_5_9_9_9_REV : 0x8C3E,
  11886. TRANSFORM_FEEDBACK_BUFFER_MODE : 0x8C7F,
  11887. MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS : 0x8C80,
  11888. TRANSFORM_FEEDBACK_VARYINGS : 0x8C83,
  11889. TRANSFORM_FEEDBACK_BUFFER_START : 0x8C84,
  11890. TRANSFORM_FEEDBACK_BUFFER_SIZE : 0x8C85,
  11891. TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN : 0x8C88,
  11892. RASTERIZER_DISCARD : 0x8C89,
  11893. MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS : 0x8C8A,
  11894. MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS : 0x8C8B,
  11895. INTERLEAVED_ATTRIBS : 0x8C8C,
  11896. SEPARATE_ATTRIBS : 0x8C8D,
  11897. TRANSFORM_FEEDBACK_BUFFER : 0x8C8E,
  11898. TRANSFORM_FEEDBACK_BUFFER_BINDING : 0x8C8F,
  11899. RGBA32UI : 0x8D70,
  11900. RGB32UI : 0x8D71,
  11901. RGBA16UI : 0x8D76,
  11902. RGB16UI : 0x8D77,
  11903. RGBA8UI : 0x8D7C,
  11904. RGB8UI : 0x8D7D,
  11905. RGBA32I : 0x8D82,
  11906. RGB32I : 0x8D83,
  11907. RGBA16I : 0x8D88,
  11908. RGB16I : 0x8D89,
  11909. RGBA8I : 0x8D8E,
  11910. RGB8I : 0x8D8F,
  11911. RED_INTEGER : 0x8D94,
  11912. RGB_INTEGER : 0x8D98,
  11913. RGBA_INTEGER : 0x8D99,
  11914. SAMPLER_2D_ARRAY : 0x8DC1,
  11915. SAMPLER_2D_ARRAY_SHADOW : 0x8DC4,
  11916. SAMPLER_CUBE_SHADOW : 0x8DC5,
  11917. UNSIGNED_INT_VEC2 : 0x8DC6,
  11918. UNSIGNED_INT_VEC3 : 0x8DC7,
  11919. UNSIGNED_INT_VEC4 : 0x8DC8,
  11920. INT_SAMPLER_2D : 0x8DCA,
  11921. INT_SAMPLER_3D : 0x8DCB,
  11922. INT_SAMPLER_CUBE : 0x8DCC,
  11923. INT_SAMPLER_2D_ARRAY : 0x8DCF,
  11924. UNSIGNED_INT_SAMPLER_2D : 0x8DD2,
  11925. UNSIGNED_INT_SAMPLER_3D : 0x8DD3,
  11926. UNSIGNED_INT_SAMPLER_CUBE : 0x8DD4,
  11927. UNSIGNED_INT_SAMPLER_2D_ARRAY : 0x8DD7,
  11928. DEPTH_COMPONENT32F : 0x8CAC,
  11929. DEPTH32F_STENCIL8 : 0x8CAD,
  11930. FLOAT_32_UNSIGNED_INT_24_8_REV : 0x8DAD,
  11931. FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING : 0x8210,
  11932. FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE : 0x8211,
  11933. FRAMEBUFFER_ATTACHMENT_RED_SIZE : 0x8212,
  11934. FRAMEBUFFER_ATTACHMENT_GREEN_SIZE : 0x8213,
  11935. FRAMEBUFFER_ATTACHMENT_BLUE_SIZE : 0x8214,
  11936. FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE : 0x8215,
  11937. FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE : 0x8216,
  11938. FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE : 0x8217,
  11939. FRAMEBUFFER_DEFAULT : 0x8218,
  11940. UNSIGNED_INT_24_8 : 0x84FA,
  11941. DEPTH24_STENCIL8 : 0x88F0,
  11942. UNSIGNED_NORMALIZED : 0x8C17,
  11943. DRAW_FRAMEBUFFER_BINDING : 0x8CA6, // Same as FRAMEBUFFER_BINDING
  11944. READ_FRAMEBUFFER : 0x8CA8,
  11945. DRAW_FRAMEBUFFER : 0x8CA9,
  11946. READ_FRAMEBUFFER_BINDING : 0x8CAA,
  11947. RENDERBUFFER_SAMPLES : 0x8CAB,
  11948. FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER : 0x8CD4,
  11949. MAX_COLOR_ATTACHMENTS : 0x8CDF,
  11950. COLOR_ATTACHMENT1 : 0x8CE1,
  11951. COLOR_ATTACHMENT2 : 0x8CE2,
  11952. COLOR_ATTACHMENT3 : 0x8CE3,
  11953. COLOR_ATTACHMENT4 : 0x8CE4,
  11954. COLOR_ATTACHMENT5 : 0x8CE5,
  11955. COLOR_ATTACHMENT6 : 0x8CE6,
  11956. COLOR_ATTACHMENT7 : 0x8CE7,
  11957. COLOR_ATTACHMENT8 : 0x8CE8,
  11958. COLOR_ATTACHMENT9 : 0x8CE9,
  11959. COLOR_ATTACHMENT10 : 0x8CEA,
  11960. COLOR_ATTACHMENT11 : 0x8CEB,
  11961. COLOR_ATTACHMENT12 : 0x8CEC,
  11962. COLOR_ATTACHMENT13 : 0x8CED,
  11963. COLOR_ATTACHMENT14 : 0x8CEE,
  11964. COLOR_ATTACHMENT15 : 0x8CEF,
  11965. FRAMEBUFFER_INCOMPLETE_MULTISAMPLE : 0x8D56,
  11966. MAX_SAMPLES : 0x8D57,
  11967. HALF_FLOAT : 0x140B,
  11968. RG : 0x8227,
  11969. RG_INTEGER : 0x8228,
  11970. R8 : 0x8229,
  11971. RG8 : 0x822B,
  11972. R16F : 0x822D,
  11973. R32F : 0x822E,
  11974. RG16F : 0x822F,
  11975. RG32F : 0x8230,
  11976. R8I : 0x8231,
  11977. R8UI : 0x8232,
  11978. R16I : 0x8233,
  11979. R16UI : 0x8234,
  11980. R32I : 0x8235,
  11981. R32UI : 0x8236,
  11982. RG8I : 0x8237,
  11983. RG8UI : 0x8238,
  11984. RG16I : 0x8239,
  11985. RG16UI : 0x823A,
  11986. RG32I : 0x823B,
  11987. RG32UI : 0x823C,
  11988. VERTEX_ARRAY_BINDING : 0x85B5,
  11989. R8_SNORM : 0x8F94,
  11990. RG8_SNORM : 0x8F95,
  11991. RGB8_SNORM : 0x8F96,
  11992. RGBA8_SNORM : 0x8F97,
  11993. SIGNED_NORMALIZED : 0x8F9C,
  11994. COPY_READ_BUFFER : 0x8F36,
  11995. COPY_WRITE_BUFFER : 0x8F37,
  11996. COPY_READ_BUFFER_BINDING : 0x8F36, // Same as COPY_READ_BUFFER
  11997. COPY_WRITE_BUFFER_BINDING : 0x8F37, // Same as COPY_WRITE_BUFFER
  11998. UNIFORM_BUFFER : 0x8A11,
  11999. UNIFORM_BUFFER_BINDING : 0x8A28,
  12000. UNIFORM_BUFFER_START : 0x8A29,
  12001. UNIFORM_BUFFER_SIZE : 0x8A2A,
  12002. MAX_VERTEX_UNIFORM_BLOCKS : 0x8A2B,
  12003. MAX_FRAGMENT_UNIFORM_BLOCKS : 0x8A2D,
  12004. MAX_COMBINED_UNIFORM_BLOCKS : 0x8A2E,
  12005. MAX_UNIFORM_BUFFER_BINDINGS : 0x8A2F,
  12006. MAX_UNIFORM_BLOCK_SIZE : 0x8A30,
  12007. MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS : 0x8A31,
  12008. MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS : 0x8A33,
  12009. UNIFORM_BUFFER_OFFSET_ALIGNMENT : 0x8A34,
  12010. ACTIVE_UNIFORM_BLOCKS : 0x8A36,
  12011. UNIFORM_TYPE : 0x8A37,
  12012. UNIFORM_SIZE : 0x8A38,
  12013. UNIFORM_BLOCK_INDEX : 0x8A3A,
  12014. UNIFORM_OFFSET : 0x8A3B,
  12015. UNIFORM_ARRAY_STRIDE : 0x8A3C,
  12016. UNIFORM_MATRIX_STRIDE : 0x8A3D,
  12017. UNIFORM_IS_ROW_MAJOR : 0x8A3E,
  12018. UNIFORM_BLOCK_BINDING : 0x8A3F,
  12019. UNIFORM_BLOCK_DATA_SIZE : 0x8A40,
  12020. UNIFORM_BLOCK_ACTIVE_UNIFORMS : 0x8A42,
  12021. UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES : 0x8A43,
  12022. UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER : 0x8A44,
  12023. UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER : 0x8A46,
  12024. INVALID_INDEX : 0xFFFFFFFF,
  12025. MAX_VERTEX_OUTPUT_COMPONENTS : 0x9122,
  12026. MAX_FRAGMENT_INPUT_COMPONENTS : 0x9125,
  12027. MAX_SERVER_WAIT_TIMEOUT : 0x9111,
  12028. OBJECT_TYPE : 0x9112,
  12029. SYNC_CONDITION : 0x9113,
  12030. SYNC_STATUS : 0x9114,
  12031. SYNC_FLAGS : 0x9115,
  12032. SYNC_FENCE : 0x9116,
  12033. SYNC_GPU_COMMANDS_COMPLETE : 0x9117,
  12034. UNSIGNALED : 0x9118,
  12035. SIGNALED : 0x9119,
  12036. ALREADY_SIGNALED : 0x911A,
  12037. TIMEOUT_EXPIRED : 0x911B,
  12038. CONDITION_SATISFIED : 0x911C,
  12039. WAIT_FAILED : 0x911D,
  12040. SYNC_FLUSH_COMMANDS_BIT : 0x00000001,
  12041. VERTEX_ATTRIB_ARRAY_DIVISOR : 0x88FE,
  12042. ANY_SAMPLES_PASSED : 0x8C2F,
  12043. ANY_SAMPLES_PASSED_CONSERVATIVE : 0x8D6A,
  12044. SAMPLER_BINDING : 0x8919,
  12045. RGB10_A2UI : 0x906F,
  12046. INT_2_10_10_10_REV : 0x8D9F,
  12047. TRANSFORM_FEEDBACK : 0x8E22,
  12048. TRANSFORM_FEEDBACK_PAUSED : 0x8E23,
  12049. TRANSFORM_FEEDBACK_ACTIVE : 0x8E24,
  12050. TRANSFORM_FEEDBACK_BINDING : 0x8E25,
  12051. COMPRESSED_R11_EAC : 0x9270,
  12052. COMPRESSED_SIGNED_R11_EAC : 0x9271,
  12053. COMPRESSED_RG11_EAC : 0x9272,
  12054. COMPRESSED_SIGNED_RG11_EAC : 0x9273,
  12055. COMPRESSED_RGB8_ETC2 : 0x9274,
  12056. COMPRESSED_SRGB8_ETC2 : 0x9275,
  12057. COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9276,
  12058. COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 : 0x9277,
  12059. COMPRESSED_RGBA8_ETC2_EAC : 0x9278,
  12060. COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : 0x9279,
  12061. TEXTURE_IMMUTABLE_FORMAT : 0x912F,
  12062. MAX_ELEMENT_INDEX : 0x8D6B,
  12063. TEXTURE_IMMUTABLE_LEVELS : 0x82DF
  12064. };
  12065. return freezeObject(WebGLConstants);
  12066. });
  12067. /*global define*/
  12068. define('Core/ComponentDatatype',[
  12069. './defaultValue',
  12070. './defined',
  12071. './DeveloperError',
  12072. './FeatureDetection',
  12073. './freezeObject',
  12074. './WebGLConstants'
  12075. ], function(
  12076. defaultValue,
  12077. defined,
  12078. DeveloperError,
  12079. FeatureDetection,
  12080. freezeObject,
  12081. WebGLConstants) {
  12082. 'use strict';
  12083. // Bail out if the browser doesn't support typed arrays, to prevent the setup function
  12084. // from failing, since we won't be able to create a WebGL context anyway.
  12085. if (!FeatureDetection.supportsTypedArrays()) {
  12086. return {};
  12087. }
  12088. /**
  12089. * WebGL component datatypes. Components are intrinsics,
  12090. * which form attributes, which form vertices.
  12091. *
  12092. * @exports ComponentDatatype
  12093. */
  12094. var ComponentDatatype = {
  12095. /**
  12096. * 8-bit signed byte corresponding to <code>gl.BYTE</code> and the type
  12097. * of an element in <code>Int8Array</code>.
  12098. *
  12099. * @type {Number}
  12100. * @constant
  12101. */
  12102. BYTE : WebGLConstants.BYTE,
  12103. /**
  12104. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  12105. * of an element in <code>Uint8Array</code>.
  12106. *
  12107. * @type {Number}
  12108. * @constant
  12109. */
  12110. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  12111. /**
  12112. * 16-bit signed short corresponding to <code>SHORT</code> and the type
  12113. * of an element in <code>Int16Array</code>.
  12114. *
  12115. * @type {Number}
  12116. * @constant
  12117. */
  12118. SHORT : WebGLConstants.SHORT,
  12119. /**
  12120. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  12121. * of an element in <code>Uint16Array</code>.
  12122. *
  12123. * @type {Number}
  12124. * @constant
  12125. */
  12126. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  12127. /**
  12128. * 32-bit signed int corresponding to <code>INT</code> and the type
  12129. * of an element in <code>Int32Array</code>.
  12130. *
  12131. * @memberOf ComponentDatatype
  12132. *
  12133. * @type {Number}
  12134. * @constant
  12135. */
  12136. INT : WebGLConstants.INT,
  12137. /**
  12138. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  12139. * of an element in <code>Uint32Array</code>.
  12140. *
  12141. * @memberOf ComponentDatatype
  12142. *
  12143. * @type {Number}
  12144. * @constant
  12145. */
  12146. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT,
  12147. /**
  12148. * 32-bit floating-point corresponding to <code>FLOAT</code> and the type
  12149. * of an element in <code>Float32Array</code>.
  12150. *
  12151. * @type {Number}
  12152. * @constant
  12153. */
  12154. FLOAT : WebGLConstants.FLOAT,
  12155. /**
  12156. * 64-bit floating-point corresponding to <code>gl.DOUBLE</code> (in Desktop OpenGL;
  12157. * this is not supported in WebGL, and is emulated in Cesium via {@link GeometryPipeline.encodeAttribute})
  12158. * and the type of an element in <code>Float64Array</code>.
  12159. *
  12160. * @memberOf ComponentDatatype
  12161. *
  12162. * @type {Number}
  12163. * @constant
  12164. * @default 0x140A
  12165. */
  12166. DOUBLE : WebGLConstants.DOUBLE
  12167. };
  12168. /**
  12169. * Returns the size, in bytes, of the corresponding datatype.
  12170. *
  12171. * @param {ComponentDatatype} componentDatatype The component datatype to get the size of.
  12172. * @returns {Number} The size in bytes.
  12173. *
  12174. * @exception {DeveloperError} componentDatatype is not a valid value.
  12175. *
  12176. * @example
  12177. * // Returns Int8Array.BYTES_PER_ELEMENT
  12178. * var size = Cesium.ComponentDatatype.getSizeInBytes(Cesium.ComponentDatatype.BYTE);
  12179. */
  12180. ComponentDatatype.getSizeInBytes = function(componentDatatype){
  12181. if (!defined(componentDatatype)) {
  12182. throw new DeveloperError('value is required.');
  12183. }
  12184. switch (componentDatatype) {
  12185. case ComponentDatatype.BYTE:
  12186. return Int8Array.BYTES_PER_ELEMENT;
  12187. case ComponentDatatype.UNSIGNED_BYTE:
  12188. return Uint8Array.BYTES_PER_ELEMENT;
  12189. case ComponentDatatype.SHORT:
  12190. return Int16Array.BYTES_PER_ELEMENT;
  12191. case ComponentDatatype.UNSIGNED_SHORT:
  12192. return Uint16Array.BYTES_PER_ELEMENT;
  12193. case ComponentDatatype.INT:
  12194. return Int32Array.BYTES_PER_ELEMENT;
  12195. case ComponentDatatype.UNSIGNED_INT:
  12196. return Uint32Array.BYTES_PER_ELEMENT;
  12197. case ComponentDatatype.FLOAT:
  12198. return Float32Array.BYTES_PER_ELEMENT;
  12199. case ComponentDatatype.DOUBLE:
  12200. return Float64Array.BYTES_PER_ELEMENT;
  12201. default:
  12202. throw new DeveloperError('componentDatatype is not a valid value.');
  12203. }
  12204. };
  12205. /**
  12206. * Gets the {@link ComponentDatatype} for the provided TypedArray instance.
  12207. *
  12208. * @param {TypedArray} array The typed array.
  12209. * @returns {ComponentDatatype} The ComponentDatatype for the provided array, or undefined if the array is not a TypedArray.
  12210. */
  12211. ComponentDatatype.fromTypedArray = function(array) {
  12212. if (array instanceof Int8Array) {
  12213. return ComponentDatatype.BYTE;
  12214. }
  12215. if (array instanceof Uint8Array) {
  12216. return ComponentDatatype.UNSIGNED_BYTE;
  12217. }
  12218. if (array instanceof Int16Array) {
  12219. return ComponentDatatype.SHORT;
  12220. }
  12221. if (array instanceof Uint16Array) {
  12222. return ComponentDatatype.UNSIGNED_SHORT;
  12223. }
  12224. if (array instanceof Int32Array) {
  12225. return ComponentDatatype.INT;
  12226. }
  12227. if (array instanceof Uint32Array) {
  12228. return ComponentDatatype.UNSIGNED_INT;
  12229. }
  12230. if (array instanceof Float32Array) {
  12231. return ComponentDatatype.FLOAT;
  12232. }
  12233. if (array instanceof Float64Array) {
  12234. return ComponentDatatype.DOUBLE;
  12235. }
  12236. };
  12237. /**
  12238. * Validates that the provided component datatype is a valid {@link ComponentDatatype}
  12239. *
  12240. * @param {ComponentDatatype} componentDatatype The component datatype to validate.
  12241. * @returns {Boolean} <code>true</code> if the provided component datatype is a valid value; otherwise, <code>false</code>.
  12242. *
  12243. * @example
  12244. * if (!Cesium.ComponentDatatype.validate(componentDatatype)) {
  12245. * throw new Cesium.DeveloperError('componentDatatype must be a valid value.');
  12246. * }
  12247. */
  12248. ComponentDatatype.validate = function(componentDatatype) {
  12249. return defined(componentDatatype) &&
  12250. (componentDatatype === ComponentDatatype.BYTE ||
  12251. componentDatatype === ComponentDatatype.UNSIGNED_BYTE ||
  12252. componentDatatype === ComponentDatatype.SHORT ||
  12253. componentDatatype === ComponentDatatype.UNSIGNED_SHORT ||
  12254. componentDatatype === ComponentDatatype.INT ||
  12255. componentDatatype === ComponentDatatype.UNSIGNED_INT ||
  12256. componentDatatype === ComponentDatatype.FLOAT ||
  12257. componentDatatype === ComponentDatatype.DOUBLE);
  12258. };
  12259. /**
  12260. * Creates a typed array corresponding to component data type.
  12261. *
  12262. * @param {ComponentDatatype} componentDatatype The component data type.
  12263. * @param {Number|Array} valuesOrLength The length of the array to create or an array.
  12264. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array.
  12265. *
  12266. * @exception {DeveloperError} componentDatatype is not a valid value.
  12267. *
  12268. * @example
  12269. * // creates a Float32Array with length of 100
  12270. * var typedArray = Cesium.ComponentDatatype.createTypedArray(Cesium.ComponentDatatype.FLOAT, 100);
  12271. */
  12272. ComponentDatatype.createTypedArray = function(componentDatatype, valuesOrLength) {
  12273. if (!defined(componentDatatype)) {
  12274. throw new DeveloperError('componentDatatype is required.');
  12275. }
  12276. if (!defined(valuesOrLength)) {
  12277. throw new DeveloperError('valuesOrLength is required.');
  12278. }
  12279. switch (componentDatatype) {
  12280. case ComponentDatatype.BYTE:
  12281. return new Int8Array(valuesOrLength);
  12282. case ComponentDatatype.UNSIGNED_BYTE:
  12283. return new Uint8Array(valuesOrLength);
  12284. case ComponentDatatype.SHORT:
  12285. return new Int16Array(valuesOrLength);
  12286. case ComponentDatatype.UNSIGNED_SHORT:
  12287. return new Uint16Array(valuesOrLength);
  12288. case ComponentDatatype.INT:
  12289. return new Int32Array(valuesOrLength);
  12290. case ComponentDatatype.UNSIGNED_INT:
  12291. return new Uint32Array(valuesOrLength);
  12292. case ComponentDatatype.FLOAT:
  12293. return new Float32Array(valuesOrLength);
  12294. case ComponentDatatype.DOUBLE:
  12295. return new Float64Array(valuesOrLength);
  12296. default:
  12297. throw new DeveloperError('componentDatatype is not a valid value.');
  12298. }
  12299. };
  12300. /**
  12301. * Creates a typed view of an array of bytes.
  12302. *
  12303. * @param {ComponentDatatype} componentDatatype The type of the view to create.
  12304. * @param {ArrayBuffer} buffer The buffer storage to use for the view.
  12305. * @param {Number} [byteOffset] The offset, in bytes, to the first element in the view.
  12306. * @param {Number} [length] The number of elements in the view.
  12307. * @returns {Int8Array|Uint8Array|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} A typed array view of the buffer.
  12308. *
  12309. * @exception {DeveloperError} componentDatatype is not a valid value.
  12310. */
  12311. ComponentDatatype.createArrayBufferView = function(componentDatatype, buffer, byteOffset, length) {
  12312. if (!defined(componentDatatype)) {
  12313. throw new DeveloperError('componentDatatype is required.');
  12314. }
  12315. if (!defined(buffer)) {
  12316. throw new DeveloperError('buffer is required.');
  12317. }
  12318. byteOffset = defaultValue(byteOffset, 0);
  12319. length = defaultValue(length, (buffer.byteLength - byteOffset) / ComponentDatatype.getSizeInBytes(componentDatatype));
  12320. switch (componentDatatype) {
  12321. case ComponentDatatype.BYTE:
  12322. return new Int8Array(buffer, byteOffset, length);
  12323. case ComponentDatatype.UNSIGNED_BYTE:
  12324. return new Uint8Array(buffer, byteOffset, length);
  12325. case ComponentDatatype.SHORT:
  12326. return new Int16Array(buffer, byteOffset, length);
  12327. case ComponentDatatype.UNSIGNED_SHORT:
  12328. return new Uint16Array(buffer, byteOffset, length);
  12329. case ComponentDatatype.INT:
  12330. return new Int32Array(buffer, byteOffset, length);
  12331. case ComponentDatatype.UNSIGNED_INT:
  12332. return new Uint32Array(buffer, byteOffset, length);
  12333. case ComponentDatatype.FLOAT:
  12334. return new Float32Array(buffer, byteOffset, length);
  12335. case ComponentDatatype.DOUBLE:
  12336. return new Float64Array(buffer, byteOffset, length);
  12337. default:
  12338. throw new DeveloperError('componentDatatype is not a valid value.');
  12339. }
  12340. };
  12341. /**
  12342. * Get the ComponentDatatype from its name.
  12343. *
  12344. * @param {String} name The name of the ComponentDatatype.
  12345. * @returns {ComponentDatatype} The ComponentDatatype.
  12346. *
  12347. * @exception {DeveloperError} name is not a valid value.
  12348. */
  12349. ComponentDatatype.fromName = function(name) {
  12350. switch (name) {
  12351. case 'BYTE':
  12352. return ComponentDatatype.BYTE;
  12353. case 'UNSIGNED_BYTE':
  12354. return ComponentDatatype.UNSIGNED_BYTE;
  12355. case 'SHORT':
  12356. return ComponentDatatype.SHORT;
  12357. case 'UNSIGNED_SHORT':
  12358. return ComponentDatatype.UNSIGNED_SHORT;
  12359. case 'INT':
  12360. return ComponentDatatype.INT;
  12361. case 'UNSIGNED_INT':
  12362. return ComponentDatatype.UNSIGNED_INT;
  12363. case 'FLOAT':
  12364. return ComponentDatatype.FLOAT;
  12365. case 'DOUBLE':
  12366. return ComponentDatatype.DOUBLE;
  12367. default:
  12368. throw new DeveloperError('name is not a valid value.');
  12369. }
  12370. };
  12371. return freezeObject(ComponentDatatype);
  12372. });
  12373. /*global define*/
  12374. define('Core/CornerType',[
  12375. './freezeObject'
  12376. ], function(
  12377. freezeObject) {
  12378. 'use strict';
  12379. /**
  12380. * Style options for corners.
  12381. *
  12382. * @demo The {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Corridor.html&label=Geometries|Corridor Demo}
  12383. * demonstrates the three corner types, as used by {@link CorridorGraphics}.
  12384. *
  12385. * @exports CornerType
  12386. */
  12387. var CornerType = {
  12388. /**
  12389. * <img src="images/CornerTypeRounded.png" style="vertical-align: middle;" width="186" height="189" />
  12390. *
  12391. * Corner has a smooth edge.
  12392. * @type {Number}
  12393. * @constant
  12394. */
  12395. ROUNDED : 0,
  12396. /**
  12397. * <img src="images/CornerTypeMitered.png" style="vertical-align: middle;" width="186" height="189" />
  12398. *
  12399. * Corner point is the intersection of adjacent edges.
  12400. * @type {Number}
  12401. * @constant
  12402. */
  12403. MITERED : 1,
  12404. /**
  12405. * <img src="images/CornerTypeBeveled.png" style="vertical-align: middle;" width="186" height="189" />
  12406. *
  12407. * Corner is clipped.
  12408. * @type {Number}
  12409. * @constant
  12410. */
  12411. BEVELED : 2
  12412. };
  12413. return freezeObject(CornerType);
  12414. });
  12415. /*global define*/
  12416. define('Core/GeometryType',[
  12417. './freezeObject'
  12418. ], function(
  12419. freezeObject) {
  12420. 'use strict';
  12421. /**
  12422. * @private
  12423. */
  12424. var GeometryType = {
  12425. NONE : 0,
  12426. TRIANGLES : 1,
  12427. LINES : 2,
  12428. POLYLINES : 3
  12429. };
  12430. return freezeObject(GeometryType);
  12431. });
  12432. /*global define*/
  12433. define('Core/PrimitiveType',[
  12434. './freezeObject',
  12435. './WebGLConstants'
  12436. ], function(
  12437. freezeObject,
  12438. WebGLConstants) {
  12439. 'use strict';
  12440. /**
  12441. * The type of a geometric primitive, i.e., points, lines, and triangles.
  12442. *
  12443. * @exports PrimitiveType
  12444. */
  12445. var PrimitiveType = {
  12446. /**
  12447. * Points primitive where each vertex (or index) is a separate point.
  12448. *
  12449. * @type {Number}
  12450. * @constant
  12451. */
  12452. POINTS : WebGLConstants.POINTS,
  12453. /**
  12454. * Lines primitive where each two vertices (or indices) is a line segment. Line segments are not necessarily connected.
  12455. *
  12456. * @type {Number}
  12457. * @constant
  12458. */
  12459. LINES : WebGLConstants.LINES,
  12460. /**
  12461. * Line loop primitive where each vertex (or index) after the first connects a line to
  12462. * the previous vertex, and the last vertex implicitly connects to the first.
  12463. *
  12464. * @type {Number}
  12465. * @constant
  12466. */
  12467. LINE_LOOP : WebGLConstants.LINE_LOOP,
  12468. /**
  12469. * Line strip primitive where each vertex (or index) after the first connects a line to the previous vertex.
  12470. *
  12471. * @type {Number}
  12472. * @constant
  12473. */
  12474. LINE_STRIP : WebGLConstants.LINE_STRIP,
  12475. /**
  12476. * Triangles primitive where each three vertices (or indices) is a triangle. Triangles do not necessarily share edges.
  12477. *
  12478. * @type {Number}
  12479. * @constant
  12480. */
  12481. TRIANGLES : WebGLConstants.TRIANGLES,
  12482. /**
  12483. * Triangle strip primitive where each vertex (or index) after the first two connect to
  12484. * the previous two vertices forming a triangle. For example, this can be used to model a wall.
  12485. *
  12486. * @type {Number}
  12487. * @constant
  12488. */
  12489. TRIANGLE_STRIP : WebGLConstants.TRIANGLE_STRIP,
  12490. /**
  12491. * Triangle fan primitive where each vertex (or index) after the first two connect to
  12492. * the previous vertex and the first vertex forming a triangle. For example, this can be used
  12493. * to model a cone or circle.
  12494. *
  12495. * @type {Number}
  12496. * @constant
  12497. */
  12498. TRIANGLE_FAN : WebGLConstants.TRIANGLE_FAN,
  12499. /**
  12500. * @private
  12501. */
  12502. validate : function(primitiveType) {
  12503. return primitiveType === PrimitiveType.POINTS ||
  12504. primitiveType === PrimitiveType.LINES ||
  12505. primitiveType === PrimitiveType.LINE_LOOP ||
  12506. primitiveType === PrimitiveType.LINE_STRIP ||
  12507. primitiveType === PrimitiveType.TRIANGLES ||
  12508. primitiveType === PrimitiveType.TRIANGLE_STRIP ||
  12509. primitiveType === PrimitiveType.TRIANGLE_FAN;
  12510. }
  12511. };
  12512. return freezeObject(PrimitiveType);
  12513. });
  12514. /*global define*/
  12515. define('Core/Geometry',[
  12516. './defaultValue',
  12517. './defined',
  12518. './DeveloperError',
  12519. './GeometryType',
  12520. './PrimitiveType'
  12521. ], function(
  12522. defaultValue,
  12523. defined,
  12524. DeveloperError,
  12525. GeometryType,
  12526. PrimitiveType) {
  12527. 'use strict';
  12528. /**
  12529. * A geometry representation with attributes forming vertices and optional index data
  12530. * defining primitives. Geometries and an {@link Appearance}, which describes the shading,
  12531. * can be assigned to a {@link Primitive} for visualization. A <code>Primitive</code> can
  12532. * be created from many heterogeneous - in many cases - geometries for performance.
  12533. * <p>
  12534. * Geometries can be transformed and optimized using functions in {@link GeometryPipeline}.
  12535. * </p>
  12536. *
  12537. * @alias Geometry
  12538. * @constructor
  12539. *
  12540. * @param {Object} options Object with the following properties:
  12541. * @param {GeometryAttributes} options.attributes Attributes, which make up the geometry's vertices.
  12542. * @param {PrimitiveType} [options.primitiveType=PrimitiveType.TRIANGLES] The type of primitives in the geometry.
  12543. * @param {Uint16Array|Uint32Array} [options.indices] Optional index data that determines the primitives in the geometry.
  12544. * @param {BoundingSphere} [options.boundingSphere] An optional bounding sphere that fully enclosed the geometry.
  12545. *
  12546. * @see PolygonGeometry
  12547. * @see RectangleGeometry
  12548. * @see EllipseGeometry
  12549. * @see CircleGeometry
  12550. * @see WallGeometry
  12551. * @see SimplePolylineGeometry
  12552. * @see BoxGeometry
  12553. * @see EllipsoidGeometry
  12554. *
  12555. * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Geometry%20and%20Appearances.html|Geometry and Appearances Demo}
  12556. *
  12557. * @example
  12558. * // Create geometry with a position attribute and indexed lines.
  12559. * var positions = new Float64Array([
  12560. * 0.0, 0.0, 0.0,
  12561. * 7500000.0, 0.0, 0.0,
  12562. * 0.0, 7500000.0, 0.0
  12563. * ]);
  12564. *
  12565. * var geometry = new Cesium.Geometry({
  12566. * attributes : {
  12567. * position : new Cesium.GeometryAttribute({
  12568. * componentDatatype : Cesium.ComponentDatatype.DOUBLE,
  12569. * componentsPerAttribute : 3,
  12570. * values : positions
  12571. * })
  12572. * },
  12573. * indices : new Uint16Array([0, 1, 1, 2, 2, 0]),
  12574. * primitiveType : Cesium.PrimitiveType.LINES,
  12575. * boundingSphere : Cesium.BoundingSphere.fromVertices(positions)
  12576. * });
  12577. */
  12578. function Geometry(options) {
  12579. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  12580. if (!defined(options.attributes)) {
  12581. throw new DeveloperError('options.attributes is required.');
  12582. }
  12583. /**
  12584. * Attributes, which make up the geometry's vertices. Each property in this object corresponds to a
  12585. * {@link GeometryAttribute} containing the attribute's data.
  12586. * <p>
  12587. * Attributes are always stored non-interleaved in a Geometry.
  12588. * </p>
  12589. * <p>
  12590. * There are reserved attribute names with well-known semantics. The following attributes
  12591. * are created by a Geometry (depending on the provided {@link VertexFormat}.
  12592. * <ul>
  12593. * <li><code>position</code> - 3D vertex position. 64-bit floating-point (for precision). 3 components per attribute. See {@link VertexFormat#position}.</li>
  12594. * <li><code>normal</code> - Normal (normalized), commonly used for lighting. 32-bit floating-point. 3 components per attribute. See {@link VertexFormat#normal}.</li>
  12595. * <li><code>st</code> - 2D texture coordinate. 32-bit floating-point. 2 components per attribute. See {@link VertexFormat#st}.</li>
  12596. * <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>
  12597. * <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>
  12598. * </ul>
  12599. * </p>
  12600. * <p>
  12601. * The following attribute names are generally not created by a Geometry, but are added
  12602. * to a Geometry by a {@link Primitive} or {@link GeometryPipeline} functions to prepare
  12603. * the geometry for rendering.
  12604. * <ul>
  12605. * <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>
  12606. * <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>
  12607. * <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>
  12608. * <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>
  12609. * <li><code>color</code> - RGBA color (normalized) usually from {@link GeometryInstance#color}. 32-bit floating-point. 4 components per attribute.</li>
  12610. * <li><code>pickColor</code> - RGBA color used for picking. 32-bit floating-point. 4 components per attribute.</li>
  12611. * </ul>
  12612. * </p>
  12613. *
  12614. * @type GeometryAttributes
  12615. *
  12616. * @default undefined
  12617. *
  12618. *
  12619. * @example
  12620. * geometry.attributes.position = new Cesium.GeometryAttribute({
  12621. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  12622. * componentsPerAttribute : 3,
  12623. * values : new Float32Array(0)
  12624. * });
  12625. *
  12626. * @see GeometryAttribute
  12627. * @see VertexFormat
  12628. */
  12629. this.attributes = options.attributes;
  12630. /**
  12631. * Optional index data that - along with {@link Geometry#primitiveType} -
  12632. * determines the primitives in the geometry.
  12633. *
  12634. * @type Array
  12635. *
  12636. * @default undefined
  12637. */
  12638. this.indices = options.indices;
  12639. /**
  12640. * The type of primitives in the geometry. This is most often {@link PrimitiveType.TRIANGLES},
  12641. * but can varying based on the specific geometry.
  12642. *
  12643. * @type PrimitiveType
  12644. *
  12645. * @default undefined
  12646. */
  12647. this.primitiveType = defaultValue(options.primitiveType, PrimitiveType.TRIANGLES);
  12648. /**
  12649. * An optional bounding sphere that fully encloses the geometry. This is
  12650. * commonly used for culling.
  12651. *
  12652. * @type BoundingSphere
  12653. *
  12654. * @default undefined
  12655. */
  12656. this.boundingSphere = options.boundingSphere;
  12657. /**
  12658. * @private
  12659. */
  12660. this.geometryType = defaultValue(options.geometryType, GeometryType.NONE);
  12661. /**
  12662. * @private
  12663. */
  12664. this.boundingSphereCV = options.boundingSphereCV;
  12665. }
  12666. /**
  12667. * Computes the number of vertices in a geometry. The runtime is linear with
  12668. * respect to the number of attributes in a vertex, not the number of vertices.
  12669. *
  12670. * @param {Geometry} geometry The geometry.
  12671. * @returns {Number} The number of vertices in the geometry.
  12672. *
  12673. * @example
  12674. * var numVertices = Cesium.Geometry.computeNumberOfVertices(geometry);
  12675. */
  12676. Geometry.computeNumberOfVertices = function(geometry) {
  12677. if (!defined(geometry)) {
  12678. throw new DeveloperError('geometry is required.');
  12679. }
  12680. var numberOfVertices = -1;
  12681. for ( var property in geometry.attributes) {
  12682. if (geometry.attributes.hasOwnProperty(property) &&
  12683. defined(geometry.attributes[property]) &&
  12684. defined(geometry.attributes[property].values)) {
  12685. var attribute = geometry.attributes[property];
  12686. var num = attribute.values.length / attribute.componentsPerAttribute;
  12687. if ((numberOfVertices !== num) && (numberOfVertices !== -1)) {
  12688. throw new DeveloperError('All attribute lists must have the same number of attributes.');
  12689. }
  12690. numberOfVertices = num;
  12691. }
  12692. }
  12693. return numberOfVertices;
  12694. };
  12695. return Geometry;
  12696. });
  12697. /*global define*/
  12698. define('Core/GeometryAttribute',[
  12699. './defaultValue',
  12700. './defined',
  12701. './DeveloperError'
  12702. ], function(
  12703. defaultValue,
  12704. defined,
  12705. DeveloperError) {
  12706. 'use strict';
  12707. /**
  12708. * Values and type information for geometry attributes. A {@link Geometry}
  12709. * generally contains one or more attributes. All attributes together form
  12710. * the geometry's vertices.
  12711. *
  12712. * @alias GeometryAttribute
  12713. * @constructor
  12714. *
  12715. * @param {Object} [options] Object with the following properties:
  12716. * @param {ComponentDatatype} [options.componentDatatype] The datatype of each component in the attribute, e.g., individual elements in values.
  12717. * @param {Number} [options.componentsPerAttribute] A number between 1 and 4 that defines the number of components in an attributes.
  12718. * @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.
  12719. * @param {TypedArray} [options.values] The values for the attributes stored in a typed array.
  12720. *
  12721. * @exception {DeveloperError} options.componentsPerAttribute must be between 1 and 4.
  12722. *
  12723. *
  12724. * @example
  12725. * var geometry = new Cesium.Geometry({
  12726. * attributes : {
  12727. * position : new Cesium.GeometryAttribute({
  12728. * componentDatatype : Cesium.ComponentDatatype.FLOAT,
  12729. * componentsPerAttribute : 3,
  12730. * values : new Float32Array([
  12731. * 0.0, 0.0, 0.0,
  12732. * 7500000.0, 0.0, 0.0,
  12733. * 0.0, 7500000.0, 0.0
  12734. * ])
  12735. * })
  12736. * },
  12737. * primitiveType : Cesium.PrimitiveType.LINE_LOOP
  12738. * });
  12739. *
  12740. * @see Geometry
  12741. */
  12742. function GeometryAttribute(options) {
  12743. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  12744. if (!defined(options.componentDatatype)) {
  12745. throw new DeveloperError('options.componentDatatype is required.');
  12746. }
  12747. if (!defined(options.componentsPerAttribute)) {
  12748. throw new DeveloperError('options.componentsPerAttribute is required.');
  12749. }
  12750. if (options.componentsPerAttribute < 1 || options.componentsPerAttribute > 4) {
  12751. throw new DeveloperError('options.componentsPerAttribute must be between 1 and 4.');
  12752. }
  12753. if (!defined(options.values)) {
  12754. throw new DeveloperError('options.values is required.');
  12755. }
  12756. /**
  12757. * The datatype of each component in the attribute, e.g., individual elements in
  12758. * {@link GeometryAttribute#values}.
  12759. *
  12760. * @type ComponentDatatype
  12761. *
  12762. * @default undefined
  12763. */
  12764. this.componentDatatype = options.componentDatatype;
  12765. /**
  12766. * A number between 1 and 4 that defines the number of components in an attributes.
  12767. * For example, a position attribute with x, y, and z components would have 3 as
  12768. * shown in the code example.
  12769. *
  12770. * @type Number
  12771. *
  12772. * @default undefined
  12773. *
  12774. * @example
  12775. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  12776. * attribute.componentsPerAttribute = 3;
  12777. * attribute.values = new Float32Array([
  12778. * 0.0, 0.0, 0.0,
  12779. * 7500000.0, 0.0, 0.0,
  12780. * 0.0, 7500000.0, 0.0
  12781. * ]);
  12782. */
  12783. this.componentsPerAttribute = options.componentsPerAttribute;
  12784. /**
  12785. * When <code>true</code> and <code>componentDatatype</code> is an integer format,
  12786. * indicate that the components should be mapped to the range [0, 1] (unsigned)
  12787. * or [-1, 1] (signed) when they are accessed as floating-point for rendering.
  12788. * <p>
  12789. * This is commonly used when storing colors using {@link ComponentDatatype.UNSIGNED_BYTE}.
  12790. * </p>
  12791. *
  12792. * @type Boolean
  12793. *
  12794. * @default false
  12795. *
  12796. * @example
  12797. * attribute.componentDatatype = Cesium.ComponentDatatype.UNSIGNED_BYTE;
  12798. * attribute.componentsPerAttribute = 4;
  12799. * attribute.normalize = true;
  12800. * attribute.values = new Uint8Array([
  12801. * Cesium.Color.floatToByte(color.red),
  12802. * Cesium.Color.floatToByte(color.green),
  12803. * Cesium.Color.floatToByte(color.blue),
  12804. * Cesium.Color.floatToByte(color.alpha)
  12805. * ]);
  12806. */
  12807. this.normalize = defaultValue(options.normalize, false);
  12808. /**
  12809. * The values for the attributes stored in a typed array. In the code example,
  12810. * every three elements in <code>values</code> defines one attributes since
  12811. * <code>componentsPerAttribute</code> is 3.
  12812. *
  12813. * @type TypedArray
  12814. *
  12815. * @default undefined
  12816. *
  12817. * @example
  12818. * attribute.componentDatatype = Cesium.ComponentDatatype.FLOAT;
  12819. * attribute.componentsPerAttribute = 3;
  12820. * attribute.values = new Float32Array([
  12821. * 0.0, 0.0, 0.0,
  12822. * 7500000.0, 0.0, 0.0,
  12823. * 0.0, 7500000.0, 0.0
  12824. * ]);
  12825. */
  12826. this.values = options.values;
  12827. }
  12828. return GeometryAttribute;
  12829. });
  12830. /*global define*/
  12831. define('Core/GeometryAttributes',[
  12832. './defaultValue'
  12833. ], function(
  12834. defaultValue) {
  12835. 'use strict';
  12836. /**
  12837. * Attributes, which make up a geometry's vertices. Each property in this object corresponds to a
  12838. * {@link GeometryAttribute} containing the attribute's data.
  12839. * <p>
  12840. * Attributes are always stored non-interleaved in a Geometry.
  12841. * </p>
  12842. *
  12843. * @alias GeometryAttributes
  12844. * @constructor
  12845. */
  12846. function GeometryAttributes(options) {
  12847. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  12848. /**
  12849. * The 3D position attribute.
  12850. * <p>
  12851. * 64-bit floating-point (for precision). 3 components per attribute.
  12852. * </p>
  12853. *
  12854. * @type GeometryAttribute
  12855. *
  12856. * @default undefined
  12857. */
  12858. this.position = options.position;
  12859. /**
  12860. * The normal attribute (normalized), which is commonly used for lighting.
  12861. * <p>
  12862. * 32-bit floating-point. 3 components per attribute.
  12863. * </p>
  12864. *
  12865. * @type GeometryAttribute
  12866. *
  12867. * @default undefined
  12868. */
  12869. this.normal = options.normal;
  12870. /**
  12871. * The 2D texture coordinate attribute.
  12872. * <p>
  12873. * 32-bit floating-point. 2 components per attribute
  12874. * </p>
  12875. *
  12876. * @type GeometryAttribute
  12877. *
  12878. * @default undefined
  12879. */
  12880. this.st = options.st;
  12881. /**
  12882. * The binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  12883. * <p>
  12884. * 32-bit floating-point. 3 components per attribute.
  12885. * </p>
  12886. *
  12887. * @type GeometryAttribute
  12888. *
  12889. * @default undefined
  12890. */
  12891. this.binormal = options.binormal;
  12892. /**
  12893. * The tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  12894. * <p>
  12895. * 32-bit floating-point. 3 components per attribute.
  12896. * </p>
  12897. *
  12898. * @type GeometryAttribute
  12899. *
  12900. * @default undefined
  12901. */
  12902. this.tangent = options.tangent;
  12903. /**
  12904. * The color attribute.
  12905. * <p>
  12906. * 8-bit unsigned integer. 4 components per attribute.
  12907. * </p>
  12908. *
  12909. * @type GeometryAttribute
  12910. *
  12911. * @default undefined
  12912. */
  12913. this.color = options.color;
  12914. }
  12915. return GeometryAttributes;
  12916. });
  12917. /*global define*/
  12918. define('Core/AttributeCompression',[
  12919. './Cartesian2',
  12920. './Cartesian3',
  12921. './defined',
  12922. './DeveloperError',
  12923. './Math'
  12924. ], function(
  12925. Cartesian2,
  12926. Cartesian3,
  12927. defined,
  12928. DeveloperError,
  12929. CesiumMath) {
  12930. 'use strict';
  12931. /**
  12932. * Attribute compression and decompression functions.
  12933. *
  12934. * @exports AttributeCompression
  12935. *
  12936. * @private
  12937. */
  12938. var AttributeCompression = {};
  12939. /**
  12940. * Encodes a normalized vector into 2 SNORM values in the range of [0-rangeMax] following the 'oct' encoding.
  12941. *
  12942. * Oct encoding is a compact representation of unit length vectors.
  12943. * The 'oct' encoding is described in "A Survey of Efficient Representations of Independent Unit Vectors",
  12944. * Cigolle et al 2014: {@link http://jcgt.org/published/0003/02/01/}
  12945. *
  12946. * @param {Cartesian3} vector The normalized vector to be compressed into 2 component 'oct' encoding.
  12947. * @param {Cartesian2} result The 2 component oct-encoded unit length vector.
  12948. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  12949. * @returns {Cartesian2} The 2 component oct-encoded unit length vector.
  12950. *
  12951. * @exception {DeveloperError} vector must be normalized.
  12952. *
  12953. * @see AttributeCompression.octDecodeInRange
  12954. */
  12955. AttributeCompression.octEncodeInRange = function(vector, rangeMax, result) {
  12956. if (!defined(vector)) {
  12957. throw new DeveloperError('vector is required.');
  12958. }
  12959. if (!defined(result)) {
  12960. throw new DeveloperError('result is required.');
  12961. }
  12962. var magSquared = Cartesian3.magnitudeSquared(vector);
  12963. if (Math.abs(magSquared - 1.0) > CesiumMath.EPSILON6) {
  12964. throw new DeveloperError('vector must be normalized.');
  12965. }
  12966. result.x = vector.x / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  12967. result.y = vector.y / (Math.abs(vector.x) + Math.abs(vector.y) + Math.abs(vector.z));
  12968. if (vector.z < 0) {
  12969. var x = result.x;
  12970. var y = result.y;
  12971. result.x = (1.0 - Math.abs(y)) * CesiumMath.signNotZero(x);
  12972. result.y = (1.0 - Math.abs(x)) * CesiumMath.signNotZero(y);
  12973. }
  12974. result.x = CesiumMath.toSNorm(result.x, rangeMax);
  12975. result.y = CesiumMath.toSNorm(result.y, rangeMax);
  12976. return result;
  12977. };
  12978. /**
  12979. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding.
  12980. *
  12981. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  12982. * @param {Cartesian2} result The 2 byte oct-encoded unit length vector.
  12983. * @returns {Cartesian2} The 2 byte oct-encoded unit length vector.
  12984. *
  12985. * @exception {DeveloperError} vector must be normalized.
  12986. *
  12987. * @see AttributeCompression.octEncodeInRange
  12988. * @see AttributeCompression.octDecode
  12989. */
  12990. AttributeCompression.octEncode = function(vector, result) {
  12991. return AttributeCompression.octEncodeInRange(vector, 255, result);
  12992. };
  12993. /**
  12994. * Decodes a unit-length vector in 'oct' encoding to a normalized 3-component vector.
  12995. *
  12996. * @param {Number} x The x component of the oct-encoded unit length vector.
  12997. * @param {Number} y The y component of the oct-encoded unit length vector.
  12998. * @param {Number} rangeMax The maximum value of the SNORM range. The encoded vector is stored in log2(rangeMax+1) bits.
  12999. * @param {Cartesian3} result The decoded and normalized vector
  13000. * @returns {Cartesian3} The decoded and normalized vector.
  13001. *
  13002. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and rangeMax.
  13003. *
  13004. * @see AttributeCompression.octEncodeInRange
  13005. */
  13006. AttributeCompression.octDecodeInRange = function(x, y, rangeMax, result) {
  13007. if (!defined(result)) {
  13008. throw new DeveloperError('result is required.');
  13009. }
  13010. if (x < 0 || x > rangeMax || y < 0 || y > rangeMax) {
  13011. throw new DeveloperError('x and y must be a signed normalized integer between 0 and ' + rangeMax);
  13012. }
  13013. result.x = CesiumMath.fromSNorm(x, rangeMax);
  13014. result.y = CesiumMath.fromSNorm(y, rangeMax);
  13015. result.z = 1.0 - (Math.abs(result.x) + Math.abs(result.y));
  13016. if (result.z < 0.0)
  13017. {
  13018. var oldVX = result.x;
  13019. result.x = (1.0 - Math.abs(result.y)) * CesiumMath.signNotZero(oldVX);
  13020. result.y = (1.0 - Math.abs(oldVX)) * CesiumMath.signNotZero(result.y);
  13021. }
  13022. return Cartesian3.normalize(result, result);
  13023. };
  13024. /**
  13025. * Decodes a unit-length vector in 2 byte 'oct' encoding to a normalized 3-component vector.
  13026. *
  13027. * @param {Number} x The x component of the oct-encoded unit length vector.
  13028. * @param {Number} y The y component of the oct-encoded unit length vector.
  13029. * @param {Cartesian3} result The decoded and normalized vector.
  13030. * @returns {Cartesian3} The decoded and normalized vector.
  13031. *
  13032. * @exception {DeveloperError} x and y must be an unsigned normalized integer between 0 and 255.
  13033. *
  13034. * @see AttributeCompression.octDecodeInRange
  13035. */
  13036. AttributeCompression.octDecode = function(x, y, result) {
  13037. return AttributeCompression.octDecodeInRange(x, y, 255, result);
  13038. };
  13039. /**
  13040. * Packs an oct encoded vector into a single floating-point number.
  13041. *
  13042. * @param {Cartesian2} encoded The oct encoded vector.
  13043. * @returns {Number} The oct encoded vector packed into a single float.
  13044. *
  13045. */
  13046. AttributeCompression.octPackFloat = function(encoded) {
  13047. if (!defined(encoded)) {
  13048. throw new DeveloperError('encoded is required.');
  13049. }
  13050. return 256.0 * encoded.x + encoded.y;
  13051. };
  13052. var scratchEncodeCart2 = new Cartesian2();
  13053. /**
  13054. * Encodes a normalized vector into 2 SNORM values in the range of [0-255] following the 'oct' encoding and
  13055. * stores those values in a single float-point number.
  13056. *
  13057. * @param {Cartesian3} vector The normalized vector to be compressed into 2 byte 'oct' encoding.
  13058. * @returns {Number} The 2 byte oct-encoded unit length vector.
  13059. *
  13060. * @exception {DeveloperError} vector must be normalized.
  13061. */
  13062. AttributeCompression.octEncodeFloat = function(vector) {
  13063. AttributeCompression.octEncode(vector, scratchEncodeCart2);
  13064. return AttributeCompression.octPackFloat(scratchEncodeCart2);
  13065. };
  13066. /**
  13067. * Decodes a unit-length vector in 'oct' encoding packed in a floating-point number to a normalized 3-component vector.
  13068. *
  13069. * @param {Number} value The oct-encoded unit length vector stored as a single floating-point number.
  13070. * @param {Cartesian3} result The decoded and normalized vector
  13071. * @returns {Cartesian3} The decoded and normalized vector.
  13072. *
  13073. */
  13074. AttributeCompression.octDecodeFloat = function(value, result) {
  13075. if (!defined(value)) {
  13076. throw new DeveloperError('value is required.');
  13077. }
  13078. var temp = value / 256.0;
  13079. var x = Math.floor(temp);
  13080. var y = (temp - x) * 256.0;
  13081. return AttributeCompression.octDecode(x, y, result);
  13082. };
  13083. /**
  13084. * Encodes three normalized vectors into 6 SNORM values in the range of [0-255] following the 'oct' encoding and
  13085. * packs those into two floating-point numbers.
  13086. *
  13087. * @param {Cartesian3} v1 A normalized vector to be compressed.
  13088. * @param {Cartesian3} v2 A normalized vector to be compressed.
  13089. * @param {Cartesian3} v3 A normalized vector to be compressed.
  13090. * @param {Cartesian2} result The 'oct' encoded vectors packed into two floating-point numbers.
  13091. * @returns {Cartesian2} The 'oct' encoded vectors packed into two floating-point numbers.
  13092. *
  13093. */
  13094. AttributeCompression.octPack = function(v1, v2, v3, result) {
  13095. if (!defined(v1)) {
  13096. throw new DeveloperError('v1 is required.');
  13097. }
  13098. if (!defined(v2)) {
  13099. throw new DeveloperError('v2 is required.');
  13100. }
  13101. if (!defined(v3)) {
  13102. throw new DeveloperError('v3 is required.');
  13103. }
  13104. if (!defined(result)) {
  13105. throw new DeveloperError('result is required.');
  13106. }
  13107. var encoded1 = AttributeCompression.octEncodeFloat(v1);
  13108. var encoded2 = AttributeCompression.octEncodeFloat(v2);
  13109. var encoded3 = AttributeCompression.octEncode(v3, scratchEncodeCart2);
  13110. result.x = 65536.0 * encoded3.x + encoded1;
  13111. result.y = 65536.0 * encoded3.y + encoded2;
  13112. return result;
  13113. };
  13114. /**
  13115. * Decodes three unit-length vectors in 'oct' encoding packed into a floating-point number to a normalized 3-component vector.
  13116. *
  13117. * @param {Cartesian2} packed The three oct-encoded unit length vectors stored as two floating-point number.
  13118. * @param {Cartesian3} v1 One decoded and normalized vector.
  13119. * @param {Cartesian3} v2 One decoded and normalized vector.
  13120. * @param {Cartesian3} v3 One decoded and normalized vector.
  13121. */
  13122. AttributeCompression.octUnpack = function(packed, v1, v2, v3) {
  13123. if (!defined(packed)) {
  13124. throw new DeveloperError('packed is required.');
  13125. }
  13126. if (!defined(v1)) {
  13127. throw new DeveloperError('v1 is required.');
  13128. }
  13129. if (!defined(v2)) {
  13130. throw new DeveloperError('v2 is required.');
  13131. }
  13132. if (!defined(v3)) {
  13133. throw new DeveloperError('v3 is required.');
  13134. }
  13135. var temp = packed.x / 65536.0;
  13136. var x = Math.floor(temp);
  13137. var encodedFloat1 = (temp - x) * 65536.0;
  13138. temp = packed.y / 65536.0;
  13139. var y = Math.floor(temp);
  13140. var encodedFloat2 = (temp - y) * 65536.0;
  13141. AttributeCompression.octDecodeFloat(encodedFloat1, v1);
  13142. AttributeCompression.octDecodeFloat(encodedFloat2, v2);
  13143. AttributeCompression.octDecode(x, y, v3);
  13144. };
  13145. /**
  13146. * Pack texture coordinates into a single float. The texture coordinates will only preserve 12 bits of precision.
  13147. *
  13148. * @param {Cartesian2} textureCoordinates The texture coordinates to compress. Both coordinates must be in the range 0.0-1.0.
  13149. * @returns {Number} The packed texture coordinates.
  13150. *
  13151. */
  13152. AttributeCompression.compressTextureCoordinates = function(textureCoordinates) {
  13153. if (!defined(textureCoordinates)) {
  13154. throw new DeveloperError('textureCoordinates is required.');
  13155. }
  13156. // Move x and y to the range 0-4095;
  13157. var x = (textureCoordinates.x * 4095.0) | 0;
  13158. var y = (textureCoordinates.y * 4095.0) | 0;
  13159. return 4096.0 * x + y;
  13160. };
  13161. /**
  13162. * Decompresses texture coordinates that were packed into a single float.
  13163. *
  13164. * @param {Number} compressed The compressed texture coordinates.
  13165. * @param {Cartesian2} result The decompressed texture coordinates.
  13166. * @returns {Cartesian2} The modified result parameter.
  13167. *
  13168. */
  13169. AttributeCompression.decompressTextureCoordinates = function(compressed, result) {
  13170. if (!defined(compressed)) {
  13171. throw new DeveloperError('compressed is required.');
  13172. }
  13173. if (!defined(result)) {
  13174. throw new DeveloperError('result is required.');
  13175. }
  13176. var temp = compressed / 4096.0;
  13177. var xZeroTo4095 = Math.floor(temp);
  13178. result.x = xZeroTo4095 / 4095.0;
  13179. result.y = (compressed - xZeroTo4095 * 4096) / 4095;
  13180. return result;
  13181. };
  13182. return AttributeCompression;
  13183. });
  13184. /*global define*/
  13185. define('Core/barycentricCoordinates',[
  13186. './Cartesian2',
  13187. './Cartesian3',
  13188. './defined',
  13189. './DeveloperError'
  13190. ], function(
  13191. Cartesian2,
  13192. Cartesian3,
  13193. defined,
  13194. DeveloperError) {
  13195. 'use strict';
  13196. var scratchCartesian1 = new Cartesian3();
  13197. var scratchCartesian2 = new Cartesian3();
  13198. var scratchCartesian3 = new Cartesian3();
  13199. /**
  13200. * Computes the barycentric coordinates for a point with respect to a triangle.
  13201. *
  13202. * @exports barycentricCoordinates
  13203. *
  13204. * @param {Cartesian2|Cartesian3} point The point to test.
  13205. * @param {Cartesian2|Cartesian3} p0 The first point of the triangle, corresponding to the barycentric x-axis.
  13206. * @param {Cartesian2|Cartesian3} p1 The second point of the triangle, corresponding to the barycentric y-axis.
  13207. * @param {Cartesian2|Cartesian3} p2 The third point of the triangle, corresponding to the barycentric z-axis.
  13208. * @param {Cartesian3} [result] The object onto which to store the result.
  13209. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided.
  13210. *
  13211. * @example
  13212. * // Returns Cartesian3.UNIT_X
  13213. * var p = new Cesium.Cartesian3(-1.0, 0.0, 0.0);
  13214. * var b = Cesium.barycentricCoordinates(p,
  13215. * new Cesium.Cartesian3(-1.0, 0.0, 0.0),
  13216. * new Cesium.Cartesian3( 1.0, 0.0, 0.0),
  13217. * new Cesium.Cartesian3( 0.0, 1.0, 1.0));
  13218. */
  13219. function barycentricCoordinates(point, p0, p1, p2, result) {
  13220. if (!defined(point) || !defined(p0) || !defined(p1) || !defined(p2)) {
  13221. throw new DeveloperError('point, p0, p1, and p2 are required.');
  13222. }
  13223. if (!defined(result)) {
  13224. result = new Cartesian3();
  13225. }
  13226. // Implementation based on http://www.blackpawn.com/texts/pointinpoly/default.html.
  13227. var v0, v1, v2;
  13228. var dot00, dot01, dot02, dot11, dot12;
  13229. if(!defined(p0.z)) {
  13230. v0 = Cartesian2.subtract(p1, p0, scratchCartesian1);
  13231. v1 = Cartesian2.subtract(p2, p0, scratchCartesian2);
  13232. v2 = Cartesian2.subtract(point, p0, scratchCartesian3);
  13233. dot00 = Cartesian2.dot(v0, v0);
  13234. dot01 = Cartesian2.dot(v0, v1);
  13235. dot02 = Cartesian2.dot(v0, v2);
  13236. dot11 = Cartesian2.dot(v1, v1);
  13237. dot12 = Cartesian2.dot(v1, v2);
  13238. } else {
  13239. v0 = Cartesian3.subtract(p1, p0, scratchCartesian1);
  13240. v1 = Cartesian3.subtract(p2, p0, scratchCartesian2);
  13241. v2 = Cartesian3.subtract(point, p0, scratchCartesian3);
  13242. dot00 = Cartesian3.dot(v0, v0);
  13243. dot01 = Cartesian3.dot(v0, v1);
  13244. dot02 = Cartesian3.dot(v0, v2);
  13245. dot11 = Cartesian3.dot(v1, v1);
  13246. dot12 = Cartesian3.dot(v1, v2);
  13247. }
  13248. var q = 1.0 / (dot00 * dot11 - dot01 * dot01);
  13249. result.y = (dot11 * dot02 - dot01 * dot12) * q;
  13250. result.z = (dot00 * dot12 - dot01 * dot02) * q;
  13251. result.x = 1.0 - result.y - result.z;
  13252. return result;
  13253. }
  13254. return barycentricCoordinates;
  13255. });
  13256. /*global define*/
  13257. define('Core/EncodedCartesian3',[
  13258. './Cartesian3',
  13259. './defined',
  13260. './DeveloperError'
  13261. ], function(
  13262. Cartesian3,
  13263. defined,
  13264. DeveloperError) {
  13265. 'use strict';
  13266. /**
  13267. * A fixed-point encoding of a {@link Cartesian3} with 64-bit floating-point components, as two {@link Cartesian3}
  13268. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  13269. * <p>
  13270. * This is used to encode positions in vertex buffers for rendering without jittering artifacts
  13271. * as described in {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  13272. * </p>
  13273. *
  13274. * @alias EncodedCartesian3
  13275. * @constructor
  13276. *
  13277. * @private
  13278. */
  13279. function EncodedCartesian3() {
  13280. /**
  13281. * The high bits for each component. Bits 0 to 22 store the whole value. Bits 23 to 31 are not used.
  13282. *
  13283. * @type {Cartesian3}
  13284. * @default {@link Cartesian3.ZERO}
  13285. */
  13286. this.high = Cartesian3.clone(Cartesian3.ZERO);
  13287. /**
  13288. * 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.
  13289. *
  13290. * @type {Cartesian3}
  13291. * @default {@link Cartesian3.ZERO}
  13292. */
  13293. this.low = Cartesian3.clone(Cartesian3.ZERO);
  13294. }
  13295. /**
  13296. * Encodes a 64-bit floating-point value as two floating-point values that, when converted to
  13297. * 32-bit floating-point and added, approximate the original input. The returned object
  13298. * has <code>high</code> and <code>low</code> properties for the high and low bits, respectively.
  13299. * <p>
  13300. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  13301. * </p>
  13302. *
  13303. * @param {Number} value The floating-point value to encode.
  13304. * @param {Object} [result] The object onto which to store the result.
  13305. * @returns {Object} The modified result parameter or a new instance if one was not provided.
  13306. *
  13307. * @example
  13308. * var value = 1234567.1234567;
  13309. * var splitValue = Cesium.EncodedCartesian3.encode(value);
  13310. */
  13311. EncodedCartesian3.encode = function(value, result) {
  13312. if (!defined(value)) {
  13313. throw new DeveloperError('value is required');
  13314. }
  13315. if (!defined(result)) {
  13316. result = {
  13317. high : 0.0,
  13318. low : 0.0
  13319. };
  13320. }
  13321. var doubleHigh;
  13322. if (value >= 0.0) {
  13323. doubleHigh = Math.floor(value / 65536.0) * 65536.0;
  13324. result.high = doubleHigh;
  13325. result.low = value - doubleHigh;
  13326. } else {
  13327. doubleHigh = Math.floor(-value / 65536.0) * 65536.0;
  13328. result.high = -doubleHigh;
  13329. result.low = value + doubleHigh;
  13330. }
  13331. return result;
  13332. };
  13333. var scratchEncode = {
  13334. high : 0.0,
  13335. low : 0.0
  13336. };
  13337. /**
  13338. * Encodes a {@link Cartesian3} with 64-bit floating-point components as two {@link Cartesian3}
  13339. * values that, when converted to 32-bit floating-point and added, approximate the original input.
  13340. * <p>
  13341. * The fixed-point encoding follows {@link http://blogs.agi.com/insight3d/index.php/2008/09/03/precisions-precisions/|Precisions, Precisions}.
  13342. * </p>
  13343. *
  13344. * @param {Cartesian3} cartesian The cartesian to encode.
  13345. * @param {EncodedCartesian3} [result] The object onto which to store the result.
  13346. * @returns {EncodedCartesian3} The modified result parameter or a new EncodedCartesian3 instance if one was not provided.
  13347. *
  13348. * @example
  13349. * var cart = new Cesium.Cartesian3(-10000000.0, 0.0, 10000000.0);
  13350. * var encoded = Cesium.EncodedCartesian3.fromCartesian(cart);
  13351. */
  13352. EncodedCartesian3.fromCartesian = function(cartesian, result) {
  13353. if (!defined(cartesian)) {
  13354. throw new DeveloperError('cartesian is required');
  13355. }
  13356. if (!defined(result)) {
  13357. result = new EncodedCartesian3();
  13358. }
  13359. var high = result.high;
  13360. var low = result.low;
  13361. EncodedCartesian3.encode(cartesian.x, scratchEncode);
  13362. high.x = scratchEncode.high;
  13363. low.x = scratchEncode.low;
  13364. EncodedCartesian3.encode(cartesian.y, scratchEncode);
  13365. high.y = scratchEncode.high;
  13366. low.y = scratchEncode.low;
  13367. EncodedCartesian3.encode(cartesian.z, scratchEncode);
  13368. high.z = scratchEncode.high;
  13369. low.z = scratchEncode.low;
  13370. return result;
  13371. };
  13372. var encodedP = new EncodedCartesian3();
  13373. /**
  13374. * Encodes the provided <code>cartesian</code>, and writes it to an array with <code>high</code>
  13375. * components followed by <code>low</code> components, i.e. <code>[high.x, high.y, high.z, low.x, low.y, low.z]</code>.
  13376. * <p>
  13377. * This is used to create interleaved high-precision position vertex attributes.
  13378. * </p>
  13379. *
  13380. * @param {Cartesian3} cartesian The cartesian to encode.
  13381. * @param {Number[]} cartesianArray The array to write to.
  13382. * @param {Number} index The index into the array to start writing. Six elements will be written.
  13383. *
  13384. * @exception {DeveloperError} index must be a number greater than or equal to 0.
  13385. *
  13386. * @example
  13387. * var positions = [
  13388. * new Cesium.Cartesian3(),
  13389. * // ...
  13390. * ];
  13391. * var encodedPositions = new Float32Array(2 * 3 * positions.length);
  13392. * var j = 0;
  13393. * for (var i = 0; i < positions.length; ++i) {
  13394. * Cesium.EncodedCartesian3.writeElement(positions[i], encodedPositions, j);
  13395. * j += 6;
  13396. * }
  13397. */
  13398. EncodedCartesian3.writeElements = function(cartesian, cartesianArray, index) {
  13399. if (!defined(cartesian)) {
  13400. throw new DeveloperError('cartesian is required');
  13401. }
  13402. if (!defined(cartesianArray)) {
  13403. throw new DeveloperError('cartesianArray is required');
  13404. }
  13405. if (typeof index !== 'number' || index < 0) {
  13406. throw new DeveloperError('index must be a number greater than or equal to 0.');
  13407. }
  13408. EncodedCartesian3.fromCartesian(cartesian, encodedP);
  13409. var high = encodedP.high;
  13410. var low = encodedP.low;
  13411. cartesianArray[index] = high.x;
  13412. cartesianArray[index + 1] = high.y;
  13413. cartesianArray[index + 2] = high.z;
  13414. cartesianArray[index + 3] = low.x;
  13415. cartesianArray[index + 4] = low.y;
  13416. cartesianArray[index + 5] = low.z;
  13417. };
  13418. return EncodedCartesian3;
  13419. });
  13420. /*global define*/
  13421. define('Core/IndexDatatype',[
  13422. './defined',
  13423. './DeveloperError',
  13424. './freezeObject',
  13425. './Math',
  13426. './WebGLConstants'
  13427. ], function(
  13428. defined,
  13429. DeveloperError,
  13430. freezeObject,
  13431. CesiumMath,
  13432. WebGLConstants) {
  13433. 'use strict';
  13434. /**
  13435. * Constants for WebGL index datatypes. These corresponds to the
  13436. * <code>type</code> parameter of {@link http://www.khronos.org/opengles/sdk/docs/man/xhtml/glDrawElements.xml|drawElements}.
  13437. *
  13438. * @exports IndexDatatype
  13439. */
  13440. var IndexDatatype = {
  13441. /**
  13442. * 8-bit unsigned byte corresponding to <code>UNSIGNED_BYTE</code> and the type
  13443. * of an element in <code>Uint8Array</code>.
  13444. *
  13445. * @type {Number}
  13446. * @constant
  13447. */
  13448. UNSIGNED_BYTE : WebGLConstants.UNSIGNED_BYTE,
  13449. /**
  13450. * 16-bit unsigned short corresponding to <code>UNSIGNED_SHORT</code> and the type
  13451. * of an element in <code>Uint16Array</code>.
  13452. *
  13453. * @type {Number}
  13454. * @constant
  13455. */
  13456. UNSIGNED_SHORT : WebGLConstants.UNSIGNED_SHORT,
  13457. /**
  13458. * 32-bit unsigned int corresponding to <code>UNSIGNED_INT</code> and the type
  13459. * of an element in <code>Uint32Array</code>.
  13460. *
  13461. * @type {Number}
  13462. * @constant
  13463. */
  13464. UNSIGNED_INT : WebGLConstants.UNSIGNED_INT
  13465. };
  13466. /**
  13467. * Returns the size, in bytes, of the corresponding datatype.
  13468. *
  13469. * @param {IndexDatatype} indexDatatype The index datatype to get the size of.
  13470. * @returns {Number} The size in bytes.
  13471. *
  13472. * @example
  13473. * // Returns 2
  13474. * var size = Cesium.IndexDatatype.getSizeInBytes(Cesium.IndexDatatype.UNSIGNED_SHORT);
  13475. */
  13476. IndexDatatype.getSizeInBytes = function(indexDatatype) {
  13477. switch(indexDatatype) {
  13478. case IndexDatatype.UNSIGNED_BYTE:
  13479. return Uint8Array.BYTES_PER_ELEMENT;
  13480. case IndexDatatype.UNSIGNED_SHORT:
  13481. return Uint16Array.BYTES_PER_ELEMENT;
  13482. case IndexDatatype.UNSIGNED_INT:
  13483. return Uint32Array.BYTES_PER_ELEMENT;
  13484. }
  13485. throw new DeveloperError('indexDatatype is required and must be a valid IndexDatatype constant.');
  13486. };
  13487. /**
  13488. * Validates that the provided index datatype is a valid {@link IndexDatatype}.
  13489. *
  13490. * @param {IndexDatatype} indexDatatype The index datatype to validate.
  13491. * @returns {Boolean} <code>true</code> if the provided index datatype is a valid value; otherwise, <code>false</code>.
  13492. *
  13493. * @example
  13494. * if (!Cesium.IndexDatatype.validate(indexDatatype)) {
  13495. * throw new Cesium.DeveloperError('indexDatatype must be a valid value.');
  13496. * }
  13497. */
  13498. IndexDatatype.validate = function(indexDatatype) {
  13499. return defined(indexDatatype) &&
  13500. (indexDatatype === IndexDatatype.UNSIGNED_BYTE ||
  13501. indexDatatype === IndexDatatype.UNSIGNED_SHORT ||
  13502. indexDatatype === IndexDatatype.UNSIGNED_INT);
  13503. };
  13504. /**
  13505. * Creates a typed array that will store indices, using either <code><Uint16Array</code>
  13506. * or <code>Uint32Array</code> depending on the number of vertices.
  13507. *
  13508. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  13509. * @param {Any} indicesLengthOrArray Passed through to the typed array constructor.
  13510. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>indicesLengthOrArray</code>.
  13511. *
  13512. * @example
  13513. * this.indices = Cesium.IndexDatatype.createTypedArray(positions.length / 3, numberOfIndices);
  13514. */
  13515. IndexDatatype.createTypedArray = function(numberOfVertices, indicesLengthOrArray) {
  13516. if (!defined(numberOfVertices)) {
  13517. throw new DeveloperError('numberOfVertices is required.');
  13518. }
  13519. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  13520. return new Uint32Array(indicesLengthOrArray);
  13521. }
  13522. return new Uint16Array(indicesLengthOrArray);
  13523. };
  13524. /**
  13525. * Creates a typed array from a source array buffer. The resulting typed array will store indices, using either <code><Uint16Array</code>
  13526. * or <code>Uint32Array</code> depending on the number of vertices.
  13527. *
  13528. * @param {Number} numberOfVertices Number of vertices that the indices will reference.
  13529. * @param {ArrayBuffer} sourceArray Passed through to the typed array constructor.
  13530. * @param {Number} byteOffset Passed through to the typed array constructor.
  13531. * @param {Number} length Passed through to the typed array constructor.
  13532. * @returns {Uint16Array|Uint32Array} A <code>Uint16Array</code> or <code>Uint32Array</code> constructed with <code>sourceArray</code>, <code>byteOffset</code>, and <code>length</code>.
  13533. *
  13534. */
  13535. IndexDatatype.createTypedArrayFromArrayBuffer = function(numberOfVertices, sourceArray, byteOffset, length) {
  13536. if (!defined(numberOfVertices)) {
  13537. throw new DeveloperError('numberOfVertices is required.');
  13538. }
  13539. if (!defined(sourceArray)) {
  13540. throw new DeveloperError('sourceArray is required.');
  13541. }
  13542. if (!defined(byteOffset)) {
  13543. throw new DeveloperError('byteOffset is required.');
  13544. }
  13545. if (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  13546. return new Uint32Array(sourceArray, byteOffset, length);
  13547. }
  13548. return new Uint16Array(sourceArray, byteOffset, length);
  13549. };
  13550. return freezeObject(IndexDatatype);
  13551. });
  13552. /*global define*/
  13553. define('Core/QuadraticRealPolynomial',[
  13554. './DeveloperError',
  13555. './Math'
  13556. ], function(
  13557. DeveloperError,
  13558. CesiumMath) {
  13559. 'use strict';
  13560. /**
  13561. * Defines functions for 2nd order polynomial functions of one variable with only real coefficients.
  13562. *
  13563. * @exports QuadraticRealPolynomial
  13564. */
  13565. var QuadraticRealPolynomial = {};
  13566. /**
  13567. * Provides the discriminant of the quadratic equation from the supplied coefficients.
  13568. *
  13569. * @param {Number} a The coefficient of the 2nd order monomial.
  13570. * @param {Number} b The coefficient of the 1st order monomial.
  13571. * @param {Number} c The coefficient of the 0th order monomial.
  13572. * @returns {Number} The value of the discriminant.
  13573. */
  13574. QuadraticRealPolynomial.computeDiscriminant = function(a, b, c) {
  13575. if (typeof a !== 'number') {
  13576. throw new DeveloperError('a is a required number.');
  13577. }
  13578. if (typeof b !== 'number') {
  13579. throw new DeveloperError('b is a required number.');
  13580. }
  13581. if (typeof c !== 'number') {
  13582. throw new DeveloperError('c is a required number.');
  13583. }
  13584. var discriminant = b * b - 4.0 * a * c;
  13585. return discriminant;
  13586. };
  13587. function addWithCancellationCheck(left, right, tolerance) {
  13588. var difference = left + right;
  13589. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  13590. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  13591. return 0.0;
  13592. }
  13593. return difference;
  13594. }
  13595. /**
  13596. * Provides the real valued roots of the quadratic polynomial with the provided coefficients.
  13597. *
  13598. * @param {Number} a The coefficient of the 2nd order monomial.
  13599. * @param {Number} b The coefficient of the 1st order monomial.
  13600. * @param {Number} c The coefficient of the 0th order monomial.
  13601. * @returns {Number[]} The real valued roots.
  13602. */
  13603. QuadraticRealPolynomial.computeRealRoots = function(a, b, c) {
  13604. if (typeof a !== 'number') {
  13605. throw new DeveloperError('a is a required number.');
  13606. }
  13607. if (typeof b !== 'number') {
  13608. throw new DeveloperError('b is a required number.');
  13609. }
  13610. if (typeof c !== 'number') {
  13611. throw new DeveloperError('c is a required number.');
  13612. }
  13613. var ratio;
  13614. if (a === 0.0) {
  13615. if (b === 0.0) {
  13616. // Constant function: c = 0.
  13617. return [];
  13618. }
  13619. // Linear function: b * x + c = 0.
  13620. return [-c / b];
  13621. } else if (b === 0.0) {
  13622. if (c === 0.0) {
  13623. // 2nd order monomial: a * x^2 = 0.
  13624. return [0.0, 0.0];
  13625. }
  13626. var cMagnitude = Math.abs(c);
  13627. var aMagnitude = Math.abs(a);
  13628. if ((cMagnitude < aMagnitude) && (cMagnitude / aMagnitude < CesiumMath.EPSILON14)) { // c ~= 0.0.
  13629. // 2nd order monomial: a * x^2 = 0.
  13630. return [0.0, 0.0];
  13631. } else if ((cMagnitude > aMagnitude) && (aMagnitude / cMagnitude < CesiumMath.EPSILON14)) { // a ~= 0.0.
  13632. // Constant function: c = 0.
  13633. return [];
  13634. }
  13635. // a * x^2 + c = 0
  13636. ratio = -c / a;
  13637. if (ratio < 0.0) {
  13638. // Both roots are complex.
  13639. return [];
  13640. }
  13641. // Both roots are real.
  13642. var root = Math.sqrt(ratio);
  13643. return [-root, root];
  13644. } else if (c === 0.0) {
  13645. // a * x^2 + b * x = 0
  13646. ratio = -b / a;
  13647. if (ratio < 0.0) {
  13648. return [ratio, 0.0];
  13649. }
  13650. return [0.0, ratio];
  13651. }
  13652. // a * x^2 + b * x + c = 0
  13653. var b2 = b * b;
  13654. var four_ac = 4.0 * a * c;
  13655. var radicand = addWithCancellationCheck(b2, -four_ac, CesiumMath.EPSILON14);
  13656. if (radicand < 0.0) {
  13657. // Both roots are complex.
  13658. return [];
  13659. }
  13660. var q = -0.5 * addWithCancellationCheck(b, CesiumMath.sign(b) * Math.sqrt(radicand), CesiumMath.EPSILON14);
  13661. if (b > 0.0) {
  13662. return [q / a, c / q];
  13663. }
  13664. return [c / q, q / a];
  13665. };
  13666. return QuadraticRealPolynomial;
  13667. });
  13668. /*global define*/
  13669. define('Core/CubicRealPolynomial',[
  13670. './DeveloperError',
  13671. './QuadraticRealPolynomial'
  13672. ], function(
  13673. DeveloperError,
  13674. QuadraticRealPolynomial) {
  13675. 'use strict';
  13676. /**
  13677. * Defines functions for 3rd order polynomial functions of one variable with only real coefficients.
  13678. *
  13679. * @exports CubicRealPolynomial
  13680. */
  13681. var CubicRealPolynomial = {};
  13682. /**
  13683. * Provides the discriminant of the cubic equation from the supplied coefficients.
  13684. *
  13685. * @param {Number} a The coefficient of the 3rd order monomial.
  13686. * @param {Number} b The coefficient of the 2nd order monomial.
  13687. * @param {Number} c The coefficient of the 1st order monomial.
  13688. * @param {Number} d The coefficient of the 0th order monomial.
  13689. * @returns {Number} The value of the discriminant.
  13690. */
  13691. CubicRealPolynomial.computeDiscriminant = function(a, b, c, d) {
  13692. if (typeof a !== 'number') {
  13693. throw new DeveloperError('a is a required number.');
  13694. }
  13695. if (typeof b !== 'number') {
  13696. throw new DeveloperError('b is a required number.');
  13697. }
  13698. if (typeof c !== 'number') {
  13699. throw new DeveloperError('c is a required number.');
  13700. }
  13701. if (typeof d !== 'number') {
  13702. throw new DeveloperError('d is a required number.');
  13703. }
  13704. var a2 = a * a;
  13705. var b2 = b * b;
  13706. var c2 = c * c;
  13707. var d2 = d * d;
  13708. var discriminant = 18.0 * a * b * c * d + b2 * c2 - 27.0 * a2 * d2 - 4.0 * (a * c2 * c + b2 * b * d);
  13709. return discriminant;
  13710. };
  13711. function computeRealRoots(a, b, c, d) {
  13712. var A = a;
  13713. var B = b / 3.0;
  13714. var C = c / 3.0;
  13715. var D = d;
  13716. var AC = A * C;
  13717. var BD = B * D;
  13718. var B2 = B * B;
  13719. var C2 = C * C;
  13720. var delta1 = A * C - B2;
  13721. var delta2 = A * D - B * C;
  13722. var delta3 = B * D - C2;
  13723. var discriminant = 4.0 * delta1 * delta3 - delta2 * delta2;
  13724. var temp;
  13725. var temp1;
  13726. if (discriminant < 0.0) {
  13727. var ABar;
  13728. var CBar;
  13729. var DBar;
  13730. if (B2 * BD >= AC * C2) {
  13731. ABar = A;
  13732. CBar = delta1;
  13733. DBar = -2.0 * B * delta1 + A * delta2;
  13734. } else {
  13735. ABar = D;
  13736. CBar = delta3;
  13737. DBar = -D * delta2 + 2.0 * C * delta3;
  13738. }
  13739. var s = (DBar < 0.0) ? -1.0 : 1.0; // This is not Math.Sign()!
  13740. var temp0 = -s * Math.abs(ABar) * Math.sqrt(-discriminant);
  13741. temp1 = -DBar + temp0;
  13742. var x = temp1 / 2.0;
  13743. var p = x < 0.0 ? -Math.pow(-x, 1.0 / 3.0) : Math.pow(x, 1.0 / 3.0);
  13744. var q = (temp1 === temp0) ? -p : -CBar / p;
  13745. temp = (CBar <= 0.0) ? p + q : -DBar / (p * p + q * q + CBar);
  13746. if (B2 * BD >= AC * C2) {
  13747. return [(temp - B) / A];
  13748. }
  13749. return [-D / (temp + C)];
  13750. }
  13751. var CBarA = delta1;
  13752. var DBarA = -2.0 * B * delta1 + A * delta2;
  13753. var CBarD = delta3;
  13754. var DBarD = -D * delta2 + 2.0 * C * delta3;
  13755. var squareRootOfDiscriminant = Math.sqrt(discriminant);
  13756. var halfSquareRootOf3 = Math.sqrt(3.0) / 2.0;
  13757. var theta = Math.abs(Math.atan2(A * squareRootOfDiscriminant, -DBarA) / 3.0);
  13758. temp = 2.0 * Math.sqrt(-CBarA);
  13759. var cosine = Math.cos(theta);
  13760. temp1 = temp * cosine;
  13761. var temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  13762. var numeratorLarge = (temp1 + temp3 > 2.0 * B) ? temp1 - B : temp3 - B;
  13763. var denominatorLarge = A;
  13764. var root1 = numeratorLarge / denominatorLarge;
  13765. theta = Math.abs(Math.atan2(D * squareRootOfDiscriminant, -DBarD) / 3.0);
  13766. temp = 2.0 * Math.sqrt(-CBarD);
  13767. cosine = Math.cos(theta);
  13768. temp1 = temp * cosine;
  13769. temp3 = temp * (-cosine / 2.0 - halfSquareRootOf3 * Math.sin(theta));
  13770. var numeratorSmall = -D;
  13771. var denominatorSmall = (temp1 + temp3 < 2.0 * C) ? temp1 + C : temp3 + C;
  13772. var root3 = numeratorSmall / denominatorSmall;
  13773. var E = denominatorLarge * denominatorSmall;
  13774. var F = -numeratorLarge * denominatorSmall - denominatorLarge * numeratorSmall;
  13775. var G = numeratorLarge * numeratorSmall;
  13776. var root2 = (C * F - B * G) / (-B * F + C * E);
  13777. if (root1 <= root2) {
  13778. if (root1 <= root3) {
  13779. if (root2 <= root3) {
  13780. return [root1, root2, root3];
  13781. }
  13782. return [root1, root3, root2];
  13783. }
  13784. return [root3, root1, root2];
  13785. }
  13786. if (root1 <= root3) {
  13787. return [root2, root1, root3];
  13788. }
  13789. if (root2 <= root3) {
  13790. return [root2, root3, root1];
  13791. }
  13792. return [root3, root2, root1];
  13793. }
  13794. /**
  13795. * Provides the real valued roots of the cubic polynomial with the provided coefficients.
  13796. *
  13797. * @param {Number} a The coefficient of the 3rd order monomial.
  13798. * @param {Number} b The coefficient of the 2nd order monomial.
  13799. * @param {Number} c The coefficient of the 1st order monomial.
  13800. * @param {Number} d The coefficient of the 0th order monomial.
  13801. * @returns {Number[]} The real valued roots.
  13802. */
  13803. CubicRealPolynomial.computeRealRoots = function(a, b, c, d) {
  13804. if (typeof a !== 'number') {
  13805. throw new DeveloperError('a is a required number.');
  13806. }
  13807. if (typeof b !== 'number') {
  13808. throw new DeveloperError('b is a required number.');
  13809. }
  13810. if (typeof c !== 'number') {
  13811. throw new DeveloperError('c is a required number.');
  13812. }
  13813. if (typeof d !== 'number') {
  13814. throw new DeveloperError('d is a required number.');
  13815. }
  13816. var roots;
  13817. var ratio;
  13818. if (a === 0.0) {
  13819. // Quadratic function: b * x^2 + c * x + d = 0.
  13820. return QuadraticRealPolynomial.computeRealRoots(b, c, d);
  13821. } else if (b === 0.0) {
  13822. if (c === 0.0) {
  13823. if (d === 0.0) {
  13824. // 3rd order monomial: a * x^3 = 0.
  13825. return [0.0, 0.0, 0.0];
  13826. }
  13827. // a * x^3 + d = 0
  13828. ratio = -d / a;
  13829. var root = (ratio < 0.0) ? -Math.pow(-ratio, 1.0 / 3.0) : Math.pow(ratio, 1.0 / 3.0);
  13830. return [root, root, root];
  13831. } else if (d === 0.0) {
  13832. // x * (a * x^2 + c) = 0.
  13833. roots = QuadraticRealPolynomial.computeRealRoots(a, 0, c);
  13834. // Return the roots in ascending order.
  13835. if (roots.Length === 0) {
  13836. return [0.0];
  13837. }
  13838. return [roots[0], 0.0, roots[1]];
  13839. }
  13840. // Deflated cubic polynomial: a * x^3 + c * x + d= 0.
  13841. return computeRealRoots(a, 0, c, d);
  13842. } else if (c === 0.0) {
  13843. if (d === 0.0) {
  13844. // x^2 * (a * x + b) = 0.
  13845. ratio = -b / a;
  13846. if (ratio < 0.0) {
  13847. return [ratio, 0.0, 0.0];
  13848. }
  13849. return [0.0, 0.0, ratio];
  13850. }
  13851. // a * x^3 + b * x^2 + d = 0.
  13852. return computeRealRoots(a, b, 0, d);
  13853. } else if (d === 0.0) {
  13854. // x * (a * x^2 + b * x + c) = 0
  13855. roots = QuadraticRealPolynomial.computeRealRoots(a, b, c);
  13856. // Return the roots in ascending order.
  13857. if (roots.length === 0) {
  13858. return [0.0];
  13859. } else if (roots[1] <= 0.0) {
  13860. return [roots[0], roots[1], 0.0];
  13861. } else if (roots[0] >= 0.0) {
  13862. return [0.0, roots[0], roots[1]];
  13863. }
  13864. return [roots[0], 0.0, roots[1]];
  13865. }
  13866. return computeRealRoots(a, b, c, d);
  13867. };
  13868. return CubicRealPolynomial;
  13869. });
  13870. /*global define*/
  13871. define('Core/QuarticRealPolynomial',[
  13872. './CubicRealPolynomial',
  13873. './DeveloperError',
  13874. './Math',
  13875. './QuadraticRealPolynomial'
  13876. ], function(
  13877. CubicRealPolynomial,
  13878. DeveloperError,
  13879. CesiumMath,
  13880. QuadraticRealPolynomial) {
  13881. 'use strict';
  13882. /**
  13883. * Defines functions for 4th order polynomial functions of one variable with only real coefficients.
  13884. *
  13885. * @exports QuarticRealPolynomial
  13886. */
  13887. var QuarticRealPolynomial = {};
  13888. /**
  13889. * Provides the discriminant of the quartic equation from the supplied coefficients.
  13890. *
  13891. * @param {Number} a The coefficient of the 4th order monomial.
  13892. * @param {Number} b The coefficient of the 3rd order monomial.
  13893. * @param {Number} c The coefficient of the 2nd order monomial.
  13894. * @param {Number} d The coefficient of the 1st order monomial.
  13895. * @param {Number} e The coefficient of the 0th order monomial.
  13896. * @returns {Number} The value of the discriminant.
  13897. */
  13898. QuarticRealPolynomial.computeDiscriminant = function(a, b, c, d, e) {
  13899. if (typeof a !== 'number') {
  13900. throw new DeveloperError('a is a required number.');
  13901. }
  13902. if (typeof b !== 'number') {
  13903. throw new DeveloperError('b is a required number.');
  13904. }
  13905. if (typeof c !== 'number') {
  13906. throw new DeveloperError('c is a required number.');
  13907. }
  13908. if (typeof d !== 'number') {
  13909. throw new DeveloperError('d is a required number.');
  13910. }
  13911. if (typeof e !== 'number') {
  13912. throw new DeveloperError('e is a required number.');
  13913. }
  13914. var a2 = a * a;
  13915. var a3 = a2 * a;
  13916. var b2 = b * b;
  13917. var b3 = b2 * b;
  13918. var c2 = c * c;
  13919. var c3 = c2 * c;
  13920. var d2 = d * d;
  13921. var d3 = d2 * d;
  13922. var e2 = e * e;
  13923. var e3 = e2 * e;
  13924. 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) +
  13925. 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) +
  13926. e2 * (144.0 * a * b2 * c - 27.0 * b2 * b2 - 128.0 * a2 * c2 - 192.0 * a2 * b * d);
  13927. return discriminant;
  13928. };
  13929. function original(a3, a2, a1, a0) {
  13930. var a3Squared = a3 * a3;
  13931. var p = a2 - 3.0 * a3Squared / 8.0;
  13932. var q = a1 - a2 * a3 / 2.0 + a3Squared * a3 / 8.0;
  13933. var r = a0 - a1 * a3 / 4.0 + a2 * a3Squared / 16.0 - 3.0 * a3Squared * a3Squared / 256.0;
  13934. // Find the roots of the cubic equations: h^6 + 2 p h^4 + (p^2 - 4 r) h^2 - q^2 = 0.
  13935. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, 2.0 * p, p * p - 4.0 * r, -q * q);
  13936. if (cubicRoots.length > 0) {
  13937. var temp = -a3 / 4.0;
  13938. // Use the largest positive root.
  13939. var hSquared = cubicRoots[cubicRoots.length - 1];
  13940. if (Math.abs(hSquared) < CesiumMath.EPSILON14) {
  13941. // y^4 + p y^2 + r = 0.
  13942. var roots = QuadraticRealPolynomial.computeRealRoots(1.0, p, r);
  13943. if (roots.length === 2) {
  13944. var root0 = roots[0];
  13945. var root1 = roots[1];
  13946. var y;
  13947. if (root0 >= 0.0 && root1 >= 0.0) {
  13948. var y0 = Math.sqrt(root0);
  13949. var y1 = Math.sqrt(root1);
  13950. return [temp - y1, temp - y0, temp + y0, temp + y1];
  13951. } else if (root0 >= 0.0 && root1 < 0.0) {
  13952. y = Math.sqrt(root0);
  13953. return [temp - y, temp + y];
  13954. } else if (root0 < 0.0 && root1 >= 0.0) {
  13955. y = Math.sqrt(root1);
  13956. return [temp - y, temp + y];
  13957. }
  13958. }
  13959. return [];
  13960. } else if (hSquared > 0.0) {
  13961. var h = Math.sqrt(hSquared);
  13962. var m = (p + hSquared - q / h) / 2.0;
  13963. var n = (p + hSquared + q / h) / 2.0;
  13964. // Now solve the two quadratic factors: (y^2 + h y + m)(y^2 - h y + n);
  13965. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, h, m);
  13966. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, -h, n);
  13967. if (roots1.length !== 0) {
  13968. roots1[0] += temp;
  13969. roots1[1] += temp;
  13970. if (roots2.length !== 0) {
  13971. roots2[0] += temp;
  13972. roots2[1] += temp;
  13973. if (roots1[1] <= roots2[0]) {
  13974. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  13975. } else if (roots2[1] <= roots1[0]) {
  13976. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  13977. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  13978. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  13979. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  13980. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  13981. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  13982. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  13983. }
  13984. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  13985. }
  13986. return roots1;
  13987. }
  13988. if (roots2.length !== 0) {
  13989. roots2[0] += temp;
  13990. roots2[1] += temp;
  13991. return roots2;
  13992. }
  13993. return [];
  13994. }
  13995. }
  13996. return [];
  13997. }
  13998. function neumark(a3, a2, a1, a0) {
  13999. var a1Squared = a1 * a1;
  14000. var a2Squared = a2 * a2;
  14001. var a3Squared = a3 * a3;
  14002. var p = -2.0 * a2;
  14003. var q = a1 * a3 + a2Squared - 4.0 * a0;
  14004. var r = a3Squared * a0 - a1 * a2 * a3 + a1Squared;
  14005. var cubicRoots = CubicRealPolynomial.computeRealRoots(1.0, p, q, r);
  14006. if (cubicRoots.length > 0) {
  14007. // Use the most positive root
  14008. var y = cubicRoots[0];
  14009. var temp = (a2 - y);
  14010. var tempSquared = temp * temp;
  14011. var g1 = a3 / 2.0;
  14012. var h1 = temp / 2.0;
  14013. var m = tempSquared - 4.0 * a0;
  14014. var mError = tempSquared + 4.0 * Math.abs(a0);
  14015. var n = a3Squared - 4.0 * y;
  14016. var nError = a3Squared + 4.0 * Math.abs(y);
  14017. var g2;
  14018. var h2;
  14019. if (y < 0.0 || (m * nError < n * mError)) {
  14020. var squareRootOfN = Math.sqrt(n);
  14021. g2 = squareRootOfN / 2.0;
  14022. h2 = squareRootOfN === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfN;
  14023. } else {
  14024. var squareRootOfM = Math.sqrt(m);
  14025. g2 = squareRootOfM === 0.0 ? 0.0 : (a3 * h1 - a1) / squareRootOfM;
  14026. h2 = squareRootOfM / 2.0;
  14027. }
  14028. var G;
  14029. var g;
  14030. if (g1 === 0.0 && g2 === 0.0) {
  14031. G = 0.0;
  14032. g = 0.0;
  14033. } else if (CesiumMath.sign(g1) === CesiumMath.sign(g2)) {
  14034. G = g1 + g2;
  14035. g = y / G;
  14036. } else {
  14037. g = g1 - g2;
  14038. G = y / g;
  14039. }
  14040. var H;
  14041. var h;
  14042. if (h1 === 0.0 && h2 === 0.0) {
  14043. H = 0.0;
  14044. h = 0.0;
  14045. } else if (CesiumMath.sign(h1) === CesiumMath.sign(h2)) {
  14046. H = h1 + h2;
  14047. h = a0 / H;
  14048. } else {
  14049. h = h1 - h2;
  14050. H = a0 / h;
  14051. }
  14052. // Now solve the two quadratic factors: (y^2 + G y + H)(y^2 + g y + h);
  14053. var roots1 = QuadraticRealPolynomial.computeRealRoots(1.0, G, H);
  14054. var roots2 = QuadraticRealPolynomial.computeRealRoots(1.0, g, h);
  14055. if (roots1.length !== 0) {
  14056. if (roots2.length !== 0) {
  14057. if (roots1[1] <= roots2[0]) {
  14058. return [roots1[0], roots1[1], roots2[0], roots2[1]];
  14059. } else if (roots2[1] <= roots1[0]) {
  14060. return [roots2[0], roots2[1], roots1[0], roots1[1]];
  14061. } else if (roots1[0] >= roots2[0] && roots1[1] <= roots2[1]) {
  14062. return [roots2[0], roots1[0], roots1[1], roots2[1]];
  14063. } else if (roots2[0] >= roots1[0] && roots2[1] <= roots1[1]) {
  14064. return [roots1[0], roots2[0], roots2[1], roots1[1]];
  14065. } else if (roots1[0] > roots2[0] && roots1[0] < roots2[1]) {
  14066. return [roots2[0], roots1[0], roots2[1], roots1[1]];
  14067. } else {
  14068. return [roots1[0], roots2[0], roots1[1], roots2[1]];
  14069. }
  14070. }
  14071. return roots1;
  14072. }
  14073. if (roots2.length !== 0) {
  14074. return roots2;
  14075. }
  14076. }
  14077. return [];
  14078. }
  14079. /**
  14080. * Provides the real valued roots of the quartic polynomial with the provided coefficients.
  14081. *
  14082. * @param {Number} a The coefficient of the 4th order monomial.
  14083. * @param {Number} b The coefficient of the 3rd order monomial.
  14084. * @param {Number} c The coefficient of the 2nd order monomial.
  14085. * @param {Number} d The coefficient of the 1st order monomial.
  14086. * @param {Number} e The coefficient of the 0th order monomial.
  14087. * @returns {Number[]} The real valued roots.
  14088. */
  14089. QuarticRealPolynomial.computeRealRoots = function(a, b, c, d, e) {
  14090. if (typeof a !== 'number') {
  14091. throw new DeveloperError('a is a required number.');
  14092. }
  14093. if (typeof b !== 'number') {
  14094. throw new DeveloperError('b is a required number.');
  14095. }
  14096. if (typeof c !== 'number') {
  14097. throw new DeveloperError('c is a required number.');
  14098. }
  14099. if (typeof d !== 'number') {
  14100. throw new DeveloperError('d is a required number.');
  14101. }
  14102. if (typeof e !== 'number') {
  14103. throw new DeveloperError('e is a required number.');
  14104. }
  14105. if (Math.abs(a) < CesiumMath.EPSILON15) {
  14106. return CubicRealPolynomial.computeRealRoots(b, c, d, e);
  14107. }
  14108. var a3 = b / a;
  14109. var a2 = c / a;
  14110. var a1 = d / a;
  14111. var a0 = e / a;
  14112. var k = (a3 < 0.0) ? 1 : 0;
  14113. k += (a2 < 0.0) ? k + 1 : k;
  14114. k += (a1 < 0.0) ? k + 1 : k;
  14115. k += (a0 < 0.0) ? k + 1 : k;
  14116. switch (k) {
  14117. case 0:
  14118. return original(a3, a2, a1, a0);
  14119. case 1:
  14120. return neumark(a3, a2, a1, a0);
  14121. case 2:
  14122. return neumark(a3, a2, a1, a0);
  14123. case 3:
  14124. return original(a3, a2, a1, a0);
  14125. case 4:
  14126. return original(a3, a2, a1, a0);
  14127. case 5:
  14128. return neumark(a3, a2, a1, a0);
  14129. case 6:
  14130. return original(a3, a2, a1, a0);
  14131. case 7:
  14132. return original(a3, a2, a1, a0);
  14133. case 8:
  14134. return neumark(a3, a2, a1, a0);
  14135. case 9:
  14136. return original(a3, a2, a1, a0);
  14137. case 10:
  14138. return original(a3, a2, a1, a0);
  14139. case 11:
  14140. return neumark(a3, a2, a1, a0);
  14141. case 12:
  14142. return original(a3, a2, a1, a0);
  14143. case 13:
  14144. return original(a3, a2, a1, a0);
  14145. case 14:
  14146. return original(a3, a2, a1, a0);
  14147. case 15:
  14148. return original(a3, a2, a1, a0);
  14149. default:
  14150. return undefined;
  14151. }
  14152. };
  14153. return QuarticRealPolynomial;
  14154. });
  14155. /*global define*/
  14156. define('Core/Ray',[
  14157. './Cartesian3',
  14158. './defaultValue',
  14159. './defined',
  14160. './DeveloperError'
  14161. ], function(
  14162. Cartesian3,
  14163. defaultValue,
  14164. defined,
  14165. DeveloperError) {
  14166. 'use strict';
  14167. /**
  14168. * Represents a ray that extends infinitely from the provided origin in the provided direction.
  14169. * @alias Ray
  14170. * @constructor
  14171. *
  14172. * @param {Cartesian3} [origin=Cartesian3.ZERO] The origin of the ray.
  14173. * @param {Cartesian3} [direction=Cartesian3.ZERO] The direction of the ray.
  14174. */
  14175. function Ray(origin, direction) {
  14176. direction = Cartesian3.clone(defaultValue(direction, Cartesian3.ZERO));
  14177. if (!Cartesian3.equals(direction, Cartesian3.ZERO)) {
  14178. Cartesian3.normalize(direction, direction);
  14179. }
  14180. /**
  14181. * The origin of the ray.
  14182. * @type {Cartesian3}
  14183. * @default {@link Cartesian3.ZERO}
  14184. */
  14185. this.origin = Cartesian3.clone(defaultValue(origin, Cartesian3.ZERO));
  14186. /**
  14187. * The direction of the ray.
  14188. * @type {Cartesian3}
  14189. */
  14190. this.direction = direction;
  14191. }
  14192. /**
  14193. * Computes the point along the ray given by r(t) = o + t*d,
  14194. * where o is the origin of the ray and d is the direction.
  14195. *
  14196. * @param {Ray} ray The ray.
  14197. * @param {Number} t A scalar value.
  14198. * @param {Cartesian3} [result] The object in which the result will be stored.
  14199. * @returns {Cartesian3} The modified result parameter, or a new instance if none was provided.
  14200. *
  14201. * @example
  14202. * //Get the first intersection point of a ray and an ellipsoid.
  14203. * var intersection = Cesium.IntersectionTests.rayEllipsoid(ray, ellipsoid);
  14204. * var point = Cesium.Ray.getPoint(ray, intersection.start);
  14205. */
  14206. Ray.getPoint = function(ray, t, result) {
  14207. if (!defined(ray)){
  14208. throw new DeveloperError('ray is requred');
  14209. }
  14210. if (typeof t !== 'number') {
  14211. throw new DeveloperError('t is a required number');
  14212. }
  14213. if (!defined(result)) {
  14214. result = new Cartesian3();
  14215. }
  14216. result = Cartesian3.multiplyByScalar(ray.direction, t, result);
  14217. return Cartesian3.add(ray.origin, result, result);
  14218. };
  14219. return Ray;
  14220. });
  14221. /*global define*/
  14222. define('Core/IntersectionTests',[
  14223. './Cartesian3',
  14224. './Cartographic',
  14225. './defaultValue',
  14226. './defined',
  14227. './DeveloperError',
  14228. './Math',
  14229. './Matrix3',
  14230. './QuadraticRealPolynomial',
  14231. './QuarticRealPolynomial',
  14232. './Ray'
  14233. ], function(
  14234. Cartesian3,
  14235. Cartographic,
  14236. defaultValue,
  14237. defined,
  14238. DeveloperError,
  14239. CesiumMath,
  14240. Matrix3,
  14241. QuadraticRealPolynomial,
  14242. QuarticRealPolynomial,
  14243. Ray) {
  14244. 'use strict';
  14245. /**
  14246. * Functions for computing the intersection between geometries such as rays, planes, triangles, and ellipsoids.
  14247. *
  14248. * @exports IntersectionTests
  14249. */
  14250. var IntersectionTests = {};
  14251. /**
  14252. * Computes the intersection of a ray and a plane.
  14253. *
  14254. * @param {Ray} ray The ray.
  14255. * @param {Plane} plane The plane.
  14256. * @param {Cartesian3} [result] The object onto which to store the result.
  14257. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  14258. */
  14259. IntersectionTests.rayPlane = function(ray, plane, result) {
  14260. if (!defined(ray)) {
  14261. throw new DeveloperError('ray is required.');
  14262. }
  14263. if (!defined(plane)) {
  14264. throw new DeveloperError('plane is required.');
  14265. }
  14266. if (!defined(result)) {
  14267. result = new Cartesian3();
  14268. }
  14269. var origin = ray.origin;
  14270. var direction = ray.direction;
  14271. var normal = plane.normal;
  14272. var denominator = Cartesian3.dot(normal, direction);
  14273. if (Math.abs(denominator) < CesiumMath.EPSILON15) {
  14274. // Ray is parallel to plane. The ray may be in the polygon's plane.
  14275. return undefined;
  14276. }
  14277. var t = (-plane.distance - Cartesian3.dot(normal, origin)) / denominator;
  14278. if (t < 0) {
  14279. return undefined;
  14280. }
  14281. result = Cartesian3.multiplyByScalar(direction, t, result);
  14282. return Cartesian3.add(origin, result, result);
  14283. };
  14284. var scratchEdge0 = new Cartesian3();
  14285. var scratchEdge1 = new Cartesian3();
  14286. var scratchPVec = new Cartesian3();
  14287. var scratchTVec = new Cartesian3();
  14288. var scratchQVec = new Cartesian3();
  14289. /**
  14290. * Computes the intersection of a ray and a triangle as a parametric distance along the input ray.
  14291. *
  14292. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  14293. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  14294. *
  14295. * @memberof IntersectionTests
  14296. *
  14297. * @param {Ray} ray The ray.
  14298. * @param {Cartesian3} p0 The first vertex of the triangle.
  14299. * @param {Cartesian3} p1 The second vertex of the triangle.
  14300. * @param {Cartesian3} p2 The third vertex of the triangle.
  14301. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  14302. * and return undefined for intersections with the back face.
  14303. * @returns {Number} The intersection as a parametric distance along the ray, or undefined if there is no intersection.
  14304. */
  14305. IntersectionTests.rayTriangleParametric = function(ray, p0, p1, p2, cullBackFaces) {
  14306. if (!defined(ray)) {
  14307. throw new DeveloperError('ray is required.');
  14308. }
  14309. if (!defined(p0)) {
  14310. throw new DeveloperError('p0 is required.');
  14311. }
  14312. if (!defined(p1)) {
  14313. throw new DeveloperError('p1 is required.');
  14314. }
  14315. if (!defined(p2)) {
  14316. throw new DeveloperError('p2 is required.');
  14317. }
  14318. cullBackFaces = defaultValue(cullBackFaces, false);
  14319. var origin = ray.origin;
  14320. var direction = ray.direction;
  14321. var edge0 = Cartesian3.subtract(p1, p0, scratchEdge0);
  14322. var edge1 = Cartesian3.subtract(p2, p0, scratchEdge1);
  14323. var p = Cartesian3.cross(direction, edge1, scratchPVec);
  14324. var det = Cartesian3.dot(edge0, p);
  14325. var tvec;
  14326. var q;
  14327. var u;
  14328. var v;
  14329. var t;
  14330. if (cullBackFaces) {
  14331. if (det < CesiumMath.EPSILON6) {
  14332. return undefined;
  14333. }
  14334. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  14335. u = Cartesian3.dot(tvec, p);
  14336. if (u < 0.0 || u > det) {
  14337. return undefined;
  14338. }
  14339. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  14340. v = Cartesian3.dot(direction, q);
  14341. if (v < 0.0 || u + v > det) {
  14342. return undefined;
  14343. }
  14344. t = Cartesian3.dot(edge1, q) / det;
  14345. } else {
  14346. if (Math.abs(det) < CesiumMath.EPSILON6) {
  14347. return undefined;
  14348. }
  14349. var invDet = 1.0 / det;
  14350. tvec = Cartesian3.subtract(origin, p0, scratchTVec);
  14351. u = Cartesian3.dot(tvec, p) * invDet;
  14352. if (u < 0.0 || u > 1.0) {
  14353. return undefined;
  14354. }
  14355. q = Cartesian3.cross(tvec, edge0, scratchQVec);
  14356. v = Cartesian3.dot(direction, q) * invDet;
  14357. if (v < 0.0 || u + v > 1.0) {
  14358. return undefined;
  14359. }
  14360. t = Cartesian3.dot(edge1, q) * invDet;
  14361. }
  14362. return t;
  14363. };
  14364. /**
  14365. * Computes the intersection of a ray and a triangle as a Cartesian3 coordinate.
  14366. *
  14367. * Implements {@link https://cadxfem.org/inf/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf|
  14368. * Fast Minimum Storage Ray/Triangle Intersection} by Tomas Moller and Ben Trumbore.
  14369. *
  14370. * @memberof IntersectionTests
  14371. *
  14372. * @param {Ray} ray The ray.
  14373. * @param {Cartesian3} p0 The first vertex of the triangle.
  14374. * @param {Cartesian3} p1 The second vertex of the triangle.
  14375. * @param {Cartesian3} p2 The third vertex of the triangle.
  14376. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  14377. * and return undefined for intersections with the back face.
  14378. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  14379. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  14380. */
  14381. IntersectionTests.rayTriangle = function(ray, p0, p1, p2, cullBackFaces, result) {
  14382. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  14383. if (!defined(t) || t < 0.0) {
  14384. return undefined;
  14385. }
  14386. if (!defined(result)) {
  14387. result = new Cartesian3();
  14388. }
  14389. Cartesian3.multiplyByScalar(ray.direction, t, result);
  14390. return Cartesian3.add(ray.origin, result, result);
  14391. };
  14392. var scratchLineSegmentTriangleRay = new Ray();
  14393. /**
  14394. * Computes the intersection of a line segment and a triangle.
  14395. * @memberof IntersectionTests
  14396. *
  14397. * @param {Cartesian3} v0 The an end point of the line segment.
  14398. * @param {Cartesian3} v1 The other end point of the line segment.
  14399. * @param {Cartesian3} p0 The first vertex of the triangle.
  14400. * @param {Cartesian3} p1 The second vertex of the triangle.
  14401. * @param {Cartesian3} p2 The third vertex of the triangle.
  14402. * @param {Boolean} [cullBackFaces=false] If <code>true</code>, will only compute an intersection with the front face of the triangle
  14403. * and return undefined for intersections with the back face.
  14404. * @param {Cartesian3} [result] The <code>Cartesian3</code> onto which to store the result.
  14405. * @returns {Cartesian3} The intersection point or undefined if there is no intersections.
  14406. */
  14407. IntersectionTests.lineSegmentTriangle = function(v0, v1, p0, p1, p2, cullBackFaces, result) {
  14408. if (!defined(v0)) {
  14409. throw new DeveloperError('v0 is required.');
  14410. }
  14411. if (!defined(v1)) {
  14412. throw new DeveloperError('v1 is required.');
  14413. }
  14414. if (!defined(p0)) {
  14415. throw new DeveloperError('p0 is required.');
  14416. }
  14417. if (!defined(p1)) {
  14418. throw new DeveloperError('p1 is required.');
  14419. }
  14420. if (!defined(p2)) {
  14421. throw new DeveloperError('p2 is required.');
  14422. }
  14423. var ray = scratchLineSegmentTriangleRay;
  14424. Cartesian3.clone(v0, ray.origin);
  14425. Cartesian3.subtract(v1, v0, ray.direction);
  14426. Cartesian3.normalize(ray.direction, ray.direction);
  14427. var t = IntersectionTests.rayTriangleParametric(ray, p0, p1, p2, cullBackFaces);
  14428. if (!defined(t) || t < 0.0 || t > Cartesian3.distance(v0, v1)) {
  14429. return undefined;
  14430. }
  14431. if (!defined(result)) {
  14432. result = new Cartesian3();
  14433. }
  14434. Cartesian3.multiplyByScalar(ray.direction, t, result);
  14435. return Cartesian3.add(ray.origin, result, result);
  14436. };
  14437. function solveQuadratic(a, b, c, result) {
  14438. var det = b * b - 4.0 * a * c;
  14439. if (det < 0.0) {
  14440. return undefined;
  14441. } else if (det > 0.0) {
  14442. var denom = 1.0 / (2.0 * a);
  14443. var disc = Math.sqrt(det);
  14444. var root0 = (-b + disc) * denom;
  14445. var root1 = (-b - disc) * denom;
  14446. if (root0 < root1) {
  14447. result.root0 = root0;
  14448. result.root1 = root1;
  14449. } else {
  14450. result.root0 = root1;
  14451. result.root1 = root0;
  14452. }
  14453. return result;
  14454. }
  14455. var root = -b / (2.0 * a);
  14456. if (root === 0.0) {
  14457. return undefined;
  14458. }
  14459. result.root0 = result.root1 = root;
  14460. return result;
  14461. }
  14462. var raySphereRoots = {
  14463. root0 : 0.0,
  14464. root1 : 0.0
  14465. };
  14466. function raySphere(ray, sphere, result) {
  14467. if (!defined(result)) {
  14468. result = {};
  14469. }
  14470. var origin = ray.origin;
  14471. var direction = ray.direction;
  14472. var center = sphere.center;
  14473. var radiusSquared = sphere.radius * sphere.radius;
  14474. var diff = Cartesian3.subtract(origin, center, scratchPVec);
  14475. var a = Cartesian3.dot(direction, direction);
  14476. var b = 2.0 * Cartesian3.dot(direction, diff);
  14477. var c = Cartesian3.magnitudeSquared(diff) - radiusSquared;
  14478. var roots = solveQuadratic(a, b, c, raySphereRoots);
  14479. if (!defined(roots)) {
  14480. return undefined;
  14481. }
  14482. result.start = roots.root0;
  14483. result.stop = roots.root1;
  14484. return result;
  14485. }
  14486. /**
  14487. * Computes the intersection points of a ray with a sphere.
  14488. * @memberof IntersectionTests
  14489. *
  14490. * @param {Ray} ray The ray.
  14491. * @param {BoundingSphere} sphere The sphere.
  14492. * @param {Object} [result] The result onto which to store the result.
  14493. * @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.
  14494. */
  14495. IntersectionTests.raySphere = function(ray, sphere, result) {
  14496. if (!defined(ray)) {
  14497. throw new DeveloperError('ray is required.');
  14498. }
  14499. if (!defined(sphere)) {
  14500. throw new DeveloperError('sphere is required.');
  14501. }
  14502. result = raySphere(ray, sphere, result);
  14503. if (!defined(result) || result.stop < 0.0) {
  14504. return undefined;
  14505. }
  14506. result.start = Math.max(result.start, 0.0);
  14507. return result;
  14508. };
  14509. var scratchLineSegmentRay = new Ray();
  14510. /**
  14511. * Computes the intersection points of a line segment with a sphere.
  14512. * @memberof IntersectionTests
  14513. *
  14514. * @param {Cartesian3} p0 An end point of the line segment.
  14515. * @param {Cartesian3} p1 The other end point of the line segment.
  14516. * @param {BoundingSphere} sphere The sphere.
  14517. * @param {Object} [result] The result onto which to store the result.
  14518. * @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.
  14519. */
  14520. IntersectionTests.lineSegmentSphere = function(p0, p1, sphere, result) {
  14521. if (!defined(p0)) {
  14522. throw new DeveloperError('p0 is required.');
  14523. }
  14524. if (!defined(p1)) {
  14525. throw new DeveloperError('p1 is required.');
  14526. }
  14527. if (!defined(sphere)) {
  14528. throw new DeveloperError('sphere is required.');
  14529. }
  14530. var ray = scratchLineSegmentRay;
  14531. Cartesian3.clone(p0, ray.origin);
  14532. var direction = Cartesian3.subtract(p1, p0, ray.direction);
  14533. var maxT = Cartesian3.magnitude(direction);
  14534. Cartesian3.normalize(direction, direction);
  14535. result = raySphere(ray, sphere, result);
  14536. if (!defined(result) || result.stop < 0.0 || result.start > maxT) {
  14537. return undefined;
  14538. }
  14539. result.start = Math.max(result.start, 0.0);
  14540. result.stop = Math.min(result.stop, maxT);
  14541. return result;
  14542. };
  14543. var scratchQ = new Cartesian3();
  14544. var scratchW = new Cartesian3();
  14545. /**
  14546. * Computes the intersection points of a ray with an ellipsoid.
  14547. *
  14548. * @param {Ray} ray The ray.
  14549. * @param {Ellipsoid} ellipsoid The ellipsoid.
  14550. * @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.
  14551. */
  14552. IntersectionTests.rayEllipsoid = function(ray, ellipsoid) {
  14553. if (!defined(ray)) {
  14554. throw new DeveloperError('ray is required.');
  14555. }
  14556. if (!defined(ellipsoid)) {
  14557. throw new DeveloperError('ellipsoid is required.');
  14558. }
  14559. var inverseRadii = ellipsoid.oneOverRadii;
  14560. var q = Cartesian3.multiplyComponents(inverseRadii, ray.origin, scratchQ);
  14561. var w = Cartesian3.multiplyComponents(inverseRadii, ray.direction, scratchW);
  14562. var q2 = Cartesian3.magnitudeSquared(q);
  14563. var qw = Cartesian3.dot(q, w);
  14564. var difference, w2, product, discriminant, temp;
  14565. if (q2 > 1.0) {
  14566. // Outside ellipsoid.
  14567. if (qw >= 0.0) {
  14568. // Looking outward or tangent (0 intersections).
  14569. return undefined;
  14570. }
  14571. // qw < 0.0.
  14572. var qw2 = qw * qw;
  14573. difference = q2 - 1.0; // Positively valued.
  14574. w2 = Cartesian3.magnitudeSquared(w);
  14575. product = w2 * difference;
  14576. if (qw2 < product) {
  14577. // Imaginary roots (0 intersections).
  14578. return undefined;
  14579. } else if (qw2 > product) {
  14580. // Distinct roots (2 intersections).
  14581. discriminant = qw * qw - product;
  14582. temp = -qw + Math.sqrt(discriminant); // Avoid cancellation.
  14583. var root0 = temp / w2;
  14584. var root1 = difference / temp;
  14585. if (root0 < root1) {
  14586. return {
  14587. start : root0,
  14588. stop : root1
  14589. };
  14590. }
  14591. return {
  14592. start : root1,
  14593. stop : root0
  14594. };
  14595. } else {
  14596. // qw2 == product. Repeated roots (2 intersections).
  14597. var root = Math.sqrt(difference / w2);
  14598. return {
  14599. start : root,
  14600. stop : root
  14601. };
  14602. }
  14603. } else if (q2 < 1.0) {
  14604. // Inside ellipsoid (2 intersections).
  14605. difference = q2 - 1.0; // Negatively valued.
  14606. w2 = Cartesian3.magnitudeSquared(w);
  14607. product = w2 * difference; // Negatively valued.
  14608. discriminant = qw * qw - product;
  14609. temp = -qw + Math.sqrt(discriminant); // Positively valued.
  14610. return {
  14611. start : 0.0,
  14612. stop : temp / w2
  14613. };
  14614. } else {
  14615. // q2 == 1.0. On ellipsoid.
  14616. if (qw < 0.0) {
  14617. // Looking inward.
  14618. w2 = Cartesian3.magnitudeSquared(w);
  14619. return {
  14620. start : 0.0,
  14621. stop : -qw / w2
  14622. };
  14623. }
  14624. // qw >= 0.0. Looking outward or tangent.
  14625. return undefined;
  14626. }
  14627. };
  14628. function addWithCancellationCheck(left, right, tolerance) {
  14629. var difference = left + right;
  14630. if ((CesiumMath.sign(left) !== CesiumMath.sign(right)) &&
  14631. Math.abs(difference / Math.max(Math.abs(left), Math.abs(right))) < tolerance) {
  14632. return 0.0;
  14633. }
  14634. return difference;
  14635. }
  14636. function quadraticVectorExpression(A, b, c, x, w) {
  14637. var xSquared = x * x;
  14638. var wSquared = w * w;
  14639. var l2 = (A[Matrix3.COLUMN1ROW1] - A[Matrix3.COLUMN2ROW2]) * wSquared;
  14640. var l1 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN1ROW0], A[Matrix3.COLUMN0ROW1], CesiumMath.EPSILON15) + b.y);
  14641. var l0 = (A[Matrix3.COLUMN0ROW0] * xSquared + A[Matrix3.COLUMN2ROW2] * wSquared) + x * b.x + c;
  14642. var r1 = wSquared * addWithCancellationCheck(A[Matrix3.COLUMN2ROW1], A[Matrix3.COLUMN1ROW2], CesiumMath.EPSILON15);
  14643. var r0 = w * (x * addWithCancellationCheck(A[Matrix3.COLUMN2ROW0], A[Matrix3.COLUMN0ROW2]) + b.z);
  14644. var cosines;
  14645. var solutions = [];
  14646. if (r0 === 0.0 && r1 === 0.0) {
  14647. cosines = QuadraticRealPolynomial.computeRealRoots(l2, l1, l0);
  14648. if (cosines.length === 0) {
  14649. return solutions;
  14650. }
  14651. var cosine0 = cosines[0];
  14652. var sine0 = Math.sqrt(Math.max(1.0 - cosine0 * cosine0, 0.0));
  14653. solutions.push(new Cartesian3(x, w * cosine0, w * -sine0));
  14654. solutions.push(new Cartesian3(x, w * cosine0, w * sine0));
  14655. if (cosines.length === 2) {
  14656. var cosine1 = cosines[1];
  14657. var sine1 = Math.sqrt(Math.max(1.0 - cosine1 * cosine1, 0.0));
  14658. solutions.push(new Cartesian3(x, w * cosine1, w * -sine1));
  14659. solutions.push(new Cartesian3(x, w * cosine1, w * sine1));
  14660. }
  14661. return solutions;
  14662. }
  14663. var r0Squared = r0 * r0;
  14664. var r1Squared = r1 * r1;
  14665. var l2Squared = l2 * l2;
  14666. var r0r1 = r0 * r1;
  14667. var c4 = l2Squared + r1Squared;
  14668. var c3 = 2.0 * (l1 * l2 + r0r1);
  14669. var c2 = 2.0 * l0 * l2 + l1 * l1 - r1Squared + r0Squared;
  14670. var c1 = 2.0 * (l0 * l1 - r0r1);
  14671. var c0 = l0 * l0 - r0Squared;
  14672. if (c4 === 0.0 && c3 === 0.0 && c2 === 0.0 && c1 === 0.0) {
  14673. return solutions;
  14674. }
  14675. cosines = QuarticRealPolynomial.computeRealRoots(c4, c3, c2, c1, c0);
  14676. var length = cosines.length;
  14677. if (length === 0) {
  14678. return solutions;
  14679. }
  14680. for ( var i = 0; i < length; ++i) {
  14681. var cosine = cosines[i];
  14682. var cosineSquared = cosine * cosine;
  14683. var sineSquared = Math.max(1.0 - cosineSquared, 0.0);
  14684. var sine = Math.sqrt(sineSquared);
  14685. //var left = l2 * cosineSquared + l1 * cosine + l0;
  14686. var left;
  14687. if (CesiumMath.sign(l2) === CesiumMath.sign(l0)) {
  14688. left = addWithCancellationCheck(l2 * cosineSquared + l0, l1 * cosine, CesiumMath.EPSILON12);
  14689. } else if (CesiumMath.sign(l0) === CesiumMath.sign(l1 * cosine)) {
  14690. left = addWithCancellationCheck(l2 * cosineSquared, l1 * cosine + l0, CesiumMath.EPSILON12);
  14691. } else {
  14692. left = addWithCancellationCheck(l2 * cosineSquared + l1 * cosine, l0, CesiumMath.EPSILON12);
  14693. }
  14694. var right = addWithCancellationCheck(r1 * cosine, r0, CesiumMath.EPSILON15);
  14695. var product = left * right;
  14696. if (product < 0.0) {
  14697. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  14698. } else if (product > 0.0) {
  14699. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  14700. } else if (sine !== 0.0) {
  14701. solutions.push(new Cartesian3(x, w * cosine, w * -sine));
  14702. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  14703. ++i;
  14704. } else {
  14705. solutions.push(new Cartesian3(x, w * cosine, w * sine));
  14706. }
  14707. }
  14708. return solutions;
  14709. }
  14710. var firstAxisScratch = new Cartesian3();
  14711. var secondAxisScratch = new Cartesian3();
  14712. var thirdAxisScratch = new Cartesian3();
  14713. var referenceScratch = new Cartesian3();
  14714. var bCart = new Cartesian3();
  14715. var bScratch = new Matrix3();
  14716. var btScratch = new Matrix3();
  14717. var diScratch = new Matrix3();
  14718. var dScratch = new Matrix3();
  14719. var cScratch = new Matrix3();
  14720. var tempMatrix = new Matrix3();
  14721. var aScratch = new Matrix3();
  14722. var sScratch = new Cartesian3();
  14723. var closestScratch = new Cartesian3();
  14724. var surfPointScratch = new Cartographic();
  14725. /**
  14726. * Provides the point along the ray which is nearest to the ellipsoid.
  14727. *
  14728. * @param {Ray} ray The ray.
  14729. * @param {Ellipsoid} ellipsoid The ellipsoid.
  14730. * @returns {Cartesian3} The nearest planetodetic point on the ray.
  14731. */
  14732. IntersectionTests.grazingAltitudeLocation = function(ray, ellipsoid) {
  14733. if (!defined(ray)) {
  14734. throw new DeveloperError('ray is required.');
  14735. }
  14736. if (!defined(ellipsoid)) {
  14737. throw new DeveloperError('ellipsoid is required.');
  14738. }
  14739. var position = ray.origin;
  14740. var direction = ray.direction;
  14741. if (!Cartesian3.equals(position, Cartesian3.ZERO)) {
  14742. var normal = ellipsoid.geodeticSurfaceNormal(position, firstAxisScratch);
  14743. if (Cartesian3.dot(direction, normal) >= 0.0) { // The location provided is the closest point in altitude
  14744. return position;
  14745. }
  14746. }
  14747. var intersects = defined(this.rayEllipsoid(ray, ellipsoid));
  14748. // Compute the scaled direction vector.
  14749. var f = ellipsoid.transformPositionToScaledSpace(direction, firstAxisScratch);
  14750. // Constructs a basis from the unit scaled direction vector. Construct its rotation and transpose.
  14751. var firstAxis = Cartesian3.normalize(f, f);
  14752. var reference = Cartesian3.mostOrthogonalAxis(f, referenceScratch);
  14753. var secondAxis = Cartesian3.normalize(Cartesian3.cross(reference, firstAxis, secondAxisScratch), secondAxisScratch);
  14754. var thirdAxis = Cartesian3.normalize(Cartesian3.cross(firstAxis, secondAxis, thirdAxisScratch), thirdAxisScratch);
  14755. var B = bScratch;
  14756. B[0] = firstAxis.x;
  14757. B[1] = firstAxis.y;
  14758. B[2] = firstAxis.z;
  14759. B[3] = secondAxis.x;
  14760. B[4] = secondAxis.y;
  14761. B[5] = secondAxis.z;
  14762. B[6] = thirdAxis.x;
  14763. B[7] = thirdAxis.y;
  14764. B[8] = thirdAxis.z;
  14765. var B_T = Matrix3.transpose(B, btScratch);
  14766. // Get the scaling matrix and its inverse.
  14767. var D_I = Matrix3.fromScale(ellipsoid.radii, diScratch);
  14768. var D = Matrix3.fromScale(ellipsoid.oneOverRadii, dScratch);
  14769. var C = cScratch;
  14770. C[0] = 0.0;
  14771. C[1] = -direction.z;
  14772. C[2] = direction.y;
  14773. C[3] = direction.z;
  14774. C[4] = 0.0;
  14775. C[5] = -direction.x;
  14776. C[6] = -direction.y;
  14777. C[7] = direction.x;
  14778. C[8] = 0.0;
  14779. var temp = Matrix3.multiply(Matrix3.multiply(B_T, D, tempMatrix), C, tempMatrix);
  14780. var A = Matrix3.multiply(Matrix3.multiply(temp, D_I, aScratch), B, aScratch);
  14781. var b = Matrix3.multiplyByVector(temp, position, bCart);
  14782. // Solve for the solutions to the expression in standard form:
  14783. var solutions = quadraticVectorExpression(A, Cartesian3.negate(b, firstAxisScratch), 0.0, 0.0, 1.0);
  14784. var s;
  14785. var altitude;
  14786. var length = solutions.length;
  14787. if (length > 0) {
  14788. var closest = Cartesian3.clone(Cartesian3.ZERO, closestScratch);
  14789. var maximumValue = Number.NEGATIVE_INFINITY;
  14790. for ( var i = 0; i < length; ++i) {
  14791. s = Matrix3.multiplyByVector(D_I, Matrix3.multiplyByVector(B, solutions[i], sScratch), sScratch);
  14792. var v = Cartesian3.normalize(Cartesian3.subtract(s, position, referenceScratch), referenceScratch);
  14793. var dotProduct = Cartesian3.dot(v, direction);
  14794. if (dotProduct > maximumValue) {
  14795. maximumValue = dotProduct;
  14796. closest = Cartesian3.clone(s, closest);
  14797. }
  14798. }
  14799. var surfacePoint = ellipsoid.cartesianToCartographic(closest, surfPointScratch);
  14800. maximumValue = CesiumMath.clamp(maximumValue, 0.0, 1.0);
  14801. altitude = Cartesian3.magnitude(Cartesian3.subtract(closest, position, referenceScratch)) * Math.sqrt(1.0 - maximumValue * maximumValue);
  14802. altitude = intersects ? -altitude : altitude;
  14803. surfacePoint.height = altitude;
  14804. return ellipsoid.cartographicToCartesian(surfacePoint, new Cartesian3());
  14805. }
  14806. return undefined;
  14807. };
  14808. var lineSegmentPlaneDifference = new Cartesian3();
  14809. /**
  14810. * Computes the intersection of a line segment and a plane.
  14811. *
  14812. * @param {Cartesian3} endPoint0 An end point of the line segment.
  14813. * @param {Cartesian3} endPoint1 The other end point of the line segment.
  14814. * @param {Plane} plane The plane.
  14815. * @param {Cartesian3} [result] The object onto which to store the result.
  14816. * @returns {Cartesian3} The intersection point or undefined if there is no intersection.
  14817. *
  14818. * @example
  14819. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  14820. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  14821. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  14822. *
  14823. * var p0 = new Cesium.Cartesian3(...);
  14824. * var p1 = new Cesium.Cartesian3(...);
  14825. *
  14826. * // find the intersection of the line segment from p0 to p1 and the tangent plane at origin.
  14827. * var intersection = Cesium.IntersectionTests.lineSegmentPlane(p0, p1, plane);
  14828. */
  14829. IntersectionTests.lineSegmentPlane = function(endPoint0, endPoint1, plane, result) {
  14830. if (!defined(endPoint0)) {
  14831. throw new DeveloperError('endPoint0 is required.');
  14832. }
  14833. if (!defined(endPoint1)) {
  14834. throw new DeveloperError('endPoint1 is required.');
  14835. }
  14836. if (!defined(plane)) {
  14837. throw new DeveloperError('plane is required.');
  14838. }
  14839. if (!defined(result)) {
  14840. result = new Cartesian3();
  14841. }
  14842. var difference = Cartesian3.subtract(endPoint1, endPoint0, lineSegmentPlaneDifference);
  14843. var normal = plane.normal;
  14844. var nDotDiff = Cartesian3.dot(normal, difference);
  14845. // check if the segment and plane are parallel
  14846. if (Math.abs(nDotDiff) < CesiumMath.EPSILON6) {
  14847. return undefined;
  14848. }
  14849. var nDotP0 = Cartesian3.dot(normal, endPoint0);
  14850. var t = -(plane.distance + nDotP0) / nDotDiff;
  14851. // intersection only if t is in [0, 1]
  14852. if (t < 0.0 || t > 1.0) {
  14853. return undefined;
  14854. }
  14855. // intersection is endPoint0 + t * (endPoint1 - endPoint0)
  14856. Cartesian3.multiplyByScalar(difference, t, result);
  14857. Cartesian3.add(endPoint0, result, result);
  14858. return result;
  14859. };
  14860. /**
  14861. * Computes the intersection of a triangle and a plane
  14862. *
  14863. * @param {Cartesian3} p0 First point of the triangle
  14864. * @param {Cartesian3} p1 Second point of the triangle
  14865. * @param {Cartesian3} p2 Third point of the triangle
  14866. * @param {Plane} plane Intersection plane
  14867. * @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)
  14868. *
  14869. * @example
  14870. * var origin = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  14871. * var normal = ellipsoid.geodeticSurfaceNormal(origin);
  14872. * var plane = Cesium.Plane.fromPointNormal(origin, normal);
  14873. *
  14874. * var p0 = new Cesium.Cartesian3(...);
  14875. * var p1 = new Cesium.Cartesian3(...);
  14876. * var p2 = new Cesium.Cartesian3(...);
  14877. *
  14878. * // convert the triangle composed of points (p0, p1, p2) to three triangles that don't cross the plane
  14879. * var triangles = Cesium.IntersectionTests.trianglePlaneIntersection(p0, p1, p2, plane);
  14880. */
  14881. IntersectionTests.trianglePlaneIntersection = function(p0, p1, p2, plane) {
  14882. if ((!defined(p0)) ||
  14883. (!defined(p1)) ||
  14884. (!defined(p2)) ||
  14885. (!defined(plane))) {
  14886. throw new DeveloperError('p0, p1, p2, and plane are required.');
  14887. }
  14888. var planeNormal = plane.normal;
  14889. var planeD = plane.distance;
  14890. var p0Behind = (Cartesian3.dot(planeNormal, p0) + planeD) < 0.0;
  14891. var p1Behind = (Cartesian3.dot(planeNormal, p1) + planeD) < 0.0;
  14892. var p2Behind = (Cartesian3.dot(planeNormal, p2) + planeD) < 0.0;
  14893. // Given these dots products, the calls to lineSegmentPlaneIntersection
  14894. // always have defined results.
  14895. var numBehind = 0;
  14896. numBehind += p0Behind ? 1 : 0;
  14897. numBehind += p1Behind ? 1 : 0;
  14898. numBehind += p2Behind ? 1 : 0;
  14899. var u1, u2;
  14900. if (numBehind === 1 || numBehind === 2) {
  14901. u1 = new Cartesian3();
  14902. u2 = new Cartesian3();
  14903. }
  14904. if (numBehind === 1) {
  14905. if (p0Behind) {
  14906. IntersectionTests.lineSegmentPlane(p0, p1, plane, u1);
  14907. IntersectionTests.lineSegmentPlane(p0, p2, plane, u2);
  14908. return {
  14909. positions : [p0, p1, p2, u1, u2 ],
  14910. indices : [
  14911. // Behind
  14912. 0, 3, 4,
  14913. // In front
  14914. 1, 2, 4,
  14915. 1, 4, 3
  14916. ]
  14917. };
  14918. } else if (p1Behind) {
  14919. IntersectionTests.lineSegmentPlane(p1, p2, plane, u1);
  14920. IntersectionTests.lineSegmentPlane(p1, p0, plane, u2);
  14921. return {
  14922. positions : [p0, p1, p2, u1, u2 ],
  14923. indices : [
  14924. // Behind
  14925. 1, 3, 4,
  14926. // In front
  14927. 2, 0, 4,
  14928. 2, 4, 3
  14929. ]
  14930. };
  14931. } else if (p2Behind) {
  14932. IntersectionTests.lineSegmentPlane(p2, p0, plane, u1);
  14933. IntersectionTests.lineSegmentPlane(p2, p1, plane, u2);
  14934. return {
  14935. positions : [p0, p1, p2, u1, u2 ],
  14936. indices : [
  14937. // Behind
  14938. 2, 3, 4,
  14939. // In front
  14940. 0, 1, 4,
  14941. 0, 4, 3
  14942. ]
  14943. };
  14944. }
  14945. } else if (numBehind === 2) {
  14946. if (!p0Behind) {
  14947. IntersectionTests.lineSegmentPlane(p1, p0, plane, u1);
  14948. IntersectionTests.lineSegmentPlane(p2, p0, plane, u2);
  14949. return {
  14950. positions : [p0, p1, p2, u1, u2 ],
  14951. indices : [
  14952. // Behind
  14953. 1, 2, 4,
  14954. 1, 4, 3,
  14955. // In front
  14956. 0, 3, 4
  14957. ]
  14958. };
  14959. } else if (!p1Behind) {
  14960. IntersectionTests.lineSegmentPlane(p2, p1, plane, u1);
  14961. IntersectionTests.lineSegmentPlane(p0, p1, plane, u2);
  14962. return {
  14963. positions : [p0, p1, p2, u1, u2 ],
  14964. indices : [
  14965. // Behind
  14966. 2, 0, 4,
  14967. 2, 4, 3,
  14968. // In front
  14969. 1, 3, 4
  14970. ]
  14971. };
  14972. } else if (!p2Behind) {
  14973. IntersectionTests.lineSegmentPlane(p0, p2, plane, u1);
  14974. IntersectionTests.lineSegmentPlane(p1, p2, plane, u2);
  14975. return {
  14976. positions : [p0, p1, p2, u1, u2 ],
  14977. indices : [
  14978. // Behind
  14979. 0, 1, 4,
  14980. 0, 4, 3,
  14981. // In front
  14982. 2, 3, 4
  14983. ]
  14984. };
  14985. }
  14986. }
  14987. // if numBehind is 3, the triangle is completely behind the plane;
  14988. // otherwise, it is completely in front (numBehind is 0).
  14989. return undefined;
  14990. };
  14991. return IntersectionTests;
  14992. });
  14993. /*global define*/
  14994. define('Core/Plane',[
  14995. './Cartesian3',
  14996. './defined',
  14997. './DeveloperError',
  14998. './freezeObject'
  14999. ], function(
  15000. Cartesian3,
  15001. defined,
  15002. DeveloperError,
  15003. freezeObject) {
  15004. 'use strict';
  15005. /**
  15006. * A plane in Hessian Normal Form defined by
  15007. * <pre>
  15008. * ax + by + cz + d = 0
  15009. * </pre>
  15010. * where (a, b, c) is the plane's <code>normal</code>, d is the signed
  15011. * <code>distance</code> to the plane, and (x, y, z) is any point on
  15012. * the plane.
  15013. *
  15014. * @alias Plane
  15015. * @constructor
  15016. *
  15017. * @param {Cartesian3} normal The plane's normal (normalized).
  15018. * @param {Number} distance The shortest distance from the origin to the plane. The sign of
  15019. * <code>distance</code> determines which side of the plane the origin
  15020. * is on. If <code>distance</code> is positive, the origin is in the half-space
  15021. * in the direction of the normal; if negative, the origin is in the half-space
  15022. * opposite to the normal; if zero, the plane passes through the origin.
  15023. *
  15024. * @example
  15025. * // The plane x=0
  15026. * var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
  15027. */
  15028. function Plane(normal, distance) {
  15029. if (!defined(normal)) {
  15030. throw new DeveloperError('normal is required.');
  15031. }
  15032. if (!defined(distance)) {
  15033. throw new DeveloperError('distance is required.');
  15034. }
  15035. /**
  15036. * The plane's normal.
  15037. *
  15038. * @type {Cartesian3}
  15039. */
  15040. this.normal = Cartesian3.clone(normal);
  15041. /**
  15042. * The shortest distance from the origin to the plane. The sign of
  15043. * <code>distance</code> determines which side of the plane the origin
  15044. * is on. If <code>distance</code> is positive, the origin is in the half-space
  15045. * in the direction of the normal; if negative, the origin is in the half-space
  15046. * opposite to the normal; if zero, the plane passes through the origin.
  15047. *
  15048. * @type {Number}
  15049. */
  15050. this.distance = distance;
  15051. }
  15052. /**
  15053. * Creates a plane from a normal and a point on the plane.
  15054. *
  15055. * @param {Cartesian3} point The point on the plane.
  15056. * @param {Cartesian3} normal The plane's normal (normalized).
  15057. * @param {Plane} [result] The object onto which to store the result.
  15058. * @returns {Plane} A new plane instance or the modified result parameter.
  15059. *
  15060. * @example
  15061. * var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
  15062. * var normal = ellipsoid.geodeticSurfaceNormal(point);
  15063. * var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
  15064. */
  15065. Plane.fromPointNormal = function(point, normal, result) {
  15066. if (!defined(point)) {
  15067. throw new DeveloperError('point is required.');
  15068. }
  15069. if (!defined(normal)) {
  15070. throw new DeveloperError('normal is required.');
  15071. }
  15072. var distance = -Cartesian3.dot(normal, point);
  15073. if (!defined(result)) {
  15074. return new Plane(normal, distance);
  15075. }
  15076. Cartesian3.clone(normal, result.normal);
  15077. result.distance = distance;
  15078. return result;
  15079. };
  15080. var scratchNormal = new Cartesian3();
  15081. /**
  15082. * Creates a plane from the general equation
  15083. *
  15084. * @param {Cartesian4} coefficients The plane's normal (normalized).
  15085. * @param {Plane} [result] The object onto which to store the result.
  15086. * @returns {Plane} A new plane instance or the modified result parameter.
  15087. */
  15088. Plane.fromCartesian4 = function(coefficients, result) {
  15089. if (!defined(coefficients)) {
  15090. throw new DeveloperError('coefficients is required.');
  15091. }
  15092. var normal = Cartesian3.fromCartesian4(coefficients, scratchNormal);
  15093. var distance = coefficients.w;
  15094. if (!defined(result)) {
  15095. return new Plane(normal, distance);
  15096. } else {
  15097. Cartesian3.clone(normal, result.normal);
  15098. result.distance = distance;
  15099. return result;
  15100. }
  15101. };
  15102. /**
  15103. * Computes the signed shortest distance of a point to a plane.
  15104. * The sign of the distance determines which side of the plane the point
  15105. * is on. If the distance is positive, the point is in the half-space
  15106. * in the direction of the normal; if negative, the point is in the half-space
  15107. * opposite to the normal; if zero, the plane passes through the point.
  15108. *
  15109. * @param {Plane} plane The plane.
  15110. * @param {Cartesian3} point The point.
  15111. * @returns {Number} The signed shortest distance of the point to the plane.
  15112. */
  15113. Plane.getPointDistance = function(plane, point) {
  15114. if (!defined(plane)) {
  15115. throw new DeveloperError('plane is required.');
  15116. }
  15117. if (!defined(point)) {
  15118. throw new DeveloperError('point is required.');
  15119. }
  15120. return Cartesian3.dot(plane.normal, point) + plane.distance;
  15121. };
  15122. /**
  15123. * A constant initialized to the XY plane passing through the origin, with normal in positive Z.
  15124. *
  15125. * @type {Plane}
  15126. * @constant
  15127. */
  15128. Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
  15129. /**
  15130. * A constant initialized to the YZ plane passing through the origin, with normal in positive X.
  15131. *
  15132. * @type {Plane}
  15133. * @constant
  15134. */
  15135. Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
  15136. /**
  15137. * A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
  15138. *
  15139. * @type {Plane}
  15140. * @constant
  15141. */
  15142. Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));
  15143. return Plane;
  15144. });
  15145. /*global define*/
  15146. define('Core/Tipsify',[
  15147. './defaultValue',
  15148. './defined',
  15149. './DeveloperError'
  15150. ], function(
  15151. defaultValue,
  15152. defined,
  15153. DeveloperError) {
  15154. 'use strict';
  15155. /**
  15156. * Encapsulates an algorithm to optimize triangles for the post
  15157. * vertex-shader cache. This is based on the 2007 SIGGRAPH paper
  15158. * 'Fast Triangle Reordering for Vertex Locality and Reduced Overdraw.'
  15159. * The runtime is linear but several passes are made.
  15160. *
  15161. * @exports Tipsify
  15162. *
  15163. * @see <a href='http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf'>
  15164. * Fast Triangle Reordering for Vertex Locality and Reduced Overdraw</a>
  15165. * by Sander, Nehab, and Barczak
  15166. *
  15167. * @private
  15168. */
  15169. var Tipsify = {};
  15170. /**
  15171. * Calculates the average cache miss ratio (ACMR) for a given set of indices.
  15172. *
  15173. * @param {Object} options Object with the following properties:
  15174. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  15175. * in the vertex buffer that define the geometry's triangles.
  15176. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  15177. * If not supplied, this value will be computed.
  15178. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  15179. * @returns {Number} The average cache miss ratio (ACMR).
  15180. *
  15181. * @exception {DeveloperError} indices length must be a multiple of three.
  15182. * @exception {DeveloperError} cacheSize must be greater than two.
  15183. *
  15184. * @example
  15185. * var indices = [0, 1, 2, 3, 4, 5];
  15186. * var maxIndex = 5;
  15187. * var cacheSize = 3;
  15188. * var acmr = Cesium.Tipsify.calculateACMR({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  15189. */
  15190. Tipsify.calculateACMR = function(options) {
  15191. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  15192. var indices = options.indices;
  15193. var maximumIndex = options.maximumIndex;
  15194. var cacheSize = defaultValue(options.cacheSize, 24);
  15195. if (!defined(indices)) {
  15196. throw new DeveloperError('indices is required.');
  15197. }
  15198. var numIndices = indices.length;
  15199. if (numIndices < 3 || numIndices % 3 !== 0) {
  15200. throw new DeveloperError('indices length must be a multiple of three.');
  15201. }
  15202. if (maximumIndex <= 0) {
  15203. throw new DeveloperError('maximumIndex must be greater than zero.');
  15204. }
  15205. if (cacheSize < 3) {
  15206. throw new DeveloperError('cacheSize must be greater than two.');
  15207. }
  15208. // Compute the maximumIndex if not given
  15209. if (!defined(maximumIndex)) {
  15210. maximumIndex = 0;
  15211. var currentIndex = 0;
  15212. var intoIndices = indices[currentIndex];
  15213. while (currentIndex < numIndices) {
  15214. if (intoIndices > maximumIndex) {
  15215. maximumIndex = intoIndices;
  15216. }
  15217. ++currentIndex;
  15218. intoIndices = indices[currentIndex];
  15219. }
  15220. }
  15221. // Vertex time stamps
  15222. var vertexTimeStamps = [];
  15223. for ( var i = 0; i < maximumIndex + 1; i++) {
  15224. vertexTimeStamps[i] = 0;
  15225. }
  15226. // Cache processing
  15227. var s = cacheSize + 1;
  15228. for ( var j = 0; j < numIndices; ++j) {
  15229. if ((s - vertexTimeStamps[indices[j]]) > cacheSize) {
  15230. vertexTimeStamps[indices[j]] = s;
  15231. ++s;
  15232. }
  15233. }
  15234. return (s - cacheSize + 1) / (numIndices / 3);
  15235. };
  15236. /**
  15237. * Optimizes triangles for the post-vertex shader cache.
  15238. *
  15239. * @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
  15240. * in the vertex buffer that define the geometry's triangles.
  15241. * @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
  15242. * If not supplied, this value will be computed.
  15243. * @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
  15244. * @returns {Number[]} A list of the input indices in an optimized order.
  15245. *
  15246. * @exception {DeveloperError} indices length must be a multiple of three.
  15247. * @exception {DeveloperError} cacheSize must be greater than two.
  15248. *
  15249. * @example
  15250. * var indices = [0, 1, 2, 3, 4, 5];
  15251. * var maxIndex = 5;
  15252. * var cacheSize = 3;
  15253. * var reorderedIndices = Cesium.Tipsify.tipsify({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
  15254. */
  15255. Tipsify.tipsify = function(options) {
  15256. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  15257. var indices = options.indices;
  15258. var maximumIndex = options.maximumIndex;
  15259. var cacheSize = defaultValue(options.cacheSize, 24);
  15260. var cursor;
  15261. function skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne) {
  15262. while (deadEnd.length >= 1) {
  15263. // while the stack is not empty
  15264. var d = deadEnd[deadEnd.length - 1]; // top of the stack
  15265. deadEnd.splice(deadEnd.length - 1, 1); // pop the stack
  15266. if (vertices[d].numLiveTriangles > 0) {
  15267. return d;
  15268. }
  15269. }
  15270. while (cursor < maximumIndexPlusOne) {
  15271. if (vertices[cursor].numLiveTriangles > 0) {
  15272. ++cursor;
  15273. return cursor - 1;
  15274. }
  15275. ++cursor;
  15276. }
  15277. return -1;
  15278. }
  15279. function getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne) {
  15280. var n = -1;
  15281. var p;
  15282. var m = -1;
  15283. var itOneRing = 0;
  15284. while (itOneRing < oneRing.length) {
  15285. var index = oneRing[itOneRing];
  15286. if (vertices[index].numLiveTriangles) {
  15287. p = 0;
  15288. if ((s - vertices[index].timeStamp + (2 * vertices[index].numLiveTriangles)) <= cacheSize) {
  15289. p = s - vertices[index].timeStamp;
  15290. }
  15291. if ((p > m) || (m === -1)) {
  15292. m = p;
  15293. n = index;
  15294. }
  15295. }
  15296. ++itOneRing;
  15297. }
  15298. if (n === -1) {
  15299. return skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne);
  15300. }
  15301. return n;
  15302. }
  15303. if (!defined(indices)) {
  15304. throw new DeveloperError('indices is required.');
  15305. }
  15306. var numIndices = indices.length;
  15307. if (numIndices < 3 || numIndices % 3 !== 0) {
  15308. throw new DeveloperError('indices length must be a multiple of three.');
  15309. }
  15310. if (maximumIndex <= 0) {
  15311. throw new DeveloperError('maximumIndex must be greater than zero.');
  15312. }
  15313. if (cacheSize < 3) {
  15314. throw new DeveloperError('cacheSize must be greater than two.');
  15315. }
  15316. // Determine maximum index
  15317. var maximumIndexPlusOne = 0;
  15318. var currentIndex = 0;
  15319. var intoIndices = indices[currentIndex];
  15320. var endIndex = numIndices;
  15321. if (defined(maximumIndex)) {
  15322. maximumIndexPlusOne = maximumIndex + 1;
  15323. } else {
  15324. while (currentIndex < endIndex) {
  15325. if (intoIndices > maximumIndexPlusOne) {
  15326. maximumIndexPlusOne = intoIndices;
  15327. }
  15328. ++currentIndex;
  15329. intoIndices = indices[currentIndex];
  15330. }
  15331. if (maximumIndexPlusOne === -1) {
  15332. return 0;
  15333. }
  15334. ++maximumIndexPlusOne;
  15335. }
  15336. // Vertices
  15337. var vertices = [];
  15338. for ( var i = 0; i < maximumIndexPlusOne; i++) {
  15339. vertices[i] = {
  15340. numLiveTriangles : 0,
  15341. timeStamp : 0,
  15342. vertexTriangles : []
  15343. };
  15344. }
  15345. currentIndex = 0;
  15346. var triangle = 0;
  15347. while (currentIndex < endIndex) {
  15348. vertices[indices[currentIndex]].vertexTriangles.push(triangle);
  15349. ++(vertices[indices[currentIndex]]).numLiveTriangles;
  15350. vertices[indices[currentIndex + 1]].vertexTriangles.push(triangle);
  15351. ++(vertices[indices[currentIndex + 1]]).numLiveTriangles;
  15352. vertices[indices[currentIndex + 2]].vertexTriangles.push(triangle);
  15353. ++(vertices[indices[currentIndex + 2]]).numLiveTriangles;
  15354. ++triangle;
  15355. currentIndex += 3;
  15356. }
  15357. // Starting index
  15358. var f = 0;
  15359. // Time Stamp
  15360. var s = cacheSize + 1;
  15361. cursor = 1;
  15362. // Process
  15363. var oneRing = [];
  15364. var deadEnd = []; //Stack
  15365. var vertex;
  15366. var intoVertices;
  15367. var currentOutputIndex = 0;
  15368. var outputIndices = [];
  15369. var numTriangles = numIndices / 3;
  15370. var triangleEmitted = [];
  15371. for (i = 0; i < numTriangles; i++) {
  15372. triangleEmitted[i] = false;
  15373. }
  15374. var index;
  15375. var limit;
  15376. while (f !== -1) {
  15377. oneRing = [];
  15378. intoVertices = vertices[f];
  15379. limit = intoVertices.vertexTriangles.length;
  15380. for ( var k = 0; k < limit; ++k) {
  15381. triangle = intoVertices.vertexTriangles[k];
  15382. if (!triangleEmitted[triangle]) {
  15383. triangleEmitted[triangle] = true;
  15384. currentIndex = triangle + triangle + triangle;
  15385. for ( var j = 0; j < 3; ++j) {
  15386. // Set this index as a possible next index
  15387. index = indices[currentIndex];
  15388. oneRing.push(index);
  15389. deadEnd.push(index);
  15390. // Output index
  15391. outputIndices[currentOutputIndex] = index;
  15392. ++currentOutputIndex;
  15393. // Cache processing
  15394. vertex = vertices[index];
  15395. --vertex.numLiveTriangles;
  15396. if ((s - vertex.timeStamp) > cacheSize) {
  15397. vertex.timeStamp = s;
  15398. ++s;
  15399. }
  15400. ++currentIndex;
  15401. }
  15402. }
  15403. }
  15404. f = getNextVertex(indices, cacheSize, oneRing, vertices, s, deadEnd, maximumIndexPlusOne);
  15405. }
  15406. return outputIndices;
  15407. };
  15408. return Tipsify;
  15409. });
  15410. /*global define*/
  15411. define('Core/GeometryPipeline',[
  15412. './AttributeCompression',
  15413. './barycentricCoordinates',
  15414. './BoundingSphere',
  15415. './Cartesian2',
  15416. './Cartesian3',
  15417. './Cartesian4',
  15418. './Cartographic',
  15419. './ComponentDatatype',
  15420. './defaultValue',
  15421. './defined',
  15422. './DeveloperError',
  15423. './EncodedCartesian3',
  15424. './GeographicProjection',
  15425. './Geometry',
  15426. './GeometryAttribute',
  15427. './GeometryType',
  15428. './IndexDatatype',
  15429. './Intersect',
  15430. './IntersectionTests',
  15431. './Math',
  15432. './Matrix3',
  15433. './Matrix4',
  15434. './Plane',
  15435. './PrimitiveType',
  15436. './Tipsify'
  15437. ], function(
  15438. AttributeCompression,
  15439. barycentricCoordinates,
  15440. BoundingSphere,
  15441. Cartesian2,
  15442. Cartesian3,
  15443. Cartesian4,
  15444. Cartographic,
  15445. ComponentDatatype,
  15446. defaultValue,
  15447. defined,
  15448. DeveloperError,
  15449. EncodedCartesian3,
  15450. GeographicProjection,
  15451. Geometry,
  15452. GeometryAttribute,
  15453. GeometryType,
  15454. IndexDatatype,
  15455. Intersect,
  15456. IntersectionTests,
  15457. CesiumMath,
  15458. Matrix3,
  15459. Matrix4,
  15460. Plane,
  15461. PrimitiveType,
  15462. Tipsify) {
  15463. 'use strict';
  15464. /**
  15465. * Content pipeline functions for geometries.
  15466. *
  15467. * @exports GeometryPipeline
  15468. *
  15469. * @see Geometry
  15470. */
  15471. var GeometryPipeline = {};
  15472. function addTriangle(lines, index, i0, i1, i2) {
  15473. lines[index++] = i0;
  15474. lines[index++] = i1;
  15475. lines[index++] = i1;
  15476. lines[index++] = i2;
  15477. lines[index++] = i2;
  15478. lines[index] = i0;
  15479. }
  15480. function trianglesToLines(triangles) {
  15481. var count = triangles.length;
  15482. var size = (count / 3) * 6;
  15483. var lines = IndexDatatype.createTypedArray(count, size);
  15484. var index = 0;
  15485. for ( var i = 0; i < count; i += 3, index += 6) {
  15486. addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]);
  15487. }
  15488. return lines;
  15489. }
  15490. function triangleStripToLines(triangles) {
  15491. var count = triangles.length;
  15492. if (count >= 3) {
  15493. var size = (count - 2) * 6;
  15494. var lines = IndexDatatype.createTypedArray(count, size);
  15495. addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]);
  15496. var index = 6;
  15497. for ( var i = 3; i < count; ++i, index += 6) {
  15498. addTriangle(lines, index, triangles[i - 1], triangles[i], triangles[i - 2]);
  15499. }
  15500. return lines;
  15501. }
  15502. return new Uint16Array();
  15503. }
  15504. function triangleFanToLines(triangles) {
  15505. if (triangles.length > 0) {
  15506. var count = triangles.length - 1;
  15507. var size = (count - 1) * 6;
  15508. var lines = IndexDatatype.createTypedArray(count, size);
  15509. var base = triangles[0];
  15510. var index = 0;
  15511. for ( var i = 1; i < count; ++i, index += 6) {
  15512. addTriangle(lines, index, base, triangles[i], triangles[i + 1]);
  15513. }
  15514. return lines;
  15515. }
  15516. return new Uint16Array();
  15517. }
  15518. /**
  15519. * Converts a geometry's triangle indices to line indices. If the geometry has an <code>indices</code>
  15520. * and its <code>primitiveType</code> is <code>TRIANGLES</code>, <code>TRIANGLE_STRIP</code>,
  15521. * <code>TRIANGLE_FAN</code>, it is converted to <code>LINES</code>; otherwise, the geometry is not changed.
  15522. * <p>
  15523. * This is commonly used to create a wireframe geometry for visual debugging.
  15524. * </p>
  15525. *
  15526. * @param {Geometry} geometry The geometry to modify.
  15527. * @returns {Geometry} The modified <code>geometry</code> argument, with its triangle indices converted to lines.
  15528. *
  15529. * @exception {DeveloperError} geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.
  15530. *
  15531. * @example
  15532. * geometry = Cesium.GeometryPipeline.toWireframe(geometry);
  15533. */
  15534. GeometryPipeline.toWireframe = function(geometry) {
  15535. if (!defined(geometry)) {
  15536. throw new DeveloperError('geometry is required.');
  15537. }
  15538. var indices = geometry.indices;
  15539. if (defined(indices)) {
  15540. switch (geometry.primitiveType) {
  15541. case PrimitiveType.TRIANGLES:
  15542. geometry.indices = trianglesToLines(indices);
  15543. break;
  15544. case PrimitiveType.TRIANGLE_STRIP:
  15545. geometry.indices = triangleStripToLines(indices);
  15546. break;
  15547. case PrimitiveType.TRIANGLE_FAN:
  15548. geometry.indices = triangleFanToLines(indices);
  15549. break;
  15550. default:
  15551. throw new DeveloperError('geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.');
  15552. }
  15553. geometry.primitiveType = PrimitiveType.LINES;
  15554. }
  15555. return geometry;
  15556. };
  15557. /**
  15558. * Creates a new {@link Geometry} with <code>LINES</code> representing the provided
  15559. * attribute (<code>attributeName</code>) for the provided geometry. This is used to
  15560. * visualize vector attributes like normals, binormals, and tangents.
  15561. *
  15562. * @param {Geometry} geometry The <code>Geometry</code> instance with the attribute.
  15563. * @param {String} [attributeName='normal'] The name of the attribute.
  15564. * @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.
  15565. * @returns {Geometry} A new <code>Geometry</code> instance with line segments for the vector.
  15566. *
  15567. * @exception {DeveloperError} geometry.attributes must have an attribute with the same name as the attributeName parameter.
  15568. *
  15569. * @example
  15570. * var geometry = Cesium.GeometryPipeline.createLineSegmentsForVectors(instance.geometry, 'binormal', 100000.0);
  15571. */
  15572. GeometryPipeline.createLineSegmentsForVectors = function(geometry, attributeName, length) {
  15573. attributeName = defaultValue(attributeName, 'normal');
  15574. if (!defined(geometry)) {
  15575. throw new DeveloperError('geometry is required.');
  15576. }
  15577. if (!defined(geometry.attributes.position)) {
  15578. throw new DeveloperError('geometry.attributes.position is required.');
  15579. }
  15580. if (!defined(geometry.attributes[attributeName])) {
  15581. throw new DeveloperError('geometry.attributes must have an attribute with the same name as the attributeName parameter, ' + attributeName + '.');
  15582. }
  15583. length = defaultValue(length, 10000.0);
  15584. var positions = geometry.attributes.position.values;
  15585. var vectors = geometry.attributes[attributeName].values;
  15586. var positionsLength = positions.length;
  15587. var newPositions = new Float64Array(2 * positionsLength);
  15588. var j = 0;
  15589. for (var i = 0; i < positionsLength; i += 3) {
  15590. newPositions[j++] = positions[i];
  15591. newPositions[j++] = positions[i + 1];
  15592. newPositions[j++] = positions[i + 2];
  15593. newPositions[j++] = positions[i] + (vectors[i] * length);
  15594. newPositions[j++] = positions[i + 1] + (vectors[i + 1] * length);
  15595. newPositions[j++] = positions[i + 2] + (vectors[i + 2] * length);
  15596. }
  15597. var newBoundingSphere;
  15598. var bs = geometry.boundingSphere;
  15599. if (defined(bs)) {
  15600. newBoundingSphere = new BoundingSphere(bs.center, bs.radius + length);
  15601. }
  15602. return new Geometry({
  15603. attributes : {
  15604. position : new GeometryAttribute({
  15605. componentDatatype : ComponentDatatype.DOUBLE,
  15606. componentsPerAttribute : 3,
  15607. values : newPositions
  15608. })
  15609. },
  15610. primitiveType : PrimitiveType.LINES,
  15611. boundingSphere : newBoundingSphere
  15612. });
  15613. };
  15614. /**
  15615. * Creates an object that maps attribute names to unique locations (indices)
  15616. * for matching vertex attributes and shader programs.
  15617. *
  15618. * @param {Geometry} geometry The geometry, which is not modified, to create the object for.
  15619. * @returns {Object} An object with attribute name / index pairs.
  15620. *
  15621. * @example
  15622. * var attributeLocations = Cesium.GeometryPipeline.createAttributeLocations(geometry);
  15623. * // Example output
  15624. * // {
  15625. * // 'position' : 0,
  15626. * // 'normal' : 1
  15627. * // }
  15628. */
  15629. GeometryPipeline.createAttributeLocations = function(geometry) {
  15630. if (!defined(geometry)) {
  15631. throw new DeveloperError('geometry is required.');
  15632. }
  15633. // There can be a WebGL performance hit when attribute 0 is disabled, so
  15634. // assign attribute locations to well-known attributes.
  15635. var semantics = [
  15636. 'position',
  15637. 'positionHigh',
  15638. 'positionLow',
  15639. // From VertexFormat.position - after 2D projection and high-precision encoding
  15640. 'position3DHigh',
  15641. 'position3DLow',
  15642. 'position2DHigh',
  15643. 'position2DLow',
  15644. // From Primitive
  15645. 'pickColor',
  15646. // From VertexFormat
  15647. 'normal',
  15648. 'st',
  15649. 'binormal',
  15650. 'tangent',
  15651. // From compressing texture coordinates and normals
  15652. 'compressedAttributes'
  15653. ];
  15654. var attributes = geometry.attributes;
  15655. var indices = {};
  15656. var j = 0;
  15657. var i;
  15658. var len = semantics.length;
  15659. // Attribute locations for well-known attributes
  15660. for (i = 0; i < len; ++i) {
  15661. var semantic = semantics[i];
  15662. if (defined(attributes[semantic])) {
  15663. indices[semantic] = j++;
  15664. }
  15665. }
  15666. // Locations for custom attributes
  15667. for (var name in attributes) {
  15668. if (attributes.hasOwnProperty(name) && (!defined(indices[name]))) {
  15669. indices[name] = j++;
  15670. }
  15671. }
  15672. return indices;
  15673. };
  15674. /**
  15675. * Reorders a geometry's attributes and <code>indices</code> to achieve better performance from the GPU's pre-vertex-shader cache.
  15676. *
  15677. * @param {Geometry} geometry The geometry to modify.
  15678. * @returns {Geometry} The modified <code>geometry</code> argument, with its attributes and indices reordered for the GPU's pre-vertex-shader cache.
  15679. *
  15680. * @exception {DeveloperError} Each attribute array in geometry.attributes must have the same number of attributes.
  15681. *
  15682. *
  15683. * @example
  15684. * geometry = Cesium.GeometryPipeline.reorderForPreVertexCache(geometry);
  15685. *
  15686. * @see GeometryPipeline.reorderForPostVertexCache
  15687. */
  15688. GeometryPipeline.reorderForPreVertexCache = function(geometry) {
  15689. if (!defined(geometry)) {
  15690. throw new DeveloperError('geometry is required.');
  15691. }
  15692. var numVertices = Geometry.computeNumberOfVertices(geometry);
  15693. var indices = geometry.indices;
  15694. if (defined(indices)) {
  15695. var indexCrossReferenceOldToNew = new Int32Array(numVertices);
  15696. for ( var i = 0; i < numVertices; i++) {
  15697. indexCrossReferenceOldToNew[i] = -1;
  15698. }
  15699. // Construct cross reference and reorder indices
  15700. var indicesIn = indices;
  15701. var numIndices = indicesIn.length;
  15702. var indicesOut = IndexDatatype.createTypedArray(numVertices, numIndices);
  15703. var intoIndicesIn = 0;
  15704. var intoIndicesOut = 0;
  15705. var nextIndex = 0;
  15706. var tempIndex;
  15707. while (intoIndicesIn < numIndices) {
  15708. tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]];
  15709. if (tempIndex !== -1) {
  15710. indicesOut[intoIndicesOut] = tempIndex;
  15711. } else {
  15712. tempIndex = indicesIn[intoIndicesIn];
  15713. indexCrossReferenceOldToNew[tempIndex] = nextIndex;
  15714. indicesOut[intoIndicesOut] = nextIndex;
  15715. ++nextIndex;
  15716. }
  15717. ++intoIndicesIn;
  15718. ++intoIndicesOut;
  15719. }
  15720. geometry.indices = indicesOut;
  15721. // Reorder attributes
  15722. var attributes = geometry.attributes;
  15723. for ( var property in attributes) {
  15724. if (attributes.hasOwnProperty(property) &&
  15725. defined(attributes[property]) &&
  15726. defined(attributes[property].values)) {
  15727. var attribute = attributes[property];
  15728. var elementsIn = attribute.values;
  15729. var intoElementsIn = 0;
  15730. var numComponents = attribute.componentsPerAttribute;
  15731. var elementsOut = ComponentDatatype.createTypedArray(attribute.componentDatatype, nextIndex * numComponents);
  15732. while (intoElementsIn < numVertices) {
  15733. var temp = indexCrossReferenceOldToNew[intoElementsIn];
  15734. if (temp !== -1) {
  15735. for (i = 0; i < numComponents; i++) {
  15736. elementsOut[numComponents * temp + i] = elementsIn[numComponents * intoElementsIn + i];
  15737. }
  15738. }
  15739. ++intoElementsIn;
  15740. }
  15741. attribute.values = elementsOut;
  15742. }
  15743. }
  15744. }
  15745. return geometry;
  15746. };
  15747. /**
  15748. * Reorders a geometry's <code>indices</code> to achieve better performance from the GPU's
  15749. * post vertex-shader cache by using the Tipsify algorithm. If the geometry <code>primitiveType</code>
  15750. * is not <code>TRIANGLES</code> or the geometry does not have an <code>indices</code>, this function has no effect.
  15751. *
  15752. * @param {Geometry} geometry The geometry to modify.
  15753. * @param {Number} [cacheCapacity=24] The number of vertices that can be held in the GPU's vertex cache.
  15754. * @returns {Geometry} The modified <code>geometry</code> argument, with its indices reordered for the post-vertex-shader cache.
  15755. *
  15756. * @exception {DeveloperError} cacheCapacity must be greater than two.
  15757. *
  15758. *
  15759. * @example
  15760. * geometry = Cesium.GeometryPipeline.reorderForPostVertexCache(geometry);
  15761. *
  15762. * @see GeometryPipeline.reorderForPreVertexCache
  15763. * @see {@link http://gfx.cs.princ0eton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf|Fast Triangle Reordering for Vertex Locality and Reduced Overdraw}
  15764. * by Sander, Nehab, and Barczak
  15765. */
  15766. GeometryPipeline.reorderForPostVertexCache = function(geometry, cacheCapacity) {
  15767. if (!defined(geometry)) {
  15768. throw new DeveloperError('geometry is required.');
  15769. }
  15770. var indices = geometry.indices;
  15771. if ((geometry.primitiveType === PrimitiveType.TRIANGLES) && (defined(indices))) {
  15772. var numIndices = indices.length;
  15773. var maximumIndex = 0;
  15774. for ( var j = 0; j < numIndices; j++) {
  15775. if (indices[j] > maximumIndex) {
  15776. maximumIndex = indices[j];
  15777. }
  15778. }
  15779. geometry.indices = Tipsify.tipsify({
  15780. indices : indices,
  15781. maximumIndex : maximumIndex,
  15782. cacheSize : cacheCapacity
  15783. });
  15784. }
  15785. return geometry;
  15786. };
  15787. function copyAttributesDescriptions(attributes) {
  15788. var newAttributes = {};
  15789. for ( var attribute in attributes) {
  15790. if (attributes.hasOwnProperty(attribute) &&
  15791. defined(attributes[attribute]) &&
  15792. defined(attributes[attribute].values)) {
  15793. var attr = attributes[attribute];
  15794. newAttributes[attribute] = new GeometryAttribute({
  15795. componentDatatype : attr.componentDatatype,
  15796. componentsPerAttribute : attr.componentsPerAttribute,
  15797. normalize : attr.normalize,
  15798. values : []
  15799. });
  15800. }
  15801. }
  15802. return newAttributes;
  15803. }
  15804. function copyVertex(destinationAttributes, sourceAttributes, index) {
  15805. for ( var attribute in sourceAttributes) {
  15806. if (sourceAttributes.hasOwnProperty(attribute) &&
  15807. defined(sourceAttributes[attribute]) &&
  15808. defined(sourceAttributes[attribute].values)) {
  15809. var attr = sourceAttributes[attribute];
  15810. for ( var k = 0; k < attr.componentsPerAttribute; ++k) {
  15811. destinationAttributes[attribute].values.push(attr.values[(index * attr.componentsPerAttribute) + k]);
  15812. }
  15813. }
  15814. }
  15815. }
  15816. /**
  15817. * Splits a geometry into multiple geometries, if necessary, to ensure that indices in the
  15818. * <code>indices</code> fit into unsigned shorts. This is used to meet the WebGL requirements
  15819. * when unsigned int indices are not supported.
  15820. * <p>
  15821. * If the geometry does not have any <code>indices</code>, this function has no effect.
  15822. * </p>
  15823. *
  15824. * @param {Geometry} geometry The geometry to be split into multiple geometries.
  15825. * @returns {Geometry[]} An array of geometries, each with indices that fit into unsigned shorts.
  15826. *
  15827. * @exception {DeveloperError} geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS
  15828. * @exception {DeveloperError} All geometry attribute lists must have the same number of attributes.
  15829. *
  15830. * @example
  15831. * var geometries = Cesium.GeometryPipeline.fitToUnsignedShortIndices(geometry);
  15832. */
  15833. GeometryPipeline.fitToUnsignedShortIndices = function(geometry) {
  15834. if (!defined(geometry)) {
  15835. throw new DeveloperError('geometry is required.');
  15836. }
  15837. if ((defined(geometry.indices)) &&
  15838. ((geometry.primitiveType !== PrimitiveType.TRIANGLES) &&
  15839. (geometry.primitiveType !== PrimitiveType.LINES) &&
  15840. (geometry.primitiveType !== PrimitiveType.POINTS))) {
  15841. throw new DeveloperError('geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS.');
  15842. }
  15843. var geometries = [];
  15844. // If there's an index list and more than 64K attributes, it is possible that
  15845. // some indices are outside the range of unsigned short [0, 64K - 1]
  15846. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  15847. if (defined(geometry.indices) && (numberOfVertices >= CesiumMath.SIXTY_FOUR_KILOBYTES)) {
  15848. var oldToNewIndex = [];
  15849. var newIndices = [];
  15850. var currentIndex = 0;
  15851. var newAttributes = copyAttributesDescriptions(geometry.attributes);
  15852. var originalIndices = geometry.indices;
  15853. var numberOfIndices = originalIndices.length;
  15854. var indicesPerPrimitive;
  15855. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  15856. indicesPerPrimitive = 3;
  15857. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  15858. indicesPerPrimitive = 2;
  15859. } else if (geometry.primitiveType === PrimitiveType.POINTS) {
  15860. indicesPerPrimitive = 1;
  15861. }
  15862. for ( var j = 0; j < numberOfIndices; j += indicesPerPrimitive) {
  15863. for (var k = 0; k < indicesPerPrimitive; ++k) {
  15864. var x = originalIndices[j + k];
  15865. var i = oldToNewIndex[x];
  15866. if (!defined(i)) {
  15867. i = currentIndex++;
  15868. oldToNewIndex[x] = i;
  15869. copyVertex(newAttributes, geometry.attributes, x);
  15870. }
  15871. newIndices.push(i);
  15872. }
  15873. if (currentIndex + indicesPerPrimitive >= CesiumMath.SIXTY_FOUR_KILOBYTES) {
  15874. geometries.push(new Geometry({
  15875. attributes : newAttributes,
  15876. indices : newIndices,
  15877. primitiveType : geometry.primitiveType,
  15878. boundingSphere : geometry.boundingSphere,
  15879. boundingSphereCV : geometry.boundingSphereCV
  15880. }));
  15881. // Reset for next vertex-array
  15882. oldToNewIndex = [];
  15883. newIndices = [];
  15884. currentIndex = 0;
  15885. newAttributes = copyAttributesDescriptions(geometry.attributes);
  15886. }
  15887. }
  15888. if (newIndices.length !== 0) {
  15889. geometries.push(new Geometry({
  15890. attributes : newAttributes,
  15891. indices : newIndices,
  15892. primitiveType : geometry.primitiveType,
  15893. boundingSphere : geometry.boundingSphere,
  15894. boundingSphereCV : geometry.boundingSphereCV
  15895. }));
  15896. }
  15897. } else {
  15898. // No need to split into multiple geometries
  15899. geometries.push(geometry);
  15900. }
  15901. return geometries;
  15902. };
  15903. var scratchProjectTo2DCartesian3 = new Cartesian3();
  15904. var scratchProjectTo2DCartographic = new Cartographic();
  15905. /**
  15906. * Projects a geometry's 3D <code>position</code> attribute to 2D, replacing the <code>position</code>
  15907. * attribute with separate <code>position3D</code> and <code>position2D</code> attributes.
  15908. * <p>
  15909. * If the geometry does not have a <code>position</code>, this function has no effect.
  15910. * </p>
  15911. *
  15912. * @param {Geometry} geometry The geometry to modify.
  15913. * @param {String} attributeName The name of the attribute.
  15914. * @param {String} attributeName3D The name of the attribute in 3D.
  15915. * @param {String} attributeName2D The name of the attribute in 2D.
  15916. * @param {Object} [projection=new GeographicProjection()] The projection to use.
  15917. * @returns {Geometry} The modified <code>geometry</code> argument with <code>position3D</code> and <code>position2D</code> attributes.
  15918. *
  15919. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  15920. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  15921. * @exception {DeveloperError} Could not project a point to 2D.
  15922. *
  15923. * @example
  15924. * geometry = Cesium.GeometryPipeline.projectTo2D(geometry, 'position', 'position3D', 'position2D');
  15925. */
  15926. GeometryPipeline.projectTo2D = function(geometry, attributeName, attributeName3D, attributeName2D, projection) {
  15927. if (!defined(geometry)) {
  15928. throw new DeveloperError('geometry is required.');
  15929. }
  15930. if (!defined(attributeName)) {
  15931. throw new DeveloperError('attributeName is required.');
  15932. }
  15933. if (!defined(attributeName3D)) {
  15934. throw new DeveloperError('attributeName3D is required.');
  15935. }
  15936. if (!defined(attributeName2D)) {
  15937. throw new DeveloperError('attributeName2D is required.');
  15938. }
  15939. if (!defined(geometry.attributes[attributeName])) {
  15940. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  15941. }
  15942. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  15943. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  15944. }
  15945. var attribute = geometry.attributes[attributeName];
  15946. projection = (defined(projection)) ? projection : new GeographicProjection();
  15947. var ellipsoid = projection.ellipsoid;
  15948. // Project original values to 2D.
  15949. var values3D = attribute.values;
  15950. var projectedValues = new Float64Array(values3D.length);
  15951. var index = 0;
  15952. for ( var i = 0; i < values3D.length; i += 3) {
  15953. var value = Cartesian3.fromArray(values3D, i, scratchProjectTo2DCartesian3);
  15954. var lonLat = ellipsoid.cartesianToCartographic(value, scratchProjectTo2DCartographic);
  15955. if (!defined(lonLat)) {
  15956. throw new DeveloperError('Could not project point (' + value.x + ', ' + value.y + ', ' + value.z + ') to 2D.');
  15957. }
  15958. var projectedLonLat = projection.project(lonLat, scratchProjectTo2DCartesian3);
  15959. projectedValues[index++] = projectedLonLat.x;
  15960. projectedValues[index++] = projectedLonLat.y;
  15961. projectedValues[index++] = projectedLonLat.z;
  15962. }
  15963. // Rename original cartesians to WGS84 cartesians.
  15964. geometry.attributes[attributeName3D] = attribute;
  15965. // Replace original cartesians with 2D projected cartesians
  15966. geometry.attributes[attributeName2D] = new GeometryAttribute({
  15967. componentDatatype : ComponentDatatype.DOUBLE,
  15968. componentsPerAttribute : 3,
  15969. values : projectedValues
  15970. });
  15971. delete geometry.attributes[attributeName];
  15972. return geometry;
  15973. };
  15974. var encodedResult = {
  15975. high : 0.0,
  15976. low : 0.0
  15977. };
  15978. /**
  15979. * Encodes floating-point geometry attribute values as two separate attributes to improve
  15980. * rendering precision.
  15981. * <p>
  15982. * This is commonly used to create high-precision position vertex attributes.
  15983. * </p>
  15984. *
  15985. * @param {Geometry} geometry The geometry to modify.
  15986. * @param {String} attributeName The name of the attribute.
  15987. * @param {String} attributeHighName The name of the attribute for the encoded high bits.
  15988. * @param {String} attributeLowName The name of the attribute for the encoded low bits.
  15989. * @returns {Geometry} The modified <code>geometry</code> argument, with its encoded attribute.
  15990. *
  15991. * @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
  15992. * @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
  15993. *
  15994. * @example
  15995. * geometry = Cesium.GeometryPipeline.encodeAttribute(geometry, 'position3D', 'position3DHigh', 'position3DLow');
  15996. */
  15997. GeometryPipeline.encodeAttribute = function(geometry, attributeName, attributeHighName, attributeLowName) {
  15998. if (!defined(geometry)) {
  15999. throw new DeveloperError('geometry is required.');
  16000. }
  16001. if (!defined(attributeName)) {
  16002. throw new DeveloperError('attributeName is required.');
  16003. }
  16004. if (!defined(attributeHighName)) {
  16005. throw new DeveloperError('attributeHighName is required.');
  16006. }
  16007. if (!defined(attributeLowName)) {
  16008. throw new DeveloperError('attributeLowName is required.');
  16009. }
  16010. if (!defined(geometry.attributes[attributeName])) {
  16011. throw new DeveloperError('geometry must have attribute matching the attributeName argument: ' + attributeName + '.');
  16012. }
  16013. if (geometry.attributes[attributeName].componentDatatype !== ComponentDatatype.DOUBLE) {
  16014. throw new DeveloperError('The attribute componentDatatype must be ComponentDatatype.DOUBLE.');
  16015. }
  16016. var attribute = geometry.attributes[attributeName];
  16017. var values = attribute.values;
  16018. var length = values.length;
  16019. var highValues = new Float32Array(length);
  16020. var lowValues = new Float32Array(length);
  16021. for (var i = 0; i < length; ++i) {
  16022. EncodedCartesian3.encode(values[i], encodedResult);
  16023. highValues[i] = encodedResult.high;
  16024. lowValues[i] = encodedResult.low;
  16025. }
  16026. var componentsPerAttribute = attribute.componentsPerAttribute;
  16027. geometry.attributes[attributeHighName] = new GeometryAttribute({
  16028. componentDatatype : ComponentDatatype.FLOAT,
  16029. componentsPerAttribute : componentsPerAttribute,
  16030. values : highValues
  16031. });
  16032. geometry.attributes[attributeLowName] = new GeometryAttribute({
  16033. componentDatatype : ComponentDatatype.FLOAT,
  16034. componentsPerAttribute : componentsPerAttribute,
  16035. values : lowValues
  16036. });
  16037. delete geometry.attributes[attributeName];
  16038. return geometry;
  16039. };
  16040. var scratchCartesian3 = new Cartesian3();
  16041. function transformPoint(matrix, attribute) {
  16042. if (defined(attribute)) {
  16043. var values = attribute.values;
  16044. var length = values.length;
  16045. for (var i = 0; i < length; i += 3) {
  16046. Cartesian3.unpack(values, i, scratchCartesian3);
  16047. Matrix4.multiplyByPoint(matrix, scratchCartesian3, scratchCartesian3);
  16048. Cartesian3.pack(scratchCartesian3, values, i);
  16049. }
  16050. }
  16051. }
  16052. function transformVector(matrix, attribute) {
  16053. if (defined(attribute)) {
  16054. var values = attribute.values;
  16055. var length = values.length;
  16056. for (var i = 0; i < length; i += 3) {
  16057. Cartesian3.unpack(values, i, scratchCartesian3);
  16058. Matrix3.multiplyByVector(matrix, scratchCartesian3, scratchCartesian3);
  16059. scratchCartesian3 = Cartesian3.normalize(scratchCartesian3, scratchCartesian3);
  16060. Cartesian3.pack(scratchCartesian3, values, i);
  16061. }
  16062. }
  16063. }
  16064. var inverseTranspose = new Matrix4();
  16065. var normalMatrix = new Matrix3();
  16066. /**
  16067. * Transforms a geometry instance to world coordinates. This changes
  16068. * the instance's <code>modelMatrix</code> to {@link Matrix4.IDENTITY} and transforms the
  16069. * following attributes if they are present: <code>position</code>, <code>normal</code>,
  16070. * <code>binormal</code>, and <code>tangent</code>.
  16071. *
  16072. * @param {GeometryInstance} instance The geometry instance to modify.
  16073. * @returns {GeometryInstance} The modified <code>instance</code> argument, with its attributes transforms to world coordinates.
  16074. *
  16075. * @example
  16076. * Cesium.GeometryPipeline.transformToWorldCoordinates(instance);
  16077. */
  16078. GeometryPipeline.transformToWorldCoordinates = function(instance) {
  16079. if (!defined(instance)) {
  16080. throw new DeveloperError('instance is required.');
  16081. }
  16082. var modelMatrix = instance.modelMatrix;
  16083. if (Matrix4.equals(modelMatrix, Matrix4.IDENTITY)) {
  16084. // Already in world coordinates
  16085. return instance;
  16086. }
  16087. var attributes = instance.geometry.attributes;
  16088. // Transform attributes in known vertex formats
  16089. transformPoint(modelMatrix, attributes.position);
  16090. transformPoint(modelMatrix, attributes.prevPosition);
  16091. transformPoint(modelMatrix, attributes.nextPosition);
  16092. if ((defined(attributes.normal)) ||
  16093. (defined(attributes.binormal)) ||
  16094. (defined(attributes.tangent))) {
  16095. Matrix4.inverse(modelMatrix, inverseTranspose);
  16096. Matrix4.transpose(inverseTranspose, inverseTranspose);
  16097. Matrix4.getRotation(inverseTranspose, normalMatrix);
  16098. transformVector(normalMatrix, attributes.normal);
  16099. transformVector(normalMatrix, attributes.binormal);
  16100. transformVector(normalMatrix, attributes.tangent);
  16101. }
  16102. var boundingSphere = instance.geometry.boundingSphere;
  16103. if (defined(boundingSphere)) {
  16104. instance.geometry.boundingSphere = BoundingSphere.transform(boundingSphere, modelMatrix, boundingSphere);
  16105. }
  16106. instance.modelMatrix = Matrix4.clone(Matrix4.IDENTITY);
  16107. return instance;
  16108. };
  16109. function findAttributesInAllGeometries(instances, propertyName) {
  16110. var length = instances.length;
  16111. var attributesInAllGeometries = {};
  16112. var attributes0 = instances[0][propertyName].attributes;
  16113. var name;
  16114. for (name in attributes0) {
  16115. if (attributes0.hasOwnProperty(name) &&
  16116. defined(attributes0[name]) &&
  16117. defined(attributes0[name].values)) {
  16118. var attribute = attributes0[name];
  16119. var numberOfComponents = attribute.values.length;
  16120. var inAllGeometries = true;
  16121. // Does this same attribute exist in all geometries?
  16122. for (var i = 1; i < length; ++i) {
  16123. var otherAttribute = instances[i][propertyName].attributes[name];
  16124. if ((!defined(otherAttribute)) ||
  16125. (attribute.componentDatatype !== otherAttribute.componentDatatype) ||
  16126. (attribute.componentsPerAttribute !== otherAttribute.componentsPerAttribute) ||
  16127. (attribute.normalize !== otherAttribute.normalize)) {
  16128. inAllGeometries = false;
  16129. break;
  16130. }
  16131. numberOfComponents += otherAttribute.values.length;
  16132. }
  16133. if (inAllGeometries) {
  16134. attributesInAllGeometries[name] = new GeometryAttribute({
  16135. componentDatatype : attribute.componentDatatype,
  16136. componentsPerAttribute : attribute.componentsPerAttribute,
  16137. normalize : attribute.normalize,
  16138. values : ComponentDatatype.createTypedArray(attribute.componentDatatype, numberOfComponents)
  16139. });
  16140. }
  16141. }
  16142. }
  16143. return attributesInAllGeometries;
  16144. }
  16145. var tempScratch = new Cartesian3();
  16146. function combineGeometries(instances, propertyName) {
  16147. var length = instances.length;
  16148. var name;
  16149. var i;
  16150. var j;
  16151. var k;
  16152. var m = instances[0].modelMatrix;
  16153. var haveIndices = (defined(instances[0][propertyName].indices));
  16154. var primitiveType = instances[0][propertyName].primitiveType;
  16155. for (i = 1; i < length; ++i) {
  16156. if (!Matrix4.equals(instances[i].modelMatrix, m)) {
  16157. throw new DeveloperError('All instances must have the same modelMatrix.');
  16158. }
  16159. if ((defined(instances[i][propertyName].indices)) !== haveIndices) {
  16160. throw new DeveloperError('All instance geometries must have an indices or not have one.');
  16161. }
  16162. if (instances[i][propertyName].primitiveType !== primitiveType) {
  16163. throw new DeveloperError('All instance geometries must have the same primitiveType.');
  16164. }
  16165. }
  16166. // Find subset of attributes in all geometries
  16167. var attributes = findAttributesInAllGeometries(instances, propertyName);
  16168. var values;
  16169. var sourceValues;
  16170. var sourceValuesLength;
  16171. // Combine attributes from each geometry into a single typed array
  16172. for (name in attributes) {
  16173. if (attributes.hasOwnProperty(name)) {
  16174. values = attributes[name].values;
  16175. k = 0;
  16176. for (i = 0; i < length; ++i) {
  16177. sourceValues = instances[i][propertyName].attributes[name].values;
  16178. sourceValuesLength = sourceValues.length;
  16179. for (j = 0; j < sourceValuesLength; ++j) {
  16180. values[k++] = sourceValues[j];
  16181. }
  16182. }
  16183. }
  16184. }
  16185. // Combine index lists
  16186. var indices;
  16187. if (haveIndices) {
  16188. var numberOfIndices = 0;
  16189. for (i = 0; i < length; ++i) {
  16190. numberOfIndices += instances[i][propertyName].indices.length;
  16191. }
  16192. var numberOfVertices = Geometry.computeNumberOfVertices(new Geometry({
  16193. attributes : attributes,
  16194. primitiveType : PrimitiveType.POINTS
  16195. }));
  16196. var destIndices = IndexDatatype.createTypedArray(numberOfVertices, numberOfIndices);
  16197. var destOffset = 0;
  16198. var offset = 0;
  16199. for (i = 0; i < length; ++i) {
  16200. var sourceIndices = instances[i][propertyName].indices;
  16201. var sourceIndicesLen = sourceIndices.length;
  16202. for (k = 0; k < sourceIndicesLen; ++k) {
  16203. destIndices[destOffset++] = offset + sourceIndices[k];
  16204. }
  16205. offset += Geometry.computeNumberOfVertices(instances[i][propertyName]);
  16206. }
  16207. indices = destIndices;
  16208. }
  16209. // Create bounding sphere that includes all instances
  16210. var center = new Cartesian3();
  16211. var radius = 0.0;
  16212. var bs;
  16213. for (i = 0; i < length; ++i) {
  16214. bs = instances[i][propertyName].boundingSphere;
  16215. if (!defined(bs)) {
  16216. // If any geometries have an undefined bounding sphere, then so does the combined geometry
  16217. center = undefined;
  16218. break;
  16219. }
  16220. Cartesian3.add(bs.center, center, center);
  16221. }
  16222. if (defined(center)) {
  16223. Cartesian3.divideByScalar(center, length, center);
  16224. for (i = 0; i < length; ++i) {
  16225. bs = instances[i][propertyName].boundingSphere;
  16226. var tempRadius = Cartesian3.magnitude(Cartesian3.subtract(bs.center, center, tempScratch)) + bs.radius;
  16227. if (tempRadius > radius) {
  16228. radius = tempRadius;
  16229. }
  16230. }
  16231. }
  16232. return new Geometry({
  16233. attributes : attributes,
  16234. indices : indices,
  16235. primitiveType : primitiveType,
  16236. boundingSphere : (defined(center)) ? new BoundingSphere(center, radius) : undefined
  16237. });
  16238. }
  16239. /**
  16240. * Combines geometry from several {@link GeometryInstance} objects into one geometry.
  16241. * This concatenates the attributes, concatenates and adjusts the indices, and creates
  16242. * a bounding sphere encompassing all instances.
  16243. * <p>
  16244. * If the instances do not have the same attributes, a subset of attributes common
  16245. * to all instances is used, and the others are ignored.
  16246. * </p>
  16247. * <p>
  16248. * This is used by {@link Primitive} to efficiently render a large amount of static data.
  16249. * </p>
  16250. *
  16251. * @private
  16252. *
  16253. * @param {GeometryInstance[]} [instances] The array of {@link GeometryInstance} objects whose geometry will be combined.
  16254. * @returns {Geometry} A single geometry created from the provided geometry instances.
  16255. *
  16256. * @exception {DeveloperError} All instances must have the same modelMatrix.
  16257. * @exception {DeveloperError} All instance geometries must have an indices or not have one.
  16258. * @exception {DeveloperError} All instance geometries must have the same primitiveType.
  16259. *
  16260. *
  16261. * @example
  16262. * for (var i = 0; i < instances.length; ++i) {
  16263. * Cesium.GeometryPipeline.transformToWorldCoordinates(instances[i]);
  16264. * }
  16265. * var geometries = Cesium.GeometryPipeline.combineInstances(instances);
  16266. *
  16267. * @see GeometryPipeline.transformToWorldCoordinates
  16268. */
  16269. GeometryPipeline.combineInstances = function(instances) {
  16270. if ((!defined(instances)) || (instances.length < 1)) {
  16271. throw new DeveloperError('instances is required and must have length greater than zero.');
  16272. }
  16273. var instanceGeometry = [];
  16274. var instanceSplitGeometry = [];
  16275. var length = instances.length;
  16276. for (var i = 0; i < length; ++i) {
  16277. var instance = instances[i];
  16278. if (defined(instance.geometry)) {
  16279. instanceGeometry.push(instance);
  16280. } else if (defined(instance.westHemisphereGeometry) && defined(instance.eastHemisphereGeometry)) {
  16281. instanceSplitGeometry.push(instance);
  16282. }
  16283. }
  16284. var geometries = [];
  16285. if (instanceGeometry.length > 0) {
  16286. geometries.push(combineGeometries(instanceGeometry, 'geometry'));
  16287. }
  16288. if (instanceSplitGeometry.length > 0) {
  16289. geometries.push(combineGeometries(instanceSplitGeometry, 'westHemisphereGeometry'));
  16290. geometries.push(combineGeometries(instanceSplitGeometry, 'eastHemisphereGeometry'));
  16291. }
  16292. return geometries;
  16293. };
  16294. var normal = new Cartesian3();
  16295. var v0 = new Cartesian3();
  16296. var v1 = new Cartesian3();
  16297. var v2 = new Cartesian3();
  16298. /**
  16299. * Computes per-vertex normals for a geometry containing <code>TRIANGLES</code> by averaging the normals of
  16300. * all triangles incident to the vertex. The result is a new <code>normal</code> attribute added to the geometry.
  16301. * This assumes a counter-clockwise winding order.
  16302. *
  16303. * @param {Geometry} geometry The geometry to modify.
  16304. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>normal</code> attribute.
  16305. *
  16306. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  16307. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  16308. *
  16309. * @example
  16310. * Cesium.GeometryPipeline.computeNormal(geometry);
  16311. */
  16312. GeometryPipeline.computeNormal = function(geometry) {
  16313. if (!defined(geometry)) {
  16314. throw new DeveloperError('geometry is required.');
  16315. }
  16316. if (!defined(geometry.attributes.position) || !defined(geometry.attributes.position.values)) {
  16317. throw new DeveloperError('geometry.attributes.position.values is required.');
  16318. }
  16319. if (!defined(geometry.indices)) {
  16320. throw new DeveloperError('geometry.indices is required.');
  16321. }
  16322. if (geometry.indices.length < 2 || geometry.indices.length % 3 !== 0) {
  16323. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  16324. }
  16325. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  16326. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  16327. }
  16328. var indices = geometry.indices;
  16329. var attributes = geometry.attributes;
  16330. var vertices = attributes.position.values;
  16331. var numVertices = attributes.position.values.length / 3;
  16332. var numIndices = indices.length;
  16333. var normalsPerVertex = new Array(numVertices);
  16334. var normalsPerTriangle = new Array(numIndices / 3);
  16335. var normalIndices = new Array(numIndices);
  16336. for ( var i = 0; i < numVertices; i++) {
  16337. normalsPerVertex[i] = {
  16338. indexOffset : 0,
  16339. count : 0,
  16340. currentCount : 0
  16341. };
  16342. }
  16343. var j = 0;
  16344. for (i = 0; i < numIndices; i += 3) {
  16345. var i0 = indices[i];
  16346. var i1 = indices[i + 1];
  16347. var i2 = indices[i + 2];
  16348. var i03 = i0 * 3;
  16349. var i13 = i1 * 3;
  16350. var i23 = i2 * 3;
  16351. v0.x = vertices[i03];
  16352. v0.y = vertices[i03 + 1];
  16353. v0.z = vertices[i03 + 2];
  16354. v1.x = vertices[i13];
  16355. v1.y = vertices[i13 + 1];
  16356. v1.z = vertices[i13 + 2];
  16357. v2.x = vertices[i23];
  16358. v2.y = vertices[i23 + 1];
  16359. v2.z = vertices[i23 + 2];
  16360. normalsPerVertex[i0].count++;
  16361. normalsPerVertex[i1].count++;
  16362. normalsPerVertex[i2].count++;
  16363. Cartesian3.subtract(v1, v0, v1);
  16364. Cartesian3.subtract(v2, v0, v2);
  16365. normalsPerTriangle[j] = Cartesian3.cross(v1, v2, new Cartesian3());
  16366. j++;
  16367. }
  16368. var indexOffset = 0;
  16369. for (i = 0; i < numVertices; i++) {
  16370. normalsPerVertex[i].indexOffset += indexOffset;
  16371. indexOffset += normalsPerVertex[i].count;
  16372. }
  16373. j = 0;
  16374. var vertexNormalData;
  16375. for (i = 0; i < numIndices; i += 3) {
  16376. vertexNormalData = normalsPerVertex[indices[i]];
  16377. var index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  16378. normalIndices[index] = j;
  16379. vertexNormalData.currentCount++;
  16380. vertexNormalData = normalsPerVertex[indices[i + 1]];
  16381. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  16382. normalIndices[index] = j;
  16383. vertexNormalData.currentCount++;
  16384. vertexNormalData = normalsPerVertex[indices[i + 2]];
  16385. index = vertexNormalData.indexOffset + vertexNormalData.currentCount;
  16386. normalIndices[index] = j;
  16387. vertexNormalData.currentCount++;
  16388. j++;
  16389. }
  16390. var normalValues = new Float32Array(numVertices * 3);
  16391. for (i = 0; i < numVertices; i++) {
  16392. var i3 = i * 3;
  16393. vertexNormalData = normalsPerVertex[i];
  16394. if (vertexNormalData.count > 0) {
  16395. Cartesian3.clone(Cartesian3.ZERO, normal);
  16396. for (j = 0; j < vertexNormalData.count; j++) {
  16397. Cartesian3.add(normal, normalsPerTriangle[normalIndices[vertexNormalData.indexOffset + j]], normal);
  16398. }
  16399. Cartesian3.normalize(normal, normal);
  16400. normalValues[i3] = normal.x;
  16401. normalValues[i3 + 1] = normal.y;
  16402. normalValues[i3 + 2] = normal.z;
  16403. } else {
  16404. normalValues[i3] = 0.0;
  16405. normalValues[i3 + 1] = 0.0;
  16406. normalValues[i3 + 2] = 1.0;
  16407. }
  16408. }
  16409. geometry.attributes.normal = new GeometryAttribute({
  16410. componentDatatype : ComponentDatatype.FLOAT,
  16411. componentsPerAttribute : 3,
  16412. values : normalValues
  16413. });
  16414. return geometry;
  16415. };
  16416. var normalScratch = new Cartesian3();
  16417. var normalScale = new Cartesian3();
  16418. var tScratch = new Cartesian3();
  16419. /**
  16420. * Computes per-vertex binormals and tangents for a geometry containing <code>TRIANGLES</code>.
  16421. * The result is new <code>binormal</code> and <code>tangent</code> attributes added to the geometry.
  16422. * This assumes a counter-clockwise winding order.
  16423. * <p>
  16424. * Based on <a href="http://www.terathon.com/code/tangent.html">Computing Tangent Space Basis Vectors
  16425. * for an Arbitrary Mesh</a> by Eric Lengyel.
  16426. * </p>
  16427. *
  16428. * @param {Geometry} geometry The geometry to modify.
  16429. * @returns {Geometry} The modified <code>geometry</code> argument with the computed <code>binormal</code> and <code>tangent</code> attributes.
  16430. *
  16431. * @exception {DeveloperError} geometry.indices length must be greater than 0 and be a multiple of 3.
  16432. * @exception {DeveloperError} geometry.primitiveType must be {@link PrimitiveType.TRIANGLES}.
  16433. *
  16434. * @example
  16435. * Cesium.GeometryPipeline.computeBinormalAndTangent(geometry);
  16436. */
  16437. GeometryPipeline.computeBinormalAndTangent = function(geometry) {
  16438. if (!defined(geometry)) {
  16439. throw new DeveloperError('geometry is required.');
  16440. }
  16441. var attributes = geometry.attributes;
  16442. var indices = geometry.indices;
  16443. if (!defined(attributes.position) || !defined(attributes.position.values)) {
  16444. throw new DeveloperError('geometry.attributes.position.values is required.');
  16445. }
  16446. if (!defined(attributes.normal) || !defined(attributes.normal.values)) {
  16447. throw new DeveloperError('geometry.attributes.normal.values is required.');
  16448. }
  16449. if (!defined(attributes.st) || !defined(attributes.st.values)) {
  16450. throw new DeveloperError('geometry.attributes.st.values is required.');
  16451. }
  16452. if (!defined(indices)) {
  16453. throw new DeveloperError('geometry.indices is required.');
  16454. }
  16455. if (indices.length < 2 || indices.length % 3 !== 0) {
  16456. throw new DeveloperError('geometry.indices length must be greater than 0 and be a multiple of 3.');
  16457. }
  16458. if (geometry.primitiveType !== PrimitiveType.TRIANGLES) {
  16459. throw new DeveloperError('geometry.primitiveType must be PrimitiveType.TRIANGLES.');
  16460. }
  16461. var vertices = geometry.attributes.position.values;
  16462. var normals = geometry.attributes.normal.values;
  16463. var st = geometry.attributes.st.values;
  16464. var numVertices = geometry.attributes.position.values.length / 3;
  16465. var numIndices = indices.length;
  16466. var tan1 = new Array(numVertices * 3);
  16467. for ( var i = 0; i < tan1.length; i++) {
  16468. tan1[i] = 0;
  16469. }
  16470. var i03;
  16471. var i13;
  16472. var i23;
  16473. for (i = 0; i < numIndices; i += 3) {
  16474. var i0 = indices[i];
  16475. var i1 = indices[i + 1];
  16476. var i2 = indices[i + 2];
  16477. i03 = i0 * 3;
  16478. i13 = i1 * 3;
  16479. i23 = i2 * 3;
  16480. var i02 = i0 * 2;
  16481. var i12 = i1 * 2;
  16482. var i22 = i2 * 2;
  16483. var ux = vertices[i03];
  16484. var uy = vertices[i03 + 1];
  16485. var uz = vertices[i03 + 2];
  16486. var wx = st[i02];
  16487. var wy = st[i02 + 1];
  16488. var t1 = st[i12 + 1] - wy;
  16489. var t2 = st[i22 + 1] - wy;
  16490. var r = 1.0 / ((st[i12] - wx) * t2 - (st[i22] - wx) * t1);
  16491. var sdirx = (t2 * (vertices[i13] - ux) - t1 * (vertices[i23] - ux)) * r;
  16492. var sdiry = (t2 * (vertices[i13 + 1] - uy) - t1 * (vertices[i23 + 1] - uy)) * r;
  16493. var sdirz = (t2 * (vertices[i13 + 2] - uz) - t1 * (vertices[i23 + 2] - uz)) * r;
  16494. tan1[i03] += sdirx;
  16495. tan1[i03 + 1] += sdiry;
  16496. tan1[i03 + 2] += sdirz;
  16497. tan1[i13] += sdirx;
  16498. tan1[i13 + 1] += sdiry;
  16499. tan1[i13 + 2] += sdirz;
  16500. tan1[i23] += sdirx;
  16501. tan1[i23 + 1] += sdiry;
  16502. tan1[i23 + 2] += sdirz;
  16503. }
  16504. var binormalValues = new Float32Array(numVertices * 3);
  16505. var tangentValues = new Float32Array(numVertices * 3);
  16506. for (i = 0; i < numVertices; i++) {
  16507. i03 = i * 3;
  16508. i13 = i03 + 1;
  16509. i23 = i03 + 2;
  16510. var n = Cartesian3.fromArray(normals, i03, normalScratch);
  16511. var t = Cartesian3.fromArray(tan1, i03, tScratch);
  16512. var scalar = Cartesian3.dot(n, t);
  16513. Cartesian3.multiplyByScalar(n, scalar, normalScale);
  16514. Cartesian3.normalize(Cartesian3.subtract(t, normalScale, t), t);
  16515. tangentValues[i03] = t.x;
  16516. tangentValues[i13] = t.y;
  16517. tangentValues[i23] = t.z;
  16518. Cartesian3.normalize(Cartesian3.cross(n, t, t), t);
  16519. binormalValues[i03] = t.x;
  16520. binormalValues[i13] = t.y;
  16521. binormalValues[i23] = t.z;
  16522. }
  16523. geometry.attributes.tangent = new GeometryAttribute({
  16524. componentDatatype : ComponentDatatype.FLOAT,
  16525. componentsPerAttribute : 3,
  16526. values : tangentValues
  16527. });
  16528. geometry.attributes.binormal = new GeometryAttribute({
  16529. componentDatatype : ComponentDatatype.FLOAT,
  16530. componentsPerAttribute : 3,
  16531. values : binormalValues
  16532. });
  16533. return geometry;
  16534. };
  16535. var scratchCartesian2 = new Cartesian2();
  16536. var toEncode1 = new Cartesian3();
  16537. var toEncode2 = new Cartesian3();
  16538. var toEncode3 = new Cartesian3();
  16539. /**
  16540. * Compresses and packs geometry normal attribute values to save memory.
  16541. *
  16542. * @param {Geometry} geometry The geometry to modify.
  16543. * @returns {Geometry} The modified <code>geometry</code> argument, with its normals compressed and packed.
  16544. *
  16545. * @example
  16546. * geometry = Cesium.GeometryPipeline.compressVertices(geometry);
  16547. */
  16548. GeometryPipeline.compressVertices = function(geometry) {
  16549. if (!defined(geometry)) {
  16550. throw new DeveloperError('geometry is required.');
  16551. }
  16552. var normalAttribute = geometry.attributes.normal;
  16553. var stAttribute = geometry.attributes.st;
  16554. if (!defined(normalAttribute) && !defined(stAttribute)) {
  16555. return geometry;
  16556. }
  16557. var tangentAttribute = geometry.attributes.tangent;
  16558. var binormalAttribute = geometry.attributes.binormal;
  16559. var normals;
  16560. var st;
  16561. var tangents;
  16562. var binormals;
  16563. if (defined(normalAttribute)) {
  16564. normals = normalAttribute.values;
  16565. }
  16566. if (defined(stAttribute)) {
  16567. st = stAttribute.values;
  16568. }
  16569. if (defined(tangentAttribute)) {
  16570. tangents = tangentAttribute.values;
  16571. }
  16572. if (binormalAttribute) {
  16573. binormals = binormalAttribute.values;
  16574. }
  16575. var length = defined(normals) ? normals.length : st.length;
  16576. var numComponents = defined(normals) ? 3.0 : 2.0;
  16577. var numVertices = length / numComponents;
  16578. var compressedLength = numVertices;
  16579. var numCompressedComponents = defined(st) && defined(normals) ? 2.0 : 1.0;
  16580. numCompressedComponents += defined(tangents) || defined(binormals) ? 1.0 : 0.0;
  16581. compressedLength *= numCompressedComponents;
  16582. var compressedAttributes = new Float32Array(compressedLength);
  16583. var normalIndex = 0;
  16584. for (var i = 0; i < numVertices; ++i) {
  16585. if (defined(st)) {
  16586. Cartesian2.fromArray(st, i * 2.0, scratchCartesian2);
  16587. compressedAttributes[normalIndex++] = AttributeCompression.compressTextureCoordinates(scratchCartesian2);
  16588. }
  16589. var index = i * 3.0;
  16590. if (defined(normals) && defined(tangents) && defined(binormals)) {
  16591. Cartesian3.fromArray(normals, index, toEncode1);
  16592. Cartesian3.fromArray(tangents, index, toEncode2);
  16593. Cartesian3.fromArray(binormals, index, toEncode3);
  16594. AttributeCompression.octPack(toEncode1, toEncode2, toEncode3, scratchCartesian2);
  16595. compressedAttributes[normalIndex++] = scratchCartesian2.x;
  16596. compressedAttributes[normalIndex++] = scratchCartesian2.y;
  16597. } else {
  16598. if (defined(normals)) {
  16599. Cartesian3.fromArray(normals, index, toEncode1);
  16600. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  16601. }
  16602. if (defined(tangents)) {
  16603. Cartesian3.fromArray(tangents, index, toEncode1);
  16604. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  16605. }
  16606. if (defined(binormals)) {
  16607. Cartesian3.fromArray(binormals, index, toEncode1);
  16608. compressedAttributes[normalIndex++] = AttributeCompression.octEncodeFloat(toEncode1);
  16609. }
  16610. }
  16611. }
  16612. geometry.attributes.compressedAttributes = new GeometryAttribute({
  16613. componentDatatype : ComponentDatatype.FLOAT,
  16614. componentsPerAttribute : numCompressedComponents,
  16615. values : compressedAttributes
  16616. });
  16617. if (defined(normals)) {
  16618. delete geometry.attributes.normal;
  16619. }
  16620. if (defined(st)) {
  16621. delete geometry.attributes.st;
  16622. }
  16623. if (defined(tangents)) {
  16624. delete geometry.attributes.tangent;
  16625. }
  16626. if (defined(binormals)) {
  16627. delete geometry.attributes.binormal;
  16628. }
  16629. return geometry;
  16630. };
  16631. function indexTriangles(geometry) {
  16632. if (defined(geometry.indices)) {
  16633. return geometry;
  16634. }
  16635. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16636. if (numberOfVertices < 3) {
  16637. throw new DeveloperError('The number of vertices must be at least three.');
  16638. }
  16639. if (numberOfVertices % 3 !== 0) {
  16640. throw new DeveloperError('The number of vertices must be a multiple of three.');
  16641. }
  16642. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  16643. for (var i = 0; i < numberOfVertices; ++i) {
  16644. indices[i] = i;
  16645. }
  16646. geometry.indices = indices;
  16647. return geometry;
  16648. }
  16649. function indexTriangleFan(geometry) {
  16650. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16651. if (numberOfVertices < 3) {
  16652. throw new DeveloperError('The number of vertices must be at least three.');
  16653. }
  16654. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  16655. indices[0] = 1;
  16656. indices[1] = 0;
  16657. indices[2] = 2;
  16658. var indicesIndex = 3;
  16659. for (var i = 3; i < numberOfVertices; ++i) {
  16660. indices[indicesIndex++] = i - 1;
  16661. indices[indicesIndex++] = 0;
  16662. indices[indicesIndex++] = i;
  16663. }
  16664. geometry.indices = indices;
  16665. geometry.primitiveType = PrimitiveType.TRIANGLES;
  16666. return geometry;
  16667. }
  16668. function indexTriangleStrip(geometry) {
  16669. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16670. if (numberOfVertices < 3) {
  16671. throw new DeveloperError('The number of vertices must be at least 3.');
  16672. }
  16673. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 2) * 3);
  16674. indices[0] = 0;
  16675. indices[1] = 1;
  16676. indices[2] = 2;
  16677. if (numberOfVertices > 3) {
  16678. indices[3] = 0;
  16679. indices[4] = 2;
  16680. indices[5] = 3;
  16681. }
  16682. var indicesIndex = 6;
  16683. for (var i = 3; i < numberOfVertices - 1; i += 2) {
  16684. indices[indicesIndex++] = i;
  16685. indices[indicesIndex++] = i - 1;
  16686. indices[indicesIndex++] = i + 1;
  16687. if (i + 2 < numberOfVertices) {
  16688. indices[indicesIndex++] = i;
  16689. indices[indicesIndex++] = i + 1;
  16690. indices[indicesIndex++] = i + 2;
  16691. }
  16692. }
  16693. geometry.indices = indices;
  16694. geometry.primitiveType = PrimitiveType.TRIANGLES;
  16695. return geometry;
  16696. }
  16697. function indexLines(geometry) {
  16698. if (defined(geometry.indices)) {
  16699. return geometry;
  16700. }
  16701. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16702. if (numberOfVertices < 2) {
  16703. throw new DeveloperError('The number of vertices must be at least two.');
  16704. }
  16705. if (numberOfVertices % 2 !== 0) {
  16706. throw new DeveloperError('The number of vertices must be a multiple of 2.');
  16707. }
  16708. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices);
  16709. for (var i = 0; i < numberOfVertices; ++i) {
  16710. indices[i] = i;
  16711. }
  16712. geometry.indices = indices;
  16713. return geometry;
  16714. }
  16715. function indexLineStrip(geometry) {
  16716. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16717. if (numberOfVertices < 2) {
  16718. throw new DeveloperError('The number of vertices must be at least two.');
  16719. }
  16720. var indices = IndexDatatype.createTypedArray(numberOfVertices, (numberOfVertices - 1) * 2);
  16721. indices[0] = 0;
  16722. indices[1] = 1;
  16723. var indicesIndex = 2;
  16724. for (var i = 2; i < numberOfVertices; ++i) {
  16725. indices[indicesIndex++] = i - 1;
  16726. indices[indicesIndex++] = i;
  16727. }
  16728. geometry.indices = indices;
  16729. geometry.primitiveType = PrimitiveType.LINES;
  16730. return geometry;
  16731. }
  16732. function indexLineLoop(geometry) {
  16733. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16734. if (numberOfVertices < 2) {
  16735. throw new DeveloperError('The number of vertices must be at least two.');
  16736. }
  16737. var indices = IndexDatatype.createTypedArray(numberOfVertices, numberOfVertices * 2);
  16738. indices[0] = 0;
  16739. indices[1] = 1;
  16740. var indicesIndex = 2;
  16741. for (var i = 2; i < numberOfVertices; ++i) {
  16742. indices[indicesIndex++] = i - 1;
  16743. indices[indicesIndex++] = i;
  16744. }
  16745. indices[indicesIndex++] = numberOfVertices - 1;
  16746. indices[indicesIndex] = 0;
  16747. geometry.indices = indices;
  16748. geometry.primitiveType = PrimitiveType.LINES;
  16749. return geometry;
  16750. }
  16751. function indexPrimitive(geometry) {
  16752. switch (geometry.primitiveType) {
  16753. case PrimitiveType.TRIANGLE_FAN:
  16754. return indexTriangleFan(geometry);
  16755. case PrimitiveType.TRIANGLE_STRIP:
  16756. return indexTriangleStrip(geometry);
  16757. case PrimitiveType.TRIANGLES:
  16758. return indexTriangles(geometry);
  16759. case PrimitiveType.LINE_STRIP:
  16760. return indexLineStrip(geometry);
  16761. case PrimitiveType.LINE_LOOP:
  16762. return indexLineLoop(geometry);
  16763. case PrimitiveType.LINES:
  16764. return indexLines(geometry);
  16765. }
  16766. return geometry;
  16767. }
  16768. function offsetPointFromXZPlane(p, isBehind) {
  16769. if (Math.abs(p.y) < CesiumMath.EPSILON6){
  16770. if (isBehind) {
  16771. p.y = -CesiumMath.EPSILON6;
  16772. } else {
  16773. p.y = CesiumMath.EPSILON6;
  16774. }
  16775. }
  16776. }
  16777. function offsetTriangleFromXZPlane(p0, p1, p2) {
  16778. if (p0.y !== 0.0 && p1.y !== 0.0 && p2.y !== 0.0) {
  16779. offsetPointFromXZPlane(p0, p0.y < 0.0);
  16780. offsetPointFromXZPlane(p1, p1.y < 0.0);
  16781. offsetPointFromXZPlane(p2, p2.y < 0.0);
  16782. return;
  16783. }
  16784. var p0y = Math.abs(p0.y);
  16785. var p1y = Math.abs(p1.y);
  16786. var p2y = Math.abs(p2.y);
  16787. var sign;
  16788. if (p0y > p1y) {
  16789. if (p0y > p2y) {
  16790. sign = CesiumMath.sign(p0.y);
  16791. } else {
  16792. sign = CesiumMath.sign(p2.y);
  16793. }
  16794. } else if (p1y > p2y) {
  16795. sign = CesiumMath.sign(p1.y);
  16796. } else {
  16797. sign = CesiumMath.sign(p2.y);
  16798. }
  16799. var isBehind = sign < 0.0;
  16800. offsetPointFromXZPlane(p0, isBehind);
  16801. offsetPointFromXZPlane(p1, isBehind);
  16802. offsetPointFromXZPlane(p2, isBehind);
  16803. }
  16804. var c3 = new Cartesian3();
  16805. function getXZIntersectionOffsetPoints(p, p1, u1, v1) {
  16806. Cartesian3.add(p, Cartesian3.multiplyByScalar(Cartesian3.subtract(p1, p, c3), p.y/(p.y-p1.y), c3), u1);
  16807. Cartesian3.clone(u1, v1);
  16808. offsetPointFromXZPlane(u1, true);
  16809. offsetPointFromXZPlane(v1, false);
  16810. }
  16811. var u1 = new Cartesian3();
  16812. var u2 = new Cartesian3();
  16813. var q1 = new Cartesian3();
  16814. var q2 = new Cartesian3();
  16815. var splitTriangleResult = {
  16816. positions : new Array(7),
  16817. indices : new Array(3 * 3)
  16818. };
  16819. function splitTriangle(p0, p1, p2) {
  16820. // In WGS84 coordinates, for a triangle approximately on the
  16821. // ellipsoid to cross the IDL, first it needs to be on the
  16822. // negative side of the plane x = 0.
  16823. if ((p0.x >= 0.0) || (p1.x >= 0.0) || (p2.x >= 0.0)) {
  16824. return undefined;
  16825. }
  16826. offsetTriangleFromXZPlane(p0, p1, p2);
  16827. var p0Behind = p0.y < 0.0;
  16828. var p1Behind = p1.y < 0.0;
  16829. var p2Behind = p2.y < 0.0;
  16830. var numBehind = 0;
  16831. numBehind += p0Behind ? 1 : 0;
  16832. numBehind += p1Behind ? 1 : 0;
  16833. numBehind += p2Behind ? 1 : 0;
  16834. var indices = splitTriangleResult.indices;
  16835. if (numBehind === 1) {
  16836. indices[1] = 3;
  16837. indices[2] = 4;
  16838. indices[5] = 6;
  16839. indices[7] = 6;
  16840. indices[8] = 5;
  16841. if (p0Behind) {
  16842. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  16843. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  16844. indices[0] = 0;
  16845. indices[3] = 1;
  16846. indices[4] = 2;
  16847. indices[6] = 1;
  16848. } else if (p1Behind) {
  16849. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  16850. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  16851. indices[0] = 1;
  16852. indices[3] = 2;
  16853. indices[4] = 0;
  16854. indices[6] = 2;
  16855. } else if (p2Behind) {
  16856. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  16857. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  16858. indices[0] = 2;
  16859. indices[3] = 0;
  16860. indices[4] = 1;
  16861. indices[6] = 0;
  16862. }
  16863. } else if (numBehind === 2) {
  16864. indices[2] = 4;
  16865. indices[4] = 4;
  16866. indices[5] = 3;
  16867. indices[7] = 5;
  16868. indices[8] = 6;
  16869. if (!p0Behind) {
  16870. getXZIntersectionOffsetPoints(p0, p1, u1, q1);
  16871. getXZIntersectionOffsetPoints(p0, p2, u2, q2);
  16872. indices[0] = 1;
  16873. indices[1] = 2;
  16874. indices[3] = 1;
  16875. indices[6] = 0;
  16876. } else if (!p1Behind) {
  16877. getXZIntersectionOffsetPoints(p1, p2, u1, q1);
  16878. getXZIntersectionOffsetPoints(p1, p0, u2, q2);
  16879. indices[0] = 2;
  16880. indices[1] = 0;
  16881. indices[3] = 2;
  16882. indices[6] = 1;
  16883. } else if (!p2Behind) {
  16884. getXZIntersectionOffsetPoints(p2, p0, u1, q1);
  16885. getXZIntersectionOffsetPoints(p2, p1, u2, q2);
  16886. indices[0] = 0;
  16887. indices[1] = 1;
  16888. indices[3] = 0;
  16889. indices[6] = 2;
  16890. }
  16891. }
  16892. var positions = splitTriangleResult.positions;
  16893. positions[0] = p0;
  16894. positions[1] = p1;
  16895. positions[2] = p2;
  16896. positions.length = 3;
  16897. if (numBehind === 1 || numBehind === 2) {
  16898. positions[3] = u1;
  16899. positions[4] = u2;
  16900. positions[5] = q1;
  16901. positions[6] = q2;
  16902. positions.length = 7;
  16903. }
  16904. return splitTriangleResult;
  16905. }
  16906. function updateGeometryAfterSplit(geometry, computeBoundingSphere) {
  16907. var attributes = geometry.attributes;
  16908. if (attributes.position.values.length === 0) {
  16909. return undefined;
  16910. }
  16911. for (var property in attributes) {
  16912. if (attributes.hasOwnProperty(property) &&
  16913. defined(attributes[property]) &&
  16914. defined(attributes[property].values)) {
  16915. var attribute = attributes[property];
  16916. attribute.values = ComponentDatatype.createTypedArray(attribute.componentDatatype, attribute.values);
  16917. }
  16918. }
  16919. var numberOfVertices = Geometry.computeNumberOfVertices(geometry);
  16920. geometry.indices = IndexDatatype.createTypedArray(numberOfVertices, geometry.indices);
  16921. if (computeBoundingSphere) {
  16922. geometry.boundingSphere = BoundingSphere.fromVertices(attributes.position.values);
  16923. }
  16924. return geometry;
  16925. }
  16926. function copyGeometryForSplit(geometry) {
  16927. var attributes = geometry.attributes;
  16928. var copiedAttributes = {};
  16929. for (var property in attributes) {
  16930. if (attributes.hasOwnProperty(property) &&
  16931. defined(attributes[property]) &&
  16932. defined(attributes[property].values)) {
  16933. var attribute = attributes[property];
  16934. copiedAttributes[property] = new GeometryAttribute({
  16935. componentDatatype : attribute.componentDatatype,
  16936. componentsPerAttribute : attribute.componentsPerAttribute,
  16937. normalize : attribute.normalize,
  16938. values : []
  16939. });
  16940. }
  16941. }
  16942. return new Geometry({
  16943. attributes : copiedAttributes,
  16944. indices : [],
  16945. primitiveType : geometry.primitiveType
  16946. });
  16947. }
  16948. function updateInstanceAfterSplit(instance, westGeometry, eastGeometry) {
  16949. var computeBoundingSphere = defined(instance.geometry.boundingSphere);
  16950. westGeometry = updateGeometryAfterSplit(westGeometry, computeBoundingSphere);
  16951. eastGeometry = updateGeometryAfterSplit(eastGeometry, computeBoundingSphere);
  16952. if (defined(eastGeometry) && !defined(westGeometry)) {
  16953. instance.geometry = eastGeometry;
  16954. } else if (!defined(eastGeometry) && defined(westGeometry)) {
  16955. instance.geometry = westGeometry;
  16956. } else {
  16957. instance.westHemisphereGeometry = westGeometry;
  16958. instance.eastHemisphereGeometry = eastGeometry;
  16959. instance.geometry = undefined;
  16960. }
  16961. }
  16962. var p0Scratch = new Cartesian3();
  16963. var p1Scratch = new Cartesian3();
  16964. var p2Scratch = new Cartesian3();
  16965. var barycentricScratch = new Cartesian3();
  16966. var s0Scratch = new Cartesian2();
  16967. var s1Scratch = new Cartesian2();
  16968. var s2Scratch = new Cartesian2();
  16969. function computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex) {
  16970. if (!defined(normals) && !defined(binormals) && !defined(tangents) && !defined(texCoords)) {
  16971. return;
  16972. }
  16973. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  16974. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  16975. var p2 = Cartesian3.fromArray(positions, i2 * 3, p2Scratch);
  16976. var coords = barycentricCoordinates(point, p0, p1, p2, barycentricScratch);
  16977. if (defined(normals)) {
  16978. var n0 = Cartesian3.fromArray(normals, i0 * 3, p0Scratch);
  16979. var n1 = Cartesian3.fromArray(normals, i1 * 3, p1Scratch);
  16980. var n2 = Cartesian3.fromArray(normals, i2 * 3, p2Scratch);
  16981. Cartesian3.multiplyByScalar(n0, coords.x, n0);
  16982. Cartesian3.multiplyByScalar(n1, coords.y, n1);
  16983. Cartesian3.multiplyByScalar(n2, coords.z, n2);
  16984. var normal = Cartesian3.add(n0, n1, n0);
  16985. Cartesian3.add(normal, n2, normal);
  16986. Cartesian3.normalize(normal, normal);
  16987. Cartesian3.pack(normal, currentAttributes.normal.values, insertedIndex * 3);
  16988. }
  16989. if (defined(binormals)) {
  16990. var b0 = Cartesian3.fromArray(binormals, i0 * 3, p0Scratch);
  16991. var b1 = Cartesian3.fromArray(binormals, i1 * 3, p1Scratch);
  16992. var b2 = Cartesian3.fromArray(binormals, i2 * 3, p2Scratch);
  16993. Cartesian3.multiplyByScalar(b0, coords.x, b0);
  16994. Cartesian3.multiplyByScalar(b1, coords.y, b1);
  16995. Cartesian3.multiplyByScalar(b2, coords.z, b2);
  16996. var binormal = Cartesian3.add(b0, b1, b0);
  16997. Cartesian3.add(binormal, b2, binormal);
  16998. Cartesian3.normalize(binormal, binormal);
  16999. Cartesian3.pack(binormal, currentAttributes.binormal.values, insertedIndex * 3);
  17000. }
  17001. if (defined(tangents)) {
  17002. var t0 = Cartesian3.fromArray(tangents, i0 * 3, p0Scratch);
  17003. var t1 = Cartesian3.fromArray(tangents, i1 * 3, p1Scratch);
  17004. var t2 = Cartesian3.fromArray(tangents, i2 * 3, p2Scratch);
  17005. Cartesian3.multiplyByScalar(t0, coords.x, t0);
  17006. Cartesian3.multiplyByScalar(t1, coords.y, t1);
  17007. Cartesian3.multiplyByScalar(t2, coords.z, t2);
  17008. var tangent = Cartesian3.add(t0, t1, t0);
  17009. Cartesian3.add(tangent, t2, tangent);
  17010. Cartesian3.normalize(tangent, tangent);
  17011. Cartesian3.pack(tangent, currentAttributes.tangent.values, insertedIndex * 3);
  17012. }
  17013. if (defined(texCoords)) {
  17014. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, s0Scratch);
  17015. var s1 = Cartesian2.fromArray(texCoords, i1 * 2, s1Scratch);
  17016. var s2 = Cartesian2.fromArray(texCoords, i2 * 2, s2Scratch);
  17017. Cartesian2.multiplyByScalar(s0, coords.x, s0);
  17018. Cartesian2.multiplyByScalar(s1, coords.y, s1);
  17019. Cartesian2.multiplyByScalar(s2, coords.z, s2);
  17020. var texCoord = Cartesian2.add(s0, s1, s0);
  17021. Cartesian2.add(texCoord, s2, texCoord);
  17022. Cartesian2.pack(texCoord, currentAttributes.st.values, insertedIndex * 2);
  17023. }
  17024. }
  17025. function insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, currentIndex, point) {
  17026. var insertIndex = currentAttributes.position.values.length / 3;
  17027. if (currentIndex !== -1) {
  17028. var prevIndex = indices[currentIndex];
  17029. var newIndex = currentIndexMap[prevIndex];
  17030. if (newIndex === -1) {
  17031. currentIndexMap[prevIndex] = insertIndex;
  17032. currentAttributes.position.values.push(point.x, point.y, point.z);
  17033. currentIndices.push(insertIndex);
  17034. return insertIndex;
  17035. }
  17036. currentIndices.push(newIndex);
  17037. return newIndex;
  17038. }
  17039. currentAttributes.position.values.push(point.x, point.y, point.z);
  17040. currentIndices.push(insertIndex);
  17041. return insertIndex;
  17042. }
  17043. function splitLongitudeTriangles(instance) {
  17044. var geometry = instance.geometry;
  17045. var attributes = geometry.attributes;
  17046. var positions = attributes.position.values;
  17047. var normals = (defined(attributes.normal)) ? attributes.normal.values : undefined;
  17048. var binormals = (defined(attributes.binormal)) ? attributes.binormal.values : undefined;
  17049. var tangents = (defined(attributes.tangent)) ? attributes.tangent.values : undefined;
  17050. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  17051. var indices = geometry.indices;
  17052. var eastGeometry = copyGeometryForSplit(geometry);
  17053. var westGeometry = copyGeometryForSplit(geometry);
  17054. var currentAttributes;
  17055. var currentIndices;
  17056. var currentIndexMap;
  17057. var insertedIndex;
  17058. var i;
  17059. var westGeometryIndexMap = [];
  17060. westGeometryIndexMap.length = positions.length / 3;
  17061. var eastGeometryIndexMap = [];
  17062. eastGeometryIndexMap.length = positions.length / 3;
  17063. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  17064. westGeometryIndexMap[i] = -1;
  17065. eastGeometryIndexMap[i] = -1;
  17066. }
  17067. var len = indices.length;
  17068. for (i = 0; i < len; i += 3) {
  17069. var i0 = indices[i];
  17070. var i1 = indices[i + 1];
  17071. var i2 = indices[i + 2];
  17072. var p0 = Cartesian3.fromArray(positions, i0 * 3);
  17073. var p1 = Cartesian3.fromArray(positions, i1 * 3);
  17074. var p2 = Cartesian3.fromArray(positions, i2 * 3);
  17075. var result = splitTriangle(p0, p1, p2);
  17076. if (defined(result) && result.positions.length > 3) {
  17077. var resultPositions = result.positions;
  17078. var resultIndices = result.indices;
  17079. var resultLength = resultIndices.length;
  17080. for (var j = 0; j < resultLength; ++j) {
  17081. var resultIndex = resultIndices[j];
  17082. var point = resultPositions[resultIndex];
  17083. if (point.y < 0.0) {
  17084. currentAttributes = westGeometry.attributes;
  17085. currentIndices = westGeometry.indices;
  17086. currentIndexMap = westGeometryIndexMap;
  17087. } else {
  17088. currentAttributes = eastGeometry.attributes;
  17089. currentIndices = eastGeometry.indices;
  17090. currentIndexMap = eastGeometryIndexMap;
  17091. }
  17092. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, resultIndex < 3 ? i + resultIndex : -1, point);
  17093. computeTriangleAttributes(i0, i1, i2, point, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17094. }
  17095. } else {
  17096. if (defined(result)) {
  17097. p0 = result.positions[0];
  17098. p1 = result.positions[1];
  17099. p2 = result.positions[2];
  17100. }
  17101. if (p0.y < 0.0) {
  17102. currentAttributes = westGeometry.attributes;
  17103. currentIndices = westGeometry.indices;
  17104. currentIndexMap = westGeometryIndexMap;
  17105. } else {
  17106. currentAttributes = eastGeometry.attributes;
  17107. currentIndices = eastGeometry.indices;
  17108. currentIndexMap = eastGeometryIndexMap;
  17109. }
  17110. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  17111. computeTriangleAttributes(i0, i1, i2, p0, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17112. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  17113. computeTriangleAttributes(i0, i1, i2, p1, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17114. insertedIndex = insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 2, p2);
  17115. computeTriangleAttributes(i0, i1, i2, p2, positions, normals, binormals, tangents, texCoords, currentAttributes, insertedIndex);
  17116. }
  17117. }
  17118. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  17119. }
  17120. var xzPlane = Plane.fromPointNormal(Cartesian3.ZERO, Cartesian3.UNIT_Y);
  17121. var offsetScratch = new Cartesian3();
  17122. var offsetPointScratch = new Cartesian3();
  17123. function splitLongitudeLines(instance) {
  17124. var geometry = instance.geometry;
  17125. var attributes = geometry.attributes;
  17126. var positions = attributes.position.values;
  17127. var indices = geometry.indices;
  17128. var eastGeometry = copyGeometryForSplit(geometry);
  17129. var westGeometry = copyGeometryForSplit(geometry);
  17130. var i;
  17131. var length = indices.length;
  17132. var westGeometryIndexMap = [];
  17133. westGeometryIndexMap.length = positions.length / 3;
  17134. var eastGeometryIndexMap = [];
  17135. eastGeometryIndexMap.length = positions.length / 3;
  17136. for (i = 0; i < westGeometryIndexMap.length; ++i) {
  17137. westGeometryIndexMap[i] = -1;
  17138. eastGeometryIndexMap[i] = -1;
  17139. }
  17140. for (i = 0; i < length; i += 2) {
  17141. var i0 = indices[i];
  17142. var i1 = indices[i + 1];
  17143. var p0 = Cartesian3.fromArray(positions, i0 * 3, p0Scratch);
  17144. var p1 = Cartesian3.fromArray(positions, i1 * 3, p1Scratch);
  17145. if (Math.abs(p0.y) < CesiumMath.EPSILON6){
  17146. if (p0.y < 0.0) {
  17147. p0.y = -CesiumMath.EPSILON6;
  17148. } else {
  17149. p0.y = CesiumMath.EPSILON6;
  17150. }
  17151. }
  17152. if (Math.abs(p1.y) < CesiumMath.EPSILON6){
  17153. if (p1.y < 0.0) {
  17154. p1.y = -CesiumMath.EPSILON6;
  17155. } else {
  17156. p1.y = CesiumMath.EPSILON6;
  17157. }
  17158. }
  17159. var p0Attributes = eastGeometry.attributes;
  17160. var p0Indices = eastGeometry.indices;
  17161. var p0IndexMap = eastGeometryIndexMap;
  17162. var p1Attributes = westGeometry.attributes;
  17163. var p1Indices = westGeometry.indices;
  17164. var p1IndexMap = westGeometryIndexMap;
  17165. var intersection = IntersectionTests.lineSegmentPlane(p0, p1, xzPlane, p2Scratch);
  17166. if (defined(intersection)) {
  17167. // move point on the xz-plane slightly away from the plane
  17168. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, 5.0 * CesiumMath.EPSILON9, offsetScratch);
  17169. if (p0.y < 0.0) {
  17170. Cartesian3.negate(offset, offset);
  17171. p0Attributes = westGeometry.attributes;
  17172. p0Indices = westGeometry.indices;
  17173. p0IndexMap = westGeometryIndexMap;
  17174. p1Attributes = eastGeometry.attributes;
  17175. p1Indices = eastGeometry.indices;
  17176. p1IndexMap = eastGeometryIndexMap;
  17177. }
  17178. var offsetPoint = Cartesian3.add(intersection, offset, offsetPointScratch);
  17179. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, i, p0);
  17180. insertSplitPoint(p0Attributes, p0Indices, p0IndexMap, indices, -1, offsetPoint);
  17181. Cartesian3.negate(offset, offset);
  17182. Cartesian3.add(intersection, offset, offsetPoint);
  17183. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, -1, offsetPoint);
  17184. insertSplitPoint(p1Attributes, p1Indices, p1IndexMap, indices, i + 1, p1);
  17185. } else {
  17186. var currentAttributes;
  17187. var currentIndices;
  17188. var currentIndexMap;
  17189. if (p0.y < 0.0) {
  17190. currentAttributes = westGeometry.attributes;
  17191. currentIndices = westGeometry.indices;
  17192. currentIndexMap = westGeometryIndexMap;
  17193. } else {
  17194. currentAttributes = eastGeometry.attributes;
  17195. currentIndices = eastGeometry.indices;
  17196. currentIndexMap = eastGeometryIndexMap;
  17197. }
  17198. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i, p0);
  17199. insertSplitPoint(currentAttributes, currentIndices, currentIndexMap, indices, i + 1, p1);
  17200. }
  17201. }
  17202. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  17203. }
  17204. var cartesian2Scratch0 = new Cartesian2();
  17205. var cartesian2Scratch1 = new Cartesian2();
  17206. var cartesian3Scratch0 = new Cartesian3();
  17207. var cartesian3Scratch2 = new Cartesian3();
  17208. var cartesian3Scratch3 = new Cartesian3();
  17209. var cartesian3Scratch4 = new Cartesian3();
  17210. var cartesian3Scratch5 = new Cartesian3();
  17211. var cartesian3Scratch6 = new Cartesian3();
  17212. var cartesian4Scratch0 = new Cartesian4();
  17213. function updateAdjacencyAfterSplit(geometry) {
  17214. var attributes = geometry.attributes;
  17215. var positions = attributes.position.values;
  17216. var prevPositions = attributes.prevPosition.values;
  17217. var nextPositions = attributes.nextPosition.values;
  17218. var length = positions.length;
  17219. for (var j = 0; j < length; j += 3) {
  17220. var position = Cartesian3.unpack(positions, j, cartesian3Scratch0);
  17221. if (position.x > 0.0) {
  17222. continue;
  17223. }
  17224. var prevPosition = Cartesian3.unpack(prevPositions, j, cartesian3Scratch2);
  17225. if ((position.y < 0.0 && prevPosition.y > 0.0) || (position.y > 0.0 && prevPosition.y < 0.0)) {
  17226. if (j - 3 > 0) {
  17227. prevPositions[j] = positions[j - 3];
  17228. prevPositions[j + 1] = positions[j - 2];
  17229. prevPositions[j + 2] = positions[j - 1];
  17230. } else {
  17231. Cartesian3.pack(position, prevPositions, j);
  17232. }
  17233. }
  17234. var nextPosition = Cartesian3.unpack(nextPositions, j, cartesian3Scratch3);
  17235. if ((position.y < 0.0 && nextPosition.y > 0.0) || (position.y > 0.0 && nextPosition.y < 0.0)) {
  17236. if (j + 3 < length) {
  17237. nextPositions[j] = positions[j + 3];
  17238. nextPositions[j + 1] = positions[j + 4];
  17239. nextPositions[j + 2] = positions[j + 5];
  17240. } else {
  17241. Cartesian3.pack(position, nextPositions, j);
  17242. }
  17243. }
  17244. }
  17245. }
  17246. var offsetScalar = 5.0 * CesiumMath.EPSILON9;
  17247. var coplanarOffset = CesiumMath.EPSILON6;
  17248. function splitLongitudePolyline(instance) {
  17249. var geometry = instance.geometry;
  17250. var attributes = geometry.attributes;
  17251. var positions = attributes.position.values;
  17252. var prevPositions = attributes.prevPosition.values;
  17253. var nextPositions = attributes.nextPosition.values;
  17254. var expandAndWidths = attributes.expandAndWidth.values;
  17255. var texCoords = (defined(attributes.st)) ? attributes.st.values : undefined;
  17256. var colors = (defined(attributes.color)) ? attributes.color.values : undefined;
  17257. var eastGeometry = copyGeometryForSplit(geometry);
  17258. var westGeometry = copyGeometryForSplit(geometry);
  17259. var i;
  17260. var j;
  17261. var index;
  17262. var intersectionFound = false;
  17263. var length = positions.length / 3;
  17264. for (i = 0; i < length; i += 4) {
  17265. var i0 = i;
  17266. var i2 = i + 2;
  17267. var p0 = Cartesian3.fromArray(positions, i0 * 3, cartesian3Scratch0);
  17268. var p2 = Cartesian3.fromArray(positions, i2 * 3, cartesian3Scratch2);
  17269. // Offset points that are close to the 180 longitude and change the previous/next point
  17270. // to be the same offset point so it can be projected to 2D. There is special handling in the
  17271. // shader for when position == prevPosition || position == nextPosition.
  17272. if (Math.abs(p0.y) < coplanarOffset) {
  17273. p0.y = coplanarOffset * (p2.y < 0.0 ? -1.0 : 1.0);
  17274. positions[i * 3 + 1] = p0.y;
  17275. positions[(i + 1) * 3 + 1] = p0.y;
  17276. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  17277. prevPositions[j] = positions[i * 3];
  17278. prevPositions[j + 1] = positions[i * 3 + 1];
  17279. prevPositions[j + 2] = positions[i * 3 + 2];
  17280. }
  17281. }
  17282. // Do the same but for when the line crosses 180 longitude in the opposite direction.
  17283. if (Math.abs(p2.y) < coplanarOffset) {
  17284. p2.y = coplanarOffset * (p0.y < 0.0 ? -1.0 : 1.0);
  17285. positions[(i + 2) * 3 + 1] = p2.y;
  17286. positions[(i + 3) * 3 + 1] = p2.y;
  17287. for (j = i0 * 3; j < i0 * 3 + 4 * 3; j += 3) {
  17288. nextPositions[j] = positions[(i + 2) * 3];
  17289. nextPositions[j + 1] = positions[(i + 2) * 3 + 1];
  17290. nextPositions[j + 2] = positions[(i + 2) * 3 + 2];
  17291. }
  17292. }
  17293. var p0Attributes = eastGeometry.attributes;
  17294. var p0Indices = eastGeometry.indices;
  17295. var p2Attributes = westGeometry.attributes;
  17296. var p2Indices = westGeometry.indices;
  17297. var intersection = IntersectionTests.lineSegmentPlane(p0, p2, xzPlane, cartesian3Scratch4);
  17298. if (defined(intersection)) {
  17299. intersectionFound = true;
  17300. // move point on the xz-plane slightly away from the plane
  17301. var offset = Cartesian3.multiplyByScalar(Cartesian3.UNIT_Y, offsetScalar, cartesian3Scratch5);
  17302. if (p0.y < 0.0) {
  17303. Cartesian3.negate(offset, offset);
  17304. p0Attributes = westGeometry.attributes;
  17305. p0Indices = westGeometry.indices;
  17306. p2Attributes = eastGeometry.attributes;
  17307. p2Indices = eastGeometry.indices;
  17308. }
  17309. var offsetPoint = Cartesian3.add(intersection, offset, cartesian3Scratch6);
  17310. p0Attributes.position.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  17311. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17312. p0Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17313. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3], prevPositions[i0 * 3 + 1], prevPositions[i0 * 3 + 2]);
  17314. p0Attributes.prevPosition.values.push(prevPositions[i0 * 3 + 3], prevPositions[i0 * 3 + 4], prevPositions[i0 * 3 + 5]);
  17315. p0Attributes.prevPosition.values.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z);
  17316. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17317. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17318. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17319. p0Attributes.nextPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17320. Cartesian3.negate(offset, offset);
  17321. Cartesian3.add(intersection, offset, offsetPoint);
  17322. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17323. p2Attributes.position.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17324. p2Attributes.position.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  17325. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17326. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17327. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17328. p2Attributes.prevPosition.values.push(offsetPoint.x, offsetPoint.y, offsetPoint.z);
  17329. p2Attributes.nextPosition.values.push(p2.x, p2.y, p2.z, p2.x, p2.y, p2.z);
  17330. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3], nextPositions[i2 * 3 + 1], nextPositions[i2 * 3 + 2]);
  17331. p2Attributes.nextPosition.values.push(nextPositions[i2 * 3 + 3], nextPositions[i2 * 3 + 4], nextPositions[i2 * 3 + 5]);
  17332. var ew0 = Cartesian2.fromArray(expandAndWidths, i0 * 2, cartesian2Scratch0);
  17333. var width = Math.abs(ew0.y);
  17334. p0Attributes.expandAndWidth.values.push(-1, width, 1, width);
  17335. p0Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  17336. p2Attributes.expandAndWidth.values.push(-1, width, 1, width);
  17337. p2Attributes.expandAndWidth.values.push(-1, -width, 1, -width);
  17338. var t = Cartesian3.magnitudeSquared(Cartesian3.subtract(intersection, p0, cartesian3Scratch3));
  17339. t /= Cartesian3.magnitudeSquared(Cartesian3.subtract(p2, p0, cartesian3Scratch3));
  17340. if (defined(colors)) {
  17341. var c0 = Cartesian4.fromArray(colors, i0 * 4, cartesian4Scratch0);
  17342. var c2 = Cartesian4.fromArray(colors, i2 * 4, cartesian4Scratch0);
  17343. var r = CesiumMath.lerp(c0.x, c2.x, t);
  17344. var g = CesiumMath.lerp(c0.y, c2.y, t);
  17345. var b = CesiumMath.lerp(c0.z, c2.z, t);
  17346. var a = CesiumMath.lerp(c0.w, c2.w, t);
  17347. for (j = i0 * 4; j < i0 * 4 + 2 * 4; ++j) {
  17348. p0Attributes.color.values.push(colors[j]);
  17349. }
  17350. p0Attributes.color.values.push(r, g, b, a);
  17351. p0Attributes.color.values.push(r, g, b, a);
  17352. p2Attributes.color.values.push(r, g, b, a);
  17353. p2Attributes.color.values.push(r, g, b, a);
  17354. for (j = i2 * 4; j < i2 * 4 + 2 * 4; ++j) {
  17355. p2Attributes.color.values.push(colors[j]);
  17356. }
  17357. }
  17358. if (defined(texCoords)) {
  17359. var s0 = Cartesian2.fromArray(texCoords, i0 * 2, cartesian2Scratch0);
  17360. var s3 = Cartesian2.fromArray(texCoords, (i + 3) * 2, cartesian2Scratch1);
  17361. var sx = CesiumMath.lerp(s0.x, s3.x, t);
  17362. for (j = i0 * 2; j < i0 * 2 + 2 * 2; ++j) {
  17363. p0Attributes.st.values.push(texCoords[j]);
  17364. }
  17365. p0Attributes.st.values.push(sx, s0.y);
  17366. p0Attributes.st.values.push(sx, s3.y);
  17367. p2Attributes.st.values.push(sx, s0.y);
  17368. p2Attributes.st.values.push(sx, s3.y);
  17369. for (j = i2 * 2; j < i2 * 2 + 2 * 2; ++j) {
  17370. p2Attributes.st.values.push(texCoords[j]);
  17371. }
  17372. }
  17373. index = p0Attributes.position.values.length / 3 - 4;
  17374. p0Indices.push(index, index + 2, index + 1);
  17375. p0Indices.push(index + 1, index + 2, index + 3);
  17376. index = p2Attributes.position.values.length / 3 - 4;
  17377. p2Indices.push(index, index + 2, index + 1);
  17378. p2Indices.push(index + 1, index + 2, index + 3);
  17379. } else {
  17380. var currentAttributes;
  17381. var currentIndices;
  17382. if (p0.y < 0.0) {
  17383. currentAttributes = westGeometry.attributes;
  17384. currentIndices = westGeometry.indices;
  17385. } else {
  17386. currentAttributes = eastGeometry.attributes;
  17387. currentIndices = eastGeometry.indices;
  17388. }
  17389. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  17390. currentAttributes.position.values.push(p0.x, p0.y, p0.z);
  17391. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  17392. currentAttributes.position.values.push(p2.x, p2.y, p2.z);
  17393. for (j = i * 3; j < i * 3 + 4 * 3; ++j) {
  17394. currentAttributes.prevPosition.values.push(prevPositions[j]);
  17395. currentAttributes.nextPosition.values.push(nextPositions[j]);
  17396. }
  17397. for (j = i * 2; j < i * 2 + 4 * 2; ++j) {
  17398. currentAttributes.expandAndWidth.values.push(expandAndWidths[j]);
  17399. if (defined(texCoords)) {
  17400. currentAttributes.st.values.push(texCoords[j]);
  17401. }
  17402. }
  17403. if (defined(colors)) {
  17404. for (j = i * 4; j < i * 4 + 4 * 4; ++j) {
  17405. currentAttributes.color.values.push(colors[j]);
  17406. }
  17407. }
  17408. index = currentAttributes.position.values.length / 3 - 4;
  17409. currentIndices.push(index, index + 2, index + 1);
  17410. currentIndices.push(index + 1, index + 2, index + 3);
  17411. }
  17412. }
  17413. if (intersectionFound) {
  17414. updateAdjacencyAfterSplit(westGeometry);
  17415. updateAdjacencyAfterSplit(eastGeometry);
  17416. }
  17417. updateInstanceAfterSplit(instance, westGeometry, eastGeometry);
  17418. }
  17419. /**
  17420. * Splits the instances's geometry, by introducing new vertices and indices,that
  17421. * intersect the International Date Line and Prime Meridian so that no primitives cross longitude
  17422. * -180/180 degrees. This is not required for 3D drawing, but is required for
  17423. * correcting drawing in 2D and Columbus view.
  17424. *
  17425. * @private
  17426. *
  17427. * @param {GeometryInstance} instance The instance to modify.
  17428. * @returns {GeometryInstance} The modified <code>instance</code> argument, with it's geometry split at the International Date Line.
  17429. *
  17430. * @example
  17431. * instance = Cesium.GeometryPipeline.splitLongitude(instance);
  17432. */
  17433. GeometryPipeline.splitLongitude = function(instance) {
  17434. if (!defined(instance)) {
  17435. throw new DeveloperError('instance is required.');
  17436. }
  17437. var geometry = instance.geometry;
  17438. var boundingSphere = geometry.boundingSphere;
  17439. if (defined(boundingSphere)) {
  17440. var minX = boundingSphere.center.x - boundingSphere.radius;
  17441. if (minX > 0 || BoundingSphere.intersectPlane(boundingSphere, Plane.ORIGIN_ZX_PLANE) !== Intersect.INTERSECTING) {
  17442. return instance;
  17443. }
  17444. }
  17445. if (geometry.geometryType !== GeometryType.NONE) {
  17446. switch (geometry.geometryType) {
  17447. case GeometryType.POLYLINES:
  17448. splitLongitudePolyline(instance);
  17449. break;
  17450. case GeometryType.TRIANGLES:
  17451. splitLongitudeTriangles(instance);
  17452. break;
  17453. case GeometryType.LINES:
  17454. splitLongitudeLines(instance);
  17455. break;
  17456. }
  17457. } else {
  17458. indexPrimitive(geometry);
  17459. if (geometry.primitiveType === PrimitiveType.TRIANGLES) {
  17460. splitLongitudeTriangles(instance);
  17461. } else if (geometry.primitiveType === PrimitiveType.LINES) {
  17462. splitLongitudeLines(instance);
  17463. }
  17464. }
  17465. return instance;
  17466. };
  17467. return GeometryPipeline;
  17468. });
  17469. /*global define*/
  17470. define('Core/oneTimeWarning',[
  17471. './defaultValue',
  17472. './defined',
  17473. './DeveloperError'
  17474. ], function(
  17475. defaultValue,
  17476. defined,
  17477. DeveloperError) {
  17478. "use strict";
  17479. var warnings = {};
  17480. /**
  17481. * Logs a one time message to the console. Use this function instead of
  17482. * <code>console.log</code> directly since this does not log duplicate messages
  17483. * unless it is called from multiple workers.
  17484. *
  17485. * @exports oneTimeWarning
  17486. *
  17487. * @param {String} identifier The unique identifier for this warning.
  17488. * @param {String} [message=identifier] The message to log to the console.
  17489. *
  17490. * @example
  17491. * for(var i=0;i<foo.length;++i) {
  17492. * if (!defined(foo[i].bar)) {
  17493. * // Something that can be recovered from but may happen a lot
  17494. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  17495. * foo[i].bar = 0;
  17496. * // ...
  17497. * }
  17498. * }
  17499. *
  17500. * @private
  17501. */
  17502. function oneTimeWarning(identifier, message) {
  17503. if (!defined(identifier)) {
  17504. throw new DeveloperError('identifier is required.');
  17505. }
  17506. if (!defined(warnings[identifier])) {
  17507. warnings[identifier] = true;
  17508. console.log(defaultValue(message, identifier));
  17509. }
  17510. }
  17511. 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.';
  17512. return oneTimeWarning;
  17513. });
  17514. /*global define*/
  17515. define('ThirdParty/earcut-2.1.1',[], function() {
  17516. 'use strict';
  17517. function earcut(data, holeIndices, dim) {
  17518. dim = dim || 2;
  17519. var hasHoles = holeIndices && holeIndices.length,
  17520. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  17521. outerNode = linkedList(data, 0, outerLen, dim, true),
  17522. triangles = [];
  17523. if (!outerNode) return triangles;
  17524. var minX, minY, maxX, maxY, x, y, size;
  17525. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  17526. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  17527. if (data.length > 80 * dim) {
  17528. minX = maxX = data[0];
  17529. minY = maxY = data[1];
  17530. for (var i = dim; i < outerLen; i += dim) {
  17531. x = data[i];
  17532. y = data[i + 1];
  17533. if (x < minX) minX = x;
  17534. if (y < minY) minY = y;
  17535. if (x > maxX) maxX = x;
  17536. if (y > maxY) maxY = y;
  17537. }
  17538. // minX, minY and size are later used to transform coords into integers for z-order calculation
  17539. size = Math.max(maxX - minX, maxY - minY);
  17540. }
  17541. earcutLinked(outerNode, triangles, dim, minX, minY, size);
  17542. return triangles;
  17543. }
  17544. // create a circular doubly linked list from polygon points in the specified winding order
  17545. function linkedList(data, start, end, dim, clockwise) {
  17546. var i, last;
  17547. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  17548. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17549. } else {
  17550. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17551. }
  17552. if (last && equals(last, last.next)) {
  17553. removeNode(last);
  17554. last = last.next;
  17555. }
  17556. return last;
  17557. }
  17558. // eliminate colinear or duplicate points
  17559. function filterPoints(start, end) {
  17560. if (!start) return start;
  17561. if (!end) end = start;
  17562. var p = start,
  17563. again;
  17564. do {
  17565. again = false;
  17566. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17567. removeNode(p);
  17568. p = end = p.prev;
  17569. if (p === p.next) return null;
  17570. again = true;
  17571. } else {
  17572. p = p.next;
  17573. }
  17574. } while (again || p !== end);
  17575. return end;
  17576. }
  17577. // main ear slicing loop which triangulates a polygon (given as a linked list)
  17578. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  17579. if (!ear) return;
  17580. // interlink polygon nodes in z-order
  17581. if (!pass && size) indexCurve(ear, minX, minY, size);
  17582. var stop = ear,
  17583. prev, next;
  17584. // iterate through ears, slicing them one by one
  17585. while (ear.prev !== ear.next) {
  17586. prev = ear.prev;
  17587. next = ear.next;
  17588. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  17589. // cut off the triangle
  17590. triangles.push(prev.i / dim);
  17591. triangles.push(ear.i / dim);
  17592. triangles.push(next.i / dim);
  17593. removeNode(ear);
  17594. // skipping the next vertice leads to less sliver triangles
  17595. ear = next.next;
  17596. stop = next.next;
  17597. continue;
  17598. }
  17599. ear = next;
  17600. // if we looped through the whole remaining polygon and can't find any more ears
  17601. if (ear === stop) {
  17602. // try filtering points and slicing again
  17603. if (!pass) {
  17604. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
  17605. // if this didn't work, try curing all small self-intersections locally
  17606. } else if (pass === 1) {
  17607. ear = cureLocalIntersections(ear, triangles, dim);
  17608. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  17609. // as a last resort, try splitting the remaining polygon into two
  17610. } else if (pass === 2) {
  17611. splitEarcut(ear, triangles, dim, minX, minY, size);
  17612. }
  17613. break;
  17614. }
  17615. }
  17616. }
  17617. // check whether a polygon node forms a valid ear with adjacent nodes
  17618. function isEar(ear) {
  17619. var a = ear.prev,
  17620. b = ear,
  17621. c = ear.next;
  17622. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17623. // now make sure we don't have other points inside the potential ear
  17624. var p = ear.next.next;
  17625. while (p !== ear.prev) {
  17626. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  17627. area(p.prev, p, p.next) >= 0) return false;
  17628. p = p.next;
  17629. }
  17630. return true;
  17631. }
  17632. function isEarHashed(ear, minX, minY, size) {
  17633. var a = ear.prev,
  17634. b = ear,
  17635. c = ear.next;
  17636. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17637. // triangle bbox; min & max are calculated like this for speed
  17638. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  17639. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  17640. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  17641. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  17642. // z-order range for the current triangle bbox;
  17643. var minZ = zOrder(minTX, minTY, minX, minY, size),
  17644. maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  17645. // first look for points inside the triangle in increasing z-order
  17646. var p = ear.nextZ;
  17647. while (p && p.z <= maxZ) {
  17648. if (p !== ear.prev && p !== ear.next &&
  17649. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  17650. area(p.prev, p, p.next) >= 0) return false;
  17651. p = p.nextZ;
  17652. }
  17653. // then look for points in decreasing z-order
  17654. p = ear.prevZ;
  17655. while (p && p.z >= minZ) {
  17656. if (p !== ear.prev && p !== ear.next &&
  17657. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  17658. area(p.prev, p, p.next) >= 0) return false;
  17659. p = p.prevZ;
  17660. }
  17661. return true;
  17662. }
  17663. // go through all polygon nodes and cure small local self-intersections
  17664. function cureLocalIntersections(start, triangles, dim) {
  17665. var p = start;
  17666. do {
  17667. var a = p.prev,
  17668. b = p.next.next;
  17669. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17670. triangles.push(a.i / dim);
  17671. triangles.push(p.i / dim);
  17672. triangles.push(b.i / dim);
  17673. // remove two nodes involved
  17674. removeNode(p);
  17675. removeNode(p.next);
  17676. p = start = b;
  17677. }
  17678. p = p.next;
  17679. } while (p !== start);
  17680. return p;
  17681. }
  17682. // try splitting polygon into two and triangulate them independently
  17683. function splitEarcut(start, triangles, dim, minX, minY, size) {
  17684. // look for a valid diagonal that divides the polygon into two
  17685. var a = start;
  17686. do {
  17687. var b = a.next.next;
  17688. while (b !== a.prev) {
  17689. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17690. // split the polygon in two by the diagonal
  17691. var c = splitPolygon(a, b);
  17692. // filter colinear points around the cuts
  17693. a = filterPoints(a, a.next);
  17694. c = filterPoints(c, c.next);
  17695. // run earcut on each half
  17696. earcutLinked(a, triangles, dim, minX, minY, size);
  17697. earcutLinked(c, triangles, dim, minX, minY, size);
  17698. return;
  17699. }
  17700. b = b.next;
  17701. }
  17702. a = a.next;
  17703. } while (a !== start);
  17704. }
  17705. // link every hole into the outer loop, producing a single-ring polygon without holes
  17706. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17707. var queue = [],
  17708. i, len, start, end, list;
  17709. for (i = 0, len = holeIndices.length; i < len; i++) {
  17710. start = holeIndices[i] * dim;
  17711. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17712. list = linkedList(data, start, end, dim, false);
  17713. if (list === list.next) list.steiner = true;
  17714. queue.push(getLeftmost(list));
  17715. }
  17716. queue.sort(compareX);
  17717. // process holes from left to right
  17718. for (i = 0; i < queue.length; i++) {
  17719. eliminateHole(queue[i], outerNode);
  17720. outerNode = filterPoints(outerNode, outerNode.next);
  17721. }
  17722. return outerNode;
  17723. }
  17724. function compareX(a, b) {
  17725. return a.x - b.x;
  17726. }
  17727. // find a bridge between vertices that connects hole with an outer ring and and link it
  17728. function eliminateHole(hole, outerNode) {
  17729. outerNode = findHoleBridge(hole, outerNode);
  17730. if (outerNode) {
  17731. var b = splitPolygon(outerNode, hole);
  17732. filterPoints(b, b.next);
  17733. }
  17734. }
  17735. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17736. function findHoleBridge(hole, outerNode) {
  17737. var p = outerNode,
  17738. hx = hole.x,
  17739. hy = hole.y,
  17740. qx = -Infinity,
  17741. m;
  17742. // find a segment intersected by a ray from the hole's leftmost point to the left;
  17743. // segment's endpoint with lesser x will be potential connection point
  17744. do {
  17745. if (hy <= p.y && hy >= p.next.y) {
  17746. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17747. if (x <= hx && x > qx) {
  17748. qx = x;
  17749. if (x === hx) {
  17750. if (hy === p.y) return p;
  17751. if (hy === p.next.y) return p.next;
  17752. }
  17753. m = p.x < p.next.x ? p : p.next;
  17754. }
  17755. }
  17756. p = p.next;
  17757. } while (p !== outerNode);
  17758. if (!m) return null;
  17759. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  17760. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17761. // if there are no points found, we have a valid connection;
  17762. // otherwise choose the point of the minimum angle with the ray as connection point
  17763. var stop = m,
  17764. mx = m.x,
  17765. my = m.y,
  17766. tanMin = Infinity,
  17767. tan;
  17768. p = m.next;
  17769. while (p !== stop) {
  17770. if (hx >= p.x && p.x >= mx &&
  17771. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  17772. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17773. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  17774. m = p;
  17775. tanMin = tan;
  17776. }
  17777. }
  17778. p = p.next;
  17779. }
  17780. return m;
  17781. }
  17782. // interlink polygon nodes in z-order
  17783. function indexCurve(start, minX, minY, size) {
  17784. var p = start;
  17785. do {
  17786. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
  17787. p.prevZ = p.prev;
  17788. p.nextZ = p.next;
  17789. p = p.next;
  17790. } while (p !== start);
  17791. p.prevZ.nextZ = null;
  17792. p.prevZ = null;
  17793. sortLinked(p);
  17794. }
  17795. // Simon Tatham's linked list merge sort algorithm
  17796. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17797. function sortLinked(list) {
  17798. var i, p, q, e, tail, numMerges, pSize, qSize,
  17799. inSize = 1;
  17800. do {
  17801. p = list;
  17802. list = null;
  17803. tail = null;
  17804. numMerges = 0;
  17805. while (p) {
  17806. numMerges++;
  17807. q = p;
  17808. pSize = 0;
  17809. for (i = 0; i < inSize; i++) {
  17810. pSize++;
  17811. q = q.nextZ;
  17812. if (!q) break;
  17813. }
  17814. qSize = inSize;
  17815. while (pSize > 0 || (qSize > 0 && q)) {
  17816. if (pSize === 0) {
  17817. e = q;
  17818. q = q.nextZ;
  17819. qSize--;
  17820. } else if (qSize === 0 || !q) {
  17821. e = p;
  17822. p = p.nextZ;
  17823. pSize--;
  17824. } else if (p.z <= q.z) {
  17825. e = p;
  17826. p = p.nextZ;
  17827. pSize--;
  17828. } else {
  17829. e = q;
  17830. q = q.nextZ;
  17831. qSize--;
  17832. }
  17833. if (tail) tail.nextZ = e;
  17834. else list = e;
  17835. e.prevZ = tail;
  17836. tail = e;
  17837. }
  17838. p = q;
  17839. }
  17840. tail.nextZ = null;
  17841. inSize *= 2;
  17842. } while (numMerges > 1);
  17843. return list;
  17844. }
  17845. // z-order of a point given coords and size of the data bounding box
  17846. function zOrder(x, y, minX, minY, size) {
  17847. // coords are transformed into non-negative 15-bit integer range
  17848. x = 32767 * (x - minX) / size;
  17849. y = 32767 * (y - minY) / size;
  17850. x = (x | (x << 8)) & 0x00FF00FF;
  17851. x = (x | (x << 4)) & 0x0F0F0F0F;
  17852. x = (x | (x << 2)) & 0x33333333;
  17853. x = (x | (x << 1)) & 0x55555555;
  17854. y = (y | (y << 8)) & 0x00FF00FF;
  17855. y = (y | (y << 4)) & 0x0F0F0F0F;
  17856. y = (y | (y << 2)) & 0x33333333;
  17857. y = (y | (y << 1)) & 0x55555555;
  17858. return x | (y << 1);
  17859. }
  17860. // find the leftmost node of a polygon ring
  17861. function getLeftmost(start) {
  17862. var p = start,
  17863. leftmost = start;
  17864. do {
  17865. if (p.x < leftmost.x) leftmost = p;
  17866. p = p.next;
  17867. } while (p !== start);
  17868. return leftmost;
  17869. }
  17870. // check if a point lies within a convex triangle
  17871. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  17872. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  17873. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  17874. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  17875. }
  17876. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17877. function isValidDiagonal(a, b) {
  17878. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
  17879. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  17880. }
  17881. // signed area of a triangle
  17882. function area(p, q, r) {
  17883. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  17884. }
  17885. // check if two points are equal
  17886. function equals(p1, p2) {
  17887. return p1.x === p2.x && p1.y === p2.y;
  17888. }
  17889. // check if two segments intersect
  17890. function intersects(p1, q1, p2, q2) {
  17891. if ((equals(p1, q1) && equals(p2, q2)) ||
  17892. (equals(p1, q2) && equals(p2, q1))) return true;
  17893. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  17894. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  17895. }
  17896. // check if a polygon diagonal intersects any polygon segments
  17897. function intersectsPolygon(a, b) {
  17898. var p = a;
  17899. do {
  17900. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  17901. intersects(p, p.next, a, b)) return true;
  17902. p = p.next;
  17903. } while (p !== a);
  17904. return false;
  17905. }
  17906. // check if a polygon diagonal is locally inside the polygon
  17907. function locallyInside(a, b) {
  17908. return area(a.prev, a, a.next) < 0 ?
  17909. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  17910. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  17911. }
  17912. // check if the middle point of a polygon diagonal is inside the polygon
  17913. function middleInside(a, b) {
  17914. var p = a,
  17915. inside = false,
  17916. px = (a.x + b.x) / 2,
  17917. py = (a.y + b.y) / 2;
  17918. do {
  17919. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  17920. inside = !inside;
  17921. p = p.next;
  17922. } while (p !== a);
  17923. return inside;
  17924. }
  17925. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17926. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17927. function splitPolygon(a, b) {
  17928. var a2 = new Node(a.i, a.x, a.y),
  17929. b2 = new Node(b.i, b.x, b.y),
  17930. an = a.next,
  17931. bp = b.prev;
  17932. a.next = b;
  17933. b.prev = a;
  17934. a2.next = an;
  17935. an.prev = a2;
  17936. b2.next = a2;
  17937. a2.prev = b2;
  17938. bp.next = b2;
  17939. b2.prev = bp;
  17940. return b2;
  17941. }
  17942. // create a node and optionally link it with previous one (in a circular doubly linked list)
  17943. function insertNode(i, x, y, last) {
  17944. var p = new Node(i, x, y);
  17945. if (!last) {
  17946. p.prev = p;
  17947. p.next = p;
  17948. } else {
  17949. p.next = last.next;
  17950. p.prev = last;
  17951. last.next.prev = p;
  17952. last.next = p;
  17953. }
  17954. return p;
  17955. }
  17956. function removeNode(p) {
  17957. p.next.prev = p.prev;
  17958. p.prev.next = p.next;
  17959. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  17960. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  17961. }
  17962. function Node(i, x, y) {
  17963. // vertice index in coordinates array
  17964. this.i = i;
  17965. // vertex coordinates
  17966. this.x = x;
  17967. this.y = y;
  17968. // previous and next vertice nodes in a polygon ring
  17969. this.prev = null;
  17970. this.next = null;
  17971. // z-order curve value
  17972. this.z = null;
  17973. // previous and next nodes in z-order
  17974. this.prevZ = null;
  17975. this.nextZ = null;
  17976. // indicates whether this is a steiner point
  17977. this.steiner = false;
  17978. }
  17979. // return a percentage difference between the polygon area and its triangulation area;
  17980. // used to verify correctness of triangulation
  17981. earcut.deviation = function (data, holeIndices, dim, triangles) {
  17982. var hasHoles = holeIndices && holeIndices.length;
  17983. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  17984. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  17985. if (hasHoles) {
  17986. for (var i = 0, len = holeIndices.length; i < len; i++) {
  17987. var start = holeIndices[i] * dim;
  17988. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17989. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  17990. }
  17991. }
  17992. var trianglesArea = 0;
  17993. for (i = 0; i < triangles.length; i += 3) {
  17994. var a = triangles[i] * dim;
  17995. var b = triangles[i + 1] * dim;
  17996. var c = triangles[i + 2] * dim;
  17997. trianglesArea += Math.abs(
  17998. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  17999. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  18000. }
  18001. return polygonArea === 0 && trianglesArea === 0 ? 0 :
  18002. Math.abs((trianglesArea - polygonArea) / polygonArea);
  18003. };
  18004. function signedArea(data, start, end, dim) {
  18005. var sum = 0;
  18006. for (var i = start, j = end - dim; i < end; i += dim) {
  18007. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18008. j = i;
  18009. }
  18010. return sum;
  18011. }
  18012. // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  18013. earcut.flatten = function (data) {
  18014. var dim = data[0][0].length,
  18015. result = {vertices: [], holes: [], dimensions: dim},
  18016. holeIndex = 0;
  18017. for (var i = 0; i < data.length; i++) {
  18018. for (var j = 0; j < data[i].length; j++) {
  18019. for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  18020. }
  18021. if (i > 0) {
  18022. holeIndex += data[i - 1].length;
  18023. result.holes.push(holeIndex);
  18024. }
  18025. }
  18026. return result;
  18027. };
  18028. return earcut;
  18029. });
  18030. /*global define*/
  18031. define('Core/WindingOrder',[
  18032. './freezeObject',
  18033. './WebGLConstants'
  18034. ], function(
  18035. freezeObject,
  18036. WebGLConstants) {
  18037. 'use strict';
  18038. /**
  18039. * Winding order defines the order of vertices for a triangle to be considered front-facing.
  18040. *
  18041. * @exports WindingOrder
  18042. */
  18043. var WindingOrder = {
  18044. /**
  18045. * Vertices are in clockwise order.
  18046. *
  18047. * @type {Number}
  18048. * @constant
  18049. */
  18050. CLOCKWISE : WebGLConstants.CW,
  18051. /**
  18052. * Vertices are in counter-clockwise order.
  18053. *
  18054. * @type {Number}
  18055. * @constant
  18056. */
  18057. COUNTER_CLOCKWISE : WebGLConstants.CCW,
  18058. /**
  18059. * @private
  18060. */
  18061. validate : function(windingOrder) {
  18062. return windingOrder === WindingOrder.CLOCKWISE ||
  18063. windingOrder === WindingOrder.COUNTER_CLOCKWISE;
  18064. }
  18065. };
  18066. return freezeObject(WindingOrder);
  18067. });
  18068. /*global define*/
  18069. define('Core/PolygonPipeline',[
  18070. '../ThirdParty/earcut-2.1.1',
  18071. './Cartesian2',
  18072. './Cartesian3',
  18073. './ComponentDatatype',
  18074. './defaultValue',
  18075. './defined',
  18076. './DeveloperError',
  18077. './Ellipsoid',
  18078. './Geometry',
  18079. './GeometryAttribute',
  18080. './Math',
  18081. './PrimitiveType',
  18082. './WindingOrder'
  18083. ], function(
  18084. earcut,
  18085. Cartesian2,
  18086. Cartesian3,
  18087. ComponentDatatype,
  18088. defaultValue,
  18089. defined,
  18090. DeveloperError,
  18091. Ellipsoid,
  18092. Geometry,
  18093. GeometryAttribute,
  18094. CesiumMath,
  18095. PrimitiveType,
  18096. WindingOrder) {
  18097. 'use strict';
  18098. var scaleToGeodeticHeightN = new Cartesian3();
  18099. var scaleToGeodeticHeightP = new Cartesian3();
  18100. /**
  18101. * @private
  18102. */
  18103. var PolygonPipeline = {};
  18104. /**
  18105. * @exception {DeveloperError} At least three positions are required.
  18106. */
  18107. PolygonPipeline.computeArea2D = function(positions) {
  18108. if (!defined(positions)) {
  18109. throw new DeveloperError('positions is required.');
  18110. }
  18111. if (positions.length < 3) {
  18112. throw new DeveloperError('At least three positions are required.');
  18113. }
  18114. var length = positions.length;
  18115. var area = 0.0;
  18116. for ( var i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
  18117. var v0 = positions[i0];
  18118. var v1 = positions[i1];
  18119. area += (v0.x * v1.y) - (v1.x * v0.y);
  18120. }
  18121. return area * 0.5;
  18122. };
  18123. /**
  18124. * @returns {WindingOrder} The winding order.
  18125. *
  18126. * @exception {DeveloperError} At least three positions are required.
  18127. */
  18128. PolygonPipeline.computeWindingOrder2D = function(positions) {
  18129. var area = PolygonPipeline.computeArea2D(positions);
  18130. return (area > 0.0) ? WindingOrder.COUNTER_CLOCKWISE : WindingOrder.CLOCKWISE;
  18131. };
  18132. /**
  18133. * Triangulate a polygon.
  18134. *
  18135. * @param {Cartesian2[]} positions Cartesian2 array containing the vertices of the polygon
  18136. * @param {Number[]} [holes] An array of the staring indices of the holes.
  18137. * @returns {Number[]} Index array representing triangles that fill the polygon
  18138. */
  18139. PolygonPipeline.triangulate = function(positions, holes) {
  18140. if (!defined(positions)) {
  18141. throw new DeveloperError('positions is required.');
  18142. }
  18143. var flattenedPositions = Cartesian2.packArray(positions);
  18144. return earcut(flattenedPositions, holes, 2);
  18145. };
  18146. var subdivisionV0Scratch = new Cartesian3();
  18147. var subdivisionV1Scratch = new Cartesian3();
  18148. var subdivisionV2Scratch = new Cartesian3();
  18149. var subdivisionS0Scratch = new Cartesian3();
  18150. var subdivisionS1Scratch = new Cartesian3();
  18151. var subdivisionS2Scratch = new Cartesian3();
  18152. var subdivisionMidScratch = new Cartesian3();
  18153. /**
  18154. * Subdivides positions and raises points to the surface of the ellipsoid.
  18155. *
  18156. * @param {Ellipsoid} ellipsoid The ellipsoid the polygon in on.
  18157. * @param {Cartesian3[]} positions An array of {@link Cartesian3} positions of the polygon.
  18158. * @param {Number[]} indices An array of indices that determines the triangles in the polygon.
  18159. * @param {Number} [granularity=CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  18160. *
  18161. * @exception {DeveloperError} At least three indices are required.
  18162. * @exception {DeveloperError} The number of indices must be divisable by three.
  18163. * @exception {DeveloperError} Granularity must be greater than zero.
  18164. */
  18165. PolygonPipeline.computeSubdivision = function(ellipsoid, positions, indices, granularity) {
  18166. granularity = defaultValue(granularity, CesiumMath.RADIANS_PER_DEGREE);
  18167. if (!defined(ellipsoid)) {
  18168. throw new DeveloperError('ellipsoid is required.');
  18169. }
  18170. if (!defined(positions)) {
  18171. throw new DeveloperError('positions is required.');
  18172. }
  18173. if (!defined(indices)) {
  18174. throw new DeveloperError('indices is required.');
  18175. }
  18176. if (indices.length < 3) {
  18177. throw new DeveloperError('At least three indices are required.');
  18178. }
  18179. if (indices.length % 3 !== 0) {
  18180. throw new DeveloperError('The number of indices must be divisable by three.');
  18181. }
  18182. if (granularity <= 0.0) {
  18183. throw new DeveloperError('granularity must be greater than zero.');
  18184. }
  18185. // triangles that need (or might need) to be subdivided.
  18186. var triangles = indices.slice(0);
  18187. // New positions due to edge splits are appended to the positions list.
  18188. var i;
  18189. var length = positions.length;
  18190. var subdividedPositions = new Array(length * 3);
  18191. var q = 0;
  18192. for (i = 0; i < length; i++) {
  18193. var item = positions[i];
  18194. subdividedPositions[q++] = item.x;
  18195. subdividedPositions[q++] = item.y;
  18196. subdividedPositions[q++] = item.z;
  18197. }
  18198. var subdividedIndices = [];
  18199. // Used to make sure shared edges are not split more than once.
  18200. var edges = {};
  18201. var radius = ellipsoid.maximumRadius;
  18202. var minDistance = CesiumMath.chordLength(granularity, radius);
  18203. var minDistanceSqrd = minDistance * minDistance;
  18204. while (triangles.length > 0) {
  18205. var i2 = triangles.pop();
  18206. var i1 = triangles.pop();
  18207. var i0 = triangles.pop();
  18208. var v0 = Cartesian3.fromArray(subdividedPositions, i0 * 3, subdivisionV0Scratch);
  18209. var v1 = Cartesian3.fromArray(subdividedPositions, i1 * 3, subdivisionV1Scratch);
  18210. var v2 = Cartesian3.fromArray(subdividedPositions, i2 * 3, subdivisionV2Scratch);
  18211. var s0 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v0, subdivisionS0Scratch), radius, subdivisionS0Scratch);
  18212. var s1 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v1, subdivisionS1Scratch), radius, subdivisionS1Scratch);
  18213. var s2 = Cartesian3.multiplyByScalar(Cartesian3.normalize(v2, subdivisionS2Scratch), radius, subdivisionS2Scratch);
  18214. var g0 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s0, s1, subdivisionMidScratch));
  18215. var g1 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s1, s2, subdivisionMidScratch));
  18216. var g2 = Cartesian3.magnitudeSquared(Cartesian3.subtract(s2, s0, subdivisionMidScratch));
  18217. var max = Math.max(g0, g1, g2);
  18218. var edge;
  18219. var mid;
  18220. // if the max length squared of a triangle edge is greater than the chord length of squared
  18221. // of the granularity, subdivide the triangle
  18222. if (max > minDistanceSqrd) {
  18223. if (g0 === max) {
  18224. edge = Math.min(i0, i1) + ' ' + Math.max(i0, i1);
  18225. i = edges[edge];
  18226. if (!defined(i)) {
  18227. mid = Cartesian3.add(v0, v1, subdivisionMidScratch);
  18228. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  18229. subdividedPositions.push(mid.x, mid.y, mid.z);
  18230. i = subdividedPositions.length / 3 - 1;
  18231. edges[edge] = i;
  18232. }
  18233. triangles.push(i0, i, i2);
  18234. triangles.push(i, i1, i2);
  18235. } else if (g1 === max) {
  18236. edge = Math.min(i1, i2) + ' ' + Math.max(i1, i2);
  18237. i = edges[edge];
  18238. if (!defined(i)) {
  18239. mid = Cartesian3.add(v1, v2, subdivisionMidScratch);
  18240. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  18241. subdividedPositions.push(mid.x, mid.y, mid.z);
  18242. i = subdividedPositions.length / 3 - 1;
  18243. edges[edge] = i;
  18244. }
  18245. triangles.push(i1, i, i0);
  18246. triangles.push(i, i2, i0);
  18247. } else if (g2 === max) {
  18248. edge = Math.min(i2, i0) + ' ' + Math.max(i2, i0);
  18249. i = edges[edge];
  18250. if (!defined(i)) {
  18251. mid = Cartesian3.add(v2, v0, subdivisionMidScratch);
  18252. Cartesian3.multiplyByScalar(mid, 0.5, mid);
  18253. subdividedPositions.push(mid.x, mid.y, mid.z);
  18254. i = subdividedPositions.length / 3 - 1;
  18255. edges[edge] = i;
  18256. }
  18257. triangles.push(i2, i, i1);
  18258. triangles.push(i, i0, i1);
  18259. }
  18260. } else {
  18261. subdividedIndices.push(i0);
  18262. subdividedIndices.push(i1);
  18263. subdividedIndices.push(i2);
  18264. }
  18265. }
  18266. return new Geometry({
  18267. attributes : {
  18268. position : new GeometryAttribute({
  18269. componentDatatype : ComponentDatatype.DOUBLE,
  18270. componentsPerAttribute : 3,
  18271. values : subdividedPositions
  18272. })
  18273. },
  18274. indices : subdividedIndices,
  18275. primitiveType : PrimitiveType.TRIANGLES
  18276. });
  18277. };
  18278. /**
  18279. * Scales each position of a geometry's position attribute to a height, in place.
  18280. *
  18281. * @param {Number[]} positions The array of numbers representing the positions to be scaled
  18282. * @param {Number} [height=0.0] The desired height to add to the positions
  18283. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  18284. * @param {Boolean} [scaleToSurface=true] <code>true</code> if the positions need to be scaled to the surface before the height is added.
  18285. * @returns {Number[]} The input array of positions, scaled to height
  18286. */
  18287. PolygonPipeline.scaleToGeodeticHeight = function(positions, height, ellipsoid, scaleToSurface) {
  18288. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  18289. var n = scaleToGeodeticHeightN;
  18290. var p = scaleToGeodeticHeightP;
  18291. height = defaultValue(height, 0.0);
  18292. scaleToSurface = defaultValue(scaleToSurface, true);
  18293. if (defined(positions)) {
  18294. var length = positions.length;
  18295. for ( var i = 0; i < length; i += 3) {
  18296. Cartesian3.fromArray(positions, i, p);
  18297. if (scaleToSurface) {
  18298. p = ellipsoid.scaleToGeodeticSurface(p, p);
  18299. }
  18300. if (height !== 0) {
  18301. n = ellipsoid.geodeticSurfaceNormal(p, n);
  18302. Cartesian3.multiplyByScalar(n, height, n);
  18303. Cartesian3.add(p, n, p);
  18304. }
  18305. positions[i] = p.x;
  18306. positions[i + 1] = p.y;
  18307. positions[i + 2] = p.z;
  18308. }
  18309. }
  18310. return positions;
  18311. };
  18312. return PolygonPipeline;
  18313. });
  18314. /*global define*/
  18315. define('Core/AxisAlignedBoundingBox',[
  18316. './Cartesian3',
  18317. './defaultValue',
  18318. './defined',
  18319. './DeveloperError',
  18320. './Intersect'
  18321. ], function(
  18322. Cartesian3,
  18323. defaultValue,
  18324. defined,
  18325. DeveloperError,
  18326. Intersect) {
  18327. 'use strict';
  18328. /**
  18329. * Creates an instance of an AxisAlignedBoundingBox from the minimum and maximum points along the x, y, and z axes.
  18330. * @alias AxisAlignedBoundingBox
  18331. * @constructor
  18332. *
  18333. * @param {Cartesian3} [minimum=Cartesian3.ZERO] The minimum point along the x, y, and z axes.
  18334. * @param {Cartesian3} [maximum=Cartesian3.ZERO] The maximum point along the x, y, and z axes.
  18335. * @param {Cartesian3} [center] The center of the box; automatically computed if not supplied.
  18336. *
  18337. * @see BoundingSphere
  18338. * @see BoundingRectangle
  18339. */
  18340. function AxisAlignedBoundingBox(minimum, maximum, center) {
  18341. /**
  18342. * The minimum point defining the bounding box.
  18343. * @type {Cartesian3}
  18344. * @default {@link Cartesian3.ZERO}
  18345. */
  18346. this.minimum = Cartesian3.clone(defaultValue(minimum, Cartesian3.ZERO));
  18347. /**
  18348. * The maximum point defining the bounding box.
  18349. * @type {Cartesian3}
  18350. * @default {@link Cartesian3.ZERO}
  18351. */
  18352. this.maximum = Cartesian3.clone(defaultValue(maximum, Cartesian3.ZERO));
  18353. //If center was not defined, compute it.
  18354. if (!defined(center)) {
  18355. center = Cartesian3.add(this.minimum, this.maximum, new Cartesian3());
  18356. Cartesian3.multiplyByScalar(center, 0.5, center);
  18357. } else {
  18358. center = Cartesian3.clone(center);
  18359. }
  18360. /**
  18361. * The center point of the bounding box.
  18362. * @type {Cartesian3}
  18363. */
  18364. this.center = center;
  18365. }
  18366. /**
  18367. * Computes an instance of an AxisAlignedBoundingBox. The box is determined by
  18368. * finding the points spaced the farthest apart on the x, y, and z axes.
  18369. *
  18370. * @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.
  18371. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  18372. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  18373. *
  18374. * @example
  18375. * // Compute an axis aligned bounding box enclosing two points.
  18376. * var box = Cesium.AxisAlignedBoundingBox.fromPoints([new Cesium.Cartesian3(2, 0, 0), new Cesium.Cartesian3(-2, 0, 0)]);
  18377. */
  18378. AxisAlignedBoundingBox.fromPoints = function(positions, result) {
  18379. if (!defined(result)) {
  18380. result = new AxisAlignedBoundingBox();
  18381. }
  18382. if (!defined(positions) || positions.length === 0) {
  18383. result.minimum = Cartesian3.clone(Cartesian3.ZERO, result.minimum);
  18384. result.maximum = Cartesian3.clone(Cartesian3.ZERO, result.maximum);
  18385. result.center = Cartesian3.clone(Cartesian3.ZERO, result.center);
  18386. return result;
  18387. }
  18388. var minimumX = positions[0].x;
  18389. var minimumY = positions[0].y;
  18390. var minimumZ = positions[0].z;
  18391. var maximumX = positions[0].x;
  18392. var maximumY = positions[0].y;
  18393. var maximumZ = positions[0].z;
  18394. var length = positions.length;
  18395. for ( var i = 1; i < length; i++) {
  18396. var p = positions[i];
  18397. var x = p.x;
  18398. var y = p.y;
  18399. var z = p.z;
  18400. minimumX = Math.min(x, minimumX);
  18401. maximumX = Math.max(x, maximumX);
  18402. minimumY = Math.min(y, minimumY);
  18403. maximumY = Math.max(y, maximumY);
  18404. minimumZ = Math.min(z, minimumZ);
  18405. maximumZ = Math.max(z, maximumZ);
  18406. }
  18407. var minimum = result.minimum;
  18408. minimum.x = minimumX;
  18409. minimum.y = minimumY;
  18410. minimum.z = minimumZ;
  18411. var maximum = result.maximum;
  18412. maximum.x = maximumX;
  18413. maximum.y = maximumY;
  18414. maximum.z = maximumZ;
  18415. var center = Cartesian3.add(minimum, maximum, result.center);
  18416. Cartesian3.multiplyByScalar(center, 0.5, center);
  18417. return result;
  18418. };
  18419. /**
  18420. * Duplicates a AxisAlignedBoundingBox instance.
  18421. *
  18422. * @param {AxisAlignedBoundingBox} box The bounding box to duplicate.
  18423. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  18424. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if none was provided. (Returns undefined if box is undefined)
  18425. */
  18426. AxisAlignedBoundingBox.clone = function(box, result) {
  18427. if (!defined(box)) {
  18428. return undefined;
  18429. }
  18430. if (!defined(result)) {
  18431. return new AxisAlignedBoundingBox(box.minimum, box.maximum);
  18432. }
  18433. result.minimum = Cartesian3.clone(box.minimum, result.minimum);
  18434. result.maximum = Cartesian3.clone(box.maximum, result.maximum);
  18435. result.center = Cartesian3.clone(box.center, result.center);
  18436. return result;
  18437. };
  18438. /**
  18439. * Compares the provided AxisAlignedBoundingBox componentwise and returns
  18440. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18441. *
  18442. * @param {AxisAlignedBoundingBox} [left] The first AxisAlignedBoundingBox.
  18443. * @param {AxisAlignedBoundingBox} [right] The second AxisAlignedBoundingBox.
  18444. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  18445. */
  18446. AxisAlignedBoundingBox.equals = function(left, right) {
  18447. return (left === right) ||
  18448. ((defined(left)) &&
  18449. (defined(right)) &&
  18450. Cartesian3.equals(left.center, right.center) &&
  18451. Cartesian3.equals(left.minimum, right.minimum) &&
  18452. Cartesian3.equals(left.maximum, right.maximum));
  18453. };
  18454. var intersectScratch = new Cartesian3();
  18455. /**
  18456. * Determines which side of a plane a box is located.
  18457. *
  18458. * @param {AxisAlignedBoundingBox} box The bounding box to test.
  18459. * @param {Plane} plane The plane to test against.
  18460. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  18461. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  18462. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  18463. * intersects the plane.
  18464. */
  18465. AxisAlignedBoundingBox.intersectPlane = function(box, plane) {
  18466. if (!defined(box)) {
  18467. throw new DeveloperError('box is required.');
  18468. }
  18469. if (!defined(plane)) {
  18470. throw new DeveloperError('plane is required.');
  18471. }
  18472. intersectScratch = Cartesian3.subtract(box.maximum, box.minimum, intersectScratch);
  18473. var h = Cartesian3.multiplyByScalar(intersectScratch, 0.5, intersectScratch); //The positive half diagonal
  18474. var normal = plane.normal;
  18475. var e = h.x * Math.abs(normal.x) + h.y * Math.abs(normal.y) + h.z * Math.abs(normal.z);
  18476. var s = Cartesian3.dot(box.center, normal) + plane.distance; //signed distance from center
  18477. if (s - e > 0) {
  18478. return Intersect.INSIDE;
  18479. }
  18480. if (s + e < 0) {
  18481. //Not in front because normals point inward
  18482. return Intersect.OUTSIDE;
  18483. }
  18484. return Intersect.INTERSECTING;
  18485. };
  18486. /**
  18487. * Duplicates this AxisAlignedBoundingBox instance.
  18488. *
  18489. * @param {AxisAlignedBoundingBox} [result] The object onto which to store the result.
  18490. * @returns {AxisAlignedBoundingBox} The modified result parameter or a new AxisAlignedBoundingBox instance if one was not provided.
  18491. */
  18492. AxisAlignedBoundingBox.prototype.clone = function(result) {
  18493. return AxisAlignedBoundingBox.clone(this, result);
  18494. };
  18495. /**
  18496. * Determines which side of a plane this box is located.
  18497. *
  18498. * @param {Plane} plane The plane to test against.
  18499. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane
  18500. * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is
  18501. * on the opposite side, and {@link Intersect.INTERSECTING} if the box
  18502. * intersects the plane.
  18503. */
  18504. AxisAlignedBoundingBox.prototype.intersectPlane = function(plane) {
  18505. return AxisAlignedBoundingBox.intersectPlane(this, plane);
  18506. };
  18507. /**
  18508. * Compares this AxisAlignedBoundingBox against the provided AxisAlignedBoundingBox componentwise and returns
  18509. * <code>true</code> if they are equal, <code>false</code> otherwise.
  18510. *
  18511. * @param {AxisAlignedBoundingBox} [right] The right hand side AxisAlignedBoundingBox.
  18512. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  18513. */
  18514. AxisAlignedBoundingBox.prototype.equals = function(right) {
  18515. return AxisAlignedBoundingBox.equals(this, right);
  18516. };
  18517. return AxisAlignedBoundingBox;
  18518. });
  18519. /**
  18520. @license
  18521. when.js - https://github.com/cujojs/when
  18522. MIT License (c) copyright B Cavalier & J Hann
  18523. * A lightweight CommonJS Promises/A and when() implementation
  18524. * when is part of the cujo.js family of libraries (http://cujojs.com/)
  18525. *
  18526. * Licensed under the MIT License at:
  18527. * http://www.opensource.org/licenses/mit-license.php
  18528. *
  18529. * @version 1.7.1
  18530. */
  18531. (function(define) { 'use strict';
  18532. define('ThirdParty/when',[],function () {
  18533. var reduceArray, slice, undef;
  18534. //
  18535. // Public API
  18536. //
  18537. when.defer = defer; // Create a deferred
  18538. when.resolve = resolve; // Create a resolved promise
  18539. when.reject = reject; // Create a rejected promise
  18540. when.join = join; // Join 2 or more promises
  18541. when.all = all; // Resolve a list of promises
  18542. when.map = map; // Array.map() for promises
  18543. when.reduce = reduce; // Array.reduce() for promises
  18544. when.any = any; // One-winner race
  18545. when.some = some; // Multi-winner race
  18546. when.chain = chain; // Make a promise trigger another resolver
  18547. when.isPromise = isPromise; // Determine if a thing is a promise
  18548. /**
  18549. * Register an observer for a promise or immediate value.
  18550. *
  18551. * @param {*} promiseOrValue
  18552. * @param {function?} [onFulfilled] callback to be called when promiseOrValue is
  18553. * successfully fulfilled. If promiseOrValue is an immediate value, callback
  18554. * will be invoked immediately.
  18555. * @param {function?} [onRejected] callback to be called when promiseOrValue is
  18556. * rejected.
  18557. * @param {function?} [onProgress] callback to be called when progress updates
  18558. * are issued for promiseOrValue.
  18559. * @returns {Promise} a new {@link Promise} that will complete with the return
  18560. * value of callback or errback or the completion value of promiseOrValue if
  18561. * callback and/or errback is not supplied.
  18562. */
  18563. function when(promiseOrValue, onFulfilled, onRejected, onProgress) {
  18564. // Get a trusted promise for the input promiseOrValue, and then
  18565. // register promise handlers
  18566. return resolve(promiseOrValue).then(onFulfilled, onRejected, onProgress);
  18567. }
  18568. /**
  18569. * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if
  18570. * promiseOrValue is a foreign promise, or a new, already-fulfilled {@link Promise}
  18571. * whose value is promiseOrValue if promiseOrValue is an immediate value.
  18572. *
  18573. * @param {*} promiseOrValue
  18574. * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise}
  18575. * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise}
  18576. * whose resolution value is:
  18577. * * the resolution value of promiseOrValue if it's a foreign promise, or
  18578. * * promiseOrValue if it's a value
  18579. */
  18580. function resolve(promiseOrValue) {
  18581. var promise, deferred;
  18582. if(promiseOrValue instanceof Promise) {
  18583. // It's a when.js promise, so we trust it
  18584. promise = promiseOrValue;
  18585. } else {
  18586. // It's not a when.js promise. See if it's a foreign promise or a value.
  18587. if(isPromise(promiseOrValue)) {
  18588. // It's a thenable, but we don't know where it came from, so don't trust
  18589. // its implementation entirely. Introduce a trusted middleman when.js promise
  18590. deferred = defer();
  18591. // IMPORTANT: This is the only place when.js should ever call .then() on an
  18592. // untrusted promise. Don't expose the return value to the untrusted promise
  18593. promiseOrValue.then(
  18594. function(value) { deferred.resolve(value); },
  18595. function(reason) { deferred.reject(reason); },
  18596. function(update) { deferred.progress(update); }
  18597. );
  18598. promise = deferred.promise;
  18599. } else {
  18600. // It's a value, not a promise. Create a resolved promise for it.
  18601. promise = fulfilled(promiseOrValue);
  18602. }
  18603. }
  18604. return promise;
  18605. }
  18606. /**
  18607. * Returns a rejected promise for the supplied promiseOrValue. The returned
  18608. * promise will be rejected with:
  18609. * - promiseOrValue, if it is a value, or
  18610. * - if promiseOrValue is a promise
  18611. * - promiseOrValue's value after it is fulfilled
  18612. * - promiseOrValue's reason after it is rejected
  18613. * @param {*} promiseOrValue the rejected value of the returned {@link Promise}
  18614. * @returns {Promise} rejected {@link Promise}
  18615. */
  18616. function reject(promiseOrValue) {
  18617. return when(promiseOrValue, rejected);
  18618. }
  18619. /**
  18620. * Trusted Promise constructor. A Promise created from this constructor is
  18621. * a trusted when.js promise. Any other duck-typed promise is considered
  18622. * untrusted.
  18623. * @constructor
  18624. * @name Promise
  18625. */
  18626. function Promise(then) {
  18627. this.then = then;
  18628. }
  18629. Promise.prototype = {
  18630. /**
  18631. * Register a callback that will be called when a promise is
  18632. * fulfilled or rejected. Optionally also register a progress handler.
  18633. * Shortcut for .then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress)
  18634. * @param {function?} [onFulfilledOrRejected]
  18635. * @param {function?} [onProgress]
  18636. * @returns {Promise}
  18637. */
  18638. always: function(onFulfilledOrRejected, onProgress) {
  18639. return this.then(onFulfilledOrRejected, onFulfilledOrRejected, onProgress);
  18640. },
  18641. /**
  18642. * Register a rejection handler. Shortcut for .then(undefined, onRejected)
  18643. * @param {function?} onRejected
  18644. * @returns {Promise}
  18645. */
  18646. otherwise: function(onRejected) {
  18647. return this.then(undef, onRejected);
  18648. },
  18649. /**
  18650. * Shortcut for .then(function() { return value; })
  18651. * @param {*} value
  18652. * @returns {Promise} a promise that:
  18653. * - is fulfilled if value is not a promise, or
  18654. * - if value is a promise, will fulfill with its value, or reject
  18655. * with its reason.
  18656. */
  18657. yield: function(value) {
  18658. return this.then(function() {
  18659. return value;
  18660. });
  18661. },
  18662. /**
  18663. * Assumes that this promise will fulfill with an array, and arranges
  18664. * for the onFulfilled to be called with the array as its argument list
  18665. * i.e. onFulfilled.spread(undefined, array).
  18666. * @param {function} onFulfilled function to receive spread arguments
  18667. * @returns {Promise}
  18668. */
  18669. spread: function(onFulfilled) {
  18670. return this.then(function(array) {
  18671. // array may contain promises, so resolve its contents.
  18672. return all(array, function(array) {
  18673. return onFulfilled.apply(undef, array);
  18674. });
  18675. });
  18676. }
  18677. };
  18678. /**
  18679. * Create an already-resolved promise for the supplied value
  18680. * @private
  18681. *
  18682. * @param {*} value
  18683. * @returns {Promise} fulfilled promise
  18684. */
  18685. function fulfilled(value) {
  18686. var p = new Promise(function(onFulfilled) {
  18687. // TODO: Promises/A+ check typeof onFulfilled
  18688. try {
  18689. return resolve(onFulfilled ? onFulfilled(value) : value);
  18690. } catch(e) {
  18691. return rejected(e);
  18692. }
  18693. });
  18694. return p;
  18695. }
  18696. /**
  18697. * Create an already-rejected {@link Promise} with the supplied
  18698. * rejection reason.
  18699. * @private
  18700. *
  18701. * @param {*} reason
  18702. * @returns {Promise} rejected promise
  18703. */
  18704. function rejected(reason) {
  18705. var p = new Promise(function(_, onRejected) {
  18706. // TODO: Promises/A+ check typeof onRejected
  18707. try {
  18708. return onRejected ? resolve(onRejected(reason)) : rejected(reason);
  18709. } catch(e) {
  18710. return rejected(e);
  18711. }
  18712. });
  18713. return p;
  18714. }
  18715. /**
  18716. * Creates a new, Deferred with fully isolated resolver and promise parts,
  18717. * either or both of which may be given out safely to consumers.
  18718. * The Deferred itself has the full API: resolve, reject, progress, and
  18719. * then. The resolver has resolve, reject, and progress. The promise
  18720. * only has then.
  18721. *
  18722. * @returns {Deferred}
  18723. */
  18724. function defer() {
  18725. var deferred, promise, handlers, progressHandlers,
  18726. _then, _progress, _resolve;
  18727. /**
  18728. * The promise for the new deferred
  18729. * @type {Promise}
  18730. */
  18731. promise = new Promise(then);
  18732. /**
  18733. * The full Deferred object, with {@link Promise} and {@link Resolver} parts
  18734. * @class Deferred
  18735. * @name Deferred
  18736. */
  18737. deferred = {
  18738. then: then, // DEPRECATED: use deferred.promise.then
  18739. resolve: promiseResolve,
  18740. reject: promiseReject,
  18741. // TODO: Consider renaming progress() to notify()
  18742. progress: promiseProgress,
  18743. promise: promise,
  18744. resolver: {
  18745. resolve: promiseResolve,
  18746. reject: promiseReject,
  18747. progress: promiseProgress
  18748. }
  18749. };
  18750. handlers = [];
  18751. progressHandlers = [];
  18752. /**
  18753. * Pre-resolution then() that adds the supplied callback, errback, and progback
  18754. * functions to the registered listeners
  18755. * @private
  18756. *
  18757. * @param {function?} [onFulfilled] resolution handler
  18758. * @param {function?} [onRejected] rejection handler
  18759. * @param {function?} [onProgress] progress handler
  18760. */
  18761. _then = function(onFulfilled, onRejected, onProgress) {
  18762. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  18763. var deferred, progressHandler;
  18764. deferred = defer();
  18765. progressHandler = typeof onProgress === 'function'
  18766. ? function(update) {
  18767. try {
  18768. // Allow progress handler to transform progress event
  18769. deferred.progress(onProgress(update));
  18770. } catch(e) {
  18771. // Use caught value as progress
  18772. deferred.progress(e);
  18773. }
  18774. }
  18775. : function(update) { deferred.progress(update); };
  18776. handlers.push(function(promise) {
  18777. promise.then(onFulfilled, onRejected)
  18778. .then(deferred.resolve, deferred.reject, progressHandler);
  18779. });
  18780. progressHandlers.push(progressHandler);
  18781. return deferred.promise;
  18782. };
  18783. /**
  18784. * Issue a progress event, notifying all progress listeners
  18785. * @private
  18786. * @param {*} update progress event payload to pass to all listeners
  18787. */
  18788. _progress = function(update) {
  18789. processQueue(progressHandlers, update);
  18790. return update;
  18791. };
  18792. /**
  18793. * Transition from pre-resolution state to post-resolution state, notifying
  18794. * all listeners of the resolution or rejection
  18795. * @private
  18796. * @param {*} value the value of this deferred
  18797. */
  18798. _resolve = function(value) {
  18799. value = resolve(value);
  18800. // Replace _then with one that directly notifies with the result.
  18801. _then = value.then;
  18802. // Replace _resolve so that this Deferred can only be resolved once
  18803. _resolve = resolve;
  18804. // Make _progress a noop, to disallow progress for the resolved promise.
  18805. _progress = noop;
  18806. // Notify handlers
  18807. processQueue(handlers, value);
  18808. // Free progressHandlers array since we'll never issue progress events
  18809. progressHandlers = handlers = undef;
  18810. return value;
  18811. };
  18812. return deferred;
  18813. /**
  18814. * Wrapper to allow _then to be replaced safely
  18815. * @param {function?} [onFulfilled] resolution handler
  18816. * @param {function?} [onRejected] rejection handler
  18817. * @param {function?} [onProgress] progress handler
  18818. * @returns {Promise} new promise
  18819. */
  18820. function then(onFulfilled, onRejected, onProgress) {
  18821. // TODO: Promises/A+ check typeof onFulfilled, onRejected, onProgress
  18822. return _then(onFulfilled, onRejected, onProgress);
  18823. }
  18824. /**
  18825. * Wrapper to allow _resolve to be replaced
  18826. */
  18827. function promiseResolve(val) {
  18828. return _resolve(val);
  18829. }
  18830. /**
  18831. * Wrapper to allow _reject to be replaced
  18832. */
  18833. function promiseReject(err) {
  18834. return _resolve(rejected(err));
  18835. }
  18836. /**
  18837. * Wrapper to allow _progress to be replaced
  18838. */
  18839. function promiseProgress(update) {
  18840. return _progress(update);
  18841. }
  18842. }
  18843. /**
  18844. * Determines if promiseOrValue is a promise or not. Uses the feature
  18845. * test from http://wiki.commonjs.org/wiki/Promises/A to determine if
  18846. * promiseOrValue is a promise.
  18847. *
  18848. * @param {*} promiseOrValue anything
  18849. * @returns {boolean} true if promiseOrValue is a {@link Promise}
  18850. */
  18851. function isPromise(promiseOrValue) {
  18852. return promiseOrValue && typeof promiseOrValue.then === 'function';
  18853. }
  18854. /**
  18855. * Initiates a competitive race, returning a promise that will resolve when
  18856. * howMany of the supplied promisesOrValues have resolved, or will reject when
  18857. * it becomes impossible for howMany to resolve, for example, when
  18858. * (promisesOrValues.length - howMany) + 1 input promises reject.
  18859. *
  18860. * @param {Array} promisesOrValues array of anything, may contain a mix
  18861. * of promises and values
  18862. * @param howMany {number} number of promisesOrValues to resolve
  18863. * @param {function?} [onFulfilled] resolution handler
  18864. * @param {function?} [onRejected] rejection handler
  18865. * @param {function?} [onProgress] progress handler
  18866. * @returns {Promise} promise that will resolve to an array of howMany values that
  18867. * resolved first, or will reject with an array of (promisesOrValues.length - howMany) + 1
  18868. * rejection reasons.
  18869. */
  18870. function some(promisesOrValues, howMany, onFulfilled, onRejected, onProgress) {
  18871. checkCallbacks(2, arguments);
  18872. return when(promisesOrValues, function(promisesOrValues) {
  18873. var toResolve, toReject, values, reasons, deferred, fulfillOne, rejectOne, progress, len, i;
  18874. len = promisesOrValues.length >>> 0;
  18875. toResolve = Math.max(0, Math.min(howMany, len));
  18876. values = [];
  18877. toReject = (len - toResolve) + 1;
  18878. reasons = [];
  18879. deferred = defer();
  18880. // No items in the input, resolve immediately
  18881. if (!toResolve) {
  18882. deferred.resolve(values);
  18883. } else {
  18884. progress = deferred.progress;
  18885. rejectOne = function(reason) {
  18886. reasons.push(reason);
  18887. if(!--toReject) {
  18888. fulfillOne = rejectOne = noop;
  18889. deferred.reject(reasons);
  18890. }
  18891. };
  18892. fulfillOne = function(val) {
  18893. // This orders the values based on promise resolution order
  18894. // Another strategy would be to use the original position of
  18895. // the corresponding promise.
  18896. values.push(val);
  18897. if (!--toResolve) {
  18898. fulfillOne = rejectOne = noop;
  18899. deferred.resolve(values);
  18900. }
  18901. };
  18902. for(i = 0; i < len; ++i) {
  18903. if(i in promisesOrValues) {
  18904. when(promisesOrValues[i], fulfiller, rejecter, progress);
  18905. }
  18906. }
  18907. }
  18908. return deferred.then(onFulfilled, onRejected, onProgress);
  18909. function rejecter(reason) {
  18910. rejectOne(reason);
  18911. }
  18912. function fulfiller(val) {
  18913. fulfillOne(val);
  18914. }
  18915. });
  18916. }
  18917. /**
  18918. * Initiates a competitive race, returning a promise that will resolve when
  18919. * any one of the supplied promisesOrValues has resolved or will reject when
  18920. * *all* promisesOrValues have rejected.
  18921. *
  18922. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  18923. * of {@link Promise}s and values
  18924. * @param {function?} [onFulfilled] resolution handler
  18925. * @param {function?} [onRejected] rejection handler
  18926. * @param {function?} [onProgress] progress handler
  18927. * @returns {Promise} promise that will resolve to the value that resolved first, or
  18928. * will reject with an array of all rejected inputs.
  18929. */
  18930. function any(promisesOrValues, onFulfilled, onRejected, onProgress) {
  18931. function unwrapSingleResult(val) {
  18932. return onFulfilled ? onFulfilled(val[0]) : val[0];
  18933. }
  18934. return some(promisesOrValues, 1, unwrapSingleResult, onRejected, onProgress);
  18935. }
  18936. /**
  18937. * Return a promise that will resolve only once all the supplied promisesOrValues
  18938. * have resolved. The resolution value of the returned promise will be an array
  18939. * containing the resolution values of each of the promisesOrValues.
  18940. * @memberOf when
  18941. *
  18942. * @param {Array|Promise} promisesOrValues array of anything, may contain a mix
  18943. * of {@link Promise}s and values
  18944. * @param {function?} [onFulfilled] resolution handler
  18945. * @param {function?} [onRejected] rejection handler
  18946. * @param {function?} [onProgress] progress handler
  18947. * @returns {Promise}
  18948. */
  18949. function all(promisesOrValues, onFulfilled, onRejected, onProgress) {
  18950. checkCallbacks(1, arguments);
  18951. return map(promisesOrValues, identity).then(onFulfilled, onRejected, onProgress);
  18952. }
  18953. /**
  18954. * Joins multiple promises into a single returned promise.
  18955. * @returns {Promise} a promise that will fulfill when *all* the input promises
  18956. * have fulfilled, or will reject when *any one* of the input promises rejects.
  18957. */
  18958. function join(/* ...promises */) {
  18959. return map(arguments, identity);
  18960. }
  18961. /**
  18962. * Traditional map function, similar to `Array.prototype.map()`, but allows
  18963. * input to contain {@link Promise}s and/or values, and mapFunc may return
  18964. * either a value or a {@link Promise}
  18965. *
  18966. * @param {Array|Promise} promise array of anything, may contain a mix
  18967. * of {@link Promise}s and values
  18968. * @param {function} mapFunc mapping function mapFunc(value) which may return
  18969. * either a {@link Promise} or value
  18970. * @returns {Promise} a {@link Promise} that will resolve to an array containing
  18971. * the mapped output values.
  18972. */
  18973. function map(promise, mapFunc) {
  18974. return when(promise, function(array) {
  18975. var results, len, toResolve, resolve, i, d;
  18976. // Since we know the resulting length, we can preallocate the results
  18977. // array to avoid array expansions.
  18978. toResolve = len = array.length >>> 0;
  18979. results = [];
  18980. d = defer();
  18981. if(!toResolve) {
  18982. d.resolve(results);
  18983. } else {
  18984. resolve = function resolveOne(item, i) {
  18985. when(item, mapFunc).then(function(mapped) {
  18986. results[i] = mapped;
  18987. if(!--toResolve) {
  18988. d.resolve(results);
  18989. }
  18990. }, d.reject);
  18991. };
  18992. // Since mapFunc may be async, get all invocations of it into flight
  18993. for(i = 0; i < len; i++) {
  18994. if(i in array) {
  18995. resolve(array[i], i);
  18996. } else {
  18997. --toResolve;
  18998. }
  18999. }
  19000. }
  19001. return d.promise;
  19002. });
  19003. }
  19004. /**
  19005. * Traditional reduce function, similar to `Array.prototype.reduce()`, but
  19006. * input may contain promises and/or values, and reduceFunc
  19007. * may return either a value or a promise, *and* initialValue may
  19008. * be a promise for the starting value.
  19009. *
  19010. * @param {Array|Promise} promise array or promise for an array of anything,
  19011. * may contain a mix of promises and values.
  19012. * @param {function} reduceFunc reduce function reduce(currentValue, nextValue, index, total),
  19013. * where total is the total number of items being reduced, and will be the same
  19014. * in each call to reduceFunc.
  19015. * @returns {Promise} that will resolve to the final reduced value
  19016. */
  19017. function reduce(promise, reduceFunc /*, initialValue */) {
  19018. var args = slice.call(arguments, 1);
  19019. return when(promise, function(array) {
  19020. var total;
  19021. total = array.length;
  19022. // Wrap the supplied reduceFunc with one that handles promises and then
  19023. // delegates to the supplied.
  19024. args[0] = function (current, val, i) {
  19025. return when(current, function (c) {
  19026. return when(val, function (value) {
  19027. return reduceFunc(c, value, i, total);
  19028. });
  19029. });
  19030. };
  19031. return reduceArray.apply(array, args);
  19032. });
  19033. }
  19034. /**
  19035. * Ensure that resolution of promiseOrValue will trigger resolver with the
  19036. * value or reason of promiseOrValue, or instead with resolveValue if it is provided.
  19037. *
  19038. * @param promiseOrValue
  19039. * @param {Object} resolver
  19040. * @param {function} resolver.resolve
  19041. * @param {function} resolver.reject
  19042. * @param {*} [resolveValue]
  19043. * @returns {Promise}
  19044. */
  19045. function chain(promiseOrValue, resolver, resolveValue) {
  19046. var useResolveValue = arguments.length > 2;
  19047. return when(promiseOrValue,
  19048. function(val) {
  19049. val = useResolveValue ? resolveValue : val;
  19050. resolver.resolve(val);
  19051. return val;
  19052. },
  19053. function(reason) {
  19054. resolver.reject(reason);
  19055. return rejected(reason);
  19056. },
  19057. resolver.progress
  19058. );
  19059. }
  19060. //
  19061. // Utility functions
  19062. //
  19063. /**
  19064. * Apply all functions in queue to value
  19065. * @param {Array} queue array of functions to execute
  19066. * @param {*} value argument passed to each function
  19067. */
  19068. function processQueue(queue, value) {
  19069. var handler, i = 0;
  19070. while (handler = queue[i++]) {
  19071. handler(value);
  19072. }
  19073. }
  19074. /**
  19075. * Helper that checks arrayOfCallbacks to ensure that each element is either
  19076. * a function, or null or undefined.
  19077. * @private
  19078. * @param {number} start index at which to start checking items in arrayOfCallbacks
  19079. * @param {Array} arrayOfCallbacks array to check
  19080. * @throws {Error} if any element of arrayOfCallbacks is something other than
  19081. * a functions, null, or undefined.
  19082. */
  19083. function checkCallbacks(start, arrayOfCallbacks) {
  19084. // TODO: Promises/A+ update type checking and docs
  19085. var arg, i = arrayOfCallbacks.length;
  19086. while(i > start) {
  19087. arg = arrayOfCallbacks[--i];
  19088. if (arg != null && typeof arg != 'function') {
  19089. throw new Error('arg '+i+' must be a function');
  19090. }
  19091. }
  19092. }
  19093. /**
  19094. * No-Op function used in method replacement
  19095. * @private
  19096. */
  19097. function noop() {}
  19098. slice = [].slice;
  19099. // ES5 reduce implementation if native not available
  19100. // See: http://es5.github.com/#x15.4.4.21 as there are many
  19101. // specifics and edge cases.
  19102. reduceArray = [].reduce ||
  19103. function(reduceFunc /*, initialValue */) {
  19104. /*jshint maxcomplexity: 7*/
  19105. // ES5 dictates that reduce.length === 1
  19106. // This implementation deviates from ES5 spec in the following ways:
  19107. // 1. It does not check if reduceFunc is a Callable
  19108. var arr, args, reduced, len, i;
  19109. i = 0;
  19110. // This generates a jshint warning, despite being valid
  19111. // "Missing 'new' prefix when invoking a constructor."
  19112. // See https://github.com/jshint/jshint/issues/392
  19113. arr = Object(this);
  19114. len = arr.length >>> 0;
  19115. args = arguments;
  19116. // If no initialValue, use first item of array (we know length !== 0 here)
  19117. // and adjust i to start at second item
  19118. if(args.length <= 1) {
  19119. // Skip to the first real element in the array
  19120. for(;;) {
  19121. if(i in arr) {
  19122. reduced = arr[i++];
  19123. break;
  19124. }
  19125. // If we reached the end of the array without finding any real
  19126. // elements, it's a TypeError
  19127. if(++i >= len) {
  19128. throw new TypeError();
  19129. }
  19130. }
  19131. } else {
  19132. // If initialValue provided, use it
  19133. reduced = args[1];
  19134. }
  19135. // Do the actual reduce
  19136. for(;i < len; ++i) {
  19137. // Skip holes
  19138. if(i in arr) {
  19139. reduced = reduceFunc(reduced, arr[i], i, arr);
  19140. }
  19141. }
  19142. return reduced;
  19143. };
  19144. function identity(x) {
  19145. return x;
  19146. }
  19147. return when;
  19148. });
  19149. })(typeof define == 'function' && define.amd
  19150. ? define
  19151. : function (factory) { typeof exports === 'object'
  19152. ? (module.exports = factory())
  19153. : (this.when = factory());
  19154. }
  19155. // Boilerplate for AMD, Node, and browser global
  19156. );
  19157. /*global define*/
  19158. define('Core/deprecationWarning',[
  19159. './defined',
  19160. './DeveloperError',
  19161. './oneTimeWarning'
  19162. ], function(
  19163. defined,
  19164. DeveloperError,
  19165. oneTimeWarning) {
  19166. 'use strict';
  19167. /**
  19168. * Logs a deprecation message to the console. Use this function instead of
  19169. * <code>console.log</code> directly since this does not log duplicate messages
  19170. * unless it is called from multiple workers.
  19171. *
  19172. * @exports deprecationWarning
  19173. *
  19174. * @param {String} identifier The unique identifier for this deprecated API.
  19175. * @param {String} message The message to log to the console.
  19176. *
  19177. * @example
  19178. * // Deprecated function or class
  19179. * function Foo() {
  19180. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  19181. * // ...
  19182. * }
  19183. *
  19184. * // Deprecated function
  19185. * Bar.prototype.func = function() {
  19186. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  19187. * // ...
  19188. * };
  19189. *
  19190. * // Deprecated property
  19191. * defineProperties(Bar.prototype, {
  19192. * prop : {
  19193. * get : function() {
  19194. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  19195. * // ...
  19196. * },
  19197. * set : function(value) {
  19198. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  19199. * // ...
  19200. * }
  19201. * }
  19202. * });
  19203. *
  19204. * @private
  19205. */
  19206. function deprecationWarning(identifier, message) {
  19207. if (!defined(identifier) || !defined(message)) {
  19208. throw new DeveloperError('identifier and message are required.');
  19209. }
  19210. oneTimeWarning(identifier, message);
  19211. }
  19212. return deprecationWarning;
  19213. });
  19214. /*global define*/
  19215. define('Core/binarySearch',[
  19216. './defined',
  19217. './DeveloperError'
  19218. ], function(
  19219. defined,
  19220. DeveloperError) {
  19221. 'use strict';
  19222. /**
  19223. * Finds an item in a sorted array.
  19224. *
  19225. * @exports binarySearch
  19226. *
  19227. * @param {Array} array The sorted array to search.
  19228. * @param {Object} itemToFind The item to find in the array.
  19229. * @param {binarySearch~Comparator} comparator The function to use to compare the item to
  19230. * elements in the array.
  19231. * @returns {Number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  19232. * does not exist, the return value is a negative number which is the bitwise complement (~)
  19233. * of the index before which the itemToFind should be inserted in order to maintain the
  19234. * sorted order of the array.
  19235. *
  19236. * @example
  19237. * // Create a comparator function to search through an array of numbers.
  19238. * function comparator(a, b) {
  19239. * return a - b;
  19240. * };
  19241. * var numbers = [0, 2, 4, 6, 8];
  19242. * var index = Cesium.binarySearch(numbers, 6, comparator); // 3
  19243. */
  19244. function binarySearch(array, itemToFind, comparator) {
  19245. if (!defined(array)) {
  19246. throw new DeveloperError('array is required.');
  19247. }
  19248. if (!defined(itemToFind)) {
  19249. throw new DeveloperError('itemToFind is required.');
  19250. }
  19251. if (!defined(comparator)) {
  19252. throw new DeveloperError('comparator is required.');
  19253. }
  19254. var low = 0;
  19255. var high = array.length - 1;
  19256. var i;
  19257. var comparison;
  19258. while (low <= high) {
  19259. i = ~~((low + high) / 2);
  19260. comparison = comparator(array[i], itemToFind);
  19261. if (comparison < 0) {
  19262. low = i + 1;
  19263. continue;
  19264. }
  19265. if (comparison > 0) {
  19266. high = i - 1;
  19267. continue;
  19268. }
  19269. return i;
  19270. }
  19271. return ~(high + 1);
  19272. }
  19273. /**
  19274. * A function used to compare two items while performing a binary search.
  19275. * @callback binarySearch~Comparator
  19276. *
  19277. * @param {Object} a An item in the array.
  19278. * @param {Object} b The item being searched for.
  19279. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  19280. * a positive value if <code>a</code> is greater than <code>b</code>, or
  19281. * 0 if <code>a</code> is equal to <code>b</code>.
  19282. *
  19283. * @example
  19284. * function compareNumbers(a, b) {
  19285. * return a - b;
  19286. * }
  19287. */
  19288. return binarySearch;
  19289. });
  19290. /*global define*/
  19291. define('Core/EarthOrientationParametersSample',[],function() {
  19292. 'use strict';
  19293. /**
  19294. * A set of Earth Orientation Parameters (EOP) sampled at a time.
  19295. *
  19296. * @alias EarthOrientationParametersSample
  19297. * @constructor
  19298. *
  19299. * @param {Number} xPoleWander The pole wander about the X axis, in radians.
  19300. * @param {Number} yPoleWander The pole wander about the Y axis, in radians.
  19301. * @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  19302. * @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  19303. * @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
  19304. *
  19305. * @private
  19306. */
  19307. function EarthOrientationParametersSample(xPoleWander, yPoleWander, xPoleOffset, yPoleOffset, ut1MinusUtc) {
  19308. /**
  19309. * The pole wander about the X axis, in radians.
  19310. * @type {Number}
  19311. */
  19312. this.xPoleWander = xPoleWander;
  19313. /**
  19314. * The pole wander about the Y axis, in radians.
  19315. * @type {Number}
  19316. */
  19317. this.yPoleWander = yPoleWander;
  19318. /**
  19319. * The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
  19320. * @type {Number}
  19321. */
  19322. this.xPoleOffset = xPoleOffset;
  19323. /**
  19324. * The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
  19325. * @type {Number}
  19326. */
  19327. this.yPoleOffset = yPoleOffset;
  19328. /**
  19329. * The difference in time standards, UT1 - UTC, in seconds.
  19330. * @type {Number}
  19331. */
  19332. this.ut1MinusUtc = ut1MinusUtc;
  19333. }
  19334. return EarthOrientationParametersSample;
  19335. });
  19336. /**
  19337. @license
  19338. sprintf.js from the php.js project - https://github.com/kvz/phpjs
  19339. Directly from https://github.com/kvz/phpjs/blob/master/functions/strings/sprintf.js
  19340. php.js is copyright 2012 Kevin van Zonneveld.
  19341. Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
  19342. (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
  19343. (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jack, Jonas
  19344. Raoni Soares Silva (http://www.jsfromhell.com), Philip Peterson, Legaev
  19345. Andrey, Ates Goral (http://magnetiq.com), Alex, Ratheous, Martijn Wieringa,
  19346. Rafa? Kukawski (http://blog.kukawski.pl), lmeyrick
  19347. (https://sourceforge.net/projects/bcmath-js/), Nate, Philippe Baumann,
  19348. Enrique Gonzalez, Webtoolkit.info (http://www.webtoolkit.info/), Carlos R.
  19349. L. Rodrigues (http://www.jsfromhell.com), Ash Searle
  19350. (http://hexmen.com/blog/), Jani Hartikainen, travc, Ole Vrijenhoek,
  19351. Erkekjetter, Michael Grier, Rafa? Kukawski (http://kukawski.pl), Johnny
  19352. Mast (http://www.phpvrouwen.nl), T.Wild, d3x,
  19353. http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
  19354. Rafa? Kukawski (http://blog.kukawski.pl/), stag019, pilus, WebDevHobo
  19355. (http://webdevhobo.blogspot.com/), marrtins, GeekFG
  19356. (http://geekfg.blogspot.com), Andrea Giammarchi
  19357. (http://webreflection.blogspot.com), Arpad Ray (mailto:arpad@php.net),
  19358. gorthaur, Paul Smith, Tim de Koning (http://www.kingsquare.nl), Joris, Oleg
  19359. Eremeev, Steve Hilder, majak, gettimeofday, KELAN, Josh Fraser
  19360. (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
  19361. Marc Palau, Martin
  19362. (http://www.erlenwiese.de/), Breaking Par Consulting Inc
  19363. (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
  19364. Chris, Mirek Slugen, saulius, Alfonso Jimenez
  19365. (http://www.alfonsojimenez.com), Diplom@t (http://difane.com/), felix,
  19366. Mailfaker (http://www.weedem.fr/), Tyler Akins (http://rumkin.com), Caio
  19367. Ariede (http://caioariede.com), Robin, Kankrelune
  19368. (http://www.webfaktory.info/), Karol Kowalski, Imgen Tata
  19369. (http://www.myipdf.com/), mdsjack (http://www.mdsjack.bo.it), Dreamer,
  19370. Felix Geisendoerfer (http://www.debuggable.com/felix), Lars Fischer, AJ,
  19371. David, Aman Gupta, Michael White, Public Domain
  19372. (http://www.json.org/json2.js), Steven Levithan
  19373. (http://blog.stevenlevithan.com), Sakimori, Pellentesque Malesuada,
  19374. Thunder.m, Dj (http://phpjs.org/functions/htmlentities:425#comment_134018),
  19375. Steve Clay, David James, Francois, class_exists, nobbler, T. Wild, Itsacon
  19376. (http://www.itsacon.net/), date, Ole Vrijenhoek (http://www.nervous.nl/),
  19377. Fox, Raphael (Ao RUDLER), Marco, noname, Mateusz "loonquawl" Zalega, Frank
  19378. Forte, Arno, ger, mktime, john (http://www.jd-tech.net), Nick Kolosov
  19379. (http://sammy.ru), marc andreu, Scott Cariss, Douglas Crockford
  19380. (http://javascript.crockford.com), madipta, Slawomir Kaniecki,
  19381. ReverseSyntax, Nathan, Alex Wilson, kenneth, Bayron Guevara, Adam Wallner
  19382. (http://web2.bitbaro.hu/), paulo kuong, jmweb, Lincoln Ramsay, djmix,
  19383. Pyerre, Jon Hohle, Thiago Mata (http://thiagomata.blog.com), lmeyrick
  19384. (https://sourceforge.net/projects/bcmath-js/this.), Linuxworld, duncan,
  19385. Gilbert, Sanjoy Roy, Shingo, sankai, Oskar Larsson H?gfeldt
  19386. (http://oskar-lh.name/), Denny Wardhana, 0m3r, Everlasto, Subhasis Deb,
  19387. josh, jd, Pier Paolo Ramon (http://www.mastersoup.com/), P, merabi, Soren
  19388. Hansen, Eugene Bulkin (http://doubleaw.com/), Der Simon
  19389. (http://innerdom.sourceforge.net/), echo is bad, Ozh, XoraX
  19390. (http://www.xorax.info), EdorFaus, JB, J A R, Marc Jansen, Francesco, LH,
  19391. Stoyan Kyosev (http://www.svest.org/), nord_ua, omid
  19392. (http://phpjs.org/functions/380:380#comment_137122), Brad Touesnard, MeEtc
  19393. (http://yass.meetcweb.com), Peter-Paul Koch
  19394. (http://www.quirksmode.org/js/beat.html), Olivier Louvignes
  19395. (http://mg-crea.com/), T0bsn, Tim Wiel, Bryan Elliott, Jalal Berrami,
  19396. Martin, JT, David Randall, Thomas Beaucourt (http://www.webapp.fr), taith,
  19397. vlado houba, Pierre-Luc Paour, Kristof Coomans (SCK-CEN Belgian Nucleair
  19398. Research Centre), Martin Pool, Kirk Strobeck, Rick Waldron, Brant Messenger
  19399. (http://www.brantmessenger.com/), Devan Penner-Woelk, Saulo Vallory, Wagner
  19400. B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
  19401. (http://carrot.org/), Christoph, Daniel Esteban, strftime, Mick@el, rezna,
  19402. Simon Willison (http://simonwillison.net), Anton Ongson, Gabriel Paderni,
  19403. Marco van Oort, penutbutterjelly, Philipp Lenssen, Bjorn Roesbeke
  19404. (http://www.bjornroesbeke.be/), Bug?, Eric Nagel, Tomasz Wesolowski,
  19405. Evertjan Garretsen, Bobby Drake, Blues (http://tech.bluesmoon.info/), Luke
  19406. Godfrey, Pul, uestla, Alan C, Ulrich, Rafal Kukawski, Yves Sucaet,
  19407. sowberry, Norman "zEh" Fuchs, hitwork, Zahlii, johnrembo, Nick Callen,
  19408. Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Brian Tafoya
  19409. (http://www.premasolutions.com/), Philippe Jausions
  19410. (http://pear.php.net/user/jausions), Aidan Lister
  19411. (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
  19412. strcmp, Taras Bogach, jpfle, Alexander Ermolaev
  19413. (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
  19414. dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
  19415. (http://www.pedrotainha.com), James, Arnout Kazemier
  19416. (http://www.3rd-Eden.com), Chris McMacken, gabriel paderni, Yannoo,
  19417. FGFEmperor, baris ozdil, Tod Gentille, Greg Frazier, jakes, 3D-GRAF, Allan
  19418. Jensen (http://www.winternet.no), Howard Yeend, Benjamin Lupton, davook,
  19419. daniel airton wermann (http://wermann.com.br), Atli T¨®r, Maximusya, Ryan
  19420. W Tenney (http://ryan.10e.us), Alexander M Beedie, fearphage
  19421. (http://http/my.opera.com/fearphage/), Nathan Sepulveda, Victor, Matteo,
  19422. Billy, stensi, Cord, Manish, T.J. Leahy, Riddler
  19423. (http://www.frontierwebdev.com/), Rafa? Kukawski, FremyCompany, Matt
  19424. Bradley, Tim de Koning, Luis Salazar (http://www.freaky-media.com/), Diogo
  19425. Resende, Rival, Andrej Pavlovic, Garagoth, Le Torbi
  19426. (http://www.letorbi.de/), Dino, Josep Sanz (http://www.ws3.es/), rem,
  19427. Russell Walker (http://www.nbill.co.uk/), Jamie Beck
  19428. (http://www.terabit.ca/), setcookie, Michael, YUI Library:
  19429. http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Blues at
  19430. http://hacks.bluesmoon.info/strftime/strftime.js, Ben
  19431. (http://benblume.co.uk/), DtTvB
  19432. (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Andreas, William,
  19433. meo, incidence, Cagri Ekin, Amirouche, Amir Habibi
  19434. (http://www.residence-mixte.com/), Luke Smith (http://lucassmith.name),
  19435. Kheang Hok Chin (http://www.distantia.ca/), Jay Klehr, Lorenzo Pisani,
  19436. Tony, Yen-Wei Liu, Greenseed, mk.keck, Leslie Hoare, dude, booeyOH, Ben
  19437. Bryan
  19438. Licensed under the MIT (MIT-LICENSE.txt) license.
  19439. Permission is hereby granted, free of charge, to any person obtaining a
  19440. copy of this software and associated documentation files (the
  19441. "Software"), to deal in the Software without restriction, including
  19442. without limitation the rights to use, copy, modify, merge, publish,
  19443. distribute, sublicense, and/or sell copies of the Software, and to
  19444. permit persons to whom the Software is furnished to do so, subject to
  19445. the following conditions:
  19446. The above copyright notice and this permission notice shall be included
  19447. in all copies or substantial portions of the Software.
  19448. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  19449. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19450. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19451. IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
  19452. OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  19453. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  19454. OTHER DEALINGS IN THE SOFTWARE.
  19455. */
  19456. /*global define*/
  19457. define('ThirdParty/sprintf',[],function() {
  19458. function sprintf () {
  19459. // http://kevin.vanzonneveld.net
  19460. // + original by: Ash Searle (http://hexmen.com/blog/)
  19461. // + namespaced by: Michael White (http://getsprink.com)
  19462. // + tweaked by: Jack
  19463. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  19464. // + input by: Paulo Freitas
  19465. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  19466. // + input by: Brett Zamir (http://brett-zamir.me)
  19467. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  19468. // + improved by: Dj
  19469. // + improved by: Allidylls
  19470. // * example 1: sprintf("%01.2f", 123.1);
  19471. // * returns 1: 123.10
  19472. // * example 2: sprintf("[%10s]", 'monkey');
  19473. // * returns 2: '[ monkey]'
  19474. // * example 3: sprintf("[%'#10s]", 'monkey');
  19475. // * returns 3: '[####monkey]'
  19476. // * example 4: sprintf("%d", 123456789012345);
  19477. // * returns 4: '123456789012345'
  19478. var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuideEfFgG])/g;
  19479. var a = arguments,
  19480. i = 0,
  19481. format = a[i++];
  19482. // pad()
  19483. var pad = function (str, len, chr, leftJustify) {
  19484. if (!chr) {
  19485. chr = ' ';
  19486. }
  19487. var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
  19488. return leftJustify ? str + padding : padding + str;
  19489. };
  19490. // justify()
  19491. var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
  19492. var diff = minWidth - value.length;
  19493. if (diff > 0) {
  19494. if (leftJustify || !zeroPad) {
  19495. value = pad(value, minWidth, customPadChar, leftJustify);
  19496. } else {
  19497. value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
  19498. }
  19499. }
  19500. return value;
  19501. };
  19502. // formatBaseX()
  19503. var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
  19504. // Note: casts negative numbers to positive ones
  19505. var number = value >>> 0;
  19506. prefix = prefix && number && {
  19507. '2': '0b',
  19508. '8': '0',
  19509. '16': '0x'
  19510. }[base] || '';
  19511. value = prefix + pad(number.toString(base), precision || 0, '0', false);
  19512. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  19513. };
  19514. // formatString()
  19515. var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
  19516. if (precision != null) {
  19517. value = value.slice(0, precision);
  19518. }
  19519. return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
  19520. };
  19521. // doFormat()
  19522. var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
  19523. var number;
  19524. var prefix;
  19525. var method;
  19526. var textTransform;
  19527. var value;
  19528. if (substring == '%%') {
  19529. return '%';
  19530. }
  19531. // parse flags
  19532. var leftJustify = false,
  19533. positivePrefix = '',
  19534. zeroPad = false,
  19535. prefixBaseX = false,
  19536. customPadChar = ' ';
  19537. var flagsl = flags.length;
  19538. for (var j = 0; flags && j < flagsl; j++) {
  19539. switch (flags.charAt(j)) {
  19540. case ' ':
  19541. positivePrefix = ' ';
  19542. break;
  19543. case '+':
  19544. positivePrefix = '+';
  19545. break;
  19546. case '-':
  19547. leftJustify = true;
  19548. break;
  19549. case "'":
  19550. customPadChar = flags.charAt(j + 1);
  19551. break;
  19552. case '0':
  19553. zeroPad = true;
  19554. break;
  19555. case '#':
  19556. prefixBaseX = true;
  19557. break;
  19558. }
  19559. }
  19560. // parameters may be null, undefined, empty-string or real valued
  19561. // we want to ignore null, undefined and empty-string values
  19562. if (!minWidth) {
  19563. minWidth = 0;
  19564. } else if (minWidth == '*') {
  19565. minWidth = +a[i++];
  19566. } else if (minWidth.charAt(0) == '*') {
  19567. minWidth = +a[minWidth.slice(1, -1)];
  19568. } else {
  19569. minWidth = +minWidth;
  19570. }
  19571. // Note: undocumented perl feature:
  19572. if (minWidth < 0) {
  19573. minWidth = -minWidth;
  19574. leftJustify = true;
  19575. }
  19576. if (!isFinite(minWidth)) {
  19577. throw new Error('sprintf: (minimum-)width must be finite');
  19578. }
  19579. if (!precision) {
  19580. precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
  19581. } else if (precision == '*') {
  19582. precision = +a[i++];
  19583. } else if (precision.charAt(0) == '*') {
  19584. precision = +a[precision.slice(1, -1)];
  19585. } else {
  19586. precision = +precision;
  19587. }
  19588. // grab value using valueIndex if required?
  19589. value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
  19590. switch (type) {
  19591. case 's':
  19592. return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
  19593. case 'c':
  19594. return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
  19595. case 'b':
  19596. return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19597. case 'o':
  19598. return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19599. case 'x':
  19600. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19601. case 'X':
  19602. return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
  19603. case 'u':
  19604. return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
  19605. case 'i':
  19606. case 'd':
  19607. number = +value || 0;
  19608. number = Math.round(number - number % 1); // Plain Math.round doesn't just truncate
  19609. prefix = number < 0 ? '-' : positivePrefix;
  19610. value = prefix + pad(String(Math.abs(number)), precision, '0', false);
  19611. return justify(value, prefix, leftJustify, minWidth, zeroPad);
  19612. case 'e':
  19613. case 'E':
  19614. case 'f': // Should handle locales (as per setlocale)
  19615. case 'F':
  19616. case 'g':
  19617. case 'G':
  19618. number = +value;
  19619. prefix = number < 0 ? '-' : positivePrefix;
  19620. method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
  19621. textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
  19622. value = prefix + Math.abs(number)[method](precision);
  19623. return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
  19624. default:
  19625. return substring;
  19626. }
  19627. };
  19628. return format.replace(regex, doFormat);
  19629. }
  19630. return sprintf;
  19631. });
  19632. /*global define*/
  19633. define('Core/GregorianDate',[],function() {
  19634. 'use strict';
  19635. /**
  19636. * Represents a Gregorian date in a more precise format than the JavaScript Date object.
  19637. * In addition to submillisecond precision, this object can also represent leap seconds.
  19638. * @alias GregorianDate
  19639. * @constructor
  19640. *
  19641. * @see JulianDate#toGregorianDate
  19642. */
  19643. function GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond) {
  19644. /**
  19645. * Gets or sets the year as a whole number.
  19646. * @type {Number}
  19647. */
  19648. this.year = year;
  19649. /**
  19650. * Gets or sets the month as a whole number with range [1, 12].
  19651. * @type {Number}
  19652. */
  19653. this.month = month;
  19654. /**
  19655. * Gets or sets the day of the month as a whole number starting at 1.
  19656. * @type {Number}
  19657. */
  19658. this.day = day;
  19659. /**
  19660. * Gets or sets the hour as a whole number with range [0, 23].
  19661. * @type {Number}
  19662. */
  19663. this.hour = hour;
  19664. /**
  19665. * Gets or sets the minute of the hour as a whole number with range [0, 59].
  19666. * @type {Number}
  19667. */
  19668. this.minute = minute;
  19669. /**
  19670. * Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
  19671. * @type {Number}
  19672. */
  19673. this.second = second;
  19674. /**
  19675. * Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
  19676. * @type {Number}
  19677. */
  19678. this.millisecond = millisecond;
  19679. /**
  19680. * Gets or sets whether this time is during a leap second.
  19681. * @type {Boolean}
  19682. */
  19683. this.isLeapSecond = isLeapSecond;
  19684. }
  19685. return GregorianDate;
  19686. });
  19687. /*global define*/
  19688. define('Core/isLeapYear',[
  19689. './DeveloperError'
  19690. ], function(
  19691. DeveloperError) {
  19692. 'use strict';
  19693. /**
  19694. * Determines if a given date is a leap year.
  19695. *
  19696. * @exports isLeapYear
  19697. *
  19698. * @param {Number} year The year to be tested.
  19699. * @returns {Boolean} True if <code>year</code> is a leap year.
  19700. *
  19701. * @example
  19702. * var leapYear = Cesium.isLeapYear(2000); // true
  19703. */
  19704. function isLeapYear(year) {
  19705. if (year === null || isNaN(year)) {
  19706. throw new DeveloperError('year is required and must be a number.');
  19707. }
  19708. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  19709. }
  19710. return isLeapYear;
  19711. });
  19712. /*global define*/
  19713. define('Core/LeapSecond',[],function() {
  19714. 'use strict';
  19715. /**
  19716. * Describes a single leap second, which is constructed from a {@link JulianDate} and a
  19717. * numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
  19718. * @alias LeapSecond
  19719. * @constructor
  19720. *
  19721. * @param {JulianDate} [date] A Julian date representing the time of the leap second.
  19722. * @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
  19723. */
  19724. function LeapSecond(date, offset) {
  19725. /**
  19726. * Gets or sets the date at which this leap second occurs.
  19727. * @type {JulianDate}
  19728. */
  19729. this.julianDate = date;
  19730. /**
  19731. * Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
  19732. * of this leap second.
  19733. * @type {Number}
  19734. */
  19735. this.offset = offset;
  19736. }
  19737. return LeapSecond;
  19738. });
  19739. /*global define*/
  19740. define('Core/TimeConstants',[
  19741. './freezeObject'
  19742. ], function(
  19743. freezeObject) {
  19744. 'use strict';
  19745. /**
  19746. * Constants for time conversions like those done by {@link JulianDate}.
  19747. *
  19748. * @exports TimeConstants
  19749. *
  19750. * @see JulianDate
  19751. *
  19752. * @private
  19753. */
  19754. var TimeConstants = {
  19755. /**
  19756. * The number of seconds in one millisecond: <code>0.001</code>
  19757. * @type {Number}
  19758. * @constant
  19759. */
  19760. SECONDS_PER_MILLISECOND : 0.001,
  19761. /**
  19762. * The number of seconds in one minute: <code>60</code>.
  19763. * @type {Number}
  19764. * @constant
  19765. */
  19766. SECONDS_PER_MINUTE : 60.0,
  19767. /**
  19768. * The number of minutes in one hour: <code>60</code>.
  19769. * @type {Number}
  19770. * @constant
  19771. */
  19772. MINUTES_PER_HOUR : 60.0,
  19773. /**
  19774. * The number of hours in one day: <code>24</code>.
  19775. * @type {Number}
  19776. * @constant
  19777. */
  19778. HOURS_PER_DAY : 24.0,
  19779. /**
  19780. * The number of seconds in one hour: <code>3600</code>.
  19781. * @type {Number}
  19782. * @constant
  19783. */
  19784. SECONDS_PER_HOUR : 3600.0,
  19785. /**
  19786. * The number of minutes in one day: <code>1440</code>.
  19787. * @type {Number}
  19788. * @constant
  19789. */
  19790. MINUTES_PER_DAY : 1440.0,
  19791. /**
  19792. * The number of seconds in one day, ignoring leap seconds: <code>86400</code>.
  19793. * @type {Number}
  19794. * @constant
  19795. */
  19796. SECONDS_PER_DAY : 86400.0,
  19797. /**
  19798. * The number of days in one Julian century: <code>36525</code>.
  19799. * @type {Number}
  19800. * @constant
  19801. */
  19802. DAYS_PER_JULIAN_CENTURY : 36525.0,
  19803. /**
  19804. * One trillionth of a second.
  19805. * @type {Number}
  19806. * @constant
  19807. */
  19808. PICOSECOND : 0.000000001,
  19809. /**
  19810. * The number of days to subtract from a Julian date to determine the
  19811. * modified Julian date, which gives the number of days since midnight
  19812. * on November 17, 1858.
  19813. * @type {Number}
  19814. * @constant
  19815. */
  19816. MODIFIED_JULIAN_DATE_DIFFERENCE : 2400000.5
  19817. };
  19818. return freezeObject(TimeConstants);
  19819. });
  19820. /*global define*/
  19821. define('Core/TimeStandard',[
  19822. './freezeObject'
  19823. ], function(
  19824. freezeObject) {
  19825. 'use strict';
  19826. /**
  19827. * Provides the type of time standards which JulianDate can take as input.
  19828. *
  19829. * @exports TimeStandard
  19830. *
  19831. * @see JulianDate
  19832. */
  19833. var TimeStandard = {
  19834. /**
  19835. * Represents the coordinated Universal Time (UTC) time standard.
  19836. *
  19837. * UTC is related to TAI according to the relationship
  19838. * <code>UTC = TAI - deltaT</code> where <code>deltaT</code> is the number of leap
  19839. * seconds which have been introduced as of the time in TAI.
  19840. *
  19841. */
  19842. UTC : 0,
  19843. /**
  19844. * Represents the International Atomic Time (TAI) time standard.
  19845. * TAI is the principal time standard to which the other time standards are related.
  19846. */
  19847. TAI : 1
  19848. };
  19849. return freezeObject(TimeStandard);
  19850. });
  19851. /*global define*/
  19852. define('Core/JulianDate',[
  19853. '../ThirdParty/sprintf',
  19854. './binarySearch',
  19855. './defaultValue',
  19856. './defined',
  19857. './DeveloperError',
  19858. './GregorianDate',
  19859. './isLeapYear',
  19860. './LeapSecond',
  19861. './TimeConstants',
  19862. './TimeStandard'
  19863. ], function(
  19864. sprintf,
  19865. binarySearch,
  19866. defaultValue,
  19867. defined,
  19868. DeveloperError,
  19869. GregorianDate,
  19870. isLeapYear,
  19871. LeapSecond,
  19872. TimeConstants,
  19873. TimeStandard) {
  19874. 'use strict';
  19875. var gregorianDateScratch = new GregorianDate();
  19876. var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  19877. var daysInLeapFeburary = 29;
  19878. function compareLeapSecondDates(leapSecond, dateToFind) {
  19879. return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
  19880. }
  19881. // we don't really need a leap second instance, anything with a julianDate property will do
  19882. var binarySearchScratchLeapSecond = new LeapSecond();
  19883. function convertUtcToTai(julianDate) {
  19884. //Even though julianDate is in UTC, we'll treat it as TAI and
  19885. //search the leap second table for it.
  19886. binarySearchScratchLeapSecond.julianDate = julianDate;
  19887. var leapSeconds = JulianDate.leapSeconds;
  19888. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  19889. if (index < 0) {
  19890. index = ~index;
  19891. }
  19892. if (index >= leapSeconds.length) {
  19893. index = leapSeconds.length - 1;
  19894. }
  19895. var offset = leapSeconds[index].offset;
  19896. if (index > 0) {
  19897. //Now we have the index of the closest leap second that comes on or after our UTC time.
  19898. //However, if the difference between the UTC date being converted and the TAI
  19899. //defined leap second is greater than the offset, we are off by one and need to use
  19900. //the previous leap second.
  19901. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  19902. if (difference > offset) {
  19903. index--;
  19904. offset = leapSeconds[index].offset;
  19905. }
  19906. }
  19907. JulianDate.addSeconds(julianDate, offset, julianDate);
  19908. }
  19909. function convertTaiToUtc(julianDate, result) {
  19910. binarySearchScratchLeapSecond.julianDate = julianDate;
  19911. var leapSeconds = JulianDate.leapSeconds;
  19912. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  19913. if (index < 0) {
  19914. index = ~index;
  19915. }
  19916. //All times before our first leap second get the first offset.
  19917. if (index === 0) {
  19918. return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
  19919. }
  19920. //All times after our leap second get the last offset.
  19921. if (index >= leapSeconds.length) {
  19922. return JulianDate.addSeconds(julianDate, -leapSeconds[index - 1].offset, result);
  19923. }
  19924. //Compute the difference between the found leap second and the time we are converting.
  19925. var difference = JulianDate.secondsDifference(leapSeconds[index].julianDate, julianDate);
  19926. if (difference === 0) {
  19927. //The date is in our leap second table.
  19928. return JulianDate.addSeconds(julianDate, -leapSeconds[index].offset, result);
  19929. }
  19930. if (difference <= 1.0) {
  19931. //The requested date is during the moment of a leap second, then we cannot convert to UTC
  19932. return undefined;
  19933. }
  19934. //The time is in between two leap seconds, index is the leap second after the date
  19935. //we're converting, so we subtract one to get the correct LeapSecond instance.
  19936. return JulianDate.addSeconds(julianDate, -leapSeconds[--index].offset, result);
  19937. }
  19938. function setComponents(wholeDays, secondsOfDay, julianDate) {
  19939. var extraDays = (secondsOfDay / TimeConstants.SECONDS_PER_DAY) | 0;
  19940. wholeDays += extraDays;
  19941. secondsOfDay -= TimeConstants.SECONDS_PER_DAY * extraDays;
  19942. if (secondsOfDay < 0) {
  19943. wholeDays--;
  19944. secondsOfDay += TimeConstants.SECONDS_PER_DAY;
  19945. }
  19946. julianDate.dayNumber = wholeDays;
  19947. julianDate.secondsOfDay = secondsOfDay;
  19948. return julianDate;
  19949. }
  19950. function computeJulianDateComponents(year, month, day, hour, minute, second, millisecond) {
  19951. // Algorithm from page 604 of the Explanatory Supplement to the
  19952. // Astronomical Almanac (Seidelmann 1992).
  19953. var a = ((month - 14) / 12) | 0;
  19954. var b = year + 4800 + a;
  19955. var dayNumber = (((1461 * b) / 4) | 0) + (((367 * (month - 2 - 12 * a)) / 12) | 0) - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + day - 32075;
  19956. // JulianDates are noon-based
  19957. hour = hour - 12;
  19958. if (hour < 0) {
  19959. hour += 24;
  19960. }
  19961. var secondsOfDay = second + ((hour * TimeConstants.SECONDS_PER_HOUR) + (minute * TimeConstants.SECONDS_PER_MINUTE) + (millisecond * TimeConstants.SECONDS_PER_MILLISECOND));
  19962. if (secondsOfDay >= 43200.0) {
  19963. dayNumber -= 1;
  19964. }
  19965. return [dayNumber, secondsOfDay];
  19966. }
  19967. //Regular expressions used for ISO8601 date parsing.
  19968. //YYYY
  19969. var matchCalendarYear = /^(\d{4})$/;
  19970. //YYYY-MM (YYYYMM is invalid)
  19971. var matchCalendarMonth = /^(\d{4})-(\d{2})$/;
  19972. //YYYY-DDD or YYYYDDD
  19973. var matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
  19974. //YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
  19975. var matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
  19976. //YYYY-MM-DD or YYYYMMDD
  19977. var matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
  19978. // Match utc offset
  19979. var utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
  19980. // Match hours HH or HH.xxxxx
  19981. var matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
  19982. // Match hours/minutes HH:MM HHMM.xxxxx
  19983. var matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  19984. // Match hours/minutes HH:MM:SS HHMMSS.xxxxx
  19985. var matchHoursMinutesSeconds = /^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
  19986. var iso8601ErrorMessage = 'Invalid ISO 8601 date.';
  19987. /**
  19988. * Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
  19989. * For increased precision, this class stores the whole number part of the date and the seconds
  19990. * part of the date in separate components. In order to be safe for arithmetic and represent
  19991. * leap seconds, the date is always stored in the International Atomic Time standard
  19992. * {@link TimeStandard.TAI}.
  19993. * @alias JulianDate
  19994. * @constructor
  19995. *
  19996. * @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
  19997. * @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.
  19998. * @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
  19999. */
  20000. function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
  20001. /**
  20002. * Gets or sets the number of whole days.
  20003. * @type {Number}
  20004. */
  20005. this.dayNumber = undefined;
  20006. /**
  20007. * Gets or sets the number of seconds into the current day.
  20008. * @type {Number}
  20009. */
  20010. this.secondsOfDay = undefined;
  20011. julianDayNumber = defaultValue(julianDayNumber, 0.0);
  20012. secondsOfDay = defaultValue(secondsOfDay, 0.0);
  20013. timeStandard = defaultValue(timeStandard, TimeStandard.UTC);
  20014. //If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
  20015. var wholeDays = julianDayNumber | 0;
  20016. secondsOfDay = secondsOfDay + (julianDayNumber - wholeDays) * TimeConstants.SECONDS_PER_DAY;
  20017. setComponents(wholeDays, secondsOfDay, this);
  20018. if (timeStandard === TimeStandard.UTC) {
  20019. convertUtcToTai(this);
  20020. }
  20021. }
  20022. /**
  20023. * Creates a new instance from a JavaScript Date.
  20024. *
  20025. * @param {Date} date A JavaScript Date.
  20026. * @param {JulianDate} [result] An existing instance to use for the result.
  20027. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  20028. *
  20029. * @exception {DeveloperError} date must be a valid JavaScript Date.
  20030. */
  20031. JulianDate.fromDate = function(date, result) {
  20032. if (!(date instanceof Date) || isNaN(date.getTime())) {
  20033. throw new DeveloperError('date must be a valid JavaScript Date.');
  20034. }
  20035. var components = computeJulianDateComponents(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());
  20036. if (!defined(result)) {
  20037. return new JulianDate(components[0], components[1], TimeStandard.UTC);
  20038. }
  20039. setComponents(components[0], components[1], result);
  20040. convertUtcToTai(result);
  20041. return result;
  20042. };
  20043. /**
  20044. * Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
  20045. * This method is superior to <code>Date.parse</code> because it will handle all valid formats defined by the ISO 8601
  20046. * specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
  20047. *
  20048. * @param {String} iso8601String An ISO 8601 date.
  20049. * @param {JulianDate} [result] An existing instance to use for the result.
  20050. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  20051. *
  20052. * @exception {DeveloperError} Invalid ISO 8601 date.
  20053. */
  20054. JulianDate.fromIso8601 = function(iso8601String, result) {
  20055. if (typeof iso8601String !== 'string') {
  20056. throw new DeveloperError(iso8601ErrorMessage);
  20057. }
  20058. //Comma and decimal point both indicate a fractional number according to ISO 8601,
  20059. //start out by blanket replacing , with . which is the only valid such symbol in JS.
  20060. iso8601String = iso8601String.replace(',', '.');
  20061. //Split the string into its date and time components, denoted by a mandatory T
  20062. var tokens = iso8601String.split('T');
  20063. var year;
  20064. var month = 1;
  20065. var day = 1;
  20066. var hour = 0;
  20067. var minute = 0;
  20068. var second = 0;
  20069. var millisecond = 0;
  20070. //Lacking a time is okay, but a missing date is illegal.
  20071. var date = tokens[0];
  20072. var time = tokens[1];
  20073. var tmp;
  20074. var inLeapYear;
  20075. if (!defined(date)) {
  20076. throw new DeveloperError(iso8601ErrorMessage);
  20077. }
  20078. var dashCount;
  20079. //First match the date against possible regular expressions.
  20080. tokens = date.match(matchCalendarDate);
  20081. if (tokens !== null) {
  20082. dashCount = date.split('-').length - 1;
  20083. if (dashCount > 0 && dashCount !== 2) {
  20084. throw new DeveloperError(iso8601ErrorMessage);
  20085. }
  20086. year = +tokens[1];
  20087. month = +tokens[2];
  20088. day = +tokens[3];
  20089. } else {
  20090. tokens = date.match(matchCalendarMonth);
  20091. if (tokens !== null) {
  20092. year = +tokens[1];
  20093. month = +tokens[2];
  20094. } else {
  20095. tokens = date.match(matchCalendarYear);
  20096. if (tokens !== null) {
  20097. year = +tokens[1];
  20098. } else {
  20099. //Not a year/month/day so it must be an ordinal date.
  20100. var dayOfYear;
  20101. tokens = date.match(matchOrdinalDate);
  20102. if (tokens !== null) {
  20103. year = +tokens[1];
  20104. dayOfYear = +tokens[2];
  20105. inLeapYear = isLeapYear(year);
  20106. //This validation is only applicable for this format.
  20107. if (dayOfYear < 1 || (inLeapYear && dayOfYear > 366) || (!inLeapYear && dayOfYear > 365)) {
  20108. throw new DeveloperError(iso8601ErrorMessage);
  20109. }
  20110. } else {
  20111. tokens = date.match(matchWeekDate);
  20112. if (tokens !== null) {
  20113. //ISO week date to ordinal date from
  20114. //http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
  20115. year = +tokens[1];
  20116. var weekNumber = +tokens[2];
  20117. var dayOfWeek = +tokens[3] || 0;
  20118. dashCount = date.split('-').length - 1;
  20119. if (dashCount > 0 &&
  20120. ((!defined(tokens[3]) && dashCount !== 1) ||
  20121. (defined(tokens[3]) && dashCount !== 2))) {
  20122. throw new DeveloperError(iso8601ErrorMessage);
  20123. }
  20124. var january4 = new Date(Date.UTC(year, 0, 4));
  20125. dayOfYear = (weekNumber * 7) + dayOfWeek - january4.getUTCDay() - 3;
  20126. } else {
  20127. //None of our regular expressions succeeded in parsing the date properly.
  20128. throw new DeveloperError(iso8601ErrorMessage);
  20129. }
  20130. }
  20131. //Split an ordinal date into month/day.
  20132. tmp = new Date(Date.UTC(year, 0, 1));
  20133. tmp.setUTCDate(dayOfYear);
  20134. month = tmp.getUTCMonth() + 1;
  20135. day = tmp.getUTCDate();
  20136. }
  20137. }
  20138. }
  20139. //Now that we have all of the date components, validate them to make sure nothing is out of range.
  20140. inLeapYear = isLeapYear(year);
  20141. if (month < 1 || month > 12 || day < 1 || ((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) || (inLeapYear && month === 2 && day > daysInLeapFeburary)) {
  20142. throw new DeveloperError(iso8601ErrorMessage);
  20143. }
  20144. //Not move onto the time string, which is much simpler.
  20145. var offsetIndex;
  20146. if (defined(time)) {
  20147. tokens = time.match(matchHoursMinutesSeconds);
  20148. if (tokens !== null) {
  20149. dashCount = time.split(':').length - 1;
  20150. if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
  20151. throw new DeveloperError(iso8601ErrorMessage);
  20152. }
  20153. hour = +tokens[1];
  20154. minute = +tokens[2];
  20155. second = +tokens[3];
  20156. millisecond = +(tokens[4] || 0) * 1000.0;
  20157. offsetIndex = 5;
  20158. } else {
  20159. tokens = time.match(matchHoursMinutes);
  20160. if (tokens !== null) {
  20161. dashCount = time.split(':').length - 1;
  20162. if (dashCount > 2) {
  20163. throw new DeveloperError(iso8601ErrorMessage);
  20164. }
  20165. hour = +tokens[1];
  20166. minute = +tokens[2];
  20167. second = +(tokens[3] || 0) * 60.0;
  20168. offsetIndex = 4;
  20169. } else {
  20170. tokens = time.match(matchHours);
  20171. if (tokens !== null) {
  20172. hour = +tokens[1];
  20173. minute = +(tokens[2] || 0) * 60.0;
  20174. offsetIndex = 3;
  20175. } else {
  20176. throw new DeveloperError(iso8601ErrorMessage);
  20177. }
  20178. }
  20179. }
  20180. //Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
  20181. if (minute >= 60 || second >= 61 || hour > 24 || (hour === 24 && (minute > 0 || second > 0 || millisecond > 0))) {
  20182. throw new DeveloperError(iso8601ErrorMessage);
  20183. }
  20184. //Check the UTC offset value, if no value exists, use local time
  20185. //a Z indicates UTC, + or - are offsets.
  20186. var offset = tokens[offsetIndex];
  20187. var offsetHours = +(tokens[offsetIndex + 1]);
  20188. var offsetMinutes = +(tokens[offsetIndex + 2] || 0);
  20189. switch (offset) {
  20190. case '+':
  20191. hour = hour - offsetHours;
  20192. minute = minute - offsetMinutes;
  20193. break;
  20194. case '-':
  20195. hour = hour + offsetHours;
  20196. minute = minute + offsetMinutes;
  20197. break;
  20198. case 'Z':
  20199. break;
  20200. default:
  20201. minute = minute + new Date(Date.UTC(year, month - 1, day, hour, minute)).getTimezoneOffset();
  20202. break;
  20203. }
  20204. } else {
  20205. //If no time is specified, it is considered the beginning of the day, local time.
  20206. minute = minute + new Date(year, month - 1, day).getTimezoneOffset();
  20207. }
  20208. //ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
  20209. //If that's the case, we need to temporarily subtract a second in order to build a UTC date.
  20210. //Then we add it back in after converting to TAI.
  20211. var isLeapSecond = second === 60;
  20212. if (isLeapSecond) {
  20213. second--;
  20214. }
  20215. //Even if we successfully parsed the string into its components, after applying UTC offset or
  20216. //special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
  20217. //milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
  20218. while (minute >= 60) {
  20219. minute -= 60;
  20220. hour++;
  20221. }
  20222. while (hour >= 24) {
  20223. hour -= 24;
  20224. day++;
  20225. }
  20226. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  20227. while (day > tmp) {
  20228. day -= tmp;
  20229. month++;
  20230. if (month > 12) {
  20231. month -= 12;
  20232. year++;
  20233. }
  20234. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  20235. }
  20236. //If UTC offset is at the beginning/end of the day, minutes can be negative.
  20237. while (minute < 0) {
  20238. minute += 60;
  20239. hour--;
  20240. }
  20241. while (hour < 0) {
  20242. hour += 24;
  20243. day--;
  20244. }
  20245. while (day < 1) {
  20246. month--;
  20247. if (month < 1) {
  20248. month += 12;
  20249. year--;
  20250. }
  20251. tmp = (inLeapYear && month === 2) ? daysInLeapFeburary : daysInMonth[month - 1];
  20252. day += tmp;
  20253. }
  20254. //Now create the JulianDate components from the Gregorian date and actually create our instance.
  20255. var components = computeJulianDateComponents(year, month, day, hour, minute, second, millisecond);
  20256. if (!defined(result)) {
  20257. result = new JulianDate(components[0], components[1], TimeStandard.UTC);
  20258. } else {
  20259. setComponents(components[0], components[1], result);
  20260. convertUtcToTai(result);
  20261. }
  20262. //If we were on a leap second, add it back.
  20263. if (isLeapSecond) {
  20264. JulianDate.addSeconds(result, 1, result);
  20265. }
  20266. return result;
  20267. };
  20268. /**
  20269. * Creates a new instance that represents the current system time.
  20270. * This is equivalent to calling <code>JulianDate.fromDate(new Date());</code>.
  20271. *
  20272. * @param {JulianDate} [result] An existing instance to use for the result.
  20273. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  20274. */
  20275. JulianDate.now = function(result) {
  20276. return JulianDate.fromDate(new Date(), result);
  20277. };
  20278. var toGregorianDateScratch = new JulianDate(0, 0, TimeStandard.TAI);
  20279. /**
  20280. * Creates a {@link GregorianDate} from the provided instance.
  20281. *
  20282. * @param {JulianDate} julianDate The date to be converted.
  20283. * @param {GregorianDate} [result] An existing instance to use for the result.
  20284. * @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
  20285. */
  20286. JulianDate.toGregorianDate = function(julianDate, result) {
  20287. if (!defined(julianDate)) {
  20288. throw new DeveloperError('julianDate is required.');
  20289. }
  20290. var isLeapSecond = false;
  20291. var thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
  20292. if (!defined(thisUtc)) {
  20293. //Conversion to UTC will fail if we are during a leap second.
  20294. //If that's the case, subtract a second and convert again.
  20295. //JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
  20296. JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
  20297. thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
  20298. isLeapSecond = true;
  20299. }
  20300. var julianDayNumber = thisUtc.dayNumber;
  20301. var secondsOfDay = thisUtc.secondsOfDay;
  20302. if (secondsOfDay >= 43200.0) {
  20303. julianDayNumber += 1;
  20304. }
  20305. // Algorithm from page 604 of the Explanatory Supplement to the
  20306. // Astronomical Almanac (Seidelmann 1992).
  20307. var L = (julianDayNumber + 68569) | 0;
  20308. var N = (4 * L / 146097) | 0;
  20309. L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
  20310. var I = ((4000 * (L + 1)) / 1461001) | 0;
  20311. L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
  20312. var J = ((80 * L) / 2447) | 0;
  20313. var day = (L - (((2447 * J) / 80) | 0)) | 0;
  20314. L = (J / 11) | 0;
  20315. var month = (J + 2 - 12 * L) | 0;
  20316. var year = (100 * (N - 49) + I + L) | 0;
  20317. var hour = (secondsOfDay / TimeConstants.SECONDS_PER_HOUR) | 0;
  20318. var remainingSeconds = secondsOfDay - (hour * TimeConstants.SECONDS_PER_HOUR);
  20319. var minute = (remainingSeconds / TimeConstants.SECONDS_PER_MINUTE) | 0;
  20320. remainingSeconds = remainingSeconds - (minute * TimeConstants.SECONDS_PER_MINUTE);
  20321. var second = remainingSeconds | 0;
  20322. var millisecond = ((remainingSeconds - second) / TimeConstants.SECONDS_PER_MILLISECOND);
  20323. // JulianDates are noon-based
  20324. hour += 12;
  20325. if (hour > 23) {
  20326. hour -= 24;
  20327. }
  20328. //If we were on a leap second, add it back.
  20329. if (isLeapSecond) {
  20330. second += 1;
  20331. }
  20332. if (!defined(result)) {
  20333. return new GregorianDate(year, month, day, hour, minute, second, millisecond, isLeapSecond);
  20334. }
  20335. result.year = year;
  20336. result.month = month;
  20337. result.day = day;
  20338. result.hour = hour;
  20339. result.minute = minute;
  20340. result.second = second;
  20341. result.millisecond = millisecond;
  20342. result.isLeapSecond = isLeapSecond;
  20343. return result;
  20344. };
  20345. /**
  20346. * Creates a JavaScript Date from the provided instance.
  20347. * Since JavaScript dates are only accurate to the nearest millisecond and
  20348. * cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
  20349. * If the provided JulianDate is during a leap second, the previous second is used.
  20350. *
  20351. * @param {JulianDate} julianDate The date to be converted.
  20352. * @returns {Date} A new instance representing the provided date.
  20353. */
  20354. JulianDate.toDate = function(julianDate) {
  20355. if (!defined(julianDate)) {
  20356. throw new DeveloperError('julianDate is required.');
  20357. }
  20358. var gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
  20359. var second = gDate.second;
  20360. if (gDate.isLeapSecond) {
  20361. second -= 1;
  20362. }
  20363. return new Date(Date.UTC(gDate.year, gDate.month - 1, gDate.day, gDate.hour, gDate.minute, second, gDate.millisecond));
  20364. };
  20365. /**
  20366. * Creates an ISO8601 representation of the provided date.
  20367. *
  20368. * @param {JulianDate} julianDate The date to be converted.
  20369. * @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
  20370. * @returns {String} The ISO8601 representation of the provided date.
  20371. */
  20372. JulianDate.toIso8601 = function(julianDate, precision) {
  20373. if (!defined(julianDate)) {
  20374. throw new DeveloperError('julianDate is required.');
  20375. }
  20376. var gDate = JulianDate.toGregorianDate(julianDate, gDate);
  20377. var millisecondStr;
  20378. if (!defined(precision) && gDate.millisecond !== 0) {
  20379. //Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
  20380. millisecondStr = (gDate.millisecond * 0.01).toString().replace('.', '');
  20381. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  20382. }
  20383. //Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
  20384. if (!defined(precision) || precision === 0) {
  20385. return sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second);
  20386. }
  20387. //Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
  20388. millisecondStr = (gDate.millisecond * 0.01).toFixed(precision).replace('.', '').slice(0, precision);
  20389. return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%sZ", gDate.year, gDate.month, gDate.day, gDate.hour, gDate.minute, gDate.second, millisecondStr);
  20390. };
  20391. /**
  20392. * Duplicates a JulianDate instance.
  20393. *
  20394. * @param {JulianDate} julianDate The date to duplicate.
  20395. * @param {JulianDate} [result] An existing instance to use for the result.
  20396. * @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
  20397. */
  20398. JulianDate.clone = function(julianDate, result) {
  20399. if (!defined(julianDate)) {
  20400. return undefined;
  20401. }
  20402. if (!defined(result)) {
  20403. return new JulianDate(julianDate.dayNumber, julianDate.secondsOfDay, TimeStandard.TAI);
  20404. }
  20405. result.dayNumber = julianDate.dayNumber;
  20406. result.secondsOfDay = julianDate.secondsOfDay;
  20407. return result;
  20408. };
  20409. /**
  20410. * Compares two instances.
  20411. *
  20412. * @param {JulianDate} left The first instance.
  20413. * @param {JulianDate} right The second instance.
  20414. * @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.
  20415. */
  20416. JulianDate.compare = function(left, right) {
  20417. if (!defined(left)) {
  20418. throw new DeveloperError('left is required.');
  20419. }
  20420. if (!defined(right)) {
  20421. throw new DeveloperError('right is required.');
  20422. }
  20423. var julianDayNumberDifference = left.dayNumber - right.dayNumber;
  20424. if (julianDayNumberDifference !== 0) {
  20425. return julianDayNumberDifference;
  20426. }
  20427. return left.secondsOfDay - right.secondsOfDay;
  20428. };
  20429. /**
  20430. * Compares two instances and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  20431. *
  20432. * @param {JulianDate} [left] The first instance.
  20433. * @param {JulianDate} [right] The second instance.
  20434. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  20435. */
  20436. JulianDate.equals = function(left, right) {
  20437. return (left === right) ||
  20438. (defined(left) &&
  20439. defined(right) &&
  20440. left.dayNumber === right.dayNumber &&
  20441. left.secondsOfDay === right.secondsOfDay);
  20442. };
  20443. /**
  20444. * Compares two instances and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  20445. * each other. That is, in order for the dates to be considered equal (and for
  20446. * this function to return <code>true</code>), the absolute value of the difference between them, in
  20447. * seconds, must be less than <code>epsilon</code>.
  20448. *
  20449. * @param {JulianDate} [left] The first instance.
  20450. * @param {JulianDate} [right] The second instance.
  20451. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  20452. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  20453. */
  20454. JulianDate.equalsEpsilon = function(left, right, epsilon) {
  20455. if (!defined(epsilon)) {
  20456. throw new DeveloperError('epsilon is required.');
  20457. }
  20458. return (left === right) ||
  20459. (defined(left) &&
  20460. defined(right) &&
  20461. Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon);
  20462. };
  20463. /**
  20464. * Computes the total number of whole and fractional days represented by the provided instance.
  20465. *
  20466. * @param {JulianDate} julianDate The date.
  20467. * @returns {Number} The Julian date as single floating point number.
  20468. */
  20469. JulianDate.totalDays = function(julianDate) {
  20470. if (!defined(julianDate)) {
  20471. throw new DeveloperError('julianDate is required.');
  20472. }
  20473. return julianDate.dayNumber + (julianDate.secondsOfDay / TimeConstants.SECONDS_PER_DAY);
  20474. };
  20475. /**
  20476. * Computes the difference in seconds between the provided instance.
  20477. *
  20478. * @param {JulianDate} left The first instance.
  20479. * @param {JulianDate} right The second instance.
  20480. * @returns {Number} The difference, in seconds, when subtracting <code>right</code> from <code>left</code>.
  20481. */
  20482. JulianDate.secondsDifference = function(left, right) {
  20483. if (!defined(left)) {
  20484. throw new DeveloperError('left is required.');
  20485. }
  20486. if (!defined(right)) {
  20487. throw new DeveloperError('right is required.');
  20488. }
  20489. var dayDifference = (left.dayNumber - right.dayNumber) * TimeConstants.SECONDS_PER_DAY;
  20490. return (dayDifference + (left.secondsOfDay - right.secondsOfDay));
  20491. };
  20492. /**
  20493. * Computes the difference in days between the provided instance.
  20494. *
  20495. * @param {JulianDate} left The first instance.
  20496. * @param {JulianDate} right The second instance.
  20497. * @returns {Number} The difference, in days, when subtracting <code>right</code> from <code>left</code>.
  20498. */
  20499. JulianDate.daysDifference = function(left, right) {
  20500. if (!defined(left)) {
  20501. throw new DeveloperError('left is required.');
  20502. }
  20503. if (!defined(right)) {
  20504. throw new DeveloperError('right is required.');
  20505. }
  20506. var dayDifference = (left.dayNumber - right.dayNumber);
  20507. var secondDifference = (left.secondsOfDay - right.secondsOfDay) / TimeConstants.SECONDS_PER_DAY;
  20508. return dayDifference + secondDifference;
  20509. };
  20510. /**
  20511. * Computes the number of seconds the provided instance is ahead of UTC.
  20512. *
  20513. * @param {JulianDate} julianDate The date.
  20514. * @returns {Number} The number of seconds the provided instance is ahead of UTC
  20515. */
  20516. JulianDate.computeTaiMinusUtc = function(julianDate) {
  20517. binarySearchScratchLeapSecond.julianDate = julianDate;
  20518. var leapSeconds = JulianDate.leapSeconds;
  20519. var index = binarySearch(leapSeconds, binarySearchScratchLeapSecond, compareLeapSecondDates);
  20520. if (index < 0) {
  20521. index = ~index;
  20522. --index;
  20523. if (index < 0) {
  20524. index = 0;
  20525. }
  20526. }
  20527. return leapSeconds[index].offset;
  20528. };
  20529. /**
  20530. * Adds the provided number of seconds to the provided date instance.
  20531. *
  20532. * @param {JulianDate} julianDate The date.
  20533. * @param {Number} seconds The number of seconds to add or subtract.
  20534. * @param {JulianDate} result An existing instance to use for the result.
  20535. * @returns {JulianDate} The modified result parameter.
  20536. */
  20537. JulianDate.addSeconds = function(julianDate, seconds, result) {
  20538. if (!defined(julianDate)) {
  20539. throw new DeveloperError('julianDate is required.');
  20540. }
  20541. if (!defined(seconds)) {
  20542. throw new DeveloperError('seconds is required.');
  20543. }
  20544. if (!defined(result)) {
  20545. throw new DeveloperError('result is required.');
  20546. }
  20547. return setComponents(julianDate.dayNumber, julianDate.secondsOfDay + seconds, result);
  20548. };
  20549. /**
  20550. * Adds the provided number of minutes to the provided date instance.
  20551. *
  20552. * @param {JulianDate} julianDate The date.
  20553. * @param {Number} minutes The number of minutes to add or subtract.
  20554. * @param {JulianDate} result An existing instance to use for the result.
  20555. * @returns {JulianDate} The modified result parameter.
  20556. */
  20557. JulianDate.addMinutes = function(julianDate, minutes, result) {
  20558. if (!defined(julianDate)) {
  20559. throw new DeveloperError('julianDate is required.');
  20560. }
  20561. if (!defined(minutes)) {
  20562. throw new DeveloperError('minutes is required.');
  20563. }
  20564. if (!defined(result)) {
  20565. throw new DeveloperError('result is required.');
  20566. }
  20567. var newSecondsOfDay = julianDate.secondsOfDay + (minutes * TimeConstants.SECONDS_PER_MINUTE);
  20568. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  20569. };
  20570. /**
  20571. * Adds the provided number of hours to the provided date instance.
  20572. *
  20573. * @param {JulianDate} julianDate The date.
  20574. * @param {Number} hours The number of hours to add or subtract.
  20575. * @param {JulianDate} result An existing instance to use for the result.
  20576. * @returns {JulianDate} The modified result parameter.
  20577. */
  20578. JulianDate.addHours = function(julianDate, hours, result) {
  20579. if (!defined(julianDate)) {
  20580. throw new DeveloperError('julianDate is required.');
  20581. }
  20582. if (!defined(hours)) {
  20583. throw new DeveloperError('hours is required.');
  20584. }
  20585. if (!defined(result)) {
  20586. throw new DeveloperError('result is required.');
  20587. }
  20588. var newSecondsOfDay = julianDate.secondsOfDay + (hours * TimeConstants.SECONDS_PER_HOUR);
  20589. return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
  20590. };
  20591. /**
  20592. * Adds the provided number of days to the provided date instance.
  20593. *
  20594. * @param {JulianDate} julianDate The date.
  20595. * @param {Number} days The number of days to add or subtract.
  20596. * @param {JulianDate} result An existing instance to use for the result.
  20597. * @returns {JulianDate} The modified result parameter.
  20598. */
  20599. JulianDate.addDays = function(julianDate, days, result) {
  20600. if (!defined(julianDate)) {
  20601. throw new DeveloperError('julianDate is required.');
  20602. }
  20603. if (!defined(days)) {
  20604. throw new DeveloperError('days is required.');
  20605. }
  20606. if (!defined(result)) {
  20607. throw new DeveloperError('result is required.');
  20608. }
  20609. var newJulianDayNumber = julianDate.dayNumber + days;
  20610. return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
  20611. };
  20612. /**
  20613. * Compares the provided instances and returns <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  20614. *
  20615. * @param {JulianDate} left The first instance.
  20616. * @param {JulianDate} right The second instance.
  20617. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than <code>right</code>, <code>false</code> otherwise.
  20618. */
  20619. JulianDate.lessThan = function(left, right) {
  20620. return JulianDate.compare(left, right) < 0;
  20621. };
  20622. /**
  20623. * 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.
  20624. *
  20625. * @param {JulianDate} left The first instance.
  20626. * @param {JulianDate} right The second instance.
  20627. * @returns {Boolean} <code>true</code> if <code>left</code> is earlier than or equal to <code>right</code>, <code>false</code> otherwise.
  20628. */
  20629. JulianDate.lessThanOrEquals = function(left, right) {
  20630. return JulianDate.compare(left, right) <= 0;
  20631. };
  20632. /**
  20633. * Compares the provided instances and returns <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  20634. *
  20635. * @param {JulianDate} left The first instance.
  20636. * @param {JulianDate} right The second instance.
  20637. * @returns {Boolean} <code>true</code> if <code>left</code> is later than <code>right</code>, <code>false</code> otherwise.
  20638. */
  20639. JulianDate.greaterThan = function(left, right) {
  20640. return JulianDate.compare(left, right) > 0;
  20641. };
  20642. /**
  20643. * 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.
  20644. *
  20645. * @param {JulianDate} left The first instance.
  20646. * @param {JulianDate} right The second instance.
  20647. * @returns {Boolean} <code>true</code> if <code>left</code> is later than or equal to <code>right</code>, <code>false</code> otherwise.
  20648. */
  20649. JulianDate.greaterThanOrEquals = function(left, right) {
  20650. return JulianDate.compare(left, right) >= 0;
  20651. };
  20652. /**
  20653. * Duplicates this instance.
  20654. *
  20655. * @param {JulianDate} [result] An existing instance to use for the result.
  20656. * @returns {JulianDate} The modified result parameter or a new instance if none was provided.
  20657. */
  20658. JulianDate.prototype.clone = function(result) {
  20659. return JulianDate.clone(this, result);
  20660. };
  20661. /**
  20662. * Compares this and the provided instance and returns <code>true</code> if they are equal, <code>false</code> otherwise.
  20663. *
  20664. * @param {JulianDate} [right] The second instance.
  20665. * @returns {Boolean} <code>true</code> if the dates are equal; otherwise, <code>false</code>.
  20666. */
  20667. JulianDate.prototype.equals = function(right) {
  20668. return JulianDate.equals(this, right);
  20669. };
  20670. /**
  20671. * Compares this and the provided instance and returns <code>true</code> if they are within <code>epsilon</code> seconds of
  20672. * each other. That is, in order for the dates to be considered equal (and for
  20673. * this function to return <code>true</code>), the absolute value of the difference between them, in
  20674. * seconds, must be less than <code>epsilon</code>.
  20675. *
  20676. * @param {JulianDate} [right] The second instance.
  20677. * @param {Number} epsilon The maximum number of seconds that should separate the two instances.
  20678. * @returns {Boolean} <code>true</code> if the two dates are within <code>epsilon</code> seconds of each other; otherwise <code>false</code>.
  20679. */
  20680. JulianDate.prototype.equalsEpsilon = function(right, epsilon) {
  20681. return JulianDate.equalsEpsilon(this, right, epsilon);
  20682. };
  20683. /**
  20684. * Creates a string representing this date in ISO8601 format.
  20685. *
  20686. * @returns {String} A string representing this date in ISO8601 format.
  20687. */
  20688. JulianDate.prototype.toString = function() {
  20689. return JulianDate.toIso8601(this);
  20690. };
  20691. /**
  20692. * Gets or sets the list of leap seconds used throughout Cesium.
  20693. * @memberof JulianDate
  20694. * @type {LeapSecond[]}
  20695. */
  20696. JulianDate.leapSeconds = [
  20697. new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard.TAI), 10), // January 1, 1972 00:00:00 UTC
  20698. new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard.TAI), 11), // July 1, 1972 00:00:00 UTC
  20699. new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard.TAI), 12), // January 1, 1973 00:00:00 UTC
  20700. new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard.TAI), 13), // January 1, 1974 00:00:00 UTC
  20701. new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard.TAI), 14), // January 1, 1975 00:00:00 UTC
  20702. new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard.TAI), 15), // January 1, 1976 00:00:00 UTC
  20703. new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard.TAI), 16), // January 1, 1977 00:00:00 UTC
  20704. new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard.TAI), 17), // January 1, 1978 00:00:00 UTC
  20705. new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard.TAI), 18), // January 1, 1979 00:00:00 UTC
  20706. new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard.TAI), 19), // January 1, 1980 00:00:00 UTC
  20707. new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard.TAI), 20), // July 1, 1981 00:00:00 UTC
  20708. new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard.TAI), 21), // July 1, 1982 00:00:00 UTC
  20709. new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard.TAI), 22), // July 1, 1983 00:00:00 UTC
  20710. new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard.TAI), 23), // July 1, 1985 00:00:00 UTC
  20711. new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard.TAI), 24), // January 1, 1988 00:00:00 UTC
  20712. new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard.TAI), 25), // January 1, 1990 00:00:00 UTC
  20713. new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard.TAI), 26), // January 1, 1991 00:00:00 UTC
  20714. new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard.TAI), 27), // July 1, 1992 00:00:00 UTC
  20715. new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard.TAI), 28), // July 1, 1993 00:00:00 UTC
  20716. new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard.TAI), 29), // July 1, 1994 00:00:00 UTC
  20717. new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard.TAI), 30), // January 1, 1996 00:00:00 UTC
  20718. new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard.TAI), 31), // July 1, 1997 00:00:00 UTC
  20719. new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard.TAI), 32), // January 1, 1999 00:00:00 UTC
  20720. new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard.TAI), 33), // January 1, 2006 00:00:00 UTC
  20721. new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard.TAI), 34), // January 1, 2009 00:00:00 UTC
  20722. new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard.TAI), 35), // July 1, 2012 00:00:00 UTC
  20723. new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard.TAI), 36), // July 1, 2015 00:00:00 UTC
  20724. new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard.TAI), 37) // January 1, 2017 00:00:00 UTC
  20725. ];
  20726. return JulianDate;
  20727. });
  20728. /*global define*/
  20729. define('Core/clone',[
  20730. './defaultValue'
  20731. ], function(
  20732. defaultValue) {
  20733. 'use strict';
  20734. /**
  20735. * Clones an object, returning a new object containing the same properties.
  20736. *
  20737. * @exports clone
  20738. *
  20739. * @param {Object} object The object to clone.
  20740. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  20741. * @returns {Object} The cloned object.
  20742. */
  20743. function clone(object, deep) {
  20744. if (object === null || typeof object !== 'object') {
  20745. return object;
  20746. }
  20747. deep = defaultValue(deep, false);
  20748. var result = new object.constructor();
  20749. for ( var propertyName in object) {
  20750. if (object.hasOwnProperty(propertyName)) {
  20751. var value = object[propertyName];
  20752. if (deep) {
  20753. value = clone(value, deep);
  20754. }
  20755. result[propertyName] = value;
  20756. }
  20757. }
  20758. return result;
  20759. }
  20760. return clone;
  20761. });
  20762. /*global define*/
  20763. define('Core/parseResponseHeaders',[], function() {
  20764. 'use strict';
  20765. /**
  20766. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  20767. * a dictionary.
  20768. *
  20769. * @exports parseResponseHeaders
  20770. *
  20771. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  20772. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  20773. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  20774. * is that header's value.
  20775. *
  20776. * @private
  20777. */
  20778. function parseResponseHeaders(headerString) {
  20779. var headers = {};
  20780. if (!headerString) {
  20781. return headers;
  20782. }
  20783. var headerPairs = headerString.split('\u000d\u000a');
  20784. for (var i = 0; i < headerPairs.length; ++i) {
  20785. var headerPair = headerPairs[i];
  20786. // Can't use split() here because it does the wrong thing
  20787. // if the header value has the string ": " in it.
  20788. var index = headerPair.indexOf('\u003a\u0020');
  20789. if (index > 0) {
  20790. var key = headerPair.substring(0, index);
  20791. var val = headerPair.substring(index + 2);
  20792. headers[key] = val;
  20793. }
  20794. }
  20795. return headers;
  20796. }
  20797. return parseResponseHeaders;
  20798. });
  20799. /*global define*/
  20800. define('Core/RequestErrorEvent',[
  20801. './defined',
  20802. './parseResponseHeaders'
  20803. ], function(
  20804. defined,
  20805. parseResponseHeaders) {
  20806. 'use strict';
  20807. /**
  20808. * An event that is raised when a request encounters an error.
  20809. *
  20810. * @constructor
  20811. * @alias RequestErrorEvent
  20812. *
  20813. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  20814. * @param {Object} [response] The response included along with the error.
  20815. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  20816. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  20817. */
  20818. function RequestErrorEvent(statusCode, response, responseHeaders) {
  20819. /**
  20820. * The HTTP error status code, such as 404. If the error does not have a particular
  20821. * HTTP code, this property will be undefined.
  20822. *
  20823. * @type {Number}
  20824. */
  20825. this.statusCode = statusCode;
  20826. /**
  20827. * The response included along with the error. If the error does not include a response,
  20828. * this property will be undefined.
  20829. *
  20830. * @type {Object}
  20831. */
  20832. this.response = response;
  20833. /**
  20834. * The headers included in the response, represented as an object literal of key/value pairs.
  20835. * If the error does not include any headers, this property will be undefined.
  20836. *
  20837. * @type {Object}
  20838. */
  20839. this.responseHeaders = responseHeaders;
  20840. if (typeof this.responseHeaders === 'string') {
  20841. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  20842. }
  20843. }
  20844. /**
  20845. * Creates a string representing this RequestErrorEvent.
  20846. * @memberof RequestErrorEvent
  20847. *
  20848. * @returns {String} A string representing the provided RequestErrorEvent.
  20849. */
  20850. RequestErrorEvent.prototype.toString = function() {
  20851. var str = 'Request has failed.';
  20852. if (defined(this.statusCode)) {
  20853. str += ' Status Code: ' + this.statusCode;
  20854. }
  20855. return str;
  20856. };
  20857. return RequestErrorEvent;
  20858. });
  20859. /**
  20860. * @license
  20861. *
  20862. * Grauw URI utilities
  20863. *
  20864. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  20865. *
  20866. * @author Laurens Holst (http://www.grauw.nl/)
  20867. *
  20868. * Copyright 2012 Laurens Holst
  20869. *
  20870. * Licensed under the Apache License, Version 2.0 (the "License");
  20871. * you may not use this file except in compliance with the License.
  20872. * You may obtain a copy of the License at
  20873. *
  20874. * http://www.apache.org/licenses/LICENSE-2.0
  20875. *
  20876. * Unless required by applicable law or agreed to in writing, software
  20877. * distributed under the License is distributed on an "AS IS" BASIS,
  20878. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20879. * See the License for the specific language governing permissions and
  20880. * limitations under the License.
  20881. *
  20882. */
  20883. /*global define*/
  20884. define('ThirdParty/Uri',[],function() {
  20885. /**
  20886. * Constructs a URI object.
  20887. * @constructor
  20888. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  20889. * @param {string|URI} uri A string or URI object to create the object from.
  20890. */
  20891. function URI(uri) {
  20892. if (uri instanceof URI) { // copy constructor
  20893. this.scheme = uri.scheme;
  20894. this.authority = uri.authority;
  20895. this.path = uri.path;
  20896. this.query = uri.query;
  20897. this.fragment = uri.fragment;
  20898. } else if (uri) { // uri is URI string or cast to string
  20899. var c = parseRegex.exec(uri);
  20900. this.scheme = c[1];
  20901. this.authority = c[2];
  20902. this.path = c[3];
  20903. this.query = c[4];
  20904. this.fragment = c[5];
  20905. }
  20906. }
  20907. // Initial values on the prototype
  20908. URI.prototype.scheme = null;
  20909. URI.prototype.authority = null;
  20910. URI.prototype.path = '';
  20911. URI.prototype.query = null;
  20912. URI.prototype.fragment = null;
  20913. // Regular expression from RFC 3986 appendix B
  20914. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  20915. /**
  20916. * Returns the scheme part of the URI.
  20917. * In "http://example.com:80/a/b?x#y" this is "http".
  20918. */
  20919. URI.prototype.getScheme = function() {
  20920. return this.scheme;
  20921. };
  20922. /**
  20923. * Returns the authority part of the URI.
  20924. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  20925. */
  20926. URI.prototype.getAuthority = function() {
  20927. return this.authority;
  20928. };
  20929. /**
  20930. * Returns the path part of the URI.
  20931. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  20932. * In "mailto:mike@example.com" this is "mike@example.com".
  20933. */
  20934. URI.prototype.getPath = function() {
  20935. return this.path;
  20936. };
  20937. /**
  20938. * Returns the query part of the URI.
  20939. * In "http://example.com:80/a/b?x#y" this is "x".
  20940. */
  20941. URI.prototype.getQuery = function() {
  20942. return this.query;
  20943. };
  20944. /**
  20945. * Returns the fragment part of the URI.
  20946. * In "http://example.com:80/a/b?x#y" this is "y".
  20947. */
  20948. URI.prototype.getFragment = function() {
  20949. return this.fragment;
  20950. };
  20951. /**
  20952. * Tests whether the URI is an absolute URI.
  20953. * See RFC 3986 section 4.3.
  20954. */
  20955. URI.prototype.isAbsolute = function() {
  20956. return !!this.scheme && !this.fragment;
  20957. };
  20958. ///**
  20959. //* Extensive validation of the URI against the ABNF in RFC 3986
  20960. //*/
  20961. //URI.prototype.validate
  20962. /**
  20963. * Tests whether the URI is a same-document reference.
  20964. * See RFC 3986 section 4.4.
  20965. *
  20966. * To perform more thorough comparison, you can normalise the URI objects.
  20967. */
  20968. URI.prototype.isSameDocumentAs = function(uri) {
  20969. return uri.scheme == this.scheme &&
  20970. uri.authority == this.authority &&
  20971. uri.path == this.path &&
  20972. uri.query == this.query;
  20973. };
  20974. /**
  20975. * Simple String Comparison of two URIs.
  20976. * See RFC 3986 section 6.2.1.
  20977. *
  20978. * To perform more thorough comparison, you can normalise the URI objects.
  20979. */
  20980. URI.prototype.equals = function(uri) {
  20981. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  20982. };
  20983. /**
  20984. * Normalizes the URI using syntax-based normalization.
  20985. * This includes case normalization, percent-encoding normalization and path segment normalization.
  20986. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  20987. * (Although that would not be a valid URI in the first place. See validate().)
  20988. * See RFC 3986 section 6.2.2.
  20989. */
  20990. URI.prototype.normalize = function() {
  20991. this.removeDotSegments();
  20992. if (this.scheme)
  20993. this.scheme = this.scheme.toLowerCase();
  20994. if (this.authority)
  20995. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  20996. replace(caseRegex, replaceCase);
  20997. if (this.path)
  20998. this.path = this.path.replace(caseRegex, replaceCase);
  20999. if (this.query)
  21000. this.query = this.query.replace(caseRegex, replaceCase);
  21001. if (this.fragment)
  21002. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  21003. };
  21004. var caseRegex = /%[0-9a-z]{2}/gi;
  21005. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  21006. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  21007. function replaceCase(str) {
  21008. var dec = unescape(str);
  21009. return percentRegex.test(dec) ? dec : str.toUpperCase();
  21010. }
  21011. function replaceAuthority(str, p1, p2, p3) {
  21012. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  21013. }
  21014. /**
  21015. * Resolve a relative URI (this) against a base URI.
  21016. * The base URI must be an absolute URI.
  21017. * See RFC 3986 section 5.2
  21018. */
  21019. URI.prototype.resolve = function(baseURI) {
  21020. var uri = new URI();
  21021. if (this.scheme) {
  21022. uri.scheme = this.scheme;
  21023. uri.authority = this.authority;
  21024. uri.path = this.path;
  21025. uri.query = this.query;
  21026. } else {
  21027. uri.scheme = baseURI.scheme;
  21028. if (this.authority) {
  21029. uri.authority = this.authority;
  21030. uri.path = this.path;
  21031. uri.query = this.query;
  21032. } else {
  21033. uri.authority = baseURI.authority;
  21034. if (this.path == '') {
  21035. uri.path = baseURI.path;
  21036. uri.query = this.query || baseURI.query;
  21037. } else {
  21038. if (this.path.charAt(0) == '/') {
  21039. uri.path = this.path;
  21040. uri.removeDotSegments();
  21041. } else {
  21042. if (baseURI.authority && baseURI.path == '') {
  21043. uri.path = '/' + this.path;
  21044. } else {
  21045. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  21046. }
  21047. uri.removeDotSegments();
  21048. }
  21049. uri.query = this.query;
  21050. }
  21051. }
  21052. }
  21053. uri.fragment = this.fragment;
  21054. return uri;
  21055. };
  21056. /**
  21057. * Remove dot segments from path.
  21058. * See RFC 3986 section 5.2.4
  21059. * @private
  21060. */
  21061. URI.prototype.removeDotSegments = function() {
  21062. var input = this.path.split('/'),
  21063. output = [],
  21064. segment,
  21065. absPath = input[0] == '';
  21066. if (absPath)
  21067. input.shift();
  21068. var sFirst = input[0] == '' ? input.shift() : null;
  21069. while (input.length) {
  21070. segment = input.shift();
  21071. if (segment == '..') {
  21072. output.pop();
  21073. } else if (segment != '.') {
  21074. output.push(segment);
  21075. }
  21076. }
  21077. if (segment == '.' || segment == '..')
  21078. output.push('');
  21079. if (absPath)
  21080. output.unshift('');
  21081. this.path = output.join('/');
  21082. };
  21083. // We don't like this function because it builds up a cache that is never cleared.
  21084. // /**
  21085. // * Resolves a relative URI against an absolute base URI.
  21086. // * Convenience method.
  21087. // * @param {String} uri the relative URI to resolve
  21088. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  21089. // */
  21090. // URI.resolve = function(sURI, sBaseURI) {
  21091. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  21092. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  21093. // return uri.resolve(baseURI).toString();
  21094. // };
  21095. // var cache = {};
  21096. /**
  21097. * Serialises the URI to a string.
  21098. */
  21099. URI.prototype.toString = function() {
  21100. var result = '';
  21101. if (this.scheme)
  21102. result += this.scheme + ':';
  21103. if (this.authority)
  21104. result += '//' + this.authority;
  21105. result += this.path;
  21106. if (this.query)
  21107. result += '?' + this.query;
  21108. if (this.fragment)
  21109. result += '#' + this.fragment;
  21110. return result;
  21111. };
  21112. return URI;
  21113. });
  21114. /*global define*/
  21115. define('Core/TrustedServers',[
  21116. '../ThirdParty/Uri',
  21117. './defined',
  21118. './DeveloperError'
  21119. ], function(
  21120. Uri,
  21121. defined,
  21122. DeveloperError) {
  21123. 'use strict';
  21124. /**
  21125. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  21126. * any requests to these servers.
  21127. *
  21128. * @exports TrustedServers
  21129. *
  21130. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  21131. */
  21132. var TrustedServers = {};
  21133. var _servers = {};
  21134. /**
  21135. * Adds a trusted server to the registry
  21136. *
  21137. * @param {String} host The host to be added.
  21138. * @param {Number} port The port used to access the host.
  21139. *
  21140. * @example
  21141. * // Add a trusted server
  21142. * TrustedServers.add('my.server.com', 80);
  21143. */
  21144. TrustedServers.add = function(host, port) {
  21145. if (!defined(host)) {
  21146. throw new DeveloperError('host is required.');
  21147. }
  21148. if (!defined(port) || port <= 0) {
  21149. throw new DeveloperError('port is required to be greater than 0.');
  21150. }
  21151. var authority = host.toLowerCase() + ':' + port;
  21152. if (!defined(_servers[authority])) {
  21153. _servers[authority] = true;
  21154. }
  21155. };
  21156. /**
  21157. * Removes a trusted server from the registry
  21158. *
  21159. * @param {String} host The host to be removed.
  21160. * @param {Number} port The port used to access the host.
  21161. *
  21162. * @example
  21163. * // Remove a trusted server
  21164. * TrustedServers.remove('my.server.com', 80);
  21165. */
  21166. TrustedServers.remove = function(host, port) {
  21167. if (!defined(host)) {
  21168. throw new DeveloperError('host is required.');
  21169. }
  21170. if (!defined(port) || port <= 0) {
  21171. throw new DeveloperError('port is required to be greater than 0.');
  21172. }
  21173. var authority = host.toLowerCase() + ':' + port;
  21174. if (defined(_servers[authority])) {
  21175. delete _servers[authority];
  21176. }
  21177. };
  21178. function getAuthority(url) {
  21179. var uri = new Uri(url);
  21180. uri.normalize();
  21181. // Removes username:password@ so we just have host[:port]
  21182. var authority = uri.getAuthority();
  21183. if (!defined(authority)) {
  21184. return undefined; // Relative URL
  21185. }
  21186. if (authority.indexOf('@') !== -1) {
  21187. var parts = authority.split('@');
  21188. authority = parts[1];
  21189. }
  21190. // If the port is missing add one based on the scheme
  21191. if (authority.indexOf(':') === -1) {
  21192. var scheme = uri.getScheme();
  21193. if (!defined(scheme)) {
  21194. scheme = window.location.protocol;
  21195. scheme = scheme.substring(0, scheme.length-1);
  21196. }
  21197. if (scheme === 'http') {
  21198. authority += ':80';
  21199. } else if (scheme === 'https') {
  21200. authority += ':443';
  21201. } else {
  21202. return undefined;
  21203. }
  21204. }
  21205. return authority;
  21206. }
  21207. /**
  21208. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  21209. *
  21210. * @param {String} url The url to be tested against the trusted list
  21211. *
  21212. * @returns {boolean} Returns true if url is trusted, false otherwise.
  21213. *
  21214. * @example
  21215. * // Add server
  21216. * TrustedServers.add('my.server.com', 81);
  21217. *
  21218. * // Check if server is trusted
  21219. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  21220. * // my.server.com:81 is trusted
  21221. * }
  21222. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  21223. * // my.server.com isn't trusted
  21224. * }
  21225. */
  21226. TrustedServers.contains = function(url) {
  21227. if (!defined(url)) {
  21228. throw new DeveloperError('url is required.');
  21229. }
  21230. var authority = getAuthority(url);
  21231. if (defined(authority) && defined(_servers[authority])) {
  21232. return true;
  21233. }
  21234. return false;
  21235. };
  21236. /**
  21237. * Clears the registry
  21238. *
  21239. * @example
  21240. * // Remove a trusted server
  21241. * TrustedServers.clear();
  21242. */
  21243. TrustedServers.clear = function() {
  21244. _servers = {};
  21245. };
  21246. return TrustedServers;
  21247. });
  21248. /*global define*/
  21249. define('Core/loadWithXhr',[
  21250. '../ThirdParty/when',
  21251. './defaultValue',
  21252. './defined',
  21253. './DeveloperError',
  21254. './RequestErrorEvent',
  21255. './RuntimeError',
  21256. './TrustedServers'
  21257. ], function(
  21258. when,
  21259. defaultValue,
  21260. defined,
  21261. DeveloperError,
  21262. RequestErrorEvent,
  21263. RuntimeError,
  21264. TrustedServers) {
  21265. 'use strict';
  21266. /**
  21267. * Asynchronously loads the given URL. Returns a promise that will resolve to
  21268. * the result once loaded, or reject if the URL failed to load. The data is loaded
  21269. * using XMLHttpRequest, which means that in order to make requests to another origin,
  21270. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  21271. *
  21272. * @exports loadWithXhr
  21273. *
  21274. * @param {Object} options Object with the following properties:
  21275. * @param {String|Promise.<String>} options.url The URL of the data, or a promise for the URL.
  21276. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  21277. * @param {String} [options.method='GET'] The HTTP method to use.
  21278. * @param {String} [options.data] The data to send with the request, if any.
  21279. * @param {Object} [options.headers] HTTP headers to send with the request, if any.
  21280. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  21281. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  21282. *
  21283. *
  21284. * @example
  21285. * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
  21286. * Cesium.loadWithXhr({
  21287. * url : 'some/url',
  21288. * responseType : 'blob'
  21289. * }).then(function(blob) {
  21290. * // use the data
  21291. * }).otherwise(function(error) {
  21292. * // an error occurred
  21293. * });
  21294. *
  21295. * @see loadArrayBuffer
  21296. * @see loadBlob
  21297. * @see loadJson
  21298. * @see loadText
  21299. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  21300. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  21301. */
  21302. function loadWithXhr(options) {
  21303. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21304. if (!defined(options.url)) {
  21305. throw new DeveloperError('options.url is required.');
  21306. }
  21307. var responseType = options.responseType;
  21308. var method = defaultValue(options.method, 'GET');
  21309. var data = options.data;
  21310. var headers = options.headers;
  21311. var overrideMimeType = options.overrideMimeType;
  21312. return when(options.url, function(url) {
  21313. var deferred = when.defer();
  21314. loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
  21315. return deferred.promise;
  21316. });
  21317. }
  21318. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21319. function decodeDataUriText(isBase64, data) {
  21320. var result = decodeURIComponent(data);
  21321. if (isBase64) {
  21322. return atob(result);
  21323. }
  21324. return result;
  21325. }
  21326. function decodeDataUriArrayBuffer(isBase64, data) {
  21327. var byteString = decodeDataUriText(isBase64, data);
  21328. var buffer = new ArrayBuffer(byteString.length);
  21329. var view = new Uint8Array(buffer);
  21330. for (var i = 0; i < byteString.length; i++) {
  21331. view[i] = byteString.charCodeAt(i);
  21332. }
  21333. return buffer;
  21334. }
  21335. function decodeDataUri(dataUriRegexResult, responseType) {
  21336. responseType = defaultValue(responseType, '');
  21337. var mimeType = dataUriRegexResult[1];
  21338. var isBase64 = !!dataUriRegexResult[2];
  21339. var data = dataUriRegexResult[3];
  21340. switch (responseType) {
  21341. case '':
  21342. case 'text':
  21343. return decodeDataUriText(isBase64, data);
  21344. case 'arraybuffer':
  21345. return decodeDataUriArrayBuffer(isBase64, data);
  21346. case 'blob':
  21347. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  21348. return new Blob([buffer], {
  21349. type : mimeType
  21350. });
  21351. case 'document':
  21352. var parser = new DOMParser();
  21353. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  21354. case 'json':
  21355. return JSON.parse(decodeDataUriText(isBase64, data));
  21356. default:
  21357. throw new DeveloperError('Unhandled responseType: ' + responseType);
  21358. }
  21359. }
  21360. // This is broken out into a separate function so that it can be mocked for testing purposes.
  21361. loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  21362. var dataUriRegexResult = dataUriRegex.exec(url);
  21363. if (dataUriRegexResult !== null) {
  21364. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  21365. return;
  21366. }
  21367. var xhr = new XMLHttpRequest();
  21368. if (TrustedServers.contains(url)) {
  21369. xhr.withCredentials = true;
  21370. }
  21371. if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
  21372. xhr.overrideMimeType(overrideMimeType);
  21373. }
  21374. xhr.open(method, url, true);
  21375. if (defined(headers)) {
  21376. for (var key in headers) {
  21377. if (headers.hasOwnProperty(key)) {
  21378. xhr.setRequestHeader(key, headers[key]);
  21379. }
  21380. }
  21381. }
  21382. if (defined(responseType)) {
  21383. xhr.responseType = responseType;
  21384. }
  21385. xhr.onload = function() {
  21386. if (xhr.status < 200 || xhr.status >= 300) {
  21387. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  21388. return;
  21389. }
  21390. var response = xhr.response;
  21391. var browserResponseType = xhr.responseType;
  21392. //All modern browsers will go into either the first if block or last else block.
  21393. //Other code paths support older browsers that either do not support the supplied responseType
  21394. //or do not support the xhr.response property.
  21395. if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
  21396. deferred.resolve(response);
  21397. } else if ((responseType === 'json') && typeof response === 'string') {
  21398. try {
  21399. deferred.resolve(JSON.parse(response));
  21400. } catch (e) {
  21401. deferred.reject(e);
  21402. }
  21403. } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  21404. deferred.resolve(xhr.responseXML);
  21405. } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
  21406. deferred.resolve(xhr.responseText);
  21407. } else {
  21408. deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
  21409. }
  21410. };
  21411. xhr.onerror = function(e) {
  21412. deferred.reject(new RequestErrorEvent());
  21413. };
  21414. xhr.send(data);
  21415. };
  21416. loadWithXhr.defaultLoad = loadWithXhr.load;
  21417. return loadWithXhr;
  21418. });
  21419. /*global define*/
  21420. define('Core/loadText',[
  21421. './loadWithXhr'
  21422. ], function(
  21423. loadWithXhr) {
  21424. 'use strict';
  21425. /**
  21426. * Asynchronously loads the given URL as text. Returns a promise that will resolve to
  21427. * a String once loaded, or reject if the URL failed to load. The data is loaded
  21428. * using XMLHttpRequest, which means that in order to make requests to another origin,
  21429. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  21430. *
  21431. * @exports loadText
  21432. *
  21433. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  21434. * @param {Object} [headers] HTTP headers to send with the request.
  21435. * @returns {Promise.<String>} a promise that will resolve to the requested data when loaded.
  21436. *
  21437. *
  21438. * @example
  21439. * // load text from a URL, setting a custom header
  21440. * Cesium.loadText('http://someUrl.com/someJson.txt', {
  21441. * 'X-Custom-Header' : 'some value'
  21442. * }).then(function(text) {
  21443. * // Do something with the text
  21444. * }).otherwise(function(error) {
  21445. * // an error occurred
  21446. * });
  21447. *
  21448. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  21449. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  21450. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  21451. */
  21452. function loadText(url, headers) {
  21453. return loadWithXhr({
  21454. url : url,
  21455. headers : headers
  21456. });
  21457. }
  21458. return loadText;
  21459. });
  21460. /*global define*/
  21461. define('Core/loadJson',[
  21462. './clone',
  21463. './defined',
  21464. './DeveloperError',
  21465. './loadText'
  21466. ], function(
  21467. clone,
  21468. defined,
  21469. DeveloperError,
  21470. loadText) {
  21471. 'use strict';
  21472. var defaultHeaders = {
  21473. Accept : 'application/json,*/*;q=0.01'
  21474. };
  21475. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  21476. /**
  21477. * Asynchronously loads the given URL as JSON. Returns a promise that will resolve to
  21478. * a JSON object once loaded, or reject if the URL failed to load. The data is loaded
  21479. * using XMLHttpRequest, which means that in order to make requests to another origin,
  21480. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  21481. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  21482. * already specified.
  21483. *
  21484. * @exports loadJson
  21485. *
  21486. * @param {String|Promise.<String>} url The URL to request, or a promise for the URL.
  21487. * @param {Object} [headers] HTTP headers to send with the request.
  21488. * 'Accept: application/json,&#42;&#47;&#42;;q=0.01' is added to the request headers automatically
  21489. * if not specified.
  21490. * @returns {Promise.<Object>} a promise that will resolve to the requested data when loaded.
  21491. *
  21492. *
  21493. * @example
  21494. * Cesium.loadJson('http://someUrl.com/someJson.txt').then(function(jsonData) {
  21495. * // Do something with the JSON object
  21496. * }).otherwise(function(error) {
  21497. * // an error occurred
  21498. * });
  21499. *
  21500. * @see loadText
  21501. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  21502. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  21503. */
  21504. function loadJson(url, headers) {
  21505. if (!defined(url)) {
  21506. throw new DeveloperError('url is required.');
  21507. }
  21508. if (!defined(headers)) {
  21509. headers = defaultHeaders;
  21510. } else if (!defined(headers.Accept)) {
  21511. // clone before adding the Accept header
  21512. headers = clone(headers);
  21513. headers.Accept = defaultHeaders.Accept;
  21514. }
  21515. return loadText(url, headers).then(function(value) {
  21516. return JSON.parse(value);
  21517. });
  21518. }
  21519. return loadJson;
  21520. });
  21521. /*global define*/
  21522. define('Core/EarthOrientationParameters',[
  21523. '../ThirdParty/when',
  21524. './binarySearch',
  21525. './defaultValue',
  21526. './defined',
  21527. './EarthOrientationParametersSample',
  21528. './freezeObject',
  21529. './JulianDate',
  21530. './LeapSecond',
  21531. './loadJson',
  21532. './RuntimeError',
  21533. './TimeConstants',
  21534. './TimeStandard'
  21535. ], function(
  21536. when,
  21537. binarySearch,
  21538. defaultValue,
  21539. defined,
  21540. EarthOrientationParametersSample,
  21541. freezeObject,
  21542. JulianDate,
  21543. LeapSecond,
  21544. loadJson,
  21545. RuntimeError,
  21546. TimeConstants,
  21547. TimeStandard) {
  21548. 'use strict';
  21549. /**
  21550. * Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
  21551. * These Earth Orientation Parameters (EOP) are primarily used in the transformation from
  21552. * the International Celestial Reference Frame (ICRF) to the International Terrestrial
  21553. * Reference Frame (ITRF).
  21554. *
  21555. * @alias EarthOrientationParameters
  21556. * @constructor
  21557. *
  21558. * @param {Object} [options] Object with the following properties:
  21559. * @param {String} [options.url] The URL from which to obtain EOP data. If neither this
  21560. * parameter nor options.data is specified, all EOP values are assumed
  21561. * to be 0.0. If options.data is specified, this parameter is
  21562. * ignored.
  21563. * @param {Object} [options.data] The actual EOP data. If neither this
  21564. * parameter nor options.data is specified, all EOP values are assumed
  21565. * to be 0.0.
  21566. * @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
  21567. * are specified in the EOP data but not in {@link JulianDate.leapSeconds}
  21568. * should be added to {@link JulianDate.leapSeconds}. False if
  21569. * new leap seconds should be handled correctly in the context
  21570. * of the EOP data but otherwise ignored.
  21571. *
  21572. * @example
  21573. * // An example EOP data file, EOP.json:
  21574. * {
  21575. * "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
  21576. * "samples" : [
  21577. * "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,
  21578. * "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,
  21579. * "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
  21580. * ]
  21581. * }
  21582. *
  21583. * @example
  21584. * // Loading the EOP data
  21585. * var eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
  21586. * Cesium.Transforms.earthOrientationParameters = eop;
  21587. *
  21588. * @private
  21589. */
  21590. function EarthOrientationParameters(options) {
  21591. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  21592. this._dates = undefined;
  21593. this._samples = undefined;
  21594. this._dateColumn = -1;
  21595. this._xPoleWanderRadiansColumn = -1;
  21596. this._yPoleWanderRadiansColumn = -1;
  21597. this._ut1MinusUtcSecondsColumn = -1;
  21598. this._xCelestialPoleOffsetRadiansColumn = -1;
  21599. this._yCelestialPoleOffsetRadiansColumn = -1;
  21600. this._taiMinusUtcSecondsColumn = -1;
  21601. this._columnCount = 0;
  21602. this._lastIndex = -1;
  21603. this._downloadPromise = undefined;
  21604. this._dataError = undefined;
  21605. this._addNewLeapSeconds = defaultValue(options.addNewLeapSeconds, true);
  21606. if (defined(options.data)) {
  21607. // Use supplied EOP data.
  21608. onDataReady(this, options.data);
  21609. } else if (defined(options.url)) {
  21610. // Download EOP data.
  21611. var that = this;
  21612. this._downloadPromise = when(loadJson(options.url), function(eopData) {
  21613. onDataReady(that, eopData);
  21614. }, function() {
  21615. that._dataError = 'An error occurred while retrieving the EOP data from the URL ' + options.url + '.';
  21616. });
  21617. } else {
  21618. // Use all zeros for EOP data.
  21619. onDataReady(this, {
  21620. 'columnNames' : ['dateIso8601', 'modifiedJulianDateUtc', 'xPoleWanderRadians', 'yPoleWanderRadians', 'ut1MinusUtcSeconds', 'lengthOfDayCorrectionSeconds', 'xCelestialPoleOffsetRadians', 'yCelestialPoleOffsetRadians', 'taiMinusUtcSeconds'],
  21621. 'samples' : []
  21622. });
  21623. }
  21624. }
  21625. /**
  21626. * A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
  21627. */
  21628. EarthOrientationParameters.NONE = freezeObject({
  21629. getPromiseToLoad : function() {
  21630. return when();
  21631. },
  21632. compute : function(date, result) {
  21633. if (!defined(result)) {
  21634. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  21635. } else {
  21636. result.xPoleWander = 0.0;
  21637. result.yPoleWander = 0.0;
  21638. result.xPoleOffset = 0.0;
  21639. result.yPoleOffset = 0.0;
  21640. result.ut1MinusUtc = 0.0;
  21641. }
  21642. return result;
  21643. }
  21644. });
  21645. /**
  21646. * Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
  21647. * ready to use.
  21648. *
  21649. * @returns {Promise.<undefined>} The promise.
  21650. *
  21651. * @see when
  21652. */
  21653. EarthOrientationParameters.prototype.getPromiseToLoad = function() {
  21654. return when(this._downloadPromise);
  21655. };
  21656. /**
  21657. * Computes the Earth Orientation Parameters (EOP) for a given date by interpolating.
  21658. * If the EOP data has not yet been download, this method returns undefined.
  21659. *
  21660. * @param {JulianDate} date The date for each to evaluate the EOP.
  21661. * @param {EarthOrientationParametersSample} [result] The instance to which to copy the result.
  21662. * If this parameter is undefined, a new instance is created and returned.
  21663. * @returns {EarthOrientationParametersSample} The EOP evaluated at the given date, or
  21664. * undefined if the data necessary to evaluate EOP at the date has not yet been
  21665. * downloaded.
  21666. *
  21667. * @exception {RuntimeError} The loaded EOP data has an error and cannot be used.
  21668. *
  21669. * @see EarthOrientationParameters#getPromiseToLoad
  21670. */
  21671. EarthOrientationParameters.prototype.compute = function(date, result) {
  21672. // We cannot compute until the samples are available.
  21673. if (!defined(this._samples)) {
  21674. if (defined(this._dataError)) {
  21675. throw new RuntimeError(this._dataError);
  21676. }
  21677. return undefined;
  21678. }
  21679. if (!defined(result)) {
  21680. result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
  21681. }
  21682. if (this._samples.length === 0) {
  21683. result.xPoleWander = 0.0;
  21684. result.yPoleWander = 0.0;
  21685. result.xPoleOffset = 0.0;
  21686. result.yPoleOffset = 0.0;
  21687. result.ut1MinusUtc = 0.0;
  21688. return result;
  21689. }
  21690. var dates = this._dates;
  21691. var lastIndex = this._lastIndex;
  21692. var before = 0;
  21693. var after = 0;
  21694. if (defined(lastIndex)) {
  21695. var previousIndexDate = dates[lastIndex];
  21696. var nextIndexDate = dates[lastIndex + 1];
  21697. var isAfterPrevious = JulianDate.lessThanOrEquals(previousIndexDate, date);
  21698. var isAfterLastSample = !defined(nextIndexDate);
  21699. var isBeforeNext = isAfterLastSample || JulianDate.greaterThanOrEquals(nextIndexDate, date);
  21700. if (isAfterPrevious && isBeforeNext) {
  21701. before = lastIndex;
  21702. if (!isAfterLastSample && nextIndexDate.equals(date)) {
  21703. ++before;
  21704. }
  21705. after = before + 1;
  21706. interpolate(this, dates, this._samples, date, before, after, result);
  21707. return result;
  21708. }
  21709. }
  21710. var index = binarySearch(dates, date, JulianDate.compare, this._dateColumn);
  21711. if (index >= 0) {
  21712. // If the next entry is the same date, use the later entry. This way, if two entries
  21713. // describe the same moment, one before a leap second and the other after, then we will use
  21714. // the post-leap second data.
  21715. if (index < dates.length - 1 && dates[index + 1].equals(date)) {
  21716. ++index;
  21717. }
  21718. before = index;
  21719. after = index;
  21720. } else {
  21721. after = ~index;
  21722. before = after - 1;
  21723. // Use the first entry if the date requested is before the beginning of the data.
  21724. if (before < 0) {
  21725. before = 0;
  21726. }
  21727. }
  21728. this._lastIndex = before;
  21729. interpolate(this, dates, this._samples, date, before, after, result);
  21730. return result;
  21731. };
  21732. function compareLeapSecondDates(leapSecond, dateToFind) {
  21733. return JulianDate.compare(leapSecond.julianDate, dateToFind);
  21734. }
  21735. function onDataReady(eop, eopData) {
  21736. if (!defined(eopData.columnNames)) {
  21737. eop._dataError = 'Error in loaded EOP data: The columnNames property is required.';
  21738. return;
  21739. }
  21740. if (!defined(eopData.samples)) {
  21741. eop._dataError = 'Error in loaded EOP data: The samples property is required.';
  21742. return;
  21743. }
  21744. var dateColumn = eopData.columnNames.indexOf('modifiedJulianDateUtc');
  21745. var xPoleWanderRadiansColumn = eopData.columnNames.indexOf('xPoleWanderRadians');
  21746. var yPoleWanderRadiansColumn = eopData.columnNames.indexOf('yPoleWanderRadians');
  21747. var ut1MinusUtcSecondsColumn = eopData.columnNames.indexOf('ut1MinusUtcSeconds');
  21748. var xCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('xCelestialPoleOffsetRadians');
  21749. var yCelestialPoleOffsetRadiansColumn = eopData.columnNames.indexOf('yCelestialPoleOffsetRadians');
  21750. var taiMinusUtcSecondsColumn = eopData.columnNames.indexOf('taiMinusUtcSeconds');
  21751. if (dateColumn < 0 || xPoleWanderRadiansColumn < 0 || yPoleWanderRadiansColumn < 0 || ut1MinusUtcSecondsColumn < 0 || xCelestialPoleOffsetRadiansColumn < 0 || yCelestialPoleOffsetRadiansColumn < 0 || taiMinusUtcSecondsColumn < 0) {
  21752. eop._dataError = 'Error in loaded EOP data: The columnNames property must include modifiedJulianDateUtc, xPoleWanderRadians, yPoleWanderRadians, ut1MinusUtcSeconds, xCelestialPoleOffsetRadians, yCelestialPoleOffsetRadians, and taiMinusUtcSeconds columns';
  21753. return;
  21754. }
  21755. var samples = eop._samples = eopData.samples;
  21756. var dates = eop._dates = [];
  21757. eop._dateColumn = dateColumn;
  21758. eop._xPoleWanderRadiansColumn = xPoleWanderRadiansColumn;
  21759. eop._yPoleWanderRadiansColumn = yPoleWanderRadiansColumn;
  21760. eop._ut1MinusUtcSecondsColumn = ut1MinusUtcSecondsColumn;
  21761. eop._xCelestialPoleOffsetRadiansColumn = xCelestialPoleOffsetRadiansColumn;
  21762. eop._yCelestialPoleOffsetRadiansColumn = yCelestialPoleOffsetRadiansColumn;
  21763. eop._taiMinusUtcSecondsColumn = taiMinusUtcSecondsColumn;
  21764. eop._columnCount = eopData.columnNames.length;
  21765. eop._lastIndex = undefined;
  21766. var lastTaiMinusUtc;
  21767. var addNewLeapSeconds = eop._addNewLeapSeconds;
  21768. // Convert the ISO8601 dates to JulianDates.
  21769. for (var i = 0, len = samples.length; i < len; i += eop._columnCount) {
  21770. var mjd = samples[i + dateColumn];
  21771. var taiMinusUtc = samples[i + taiMinusUtcSecondsColumn];
  21772. var day = mjd + TimeConstants.MODIFIED_JULIAN_DATE_DIFFERENCE;
  21773. var date = new JulianDate(day, taiMinusUtc, TimeStandard.TAI);
  21774. dates.push(date);
  21775. if (addNewLeapSeconds) {
  21776. if (taiMinusUtc !== lastTaiMinusUtc && defined(lastTaiMinusUtc)) {
  21777. // We crossed a leap second boundary, so add the leap second
  21778. // if it does not already exist.
  21779. var leapSeconds = JulianDate.leapSeconds;
  21780. var leapSecondIndex = binarySearch(leapSeconds, date, compareLeapSecondDates);
  21781. if (leapSecondIndex < 0) {
  21782. var leapSecond = new LeapSecond(date, taiMinusUtc);
  21783. leapSeconds.splice(~leapSecondIndex, 0, leapSecond);
  21784. }
  21785. }
  21786. lastTaiMinusUtc = taiMinusUtc;
  21787. }
  21788. }
  21789. }
  21790. function fillResultFromIndex(eop, samples, index, columnCount, result) {
  21791. var start = index * columnCount;
  21792. result.xPoleWander = samples[start + eop._xPoleWanderRadiansColumn];
  21793. result.yPoleWander = samples[start + eop._yPoleWanderRadiansColumn];
  21794. result.xPoleOffset = samples[start + eop._xCelestialPoleOffsetRadiansColumn];
  21795. result.yPoleOffset = samples[start + eop._yCelestialPoleOffsetRadiansColumn];
  21796. result.ut1MinusUtc = samples[start + eop._ut1MinusUtcSecondsColumn];
  21797. }
  21798. function linearInterp(dx, y1, y2) {
  21799. return y1 + dx * (y2 - y1);
  21800. }
  21801. function interpolate(eop, dates, samples, date, before, after, result) {
  21802. var columnCount = eop._columnCount;
  21803. // First check the bounds on the EOP data
  21804. // If we are after the bounds of the data, return zeros.
  21805. // The 'before' index should never be less than zero.
  21806. if (after > dates.length - 1) {
  21807. result.xPoleWander = 0;
  21808. result.yPoleWander = 0;
  21809. result.xPoleOffset = 0;
  21810. result.yPoleOffset = 0;
  21811. result.ut1MinusUtc = 0;
  21812. return result;
  21813. }
  21814. var beforeDate = dates[before];
  21815. var afterDate = dates[after];
  21816. if (beforeDate.equals(afterDate) || date.equals(beforeDate)) {
  21817. fillResultFromIndex(eop, samples, before, columnCount, result);
  21818. return result;
  21819. } else if (date.equals(afterDate)) {
  21820. fillResultFromIndex(eop, samples, after, columnCount, result);
  21821. return result;
  21822. }
  21823. var factor = JulianDate.secondsDifference(date, beforeDate) / JulianDate.secondsDifference(afterDate, beforeDate);
  21824. var startBefore = before * columnCount;
  21825. var startAfter = after * columnCount;
  21826. // Handle UT1 leap second edge case
  21827. var beforeUt1MinusUtc = samples[startBefore + eop._ut1MinusUtcSecondsColumn];
  21828. var afterUt1MinusUtc = samples[startAfter + eop._ut1MinusUtcSecondsColumn];
  21829. var offsetDifference = afterUt1MinusUtc - beforeUt1MinusUtc;
  21830. if (offsetDifference > 0.5 || offsetDifference < -0.5) {
  21831. // The absolute difference between the values is more than 0.5, so we may have
  21832. // crossed a leap second. Check if this is the case and, if so, adjust the
  21833. // afterValue to account for the leap second. This way, our interpolation will
  21834. // produce reasonable results.
  21835. var beforeTaiMinusUtc = samples[startBefore + eop._taiMinusUtcSecondsColumn];
  21836. var afterTaiMinusUtc = samples[startAfter + eop._taiMinusUtcSecondsColumn];
  21837. if (beforeTaiMinusUtc !== afterTaiMinusUtc) {
  21838. if (afterDate.equals(date)) {
  21839. // If we are at the end of the leap second interval, take the second value
  21840. // Otherwise, the interpolation below will yield the wrong side of the
  21841. // discontinuity
  21842. // At the end of the leap second, we need to start accounting for the jump
  21843. beforeUt1MinusUtc = afterUt1MinusUtc;
  21844. } else {
  21845. // Otherwise, remove the leap second so that the interpolation is correct
  21846. afterUt1MinusUtc -= afterTaiMinusUtc - beforeTaiMinusUtc;
  21847. }
  21848. }
  21849. }
  21850. result.xPoleWander = linearInterp(factor, samples[startBefore + eop._xPoleWanderRadiansColumn], samples[startAfter + eop._xPoleWanderRadiansColumn]);
  21851. result.yPoleWander = linearInterp(factor, samples[startBefore + eop._yPoleWanderRadiansColumn], samples[startAfter + eop._yPoleWanderRadiansColumn]);
  21852. result.xPoleOffset = linearInterp(factor, samples[startBefore + eop._xCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._xCelestialPoleOffsetRadiansColumn]);
  21853. result.yPoleOffset = linearInterp(factor, samples[startBefore + eop._yCelestialPoleOffsetRadiansColumn], samples[startAfter + eop._yCelestialPoleOffsetRadiansColumn]);
  21854. result.ut1MinusUtc = linearInterp(factor, beforeUt1MinusUtc, afterUt1MinusUtc);
  21855. return result;
  21856. }
  21857. return EarthOrientationParameters;
  21858. });
  21859. /*global define*/
  21860. define('Core/HeadingPitchRoll',[
  21861. './defaultValue',
  21862. './defined',
  21863. './DeveloperError',
  21864. './Math'
  21865. ], function(
  21866. defaultValue,
  21867. defined,
  21868. DeveloperError,
  21869. CesiumMath) {
  21870. "use strict";
  21871. /**
  21872. * A rotation expressed as a heading, pitch, and roll. Heading is the rotation about the
  21873. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  21874. * the positive x axis.
  21875. * @alias HeadingPitchRoll
  21876. * @constructor
  21877. *
  21878. * @param {Number} [heading=0.0] The heading component in radians.
  21879. * @param {Number} [pitch=0.0] The pitch component in radians.
  21880. * @param {Number} [roll=0.0] The roll component in radians.
  21881. */
  21882. function HeadingPitchRoll(heading, pitch, roll) {
  21883. this.heading = defaultValue(heading, 0.0);
  21884. this.pitch = defaultValue(pitch, 0.0);
  21885. this.roll = defaultValue(roll, 0.0);
  21886. }
  21887. /**
  21888. * Computes the heading, pitch and roll from a quaternion (see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles )
  21889. *
  21890. * @param {Quaternion} quaternion The quaternion from which to retrieve heading, pitch, and roll, all expressed in radians.
  21891. * @param {Quaternion} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  21892. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  21893. */
  21894. HeadingPitchRoll.fromQuaternion = function(quaternion, result) {
  21895. if (!defined(quaternion)) {
  21896. throw new DeveloperError('quaternion is required');
  21897. }
  21898. if (!defined(result)) {
  21899. result = new HeadingPitchRoll();
  21900. }
  21901. var test = 2 * (quaternion.w * quaternion.y - quaternion.z * quaternion.x);
  21902. var denominatorRoll = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
  21903. var numeratorRoll = 2 * (quaternion.w * quaternion.x + quaternion.y * quaternion.z);
  21904. var denominatorHeading = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
  21905. var numeratorHeading = 2 * (quaternion.w * quaternion.z + quaternion.x * quaternion.y);
  21906. result.heading = -Math.atan2(numeratorHeading, denominatorHeading);
  21907. result.roll = Math.atan2(numeratorRoll, denominatorRoll);
  21908. result.pitch = -Math.asin(test);
  21909. return result;
  21910. };
  21911. /**
  21912. * Returns a new HeadingPitchRoll instance from angles given in degrees.
  21913. *
  21914. * @param {Number} heading the heading in degrees
  21915. * @param {Number} pitch the pitch in degrees
  21916. * @param {Number} roll the heading in degrees
  21917. * @param {HeadingPitchRoll} [result] The object in which to store the result. If not provided, a new instance is created and returned.
  21918. * @returns {HeadingPitchRoll} A new HeadingPitchRoll instance
  21919. */
  21920. HeadingPitchRoll.fromDegrees = function(heading, pitch, roll, result) {
  21921. if (!defined(heading)) {
  21922. throw new DeveloperError('heading is required');
  21923. }
  21924. if (!defined(pitch)) {
  21925. throw new DeveloperError('pitch is required');
  21926. }
  21927. if (!defined(roll)) {
  21928. throw new DeveloperError('roll is required');
  21929. }
  21930. if (!defined(result)) {
  21931. result = new HeadingPitchRoll();
  21932. }
  21933. result.heading = heading * CesiumMath.RADIANS_PER_DEGREE;
  21934. result.pitch = pitch * CesiumMath.RADIANS_PER_DEGREE;
  21935. result.roll = roll * CesiumMath.RADIANS_PER_DEGREE;
  21936. return result;
  21937. };
  21938. /**
  21939. * Duplicates a HeadingPitchRoll instance.
  21940. *
  21941. * @param {HeadingPitchRoll} headingPitchRoll The HeadingPitchRoll to duplicate.
  21942. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  21943. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided. (Returns undefined if headingPitchRoll is undefined)
  21944. */
  21945. HeadingPitchRoll.clone = function(headingPitchRoll, result) {
  21946. if (!defined(headingPitchRoll)) {
  21947. return undefined;
  21948. }
  21949. if (!defined(result)) {
  21950. return new HeadingPitchRoll(headingPitchRoll.heading, headingPitchRoll.pitch, headingPitchRoll.roll);
  21951. }
  21952. result.heading = headingPitchRoll.heading;
  21953. result.pitch = headingPitchRoll.pitch;
  21954. result.roll = headingPitchRoll.roll;
  21955. return result;
  21956. };
  21957. /**
  21958. * Compares the provided HeadingPitchRolls componentwise and returns
  21959. * <code>true</code> if they are equal, <code>false</code> otherwise.
  21960. *
  21961. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  21962. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  21963. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  21964. */
  21965. HeadingPitchRoll.equals = function(left, right) {
  21966. return (left === right) ||
  21967. ((defined(left)) &&
  21968. (defined(right)) &&
  21969. (left.heading === right.heading) &&
  21970. (left.pitch === right.pitch) &&
  21971. (left.roll === right.roll));
  21972. };
  21973. /**
  21974. * Compares the provided HeadingPitchRolls componentwise and returns
  21975. * <code>true</code> if they pass an absolute or relative tolerance test,
  21976. * <code>false</code> otherwise.
  21977. *
  21978. * @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
  21979. * @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
  21980. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  21981. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  21982. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  21983. */
  21984. HeadingPitchRoll.equalsEpsilon = function(left, right, relativeEpsilon, absoluteEpsilon) {
  21985. return (left === right) ||
  21986. (defined(left) &&
  21987. defined(right) &&
  21988. CesiumMath.equalsEpsilon(left.heading, right.heading, relativeEpsilon, absoluteEpsilon) &&
  21989. CesiumMath.equalsEpsilon(left.pitch, right.pitch, relativeEpsilon, absoluteEpsilon) &&
  21990. CesiumMath.equalsEpsilon(left.roll, right.roll, relativeEpsilon, absoluteEpsilon));
  21991. };
  21992. /**
  21993. * Duplicates this HeadingPitchRoll instance.
  21994. *
  21995. * @param {HeadingPitchRoll} [result] The object onto which to store the result.
  21996. * @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
  21997. */
  21998. HeadingPitchRoll.prototype.clone = function(result) {
  21999. return HeadingPitchRoll.clone(this, result);
  22000. };
  22001. /**
  22002. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  22003. * <code>true</code> if they are equal, <code>false</code> otherwise.
  22004. *
  22005. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  22006. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise.
  22007. */
  22008. HeadingPitchRoll.prototype.equals = function(right) {
  22009. return HeadingPitchRoll.equals(this, right);
  22010. };
  22011. /**
  22012. * Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
  22013. * <code>true</code> if they pass an absolute or relative tolerance test,
  22014. * <code>false</code> otherwise.
  22015. *
  22016. * @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
  22017. * @param {Number} relativeEpsilon The relative epsilon tolerance to use for equality testing.
  22018. * @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
  22019. * @returns {Boolean} <code>true</code> if they are within the provided epsilon, <code>false</code> otherwise.
  22020. */
  22021. HeadingPitchRoll.prototype.equalsEpsilon = function(right, relativeEpsilon, absoluteEpsilon) {
  22022. return HeadingPitchRoll.equalsEpsilon(this, right, relativeEpsilon, absoluteEpsilon);
  22023. };
  22024. /**
  22025. * Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
  22026. *
  22027. * @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
  22028. */
  22029. HeadingPitchRoll.prototype.toString = function() {
  22030. return '(' + this.heading + ', ' + this.pitch + ', ' + this.roll + ')';
  22031. };
  22032. return HeadingPitchRoll;
  22033. });
  22034. /*global define*/
  22035. define('Core/getAbsoluteUri',[
  22036. '../ThirdParty/Uri',
  22037. './defaultValue',
  22038. './defined',
  22039. './DeveloperError'
  22040. ], function(
  22041. Uri,
  22042. defaultValue,
  22043. defined,
  22044. DeveloperError) {
  22045. 'use strict';
  22046. /**
  22047. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  22048. * @exports getAbsoluteUri
  22049. *
  22050. * @param {String} relative The relative Uri.
  22051. * @param {String} [base] The base Uri.
  22052. * @returns {String} The absolute Uri of the given relative Uri.
  22053. *
  22054. * @example
  22055. * //absolute Uri will be "https://test.com/awesome.png";
  22056. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  22057. */
  22058. function getAbsoluteUri(relative, base) {
  22059. if (!defined(relative)) {
  22060. throw new DeveloperError('relative uri is required.');
  22061. }
  22062. base = defaultValue(base, document.location.href);
  22063. var baseUri = new Uri(base);
  22064. var relativeUri = new Uri(relative);
  22065. return relativeUri.resolve(baseUri).toString();
  22066. }
  22067. return getAbsoluteUri;
  22068. });
  22069. /*global define*/
  22070. define('Core/joinUrls',[
  22071. '../ThirdParty/Uri',
  22072. './defaultValue',
  22073. './defined',
  22074. './DeveloperError'
  22075. ], function(
  22076. Uri,
  22077. defaultValue,
  22078. defined,
  22079. DeveloperError) {
  22080. 'use strict';
  22081. /**
  22082. * Function for joining URLs in a manner that is aware of query strings and fragments.
  22083. * This is useful when the base URL has a query string that needs to be maintained
  22084. * (e.g. a presigned base URL).
  22085. * @param {String|Uri} first The base URL.
  22086. * @param {String|Uri} second The URL path to join to the base URL. If this URL is absolute, it is returned unmodified.
  22087. * @param {Boolean} [appendSlash=true] The boolean determining whether there should be a forward slash between first and second.
  22088. * @private
  22089. */
  22090. function joinUrls(first, second, appendSlash) {
  22091. if (!defined(first)) {
  22092. throw new DeveloperError('first is required');
  22093. }
  22094. if (!defined(second)) {
  22095. throw new DeveloperError('second is required');
  22096. }
  22097. appendSlash = defaultValue(appendSlash, true);
  22098. if (!(first instanceof Uri)) {
  22099. first = new Uri(first);
  22100. }
  22101. if (!(second instanceof Uri)) {
  22102. second = new Uri(second);
  22103. }
  22104. // Uri.isAbsolute returns false for a URL like '//foo.com'. So if we have an authority but
  22105. // not a scheme, add a scheme matching the page's scheme.
  22106. if (defined(second.authority) && !defined(second.scheme)) {
  22107. if (typeof document !== 'undefined' && defined(document.location) && defined(document.location.href)) {
  22108. second.scheme = new Uri(document.location.href).scheme;
  22109. } else {
  22110. // Not in a browser? Use the first URL's scheme instead.
  22111. second.scheme = first.scheme;
  22112. }
  22113. }
  22114. // If the second URL is absolute, use it for the scheme, authority, and path.
  22115. var baseUri = first;
  22116. if (second.isAbsolute()) {
  22117. baseUri = second;
  22118. }
  22119. var url = '';
  22120. if (defined(baseUri.scheme)) {
  22121. url += baseUri.scheme + ':';
  22122. }
  22123. if (defined(baseUri.authority)) {
  22124. url += '//' + baseUri.authority;
  22125. if (baseUri.path !== '' && baseUri.path !== '/') {
  22126. url = url.replace(/\/?$/, '/');
  22127. baseUri.path = baseUri.path.replace(/^\/?/g, '');
  22128. }
  22129. }
  22130. // Combine the paths (only if second is relative).
  22131. if (baseUri === first) {
  22132. if (appendSlash) {
  22133. url += first.path.replace(/\/?$/, '/') + second.path.replace(/^\/?/g, '');
  22134. } else {
  22135. url += first.path + second.path;
  22136. }
  22137. } else {
  22138. url += second.path;
  22139. }
  22140. // Combine the queries and fragments.
  22141. var hasFirstQuery = defined(first.query);
  22142. var hasSecondQuery = defined(second.query);
  22143. if (hasFirstQuery && hasSecondQuery) {
  22144. url += '?' + first.query + '&' + second.query;
  22145. } else if (hasFirstQuery && !hasSecondQuery) {
  22146. url += '?' + first.query;
  22147. } else if (!hasFirstQuery && hasSecondQuery) {
  22148. url += '?' + second.query;
  22149. }
  22150. var hasSecondFragment = defined(second.fragment);
  22151. if (defined(first.fragment) && !hasSecondFragment) {
  22152. url += '#' + first.fragment;
  22153. } else if (hasSecondFragment) {
  22154. url += '#' + second.fragment;
  22155. }
  22156. return url;
  22157. }
  22158. return joinUrls;
  22159. });
  22160. /*global define*/
  22161. define('Core/buildModuleUrl',[
  22162. '../ThirdParty/Uri',
  22163. './defined',
  22164. './DeveloperError',
  22165. './getAbsoluteUri',
  22166. './joinUrls',
  22167. 'require'
  22168. ], function(
  22169. Uri,
  22170. defined,
  22171. DeveloperError,
  22172. getAbsoluteUri,
  22173. joinUrls,
  22174. require) {
  22175. 'use strict';
  22176. /*global CESIUM_BASE_URL*/
  22177. var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i;
  22178. function getBaseUrlFromCesiumScript() {
  22179. var scripts = document.getElementsByTagName('script');
  22180. for ( var i = 0, len = scripts.length; i < len; ++i) {
  22181. var src = scripts[i].getAttribute('src');
  22182. var result = cesiumScriptRegex.exec(src);
  22183. if (result !== null) {
  22184. return result[1];
  22185. }
  22186. }
  22187. return undefined;
  22188. }
  22189. var baseUrl;
  22190. function getCesiumBaseUrl() {
  22191. if (defined(baseUrl)) {
  22192. return baseUrl;
  22193. }
  22194. var baseUrlString;
  22195. if (typeof CESIUM_BASE_URL !== 'undefined') {
  22196. baseUrlString = CESIUM_BASE_URL;
  22197. } else {
  22198. baseUrlString = getBaseUrlFromCesiumScript();
  22199. }
  22200. if (!defined(baseUrlString)) {
  22201. throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  22202. }
  22203. baseUrl = new Uri(getAbsoluteUri(baseUrlString));
  22204. return baseUrl;
  22205. }
  22206. function buildModuleUrlFromRequireToUrl(moduleID) {
  22207. //moduleID will be non-relative, so require it relative to this module, in Core.
  22208. return require.toUrl('../' + moduleID);
  22209. }
  22210. function buildModuleUrlFromBaseUrl(moduleID) {
  22211. return joinUrls(getCesiumBaseUrl(), moduleID);
  22212. }
  22213. var implementation;
  22214. var a;
  22215. /**
  22216. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  22217. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  22218. * the base URL of the Cesium.js script.
  22219. *
  22220. * @private
  22221. */
  22222. function buildModuleUrl(moduleID) {
  22223. if (!defined(implementation)) {
  22224. //select implementation
  22225. if (defined(require.toUrl)) {
  22226. implementation = buildModuleUrlFromRequireToUrl;
  22227. } else {
  22228. implementation = buildModuleUrlFromBaseUrl;
  22229. }
  22230. }
  22231. if (!defined(a)) {
  22232. a = document.createElement('a');
  22233. }
  22234. var url = implementation(moduleID);
  22235. a.href = url;
  22236. a.href = a.href; // IE only absolutizes href on get, not set
  22237. return a.href;
  22238. }
  22239. // exposed for testing
  22240. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  22241. /**
  22242. * Sets the base URL for resolving modules.
  22243. * @param {String} value The new base URL.
  22244. */
  22245. buildModuleUrl.setBaseUrl = function(value) {
  22246. baseUrl = new Uri(value).resolve(new Uri(document.location.href));
  22247. };
  22248. return buildModuleUrl;
  22249. });
  22250. /*global define*/
  22251. define('Core/Iau2006XysSample',[],function() {
  22252. 'use strict';
  22253. /**
  22254. * An IAU 2006 XYS value sampled at a particular time.
  22255. *
  22256. * @alias Iau2006XysSample
  22257. * @constructor
  22258. *
  22259. * @param {Number} x The X value.
  22260. * @param {Number} y The Y value.
  22261. * @param {Number} s The S value.
  22262. *
  22263. * @private
  22264. */
  22265. function Iau2006XysSample(x, y, s) {
  22266. /**
  22267. * The X value.
  22268. * @type {Number}
  22269. */
  22270. this.x = x;
  22271. /**
  22272. * The Y value.
  22273. * @type {Number}
  22274. */
  22275. this.y = y;
  22276. /**
  22277. * The S value.
  22278. * @type {Number}
  22279. */
  22280. this.s = s;
  22281. }
  22282. return Iau2006XysSample;
  22283. });
  22284. /*global define*/
  22285. define('Core/Iau2006XysData',[
  22286. '../ThirdParty/when',
  22287. './buildModuleUrl',
  22288. './defaultValue',
  22289. './defined',
  22290. './Iau2006XysSample',
  22291. './JulianDate',
  22292. './loadJson',
  22293. './TimeStandard'
  22294. ], function(
  22295. when,
  22296. buildModuleUrl,
  22297. defaultValue,
  22298. defined,
  22299. Iau2006XysSample,
  22300. JulianDate,
  22301. loadJson,
  22302. TimeStandard) {
  22303. 'use strict';
  22304. /**
  22305. * A set of IAU2006 XYS data that is used to evaluate the transformation between the International
  22306. * Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
  22307. *
  22308. * @alias Iau2006XysData
  22309. * @constructor
  22310. *
  22311. * @param {Object} [options] Object with the following properties:
  22312. * @param {String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
  22313. * `{0}` will be replaced with the file index.
  22314. * @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
  22315. * @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
  22316. * first XYS sample.
  22317. * @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
  22318. * @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
  22319. * @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
  22320. *
  22321. * @private
  22322. */
  22323. function Iau2006XysData(options) {
  22324. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  22325. this._xysFileUrlTemplate = options.xysFileUrlTemplate;
  22326. this._interpolationOrder = defaultValue(options.interpolationOrder, 9);
  22327. this._sampleZeroJulianEphemerisDate = defaultValue(options.sampleZeroJulianEphemerisDate, 2442396.5);
  22328. this._sampleZeroDateTT = new JulianDate(this._sampleZeroJulianEphemerisDate, 0.0, TimeStandard.TAI);
  22329. this._stepSizeDays = defaultValue(options.stepSizeDays, 1.0);
  22330. this._samplesPerXysFile = defaultValue(options.samplesPerXysFile, 1000);
  22331. this._totalSamples = defaultValue(options.totalSamples, 27426);
  22332. this._samples = new Array(this._totalSamples * 3);
  22333. this._chunkDownloadsInProgress = [];
  22334. var order = this._interpolationOrder;
  22335. // Compute denominators and X values for interpolation.
  22336. var denom = this._denominators = new Array(order + 1);
  22337. var xTable = this._xTable = new Array(order + 1);
  22338. var stepN = Math.pow(this._stepSizeDays, order);
  22339. for ( var i = 0; i <= order; ++i) {
  22340. denom[i] = stepN;
  22341. xTable[i] = i * this._stepSizeDays;
  22342. for ( var j = 0; j <= order; ++j) {
  22343. if (j !== i) {
  22344. denom[i] *= (i - j);
  22345. }
  22346. }
  22347. denom[i] = 1.0 / denom[i];
  22348. }
  22349. // Allocate scratch arrays for interpolation.
  22350. this._work = new Array(order + 1);
  22351. this._coef = new Array(order + 1);
  22352. }
  22353. var julianDateScratch = new JulianDate(0, 0.0, TimeStandard.TAI);
  22354. function getDaysSinceEpoch(xys, dayTT, secondTT) {
  22355. var dateTT = julianDateScratch;
  22356. dateTT.dayNumber = dayTT;
  22357. dateTT.secondsOfDay = secondTT;
  22358. return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
  22359. }
  22360. /**
  22361. * Preloads XYS data for a specified date range.
  22362. *
  22363. * @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
  22364. * the Terrestrial Time (TT) time standard.
  22365. * @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
  22366. * the Terrestrial Time (TT) time standard.
  22367. * @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
  22368. * the Terrestrial Time (TT) time standard.
  22369. * @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
  22370. * the Terrestrial Time (TT) time standard.
  22371. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the requested interval has been
  22372. * preloaded.
  22373. */
  22374. Iau2006XysData.prototype.preload = function(startDayTT, startSecondTT, stopDayTT, stopSecondTT) {
  22375. var startDaysSinceEpoch = getDaysSinceEpoch(this, startDayTT, startSecondTT);
  22376. var stopDaysSinceEpoch = getDaysSinceEpoch(this, stopDayTT, stopSecondTT);
  22377. var startIndex = (startDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0;
  22378. if (startIndex < 0) {
  22379. startIndex = 0;
  22380. }
  22381. var stopIndex = (stopDaysSinceEpoch / this._stepSizeDays - this._interpolationOrder / 2) | 0 + this._interpolationOrder;
  22382. if (stopIndex >= this._totalSamples) {
  22383. stopIndex = this._totalSamples - 1;
  22384. }
  22385. var startChunk = (startIndex / this._samplesPerXysFile) | 0;
  22386. var stopChunk = (stopIndex / this._samplesPerXysFile) | 0;
  22387. var promises = [];
  22388. for ( var i = startChunk; i <= stopChunk; ++i) {
  22389. promises.push(requestXysChunk(this, i));
  22390. }
  22391. return when.all(promises);
  22392. };
  22393. /**
  22394. * Computes the XYS values for a given date by interpolating. If the required data is not yet downloaded,
  22395. * this method will return undefined.
  22396. *
  22397. * @param {Number} dayTT The Julian day number for which to compute the XYS value, expressed in
  22398. * the Terrestrial Time (TT) time standard.
  22399. * @param {Number} secondTT The seconds past noon of the date for which to compute the XYS value, expressed in
  22400. * the Terrestrial Time (TT) time standard.
  22401. * @param {Iau2006XysSample} [result] The instance to which to copy the interpolated result. If this parameter
  22402. * is undefined, a new instance is allocated and returned.
  22403. * @returns {Iau2006XysSample} The interpolated XYS values, or undefined if the required data for this
  22404. * computation has not yet been downloaded.
  22405. *
  22406. * @see Iau2006XysData#preload
  22407. */
  22408. Iau2006XysData.prototype.computeXysRadians = function(dayTT, secondTT, result) {
  22409. var daysSinceEpoch = getDaysSinceEpoch(this, dayTT, secondTT);
  22410. if (daysSinceEpoch < 0.0) {
  22411. // Can't evaluate prior to the epoch of the data.
  22412. return undefined;
  22413. }
  22414. var centerIndex = (daysSinceEpoch / this._stepSizeDays) | 0;
  22415. if (centerIndex >= this._totalSamples) {
  22416. // Can't evaluate after the last sample in the data.
  22417. return undefined;
  22418. }
  22419. var degree = this._interpolationOrder;
  22420. var firstIndex = centerIndex - ((degree / 2) | 0);
  22421. if (firstIndex < 0) {
  22422. firstIndex = 0;
  22423. }
  22424. var lastIndex = firstIndex + degree;
  22425. if (lastIndex >= this._totalSamples) {
  22426. lastIndex = this._totalSamples - 1;
  22427. firstIndex = lastIndex - degree;
  22428. if (firstIndex < 0) {
  22429. firstIndex = 0;
  22430. }
  22431. }
  22432. // Are all the samples we need present?
  22433. // We can assume so if the first and last are present
  22434. var isDataMissing = false;
  22435. var samples = this._samples;
  22436. if (!defined(samples[firstIndex * 3])) {
  22437. requestXysChunk(this, (firstIndex / this._samplesPerXysFile) | 0);
  22438. isDataMissing = true;
  22439. }
  22440. if (!defined(samples[lastIndex * 3])) {
  22441. requestXysChunk(this, (lastIndex / this._samplesPerXysFile) | 0);
  22442. isDataMissing = true;
  22443. }
  22444. if (isDataMissing) {
  22445. return undefined;
  22446. }
  22447. if (!defined(result)) {
  22448. result = new Iau2006XysSample(0.0, 0.0, 0.0);
  22449. } else {
  22450. result.x = 0.0;
  22451. result.y = 0.0;
  22452. result.s = 0.0;
  22453. }
  22454. var x = daysSinceEpoch - firstIndex * this._stepSizeDays;
  22455. var work = this._work;
  22456. var denom = this._denominators;
  22457. var coef = this._coef;
  22458. var xTable = this._xTable;
  22459. var i, j;
  22460. for (i = 0; i <= degree; ++i) {
  22461. work[i] = x - xTable[i];
  22462. }
  22463. for (i = 0; i <= degree; ++i) {
  22464. coef[i] = 1.0;
  22465. for (j = 0; j <= degree; ++j) {
  22466. if (j !== i) {
  22467. coef[i] *= work[j];
  22468. }
  22469. }
  22470. coef[i] *= denom[i];
  22471. var sampleIndex = (firstIndex + i) * 3;
  22472. result.x += coef[i] * samples[sampleIndex++];
  22473. result.y += coef[i] * samples[sampleIndex++];
  22474. result.s += coef[i] * samples[sampleIndex];
  22475. }
  22476. return result;
  22477. };
  22478. function requestXysChunk(xysData, chunkIndex) {
  22479. if (xysData._chunkDownloadsInProgress[chunkIndex]) {
  22480. // Chunk has already been requested.
  22481. return xysData._chunkDownloadsInProgress[chunkIndex];
  22482. }
  22483. var deferred = when.defer();
  22484. xysData._chunkDownloadsInProgress[chunkIndex] = deferred;
  22485. var chunkUrl;
  22486. var xysFileUrlTemplate = xysData._xysFileUrlTemplate;
  22487. if (defined(xysFileUrlTemplate)) {
  22488. chunkUrl = xysFileUrlTemplate.replace('{0}', chunkIndex);
  22489. } else {
  22490. chunkUrl = buildModuleUrl('Assets/IAU2006_XYS/IAU2006_XYS_' + chunkIndex + '.json');
  22491. }
  22492. when(loadJson(chunkUrl), function(chunk) {
  22493. xysData._chunkDownloadsInProgress[chunkIndex] = false;
  22494. var samples = xysData._samples;
  22495. var newSamples = chunk.samples;
  22496. var startIndex = chunkIndex * xysData._samplesPerXysFile * 3;
  22497. for ( var i = 0, len = newSamples.length; i < len; ++i) {
  22498. samples[startIndex + i] = newSamples[i];
  22499. }
  22500. deferred.resolve();
  22501. });
  22502. return deferred.promise;
  22503. }
  22504. return Iau2006XysData;
  22505. });
  22506. /*global define*/
  22507. define('Core/Quaternion',[
  22508. './Cartesian3',
  22509. './defaultValue',
  22510. './defined',
  22511. './DeveloperError',
  22512. './FeatureDetection',
  22513. './freezeObject',
  22514. './Math',
  22515. './Matrix3'
  22516. ], function(
  22517. Cartesian3,
  22518. defaultValue,
  22519. defined,
  22520. DeveloperError,
  22521. FeatureDetection,
  22522. freezeObject,
  22523. CesiumMath,
  22524. Matrix3) {
  22525. 'use strict';
  22526. /**
  22527. * A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
  22528. * @alias Quaternion
  22529. * @constructor
  22530. *
  22531. * @param {Number} [x=0.0] The X component.
  22532. * @param {Number} [y=0.0] The Y component.
  22533. * @param {Number} [z=0.0] The Z component.
  22534. * @param {Number} [w=0.0] The W component.
  22535. *
  22536. * @see PackableForInterpolation
  22537. */
  22538. function Quaternion(x, y, z, w) {
  22539. /**
  22540. * The X component.
  22541. * @type {Number}
  22542. * @default 0.0
  22543. */
  22544. this.x = defaultValue(x, 0.0);
  22545. /**
  22546. * The Y component.
  22547. * @type {Number}
  22548. * @default 0.0
  22549. */
  22550. this.y = defaultValue(y, 0.0);
  22551. /**
  22552. * The Z component.
  22553. * @type {Number}
  22554. * @default 0.0
  22555. */
  22556. this.z = defaultValue(z, 0.0);
  22557. /**
  22558. * The W component.
  22559. * @type {Number}
  22560. * @default 0.0
  22561. */
  22562. this.w = defaultValue(w, 0.0);
  22563. }
  22564. var fromAxisAngleScratch = new Cartesian3();
  22565. /**
  22566. * Computes a quaternion representing a rotation around an axis.
  22567. *
  22568. * @param {Cartesian3} axis The axis of rotation.
  22569. * @param {Number} angle The angle in radians to rotate around the axis.
  22570. * @param {Quaternion} [result] The object onto which to store the result.
  22571. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  22572. */
  22573. Quaternion.fromAxisAngle = function(axis, angle, result) {
  22574. if (!defined(axis)) {
  22575. throw new DeveloperError('axis is required.');
  22576. }
  22577. if (typeof angle !== 'number') {
  22578. throw new DeveloperError('angle is required and must be a number.');
  22579. }
  22580. var halfAngle = angle / 2.0;
  22581. var s = Math.sin(halfAngle);
  22582. fromAxisAngleScratch = Cartesian3.normalize(axis, fromAxisAngleScratch);
  22583. var x = fromAxisAngleScratch.x * s;
  22584. var y = fromAxisAngleScratch.y * s;
  22585. var z = fromAxisAngleScratch.z * s;
  22586. var w = Math.cos(halfAngle);
  22587. if (!defined(result)) {
  22588. return new Quaternion(x, y, z, w);
  22589. }
  22590. result.x = x;
  22591. result.y = y;
  22592. result.z = z;
  22593. result.w = w;
  22594. return result;
  22595. };
  22596. var fromRotationMatrixNext = [1, 2, 0];
  22597. var fromRotationMatrixQuat = new Array(3);
  22598. /**
  22599. * Computes a Quaternion from the provided Matrix3 instance.
  22600. *
  22601. * @param {Matrix3} matrix The rotation matrix.
  22602. * @param {Quaternion} [result] The object onto which to store the result.
  22603. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  22604. *
  22605. * @see Matrix3.fromQuaternion
  22606. */
  22607. Quaternion.fromRotationMatrix = function(matrix, result) {
  22608. if (!defined(matrix)) {
  22609. throw new DeveloperError('matrix is required.');
  22610. }
  22611. var root;
  22612. var x;
  22613. var y;
  22614. var z;
  22615. var w;
  22616. var m00 = matrix[Matrix3.COLUMN0ROW0];
  22617. var m11 = matrix[Matrix3.COLUMN1ROW1];
  22618. var m22 = matrix[Matrix3.COLUMN2ROW2];
  22619. var trace = m00 + m11 + m22;
  22620. if (trace > 0.0) {
  22621. // |w| > 1/2, may as well choose w > 1/2
  22622. root = Math.sqrt(trace + 1.0); // 2w
  22623. w = 0.5 * root;
  22624. root = 0.5 / root; // 1/(4w)
  22625. x = (matrix[Matrix3.COLUMN1ROW2] - matrix[Matrix3.COLUMN2ROW1]) * root;
  22626. y = (matrix[Matrix3.COLUMN2ROW0] - matrix[Matrix3.COLUMN0ROW2]) * root;
  22627. z = (matrix[Matrix3.COLUMN0ROW1] - matrix[Matrix3.COLUMN1ROW0]) * root;
  22628. } else {
  22629. // |w| <= 1/2
  22630. var next = fromRotationMatrixNext;
  22631. var i = 0;
  22632. if (m11 > m00) {
  22633. i = 1;
  22634. }
  22635. if (m22 > m00 && m22 > m11) {
  22636. i = 2;
  22637. }
  22638. var j = next[i];
  22639. var k = next[j];
  22640. root = Math.sqrt(matrix[Matrix3.getElementIndex(i, i)] - matrix[Matrix3.getElementIndex(j, j)] - matrix[Matrix3.getElementIndex(k, k)] + 1.0);
  22641. var quat = fromRotationMatrixQuat;
  22642. quat[i] = 0.5 * root;
  22643. root = 0.5 / root;
  22644. w = (matrix[Matrix3.getElementIndex(k, j)] - matrix[Matrix3.getElementIndex(j, k)]) * root;
  22645. quat[j] = (matrix[Matrix3.getElementIndex(j, i)] + matrix[Matrix3.getElementIndex(i, j)]) * root;
  22646. quat[k] = (matrix[Matrix3.getElementIndex(k, i)] + matrix[Matrix3.getElementIndex(i, k)]) * root;
  22647. x = -quat[0];
  22648. y = -quat[1];
  22649. z = -quat[2];
  22650. }
  22651. if (!defined(result)) {
  22652. return new Quaternion(x, y, z, w);
  22653. }
  22654. result.x = x;
  22655. result.y = y;
  22656. result.z = z;
  22657. result.w = w;
  22658. return result;
  22659. };
  22660. var scratchHPRQuaternion = new Quaternion();
  22661. /**
  22662. * Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
  22663. * negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
  22664. * the positive x axis.
  22665. *
  22666. * @param {Number} heading The heading angle in radians.
  22667. * @param {Number} pitch The pitch angle in radians.
  22668. * @param {Number} roll The roll angle in radians.
  22669. * @param {Quaternion} [result] The object onto which to store the result.
  22670. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  22671. */
  22672. Quaternion.fromHeadingPitchRoll = function(heading, pitch, roll, result) {
  22673. if (!defined(heading)) {
  22674. throw new DeveloperError('heading is required.');
  22675. }
  22676. if (!defined(pitch)) {
  22677. throw new DeveloperError('pitch is required.');
  22678. }
  22679. if (!defined(roll)) {
  22680. throw new DeveloperError('roll is required.');
  22681. }
  22682. var rollQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_X, roll, scratchHPRQuaternion);
  22683. var pitchQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Y, -pitch, result);
  22684. result = Quaternion.multiply(pitchQuaternion, rollQuaternion, pitchQuaternion);
  22685. var headingQuaternion = Quaternion.fromAxisAngle(Cartesian3.UNIT_Z, -heading, scratchHPRQuaternion);
  22686. return Quaternion.multiply(headingQuaternion, result, result);
  22687. };
  22688. var sampledQuaternionAxis = new Cartesian3();
  22689. var sampledQuaternionRotation = new Cartesian3();
  22690. var sampledQuaternionTempQuaternion = new Quaternion();
  22691. var sampledQuaternionQuaternion0 = new Quaternion();
  22692. var sampledQuaternionQuaternion0Conjugate = new Quaternion();
  22693. /**
  22694. * The number of elements used to pack the object into an array.
  22695. * @type {Number}
  22696. */
  22697. Quaternion.packedLength = 4;
  22698. /**
  22699. * Stores the provided instance into the provided array.
  22700. *
  22701. * @param {Quaternion} value The value to pack.
  22702. * @param {Number[]} array The array to pack into.
  22703. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  22704. *
  22705. * @returns {Number[]} The array that was packed into
  22706. */
  22707. Quaternion.pack = function(value, array, startingIndex) {
  22708. if (!defined(value)) {
  22709. throw new DeveloperError('value is required');
  22710. }
  22711. if (!defined(array)) {
  22712. throw new DeveloperError('array is required');
  22713. }
  22714. startingIndex = defaultValue(startingIndex, 0);
  22715. array[startingIndex++] = value.x;
  22716. array[startingIndex++] = value.y;
  22717. array[startingIndex++] = value.z;
  22718. array[startingIndex] = value.w;
  22719. return array;
  22720. };
  22721. /**
  22722. * Retrieves an instance from a packed array.
  22723. *
  22724. * @param {Number[]} array The packed array.
  22725. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  22726. * @param {Quaternion} [result] The object into which to store the result.
  22727. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  22728. */
  22729. Quaternion.unpack = function(array, startingIndex, result) {
  22730. if (!defined(array)) {
  22731. throw new DeveloperError('array is required');
  22732. }
  22733. startingIndex = defaultValue(startingIndex, 0);
  22734. if (!defined(result)) {
  22735. result = new Quaternion();
  22736. }
  22737. result.x = array[startingIndex];
  22738. result.y = array[startingIndex + 1];
  22739. result.z = array[startingIndex + 2];
  22740. result.w = array[startingIndex + 3];
  22741. return result;
  22742. };
  22743. /**
  22744. * The number of elements used to store the object into an array in its interpolatable form.
  22745. * @type {Number}
  22746. */
  22747. Quaternion.packedInterpolationLength = 3;
  22748. /**
  22749. * Converts a packed array into a form suitable for interpolation.
  22750. *
  22751. * @param {Number[]} packedArray The packed array.
  22752. * @param {Number} [startingIndex=0] The index of the first element to be converted.
  22753. * @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
  22754. * @param {Number[]} result The object into which to store the result.
  22755. */
  22756. Quaternion.convertPackedArrayForInterpolation = function(packedArray, startingIndex, lastIndex, result) {
  22757. Quaternion.unpack(packedArray, lastIndex * 4, sampledQuaternionQuaternion0Conjugate);
  22758. Quaternion.conjugate(sampledQuaternionQuaternion0Conjugate, sampledQuaternionQuaternion0Conjugate);
  22759. for (var i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
  22760. var offset = i * 3;
  22761. Quaternion.unpack(packedArray, (startingIndex + i) * 4, sampledQuaternionTempQuaternion);
  22762. Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0Conjugate, sampledQuaternionTempQuaternion);
  22763. if (sampledQuaternionTempQuaternion.w < 0) {
  22764. Quaternion.negate(sampledQuaternionTempQuaternion, sampledQuaternionTempQuaternion);
  22765. }
  22766. Quaternion.computeAxis(sampledQuaternionTempQuaternion, sampledQuaternionAxis);
  22767. var angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
  22768. result[offset] = sampledQuaternionAxis.x * angle;
  22769. result[offset + 1] = sampledQuaternionAxis.y * angle;
  22770. result[offset + 2] = sampledQuaternionAxis.z * angle;
  22771. }
  22772. };
  22773. /**
  22774. * Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
  22775. *
  22776. * @param {Number[]} array The array previously packed for interpolation.
  22777. * @param {Number[]} sourceArray The original packed array.
  22778. * @param {Number} [startingIndex=0] The startingIndex used to convert the array.
  22779. * @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
  22780. * @param {Quaternion} [result] The object into which to store the result.
  22781. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  22782. */
  22783. Quaternion.unpackInterpolationResult = function(array, sourceArray, firstIndex, lastIndex, result) {
  22784. if (!defined(result)) {
  22785. result = new Quaternion();
  22786. }
  22787. Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
  22788. var magnitude = Cartesian3.magnitude(sampledQuaternionRotation);
  22789. Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
  22790. if (magnitude === 0) {
  22791. Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
  22792. } else {
  22793. Quaternion.fromAxisAngle(sampledQuaternionRotation, magnitude, sampledQuaternionTempQuaternion);
  22794. }
  22795. return Quaternion.multiply(sampledQuaternionTempQuaternion, sampledQuaternionQuaternion0, result);
  22796. };
  22797. /**
  22798. * Duplicates a Quaternion instance.
  22799. *
  22800. * @param {Quaternion} quaternion The quaternion to duplicate.
  22801. * @param {Quaternion} [result] The object onto which to store the result.
  22802. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
  22803. */
  22804. Quaternion.clone = function(quaternion, result) {
  22805. if (!defined(quaternion)) {
  22806. return undefined;
  22807. }
  22808. if (!defined(result)) {
  22809. return new Quaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  22810. }
  22811. result.x = quaternion.x;
  22812. result.y = quaternion.y;
  22813. result.z = quaternion.z;
  22814. result.w = quaternion.w;
  22815. return result;
  22816. };
  22817. /**
  22818. * Computes the conjugate of the provided quaternion.
  22819. *
  22820. * @param {Quaternion} quaternion The quaternion to conjugate.
  22821. * @param {Quaternion} result The object onto which to store the result.
  22822. * @returns {Quaternion} The modified result parameter.
  22823. */
  22824. Quaternion.conjugate = function(quaternion, result) {
  22825. if (!defined(quaternion)) {
  22826. throw new DeveloperError('quaternion is required');
  22827. }
  22828. if (!defined(result)) {
  22829. throw new DeveloperError('result is required');
  22830. }
  22831. result.x = -quaternion.x;
  22832. result.y = -quaternion.y;
  22833. result.z = -quaternion.z;
  22834. result.w = quaternion.w;
  22835. return result;
  22836. };
  22837. /**
  22838. * Computes magnitude squared for the provided quaternion.
  22839. *
  22840. * @param {Quaternion} quaternion The quaternion to conjugate.
  22841. * @returns {Number} The magnitude squared.
  22842. */
  22843. Quaternion.magnitudeSquared = function(quaternion) {
  22844. if (!defined(quaternion)) {
  22845. throw new DeveloperError('quaternion is required');
  22846. }
  22847. return quaternion.x * quaternion.x + quaternion.y * quaternion.y + quaternion.z * quaternion.z + quaternion.w * quaternion.w;
  22848. };
  22849. /**
  22850. * Computes magnitude for the provided quaternion.
  22851. *
  22852. * @param {Quaternion} quaternion The quaternion to conjugate.
  22853. * @returns {Number} The magnitude.
  22854. */
  22855. Quaternion.magnitude = function(quaternion) {
  22856. return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
  22857. };
  22858. /**
  22859. * Computes the normalized form of the provided quaternion.
  22860. *
  22861. * @param {Quaternion} quaternion The quaternion to normalize.
  22862. * @param {Quaternion} result The object onto which to store the result.
  22863. * @returns {Quaternion} The modified result parameter.
  22864. */
  22865. Quaternion.normalize = function(quaternion, result) {
  22866. if (!defined(result)) {
  22867. throw new DeveloperError('result is required');
  22868. }
  22869. var inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
  22870. var x = quaternion.x * inverseMagnitude;
  22871. var y = quaternion.y * inverseMagnitude;
  22872. var z = quaternion.z * inverseMagnitude;
  22873. var w = quaternion.w * inverseMagnitude;
  22874. result.x = x;
  22875. result.y = y;
  22876. result.z = z;
  22877. result.w = w;
  22878. return result;
  22879. };
  22880. /**
  22881. * Computes the inverse of the provided quaternion.
  22882. *
  22883. * @param {Quaternion} quaternion The quaternion to normalize.
  22884. * @param {Quaternion} result The object onto which to store the result.
  22885. * @returns {Quaternion} The modified result parameter.
  22886. */
  22887. Quaternion.inverse = function(quaternion, result) {
  22888. if (!defined(result)) {
  22889. throw new DeveloperError('result is required');
  22890. }
  22891. var magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
  22892. result = Quaternion.conjugate(quaternion, result);
  22893. return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
  22894. };
  22895. /**
  22896. * Computes the componentwise sum of two quaternions.
  22897. *
  22898. * @param {Quaternion} left The first quaternion.
  22899. * @param {Quaternion} right The second quaternion.
  22900. * @param {Quaternion} result The object onto which to store the result.
  22901. * @returns {Quaternion} The modified result parameter.
  22902. */
  22903. Quaternion.add = function(left, right, result) {
  22904. if (!defined(left)) {
  22905. throw new DeveloperError('left is required');
  22906. }
  22907. if (!defined(right)) {
  22908. throw new DeveloperError('right is required');
  22909. }
  22910. if (!defined(result)) {
  22911. throw new DeveloperError('result is required');
  22912. }
  22913. result.x = left.x + right.x;
  22914. result.y = left.y + right.y;
  22915. result.z = left.z + right.z;
  22916. result.w = left.w + right.w;
  22917. return result;
  22918. };
  22919. /**
  22920. * Computes the componentwise difference of two quaternions.
  22921. *
  22922. * @param {Quaternion} left The first quaternion.
  22923. * @param {Quaternion} right The second quaternion.
  22924. * @param {Quaternion} result The object onto which to store the result.
  22925. * @returns {Quaternion} The modified result parameter.
  22926. */
  22927. Quaternion.subtract = function(left, right, result) {
  22928. if (!defined(left)) {
  22929. throw new DeveloperError('left is required');
  22930. }
  22931. if (!defined(right)) {
  22932. throw new DeveloperError('right is required');
  22933. }
  22934. if (!defined(result)) {
  22935. throw new DeveloperError('result is required');
  22936. }
  22937. result.x = left.x - right.x;
  22938. result.y = left.y - right.y;
  22939. result.z = left.z - right.z;
  22940. result.w = left.w - right.w;
  22941. return result;
  22942. };
  22943. /**
  22944. * Negates the provided quaternion.
  22945. *
  22946. * @param {Quaternion} quaternion The quaternion to be negated.
  22947. * @param {Quaternion} result The object onto which to store the result.
  22948. * @returns {Quaternion} The modified result parameter.
  22949. */
  22950. Quaternion.negate = function(quaternion, result) {
  22951. if (!defined(quaternion)) {
  22952. throw new DeveloperError('quaternion is required');
  22953. }
  22954. if (!defined(result)) {
  22955. throw new DeveloperError('result is required');
  22956. }
  22957. result.x = -quaternion.x;
  22958. result.y = -quaternion.y;
  22959. result.z = -quaternion.z;
  22960. result.w = -quaternion.w;
  22961. return result;
  22962. };
  22963. /**
  22964. * Computes the dot (scalar) product of two quaternions.
  22965. *
  22966. * @param {Quaternion} left The first quaternion.
  22967. * @param {Quaternion} right The second quaternion.
  22968. * @returns {Number} The dot product.
  22969. */
  22970. Quaternion.dot = function(left, right) {
  22971. if (!defined(left)) {
  22972. throw new DeveloperError('left is required');
  22973. }
  22974. if (!defined(right)) {
  22975. throw new DeveloperError('right is required');
  22976. }
  22977. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  22978. };
  22979. /**
  22980. * Computes the product of two quaternions.
  22981. *
  22982. * @param {Quaternion} left The first quaternion.
  22983. * @param {Quaternion} right The second quaternion.
  22984. * @param {Quaternion} result The object onto which to store the result.
  22985. * @returns {Quaternion} The modified result parameter.
  22986. */
  22987. Quaternion.multiply = function(left, right, result) {
  22988. if (!defined(left)) {
  22989. throw new DeveloperError('left is required');
  22990. }
  22991. if (!defined(right)) {
  22992. throw new DeveloperError('right is required');
  22993. }
  22994. if (!defined(result)) {
  22995. throw new DeveloperError('result is required');
  22996. }
  22997. var leftX = left.x;
  22998. var leftY = left.y;
  22999. var leftZ = left.z;
  23000. var leftW = left.w;
  23001. var rightX = right.x;
  23002. var rightY = right.y;
  23003. var rightZ = right.z;
  23004. var rightW = right.w;
  23005. var x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
  23006. var y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
  23007. var z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
  23008. var w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
  23009. result.x = x;
  23010. result.y = y;
  23011. result.z = z;
  23012. result.w = w;
  23013. return result;
  23014. };
  23015. /**
  23016. * Multiplies the provided quaternion componentwise by the provided scalar.
  23017. *
  23018. * @param {Quaternion} quaternion The quaternion to be scaled.
  23019. * @param {Number} scalar The scalar to multiply with.
  23020. * @param {Quaternion} result The object onto which to store the result.
  23021. * @returns {Quaternion} The modified result parameter.
  23022. */
  23023. Quaternion.multiplyByScalar = function(quaternion, scalar, result) {
  23024. if (!defined(quaternion)) {
  23025. throw new DeveloperError('quaternion is required');
  23026. }
  23027. if (typeof scalar !== 'number') {
  23028. throw new DeveloperError('scalar is required and must be a number.');
  23029. }
  23030. if (!defined(result)) {
  23031. throw new DeveloperError('result is required');
  23032. }
  23033. result.x = quaternion.x * scalar;
  23034. result.y = quaternion.y * scalar;
  23035. result.z = quaternion.z * scalar;
  23036. result.w = quaternion.w * scalar;
  23037. return result;
  23038. };
  23039. /**
  23040. * Divides the provided quaternion componentwise by the provided scalar.
  23041. *
  23042. * @param {Quaternion} quaternion The quaternion to be divided.
  23043. * @param {Number} scalar The scalar to divide by.
  23044. * @param {Quaternion} result The object onto which to store the result.
  23045. * @returns {Quaternion} The modified result parameter.
  23046. */
  23047. Quaternion.divideByScalar = function(quaternion, scalar, result) {
  23048. if (!defined(quaternion)) {
  23049. throw new DeveloperError('quaternion is required');
  23050. }
  23051. if (typeof scalar !== 'number') {
  23052. throw new DeveloperError('scalar is required and must be a number.');
  23053. }
  23054. if (!defined(result)) {
  23055. throw new DeveloperError('result is required');
  23056. }
  23057. result.x = quaternion.x / scalar;
  23058. result.y = quaternion.y / scalar;
  23059. result.z = quaternion.z / scalar;
  23060. result.w = quaternion.w / scalar;
  23061. return result;
  23062. };
  23063. /**
  23064. * Computes the axis of rotation of the provided quaternion.
  23065. *
  23066. * @param {Quaternion} quaternion The quaternion to use.
  23067. * @param {Cartesian3} result The object onto which to store the result.
  23068. * @returns {Cartesian3} The modified result parameter.
  23069. */
  23070. Quaternion.computeAxis = function(quaternion, result) {
  23071. if (!defined(quaternion)) {
  23072. throw new DeveloperError('quaternion is required');
  23073. }
  23074. if (!defined(result)) {
  23075. throw new DeveloperError('result is required');
  23076. }
  23077. var w = quaternion.w;
  23078. if (Math.abs(w - 1.0) < CesiumMath.EPSILON6) {
  23079. result.x = result.y = result.z = 0;
  23080. return result;
  23081. }
  23082. var scalar = 1.0 / Math.sqrt(1.0 - (w * w));
  23083. result.x = quaternion.x * scalar;
  23084. result.y = quaternion.y * scalar;
  23085. result.z = quaternion.z * scalar;
  23086. return result;
  23087. };
  23088. /**
  23089. * Computes the angle of rotation of the provided quaternion.
  23090. *
  23091. * @param {Quaternion} quaternion The quaternion to use.
  23092. * @returns {Number} The angle of rotation.
  23093. */
  23094. Quaternion.computeAngle = function(quaternion) {
  23095. if (!defined(quaternion)) {
  23096. throw new DeveloperError('quaternion is required');
  23097. }
  23098. if (Math.abs(quaternion.w - 1.0) < CesiumMath.EPSILON6) {
  23099. return 0.0;
  23100. }
  23101. return 2.0 * Math.acos(quaternion.w);
  23102. };
  23103. var lerpScratch = new Quaternion();
  23104. /**
  23105. * Computes the linear interpolation or extrapolation at t using the provided quaternions.
  23106. *
  23107. * @param {Quaternion} start The value corresponding to t at 0.0.
  23108. * @param {Quaternion} end The value corresponding to t at 1.0.
  23109. * @param {Number} t The point along t at which to interpolate.
  23110. * @param {Quaternion} result The object onto which to store the result.
  23111. * @returns {Quaternion} The modified result parameter.
  23112. */
  23113. Quaternion.lerp = function(start, end, t, result) {
  23114. if (!defined(start)) {
  23115. throw new DeveloperError('start is required.');
  23116. }
  23117. if (!defined(end)) {
  23118. throw new DeveloperError('end is required.');
  23119. }
  23120. if (typeof t !== 'number') {
  23121. throw new DeveloperError('t is required and must be a number.');
  23122. }
  23123. if (!defined(result)) {
  23124. throw new DeveloperError('result is required');
  23125. }
  23126. lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
  23127. result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
  23128. return Quaternion.add(lerpScratch, result, result);
  23129. };
  23130. var slerpEndNegated = new Quaternion();
  23131. var slerpScaledP = new Quaternion();
  23132. var slerpScaledR = new Quaternion();
  23133. /**
  23134. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  23135. *
  23136. * @param {Quaternion} start The value corresponding to t at 0.0.
  23137. * @param {Quaternion} end The value corresponding to t at 1.0.
  23138. * @param {Number} t The point along t at which to interpolate.
  23139. * @param {Quaternion} result The object onto which to store the result.
  23140. * @returns {Quaternion} The modified result parameter.
  23141. *
  23142. * @see Quaternion#fastSlerp
  23143. */
  23144. Quaternion.slerp = function(start, end, t, result) {
  23145. if (!defined(start)) {
  23146. throw new DeveloperError('start is required.');
  23147. }
  23148. if (!defined(end)) {
  23149. throw new DeveloperError('end is required.');
  23150. }
  23151. if (typeof t !== 'number') {
  23152. throw new DeveloperError('t is required and must be a number.');
  23153. }
  23154. if (!defined(result)) {
  23155. throw new DeveloperError('result is required');
  23156. }
  23157. var dot = Quaternion.dot(start, end);
  23158. // The angle between start must be acute. Since q and -q represent
  23159. // the same rotation, negate q to get the acute angle.
  23160. var r = end;
  23161. if (dot < 0.0) {
  23162. dot = -dot;
  23163. r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
  23164. }
  23165. // dot > 0, as the dot product approaches 1, the angle between the
  23166. // quaternions vanishes. use linear interpolation.
  23167. if (1.0 - dot < CesiumMath.EPSILON6) {
  23168. return Quaternion.lerp(start, r, t, result);
  23169. }
  23170. var theta = Math.acos(dot);
  23171. slerpScaledP = Quaternion.multiplyByScalar(start, Math.sin((1 - t) * theta), slerpScaledP);
  23172. slerpScaledR = Quaternion.multiplyByScalar(r, Math.sin(t * theta), slerpScaledR);
  23173. result = Quaternion.add(slerpScaledP, slerpScaledR, result);
  23174. return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
  23175. };
  23176. /**
  23177. * The logarithmic quaternion function.
  23178. *
  23179. * @param {Quaternion} quaternion The unit quaternion.
  23180. * @param {Cartesian3} result The object onto which to store the result.
  23181. * @returns {Cartesian3} The modified result parameter.
  23182. */
  23183. Quaternion.log = function(quaternion, result) {
  23184. if (!defined(quaternion)) {
  23185. throw new DeveloperError('quaternion is required.');
  23186. }
  23187. if (!defined(result)) {
  23188. throw new DeveloperError('result is required');
  23189. }
  23190. var theta = CesiumMath.acosClamped(quaternion.w);
  23191. var thetaOverSinTheta = 0.0;
  23192. if (theta !== 0.0) {
  23193. thetaOverSinTheta = theta / Math.sin(theta);
  23194. }
  23195. return Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
  23196. };
  23197. /**
  23198. * The exponential quaternion function.
  23199. *
  23200. * @param {Cartesian3} cartesian The cartesian.
  23201. * @param {Quaternion} result The object onto which to store the result.
  23202. * @returns {Quaternion} The modified result parameter.
  23203. */
  23204. Quaternion.exp = function(cartesian, result) {
  23205. if (!defined(cartesian)) {
  23206. throw new DeveloperError('cartesian is required.');
  23207. }
  23208. if (!defined(result)) {
  23209. throw new DeveloperError('result is required');
  23210. }
  23211. var theta = Cartesian3.magnitude(cartesian);
  23212. var sinThetaOverTheta = 0.0;
  23213. if (theta !== 0.0) {
  23214. sinThetaOverTheta = Math.sin(theta) / theta;
  23215. }
  23216. result.x = cartesian.x * sinThetaOverTheta;
  23217. result.y = cartesian.y * sinThetaOverTheta;
  23218. result.z = cartesian.z * sinThetaOverTheta;
  23219. result.w = Math.cos(theta);
  23220. return result;
  23221. };
  23222. var squadScratchCartesian0 = new Cartesian3();
  23223. var squadScratchCartesian1 = new Cartesian3();
  23224. var squadScratchQuaternion0 = new Quaternion();
  23225. var squadScratchQuaternion1 = new Quaternion();
  23226. /**
  23227. * Computes an inner quadrangle point.
  23228. * <p>This will compute quaternions that ensure a squad curve is C<sup>1</sup>.</p>
  23229. *
  23230. * @param {Quaternion} q0 The first quaternion.
  23231. * @param {Quaternion} q1 The second quaternion.
  23232. * @param {Quaternion} q2 The third quaternion.
  23233. * @param {Quaternion} result The object onto which to store the result.
  23234. * @returns {Quaternion} The modified result parameter.
  23235. *
  23236. * @see Quaternion#squad
  23237. */
  23238. Quaternion.computeInnerQuadrangle = function(q0, q1, q2, result) {
  23239. if (!defined(q0) || !defined(q1) || !defined(q2)) {
  23240. throw new DeveloperError('q0, q1, and q2 are required.');
  23241. }
  23242. if (!defined(result)) {
  23243. throw new DeveloperError('result is required');
  23244. }
  23245. var qInv = Quaternion.conjugate(q1, squadScratchQuaternion0);
  23246. Quaternion.multiply(qInv, q2, squadScratchQuaternion1);
  23247. var cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0);
  23248. Quaternion.multiply(qInv, q0, squadScratchQuaternion1);
  23249. var cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1);
  23250. Cartesian3.add(cart0, cart1, cart0);
  23251. Cartesian3.multiplyByScalar(cart0, 0.25, cart0);
  23252. Cartesian3.negate(cart0, cart0);
  23253. Quaternion.exp(cart0, squadScratchQuaternion0);
  23254. return Quaternion.multiply(q1, squadScratchQuaternion0, result);
  23255. };
  23256. /**
  23257. * Computes the spherical quadrangle interpolation between quaternions.
  23258. *
  23259. * @param {Quaternion} q0 The first quaternion.
  23260. * @param {Quaternion} q1 The second quaternion.
  23261. * @param {Quaternion} s0 The first inner quadrangle.
  23262. * @param {Quaternion} s1 The second inner quadrangle.
  23263. * @param {Number} t The time in [0,1] used to interpolate.
  23264. * @param {Quaternion} result The object onto which to store the result.
  23265. * @returns {Quaternion} The modified result parameter.
  23266. *
  23267. *
  23268. * @example
  23269. * // 1. compute the squad interpolation between two quaternions on a curve
  23270. * var s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion());
  23271. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion());
  23272. * var q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion());
  23273. *
  23274. * // 2. compute the squad interpolation as above but where the first quaternion is a end point.
  23275. * var s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion());
  23276. * var q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion());
  23277. *
  23278. * @see Quaternion#computeInnerQuadrangle
  23279. */
  23280. Quaternion.squad = function(q0, q1, s0, s1, t, result) {
  23281. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  23282. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  23283. }
  23284. if (typeof t !== 'number') {
  23285. throw new DeveloperError('t is required and must be a number.');
  23286. }
  23287. if (!defined(result)) {
  23288. throw new DeveloperError('result is required');
  23289. }
  23290. var slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0);
  23291. var slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1);
  23292. return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  23293. };
  23294. var fastSlerpScratchQuaternion = new Quaternion();
  23295. var opmu = 1.90110745351730037;
  23296. var u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  23297. var v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  23298. var bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  23299. var bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : [];
  23300. for (var i = 0; i < 7; ++i) {
  23301. var s = i + 1.0;
  23302. var t = 2.0 * s + 1.0;
  23303. u[i] = 1.0 / (s * t);
  23304. v[i] = s / t;
  23305. }
  23306. u[7] = opmu / (8.0 * 17.0);
  23307. v[7] = opmu * 8.0 / 17.0;
  23308. /**
  23309. * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
  23310. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10<sup>-6</sup>.
  23311. *
  23312. * @param {Quaternion} start The value corresponding to t at 0.0.
  23313. * @param {Quaternion} end The value corresponding to t at 1.0.
  23314. * @param {Number} t The point along t at which to interpolate.
  23315. * @param {Quaternion} result The object onto which to store the result.
  23316. * @returns {Quaternion} The modified result parameter.
  23317. *
  23318. * @see Quaternion#slerp
  23319. */
  23320. Quaternion.fastSlerp = function(start, end, t, result) {
  23321. if (!defined(start)) {
  23322. throw new DeveloperError('start is required.');
  23323. }
  23324. if (!defined(end)) {
  23325. throw new DeveloperError('end is required.');
  23326. }
  23327. if (typeof t !== 'number') {
  23328. throw new DeveloperError('t is required and must be a number.');
  23329. }
  23330. if (!defined(result)) {
  23331. throw new DeveloperError('result is required');
  23332. }
  23333. var x = Quaternion.dot(start, end);
  23334. var sign;
  23335. if (x >= 0) {
  23336. sign = 1.0;
  23337. } else {
  23338. sign = -1.0;
  23339. x = -x;
  23340. }
  23341. var xm1 = x - 1.0;
  23342. var d = 1.0 - t;
  23343. var sqrT = t * t;
  23344. var sqrD = d * d;
  23345. for (var i = 7; i >= 0; --i) {
  23346. bT[i] = (u[i] * sqrT - v[i]) * xm1;
  23347. bD[i] = (u[i] * sqrD - v[i]) * xm1;
  23348. }
  23349. var cT = sign * t * (
  23350. 1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (
  23351. 1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7]))))))));
  23352. var cD = d * (
  23353. 1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (
  23354. 1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7]))))))));
  23355. var temp = Quaternion.multiplyByScalar(start, cD, fastSlerpScratchQuaternion);
  23356. Quaternion.multiplyByScalar(end, cT, result);
  23357. return Quaternion.add(temp, result, result);
  23358. };
  23359. /**
  23360. * Computes the spherical quadrangle interpolation between quaternions.
  23361. * An implementation that is faster than {@link Quaternion#squad}, but less accurate.
  23362. *
  23363. * @param {Quaternion} q0 The first quaternion.
  23364. * @param {Quaternion} q1 The second quaternion.
  23365. * @param {Quaternion} s0 The first inner quadrangle.
  23366. * @param {Quaternion} s1 The second inner quadrangle.
  23367. * @param {Number} t The time in [0,1] used to interpolate.
  23368. * @param {Quaternion} result The object onto which to store the result.
  23369. * @returns {Quaternion} The modified result parameter or a new instance if none was provided.
  23370. *
  23371. * @see Quaternion#squad
  23372. */
  23373. Quaternion.fastSquad = function(q0, q1, s0, s1, t, result) {
  23374. if (!defined(q0) || !defined(q1) || !defined(s0) || !defined(s1)) {
  23375. throw new DeveloperError('q0, q1, s0, and s1 are required.');
  23376. }
  23377. if (typeof t !== 'number') {
  23378. throw new DeveloperError('t is required and must be a number.');
  23379. }
  23380. if (!defined(result)) {
  23381. throw new DeveloperError('result is required');
  23382. }
  23383. var slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0);
  23384. var slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1);
  23385. return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result);
  23386. };
  23387. /**
  23388. * Compares the provided quaternions componentwise and returns
  23389. * <code>true</code> if they are equal, <code>false</code> otherwise.
  23390. *
  23391. * @param {Quaternion} [left] The first quaternion.
  23392. * @param {Quaternion} [right] The second quaternion.
  23393. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  23394. */
  23395. Quaternion.equals = function(left, right) {
  23396. return (left === right) ||
  23397. ((defined(left)) &&
  23398. (defined(right)) &&
  23399. (left.x === right.x) &&
  23400. (left.y === right.y) &&
  23401. (left.z === right.z) &&
  23402. (left.w === right.w));
  23403. };
  23404. /**
  23405. * Compares the provided quaternions componentwise and returns
  23406. * <code>true</code> if they are within the provided epsilon,
  23407. * <code>false</code> otherwise.
  23408. *
  23409. * @param {Quaternion} [left] The first quaternion.
  23410. * @param {Quaternion} [right] The second quaternion.
  23411. * @param {Number} epsilon The epsilon to use for equality testing.
  23412. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  23413. */
  23414. Quaternion.equalsEpsilon = function(left, right, epsilon) {
  23415. if (typeof epsilon !== 'number') {
  23416. throw new DeveloperError('epsilon is required and must be a number.');
  23417. }
  23418. return (left === right) ||
  23419. ((defined(left)) &&
  23420. (defined(right)) &&
  23421. (Math.abs(left.x - right.x) <= epsilon) &&
  23422. (Math.abs(left.y - right.y) <= epsilon) &&
  23423. (Math.abs(left.z - right.z) <= epsilon) &&
  23424. (Math.abs(left.w - right.w) <= epsilon));
  23425. };
  23426. /**
  23427. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
  23428. *
  23429. * @type {Quaternion}
  23430. * @constant
  23431. */
  23432. Quaternion.ZERO = freezeObject(new Quaternion(0.0, 0.0, 0.0, 0.0));
  23433. /**
  23434. * An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
  23435. *
  23436. * @type {Quaternion}
  23437. * @constant
  23438. */
  23439. Quaternion.IDENTITY = freezeObject(new Quaternion(0.0, 0.0, 0.0, 1.0));
  23440. /**
  23441. * Duplicates this Quaternion instance.
  23442. *
  23443. * @param {Quaternion} [result] The object onto which to store the result.
  23444. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
  23445. */
  23446. Quaternion.prototype.clone = function(result) {
  23447. return Quaternion.clone(this, result);
  23448. };
  23449. /**
  23450. * Compares this and the provided quaternion componentwise and returns
  23451. * <code>true</code> if they are equal, <code>false</code> otherwise.
  23452. *
  23453. * @param {Quaternion} [right] The right hand side quaternion.
  23454. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise.
  23455. */
  23456. Quaternion.prototype.equals = function(right) {
  23457. return Quaternion.equals(this, right);
  23458. };
  23459. /**
  23460. * Compares this and the provided quaternion componentwise and returns
  23461. * <code>true</code> if they are within the provided epsilon,
  23462. * <code>false</code> otherwise.
  23463. *
  23464. * @param {Quaternion} [right] The right hand side quaternion.
  23465. * @param {Number} epsilon The epsilon to use for equality testing.
  23466. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise.
  23467. */
  23468. Quaternion.prototype.equalsEpsilon = function(right, epsilon) {
  23469. return Quaternion.equalsEpsilon(this, right, epsilon);
  23470. };
  23471. /**
  23472. * Returns a string representing this quaternion in the format (x, y, z, w).
  23473. *
  23474. * @returns {String} A string representing this Quaternion.
  23475. */
  23476. Quaternion.prototype.toString = function() {
  23477. return '(' + this.x + ', ' + this.y + ', ' + this.z + ', ' + this.w + ')';
  23478. };
  23479. return Quaternion;
  23480. });
  23481. /*global define*/
  23482. define('Core/Transforms',[
  23483. '../ThirdParty/when',
  23484. './Cartesian2',
  23485. './Cartesian3',
  23486. './Cartesian4',
  23487. './Cartographic',
  23488. './defaultValue',
  23489. './defined',
  23490. './deprecationWarning',
  23491. './DeveloperError',
  23492. './EarthOrientationParameters',
  23493. './EarthOrientationParametersSample',
  23494. './Ellipsoid',
  23495. './HeadingPitchRoll',
  23496. './Iau2006XysData',
  23497. './Iau2006XysSample',
  23498. './JulianDate',
  23499. './Math',
  23500. './Matrix3',
  23501. './Matrix4',
  23502. './Quaternion',
  23503. './TimeConstants'
  23504. ], function(
  23505. when,
  23506. Cartesian2,
  23507. Cartesian3,
  23508. Cartesian4,
  23509. Cartographic,
  23510. defaultValue,
  23511. defined,
  23512. deprecationWarning,
  23513. DeveloperError,
  23514. EarthOrientationParameters,
  23515. EarthOrientationParametersSample,
  23516. Ellipsoid,
  23517. HeadingPitchRoll,
  23518. Iau2006XysData,
  23519. Iau2006XysSample,
  23520. JulianDate,
  23521. CesiumMath,
  23522. Matrix3,
  23523. Matrix4,
  23524. Quaternion,
  23525. TimeConstants) {
  23526. 'use strict';
  23527. /**
  23528. * Contains functions for transforming positions to various reference frames.
  23529. *
  23530. * @exports Transforms
  23531. */
  23532. var Transforms = {};
  23533. var eastNorthUpToFixedFrameNormal = new Cartesian3();
  23534. var eastNorthUpToFixedFrameTangent = new Cartesian3();
  23535. var eastNorthUpToFixedFrameBitangent = new Cartesian3();
  23536. /**
  23537. * Computes a 4x4 transformation matrix from a reference frame with an east-north-up axes
  23538. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  23539. * The local axes are defined as:
  23540. * <ul>
  23541. * <li>The <code>x</code> axis points in the local east direction.</li>
  23542. * <li>The <code>y</code> axis points in the local north direction.</li>
  23543. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  23544. * </ul>
  23545. *
  23546. * @param {Cartesian3} origin The center point of the local reference frame.
  23547. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  23548. * @param {Matrix4} [result] The object onto which to store the result.
  23549. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  23550. *
  23551. * @example
  23552. * // Get the transform from local east-north-up at cartographic (0.0, 0.0) to Earth's fixed frame.
  23553. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  23554. * var transform = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  23555. */
  23556. Transforms.eastNorthUpToFixedFrame = function(origin, ellipsoid, result) {
  23557. if (!defined(origin)) {
  23558. throw new DeveloperError('origin is required.');
  23559. }
  23560. // If x and y are zero, assume origin is at a pole, which is a special case.
  23561. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  23562. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  23563. var sign = CesiumMath.sign(origin.z);
  23564. if (!defined(result)) {
  23565. return new Matrix4(
  23566. 0.0, -sign, 0.0, origin.x,
  23567. 1.0, 0.0, 0.0, origin.y,
  23568. 0.0, 0.0, sign, origin.z,
  23569. 0.0, 0.0, 0.0, 1.0);
  23570. }
  23571. result[0] = 0.0;
  23572. result[1] = 1.0;
  23573. result[2] = 0.0;
  23574. result[3] = 0.0;
  23575. result[4] = -sign;
  23576. result[5] = 0.0;
  23577. result[6] = 0.0;
  23578. result[7] = 0.0;
  23579. result[8] = 0.0;
  23580. result[9] = 0.0;
  23581. result[10] = sign;
  23582. result[11] = 0.0;
  23583. result[12] = origin.x;
  23584. result[13] = origin.y;
  23585. result[14] = origin.z;
  23586. result[15] = 1.0;
  23587. return result;
  23588. }
  23589. var normal = eastNorthUpToFixedFrameNormal;
  23590. var tangent = eastNorthUpToFixedFrameTangent;
  23591. var bitangent = eastNorthUpToFixedFrameBitangent;
  23592. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  23593. ellipsoid.geodeticSurfaceNormal(origin, normal);
  23594. tangent.x = -origin.y;
  23595. tangent.y = origin.x;
  23596. tangent.z = 0.0;
  23597. Cartesian3.normalize(tangent, tangent);
  23598. Cartesian3.cross(normal, tangent, bitangent);
  23599. if (!defined(result)) {
  23600. return new Matrix4(
  23601. tangent.x, bitangent.x, normal.x, origin.x,
  23602. tangent.y, bitangent.y, normal.y, origin.y,
  23603. tangent.z, bitangent.z, normal.z, origin.z,
  23604. 0.0, 0.0, 0.0, 1.0);
  23605. }
  23606. result[0] = tangent.x;
  23607. result[1] = tangent.y;
  23608. result[2] = tangent.z;
  23609. result[3] = 0.0;
  23610. result[4] = bitangent.x;
  23611. result[5] = bitangent.y;
  23612. result[6] = bitangent.z;
  23613. result[7] = 0.0;
  23614. result[8] = normal.x;
  23615. result[9] = normal.y;
  23616. result[10] = normal.z;
  23617. result[11] = 0.0;
  23618. result[12] = origin.x;
  23619. result[13] = origin.y;
  23620. result[14] = origin.z;
  23621. result[15] = 1.0;
  23622. return result;
  23623. };
  23624. var northEastDownToFixedFrameNormal = new Cartesian3();
  23625. var northEastDownToFixedFrameTangent = new Cartesian3();
  23626. var northEastDownToFixedFrameBitangent = new Cartesian3();
  23627. /**
  23628. * Computes a 4x4 transformation matrix from a reference frame with an north-east-down axes
  23629. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  23630. * The local axes are defined as:
  23631. * <ul>
  23632. * <li>The <code>x</code> axis points in the local north direction.</li>
  23633. * <li>The <code>y</code> axis points in the local east direction.</li>
  23634. * <li>The <code>z</code> axis points in the opposite direction of the ellipsoid surface normal which passes through the position.</li>
  23635. * </ul>
  23636. *
  23637. * @param {Cartesian3} origin The center point of the local reference frame.
  23638. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  23639. * @param {Matrix4} [result] The object onto which to store the result.
  23640. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  23641. *
  23642. * @example
  23643. * // Get the transform from local north-east-down at cartographic (0.0, 0.0) to Earth's fixed frame.
  23644. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  23645. * var transform = Cesium.Transforms.northEastDownToFixedFrame(center);
  23646. */
  23647. Transforms.northEastDownToFixedFrame = function(origin, ellipsoid, result) {
  23648. if (!defined(origin)) {
  23649. throw new DeveloperError('origin is required.');
  23650. }
  23651. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  23652. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  23653. // The poles are special cases. If x and y are zero, assume origin is at a pole.
  23654. var sign = CesiumMath.sign(origin.z);
  23655. if (!defined(result)) {
  23656. return new Matrix4(
  23657. -sign, 0.0, 0.0, origin.x,
  23658. 0.0, 1.0, 0.0, origin.y,
  23659. 0.0, 0.0, -sign, origin.z,
  23660. 0.0, 0.0, 0.0, 1.0);
  23661. }
  23662. result[0] = -sign;
  23663. result[1] = 0.0;
  23664. result[2] = 0.0;
  23665. result[3] = 0.0;
  23666. result[4] = 0.0;
  23667. result[5] = 1.0;
  23668. result[6] = 0.0;
  23669. result[7] = 0.0;
  23670. result[8] = 0.0;
  23671. result[9] = 0.0;
  23672. result[10] = -sign;
  23673. result[11] = 0.0;
  23674. result[12] = origin.x;
  23675. result[13] = origin.y;
  23676. result[14] = origin.z;
  23677. result[15] = 1.0;
  23678. return result;
  23679. }
  23680. var normal = northEastDownToFixedFrameNormal;
  23681. var tangent = northEastDownToFixedFrameTangent;
  23682. var bitangent = northEastDownToFixedFrameBitangent;
  23683. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  23684. ellipsoid.geodeticSurfaceNormal(origin, normal);
  23685. tangent.x = -origin.y;
  23686. tangent.y = origin.x;
  23687. tangent.z = 0.0;
  23688. Cartesian3.normalize(tangent, tangent);
  23689. Cartesian3.cross(normal, tangent, bitangent);
  23690. if (!defined(result)) {
  23691. return new Matrix4(
  23692. bitangent.x, tangent.x, -normal.x, origin.x,
  23693. bitangent.y, tangent.y, -normal.y, origin.y,
  23694. bitangent.z, tangent.z, -normal.z, origin.z,
  23695. 0.0, 0.0, 0.0, 1.0);
  23696. }
  23697. result[0] = bitangent.x;
  23698. result[1] = bitangent.y;
  23699. result[2] = bitangent.z;
  23700. result[3] = 0.0;
  23701. result[4] = tangent.x;
  23702. result[5] = tangent.y;
  23703. result[6] = tangent.z;
  23704. result[7] = 0.0;
  23705. result[8] = -normal.x;
  23706. result[9] = -normal.y;
  23707. result[10] = -normal.z;
  23708. result[11] = 0.0;
  23709. result[12] = origin.x;
  23710. result[13] = origin.y;
  23711. result[14] = origin.z;
  23712. result[15] = 1.0;
  23713. return result;
  23714. };
  23715. /**
  23716. * Computes a 4x4 transformation matrix from a reference frame with an north-up-east axes
  23717. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  23718. * The local axes are defined as:
  23719. * <ul>
  23720. * <li>The <code>x</code> axis points in the local north direction.</li>
  23721. * <li>The <code>y</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  23722. * <li>The <code>z</code> axis points in the local east direction.</li>
  23723. * </ul>
  23724. *
  23725. * @param {Cartesian3} origin The center point of the local reference frame.
  23726. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  23727. * @param {Matrix4} [result] The object onto which to store the result.
  23728. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  23729. *
  23730. * @example
  23731. * // Get the transform from local north-up-east at cartographic (0.0, 0.0) to Earth's fixed frame.
  23732. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  23733. * var transform = Cesium.Transforms.northUpEastToFixedFrame(center);
  23734. */
  23735. Transforms.northUpEastToFixedFrame = function(origin, ellipsoid, result) {
  23736. if (!defined(origin)) {
  23737. throw new DeveloperError('origin is required.');
  23738. }
  23739. // If x and y are zero, assume origin is at a pole, which is a special case.
  23740. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  23741. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  23742. var sign = CesiumMath.sign(origin.z);
  23743. if (!defined(result)) {
  23744. return new Matrix4(
  23745. -sign, 0.0, 0.0, origin.x,
  23746. 0.0, 0.0, 1.0, origin.y,
  23747. 0.0, sign, 0.0, origin.z,
  23748. 0.0, 0.0, 0.0, 1.0);
  23749. }
  23750. result[0] = -sign;
  23751. result[1] = 0.0;
  23752. result[2] = 0.0;
  23753. result[3] = 0.0;
  23754. result[4] = 0.0;
  23755. result[5] = 0.0;
  23756. result[6] = sign;
  23757. result[7] = 0.0;
  23758. result[8] = 0.0;
  23759. result[9] = 1.0;
  23760. result[10] = 0.0;
  23761. result[11] = 0.0;
  23762. result[12] = origin.x;
  23763. result[13] = origin.y;
  23764. result[14] = origin.z;
  23765. result[15] = 1.0;
  23766. return result;
  23767. }
  23768. var normal = eastNorthUpToFixedFrameNormal;
  23769. var tangent = eastNorthUpToFixedFrameTangent;
  23770. var bitangent = eastNorthUpToFixedFrameBitangent;
  23771. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  23772. ellipsoid.geodeticSurfaceNormal(origin, normal);
  23773. tangent.x = -origin.y;
  23774. tangent.y = origin.x;
  23775. tangent.z = 0.0;
  23776. Cartesian3.normalize(tangent, tangent);
  23777. Cartesian3.cross(normal, tangent, bitangent);
  23778. if (!defined(result)) {
  23779. return new Matrix4(
  23780. bitangent.x, normal.x, tangent.x, origin.x,
  23781. bitangent.y, normal.y, tangent.y, origin.y,
  23782. bitangent.z, normal.z, tangent.z, origin.z,
  23783. 0.0, 0.0, 0.0, 1.0);
  23784. }
  23785. result[0] = bitangent.x;
  23786. result[1] = bitangent.y;
  23787. result[2] = bitangent.z;
  23788. result[3] = 0.0;
  23789. result[4] = normal.x;
  23790. result[5] = normal.y;
  23791. result[6] = normal.z;
  23792. result[7] = 0.0;
  23793. result[8] = tangent.x;
  23794. result[9] = tangent.y;
  23795. result[10] = tangent.z;
  23796. result[11] = 0.0;
  23797. result[12] = origin.x;
  23798. result[13] = origin.y;
  23799. result[14] = origin.z;
  23800. result[15] = 1.0;
  23801. return result;
  23802. };
  23803. /**
  23804. * Computes a 4x4 transformation matrix from a reference frame with an north-west-up axes
  23805. * centered at the provided origin to the provided ellipsoid's fixed reference frame.
  23806. * The local axes are defined as:
  23807. * <ul>
  23808. * <li>The <code>x</code> axis points in the local north direction.</li>
  23809. * <li>The <code>y</code> axis points in the local west direction.</li>
  23810. * <li>The <code>z</code> axis points in the direction of the ellipsoid surface normal which passes through the position.</li>
  23811. * </ul>
  23812. *
  23813. * @param {Cartesian3} origin The center point of the local reference frame.
  23814. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  23815. * @param {Matrix4} [result] The object onto which to store the result.
  23816. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  23817. *
  23818. * @example
  23819. * // Get the transform from local north-West-Up at cartographic (0.0, 0.0) to Earth's fixed frame.
  23820. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  23821. * var transform = Cesium.Transforms.northWestUpToFixedFrame(center);
  23822. */
  23823. Transforms.northWestUpToFixedFrame = function(origin, ellipsoid, result) {
  23824. if (!defined(origin)) {
  23825. throw new DeveloperError('origin is required.');
  23826. }
  23827. // If x and y are zero, assume origin is at a pole, which is a special case.
  23828. if (CesiumMath.equalsEpsilon(origin.x, 0.0, CesiumMath.EPSILON14) &&
  23829. CesiumMath.equalsEpsilon(origin.y, 0.0, CesiumMath.EPSILON14)) {
  23830. var sign = CesiumMath.sign(origin.z);
  23831. if (!defined(result)) {
  23832. return new Matrix4(
  23833. -sign, 0.0, 0.0, origin.x,
  23834. 0.0, -1.0, 0.0, origin.y,
  23835. 0.0, 0.0, sign, origin.z,
  23836. 0.0, 0.0, 0.0, 1.0);
  23837. }
  23838. result[0] = -sign;
  23839. result[1] = 0.0;
  23840. result[2] = 0.0;
  23841. result[3] = 0.0;
  23842. result[4] = 0.0;
  23843. result[5] = -1.0;
  23844. result[6] = 0.0;
  23845. result[7] = 0.0;
  23846. result[8] = 0.0;
  23847. result[9] = 0.0;
  23848. result[10] = sign;
  23849. result[11] = 0.0;
  23850. result[12] = origin.x;
  23851. result[13] = origin.y;
  23852. result[14] = origin.z;
  23853. result[15] = 1.0;
  23854. return result;
  23855. }
  23856. var normal = eastNorthUpToFixedFrameNormal;//Up
  23857. var tangent = eastNorthUpToFixedFrameTangent;//East
  23858. var bitangent = eastNorthUpToFixedFrameBitangent;//North
  23859. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  23860. ellipsoid.geodeticSurfaceNormal(origin, normal);
  23861. tangent.x = -origin.y;
  23862. tangent.y = origin.x;
  23863. tangent.z = 0.0;
  23864. Cartesian3.normalize(tangent, tangent);
  23865. Cartesian3.cross(normal, tangent, bitangent);
  23866. if (!defined(result)) {
  23867. return new Matrix4(
  23868. bitangent.x, -tangent.x, normal.x, origin.x,
  23869. bitangent.y, -tangent.y, normal.y, origin.y,
  23870. bitangent.z, -tangent.z, normal.z, origin.z,
  23871. 0.0, 0.0, 0.0, 1.0);
  23872. }
  23873. result[0] = bitangent.x;
  23874. result[1] = bitangent.y;
  23875. result[2] = bitangent.z;
  23876. result[3] = 0.0;
  23877. result[4] = -tangent.x;
  23878. result[5] = -tangent.y;
  23879. result[6] = -tangent.z;
  23880. result[7] = 0.0;
  23881. result[8] = normal.x;
  23882. result[9] = normal.y;
  23883. result[10] = normal.z;
  23884. result[11] = 0.0;
  23885. result[12] = origin.x;
  23886. result[13] = origin.y;
  23887. result[14] = origin.z;
  23888. result[15] = 1.0;
  23889. return result;
  23890. };
  23891. var scratchHPRQuaternion = new Quaternion();
  23892. var scratchScale = new Cartesian3(1.0, 1.0, 1.0);
  23893. var scratchHPRMatrix4 = new Matrix4();
  23894. /**
  23895. * Computes a 4x4 transformation matrix from a reference frame with axes computed from the heading-pitch-roll angles
  23896. * centered at the provided origin to the provided ellipsoid's fixed reference frame. Heading is the rotation from the local north
  23897. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  23898. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  23899. *
  23900. * @param {Cartesian3} origin The center point of the local reference frame.
  23901. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  23902. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  23903. * @param {Matrix4} [result] The object onto which to store the result.
  23904. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if none was provided.
  23905. *
  23906. * @example
  23907. * // Get the transform from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  23908. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  23909. * var heading = -Cesium.Math.PI_OVER_TWO;
  23910. * var pitch = Cesium.Math.PI_OVER_FOUR;
  23911. * var roll = 0.0;
  23912. * var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
  23913. * var transform = Cesium.Transforms.headingPitchRollToFixedFrame(center, hpr);
  23914. */
  23915. Transforms.headingPitchRollToFixedFrame = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  23916. var heading;
  23917. if (typeof headingPitchRoll === 'object') {
  23918. // Shift arguments using assignments to encourage JIT optimization.
  23919. ellipsoid = pitch;
  23920. result = roll;
  23921. heading = headingPitchRoll.heading;
  23922. pitch = headingPitchRoll.pitch;
  23923. roll = headingPitchRoll.roll;
  23924. } else {
  23925. 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.');
  23926. heading = headingPitchRoll;
  23927. }
  23928. // checks for required parameters happen in the called functions
  23929. var hprQuaternion = Quaternion.fromHeadingPitchRoll(heading, pitch, roll, scratchHPRQuaternion);
  23930. var hprMatrix = Matrix4.fromTranslationQuaternionRotationScale(Cartesian3.ZERO, hprQuaternion, scratchScale, scratchHPRMatrix4);
  23931. result = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, result);
  23932. return Matrix4.multiply(result, hprMatrix, result);
  23933. };
  23934. var scratchHPR = new HeadingPitchRoll();
  23935. var scratchENUMatrix4 = new Matrix4();
  23936. var scratchHPRMatrix3 = new Matrix3();
  23937. /**
  23938. * Computes a quaternion from a reference frame with axes computed from the heading-pitch-roll angles
  23939. * centered at the provided origin. Heading is the rotation from the local north
  23940. * direction where a positive angle is increasing eastward. Pitch is the rotation from the local east-north plane. Positive pitch angles
  23941. * are above the plane. Negative pitch angles are below the plane. Roll is the first rotation applied about the local east axis.
  23942. *
  23943. * @param {Cartesian3} origin The center point of the local reference frame.
  23944. * @param {HeadingPitchRoll} headingPitchRoll The heading, pitch, and roll.
  23945. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid whose fixed frame is used in the transformation.
  23946. * @param {Quaternion} [result] The object onto which to store the result.
  23947. * @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
  23948. *
  23949. * @example
  23950. * // Get the quaternion from local heading-pitch-roll at cartographic (0.0, 0.0) to Earth's fixed frame.
  23951. * var center = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  23952. * var heading = -Cesium.Math.PI_OVER_TWO;
  23953. * var pitch = Cesium.Math.PI_OVER_FOUR;
  23954. * var roll = 0.0;
  23955. * var hpr = new HeadingPitchRoll(heading, pitch, roll);
  23956. * var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
  23957. */
  23958. Transforms.headingPitchRollQuaternion = function(origin, headingPitchRoll, pitch, roll, ellipsoid, result) {
  23959. var hpr;
  23960. if (typeof headingPitchRoll === 'object') {
  23961. // Shift arguments using assignment to encourage JIT optimization.
  23962. hpr = headingPitchRoll;
  23963. ellipsoid = pitch;
  23964. result = roll;
  23965. } else {
  23966. 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.');
  23967. scratchHPR.heading = headingPitchRoll;
  23968. scratchHPR.pitch = pitch;
  23969. scratchHPR.roll = roll;
  23970. hpr = scratchHPR;
  23971. }
  23972. // checks for required parameters happen in the called functions
  23973. var transform = Transforms.headingPitchRollToFixedFrame(origin, hpr, ellipsoid, scratchENUMatrix4);
  23974. var rotation = Matrix4.getRotation(transform, scratchHPRMatrix3);
  23975. return Quaternion.fromRotationMatrix(rotation, result);
  23976. };
  23977. var gmstConstant0 = 6 * 3600 + 41 * 60 + 50.54841;
  23978. var gmstConstant1 = 8640184.812866;
  23979. var gmstConstant2 = 0.093104;
  23980. var gmstConstant3 = -6.2E-6;
  23981. var rateCoef = 1.1772758384668e-19;
  23982. var wgs84WRPrecessing = 7.2921158553E-5;
  23983. var twoPiOverSecondsInDay = CesiumMath.TWO_PI / 86400.0;
  23984. var dateInUtc = new JulianDate();
  23985. /**
  23986. * Computes a rotation matrix to transform a point or vector from True Equator Mean Equinox (TEME) axes to the
  23987. * pseudo-fixed axes at a given time. This method treats the UT1 time standard as equivalent to UTC.
  23988. *
  23989. * @param {JulianDate} date The time at which to compute the rotation matrix.
  23990. * @param {Matrix3} [result] The object onto which to store the result.
  23991. * @returns {Matrix3} The modified result parameter or a new Matrix3 instance if none was provided.
  23992. *
  23993. * @example
  23994. * //Set the view to in the inertial frame.
  23995. * scene.preRender.addEventListener(function(scene, time) {
  23996. * var now = Cesium.JulianDate.now();
  23997. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  23998. * var transform = Cesium.Matrix4.fromRotationTranslation(Cesium.Transforms.computeTemeToPseudoFixedMatrix(now));
  23999. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  24000. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  24001. * camera.lookAtTransform(transform, offset);
  24002. * });
  24003. */
  24004. Transforms.computeTemeToPseudoFixedMatrix = function (date, result) {
  24005. if (!defined(date)) {
  24006. throw new DeveloperError('date is required.');
  24007. }
  24008. // GMST is actually computed using UT1. We're using UTC as an approximation of UT1.
  24009. // We do not want to use the function like convertTaiToUtc in JulianDate because
  24010. // we explicitly do not want to fail when inside the leap second.
  24011. dateInUtc = JulianDate.addSeconds(date, -JulianDate.computeTaiMinusUtc(date), dateInUtc);
  24012. var utcDayNumber = dateInUtc.dayNumber;
  24013. var utcSecondsIntoDay = dateInUtc.secondsOfDay;
  24014. var t;
  24015. var diffDays = utcDayNumber - 2451545;
  24016. if (utcSecondsIntoDay >= 43200.0) {
  24017. t = (diffDays + 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  24018. } else {
  24019. t = (diffDays - 0.5) / TimeConstants.DAYS_PER_JULIAN_CENTURY;
  24020. }
  24021. var gmst0 = gmstConstant0 + t * (gmstConstant1 + t * (gmstConstant2 + t * gmstConstant3));
  24022. var angle = (gmst0 * twoPiOverSecondsInDay) % CesiumMath.TWO_PI;
  24023. var ratio = wgs84WRPrecessing + rateCoef * (utcDayNumber - 2451545.5);
  24024. var secondsSinceMidnight = (utcSecondsIntoDay + TimeConstants.SECONDS_PER_DAY * 0.5) % TimeConstants.SECONDS_PER_DAY;
  24025. var gha = angle + (ratio * secondsSinceMidnight);
  24026. var cosGha = Math.cos(gha);
  24027. var sinGha = Math.sin(gha);
  24028. if (!defined(result)) {
  24029. return new Matrix3(cosGha, sinGha, 0.0,
  24030. -sinGha, cosGha, 0.0,
  24031. 0.0, 0.0, 1.0);
  24032. }
  24033. result[0] = cosGha;
  24034. result[1] = -sinGha;
  24035. result[2] = 0.0;
  24036. result[3] = sinGha;
  24037. result[4] = cosGha;
  24038. result[5] = 0.0;
  24039. result[6] = 0.0;
  24040. result[7] = 0.0;
  24041. result[8] = 1.0;
  24042. return result;
  24043. };
  24044. /**
  24045. * The source of IAU 2006 XYS data, used for computing the transformation between the
  24046. * Fixed and ICRF axes.
  24047. * @type {Iau2006XysData}
  24048. *
  24049. * @see Transforms.computeIcrfToFixedMatrix
  24050. * @see Transforms.computeFixedToIcrfMatrix
  24051. *
  24052. * @private
  24053. */
  24054. Transforms.iau2006XysData = new Iau2006XysData();
  24055. /**
  24056. * The source of Earth Orientation Parameters (EOP) data, used for computing the transformation
  24057. * between the Fixed and ICRF axes. By default, zero values are used for all EOP values,
  24058. * yielding a reasonable but not completely accurate representation of the ICRF axes.
  24059. * @type {EarthOrientationParameters}
  24060. *
  24061. * @see Transforms.computeIcrfToFixedMatrix
  24062. * @see Transforms.computeFixedToIcrfMatrix
  24063. *
  24064. * @private
  24065. */
  24066. Transforms.earthOrientationParameters = EarthOrientationParameters.NONE;
  24067. var ttMinusTai = 32.184;
  24068. var j2000ttDays = 2451545.0;
  24069. /**
  24070. * Preloads the data necessary to transform between the ICRF and Fixed axes, in either
  24071. * direction, over a given interval. This function returns a promise that, when resolved,
  24072. * indicates that the preload has completed.
  24073. *
  24074. * @param {TimeInterval} timeInterval The interval to preload.
  24075. * @returns {Promise.<undefined>} A promise that, when resolved, indicates that the preload has completed
  24076. * and evaluation of the transformation between the fixed and ICRF axes will
  24077. * no longer return undefined for a time inside the interval.
  24078. *
  24079. *
  24080. * @example
  24081. * var interval = new Cesium.TimeInterval(...);
  24082. * when(Cesium.Transforms.preloadIcrfFixed(interval), function() {
  24083. * // the data is now loaded
  24084. * });
  24085. *
  24086. * @see Transforms.computeIcrfToFixedMatrix
  24087. * @see Transforms.computeFixedToIcrfMatrix
  24088. * @see when
  24089. */
  24090. Transforms.preloadIcrfFixed = function(timeInterval) {
  24091. var startDayTT = timeInterval.start.dayNumber;
  24092. var startSecondTT = timeInterval.start.secondsOfDay + ttMinusTai;
  24093. var stopDayTT = timeInterval.stop.dayNumber;
  24094. var stopSecondTT = timeInterval.stop.secondsOfDay + ttMinusTai;
  24095. var xysPromise = Transforms.iau2006XysData.preload(startDayTT, startSecondTT, stopDayTT, stopSecondTT);
  24096. var eopPromise = Transforms.earthOrientationParameters.getPromiseToLoad();
  24097. return when.all([xysPromise, eopPromise]);
  24098. };
  24099. /**
  24100. * Computes a rotation matrix to transform a point or vector from the International Celestial
  24101. * Reference Frame (GCRF/ICRF) inertial frame axes to the Earth-Fixed frame axes (ITRF)
  24102. * at a given time. This function may return undefined if the data necessary to
  24103. * do the transformation is not yet loaded.
  24104. *
  24105. * @param {JulianDate} date The time at which to compute the rotation matrix.
  24106. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  24107. * not specified, a new instance is created and returned.
  24108. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  24109. * transformation is not yet loaded.
  24110. *
  24111. *
  24112. * @example
  24113. * scene.preRender.addEventListener(function(scene, time) {
  24114. * var icrfToFixed = Cesium.Transforms.computeIcrfToFixedMatrix(time);
  24115. * if (Cesium.defined(icrfToFixed)) {
  24116. * var offset = Cesium.Matrix4.multiplyByPoint(camera.transform, camera.position, new Cesium.Cartesian3());
  24117. * var transform = Cesium.Matrix4.fromRotationTranslation(icrfToFixed)
  24118. * var inverseTransform = Cesium.Matrix4.inverseTransformation(transform, new Cesium.Matrix4());
  24119. * Cesium.Matrix4.multiplyByPoint(inverseTransform, offset, offset);
  24120. * camera.lookAtTransform(transform, offset);
  24121. * }
  24122. * });
  24123. *
  24124. * @see Transforms.preloadIcrfFixed
  24125. */
  24126. Transforms.computeIcrfToFixedMatrix = function(date, result) {
  24127. if (!defined(date)) {
  24128. throw new DeveloperError('date is required.');
  24129. }
  24130. if (!defined(result)) {
  24131. result = new Matrix3();
  24132. }
  24133. var fixedToIcrfMtx = Transforms.computeFixedToIcrfMatrix(date, result);
  24134. if (!defined(fixedToIcrfMtx)) {
  24135. return undefined;
  24136. }
  24137. return Matrix3.transpose(fixedToIcrfMtx, result);
  24138. };
  24139. var xysScratch = new Iau2006XysSample(0.0, 0.0, 0.0);
  24140. var eopScratch = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  24141. var rotation1Scratch = new Matrix3();
  24142. var rotation2Scratch = new Matrix3();
  24143. /**
  24144. * Computes a rotation matrix to transform a point or vector from the Earth-Fixed frame axes (ITRF)
  24145. * to the International Celestial Reference Frame (GCRF/ICRF) inertial frame axes
  24146. * at a given time. This function may return undefined if the data necessary to
  24147. * do the transformation is not yet loaded.
  24148. *
  24149. * @param {JulianDate} date The time at which to compute the rotation matrix.
  24150. * @param {Matrix3} [result] The object onto which to store the result. If this parameter is
  24151. * not specified, a new instance is created and returned.
  24152. * @returns {Matrix3} The rotation matrix, or undefined if the data necessary to do the
  24153. * transformation is not yet loaded.
  24154. *
  24155. *
  24156. * @example
  24157. * // Transform a point from the ICRF axes to the Fixed axes.
  24158. * var now = Cesium.JulianDate.now();
  24159. * var pointInFixed = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  24160. * var fixedToIcrf = Cesium.Transforms.computeIcrfToFixedMatrix(now);
  24161. * var pointInInertial = new Cesium.Cartesian3();
  24162. * if (Cesium.defined(fixedToIcrf)) {
  24163. * pointInInertial = Cesium.Matrix3.multiplyByVector(fixedToIcrf, pointInFixed, pointInInertial);
  24164. * }
  24165. *
  24166. * @see Transforms.preloadIcrfFixed
  24167. */
  24168. Transforms.computeFixedToIcrfMatrix = function(date, result) {
  24169. if (!defined(date)) {
  24170. throw new DeveloperError('date is required.');
  24171. }
  24172. if (!defined(result)) {
  24173. result = new Matrix3();
  24174. }
  24175. // Compute pole wander
  24176. var eop = Transforms.earthOrientationParameters.compute(date, eopScratch);
  24177. if (!defined(eop)) {
  24178. return undefined;
  24179. }
  24180. // There is no external conversion to Terrestrial Time (TT).
  24181. // So use International Atomic Time (TAI) and convert using offsets.
  24182. // Here we are assuming that dayTT and secondTT are positive
  24183. var dayTT = date.dayNumber;
  24184. // It's possible here that secondTT could roll over 86400
  24185. // This does not seem to affect the precision (unit tests check for this)
  24186. var secondTT = date.secondsOfDay + ttMinusTai;
  24187. var xys = Transforms.iau2006XysData.computeXysRadians(dayTT, secondTT, xysScratch);
  24188. if (!defined(xys)) {
  24189. return undefined;
  24190. }
  24191. var x = xys.x + eop.xPoleOffset;
  24192. var y = xys.y + eop.yPoleOffset;
  24193. // Compute XYS rotation
  24194. var a = 1.0 / (1.0 + Math.sqrt(1.0 - x * x - y * y));
  24195. var rotation1 = rotation1Scratch;
  24196. rotation1[0] = 1.0 - a * x * x;
  24197. rotation1[3] = -a * x * y;
  24198. rotation1[6] = x;
  24199. rotation1[1] = -a * x * y;
  24200. rotation1[4] = 1 - a * y * y;
  24201. rotation1[7] = y;
  24202. rotation1[2] = -x;
  24203. rotation1[5] = -y;
  24204. rotation1[8] = 1 - a * (x * x + y * y);
  24205. var rotation2 = Matrix3.fromRotationZ(-xys.s, rotation2Scratch);
  24206. var matrixQ = Matrix3.multiply(rotation1, rotation2, rotation1Scratch);
  24207. // Similar to TT conversions above
  24208. // It's possible here that secondTT could roll over 86400
  24209. // This does not seem to affect the precision (unit tests check for this)
  24210. var dateUt1day = date.dayNumber;
  24211. var dateUt1sec = date.secondsOfDay - JulianDate.computeTaiMinusUtc(date) + eop.ut1MinusUtc;
  24212. // Compute Earth rotation angle
  24213. // The IERS standard for era is
  24214. // era = 0.7790572732640 + 1.00273781191135448 * Tu
  24215. // where
  24216. // Tu = JulianDateInUt1 - 2451545.0
  24217. // However, you get much more precision if you make the following simplification
  24218. // era = a + (1 + b) * (JulianDayNumber + FractionOfDay - 2451545)
  24219. // era = a + (JulianDayNumber - 2451545) + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  24220. // era = a + FractionOfDay + b (JulianDayNumber - 2451545 + FractionOfDay)
  24221. // since (JulianDayNumber - 2451545) represents an integer number of revolutions which will be discarded anyway.
  24222. var daysSinceJ2000 = dateUt1day - 2451545;
  24223. var fractionOfDay = dateUt1sec / TimeConstants.SECONDS_PER_DAY;
  24224. var era = 0.7790572732640 + fractionOfDay + 0.00273781191135448 * (daysSinceJ2000 + fractionOfDay);
  24225. era = (era % 1.0) * CesiumMath.TWO_PI;
  24226. var earthRotation = Matrix3.fromRotationZ(era, rotation2Scratch);
  24227. // pseudoFixed to ICRF
  24228. var pfToIcrf = Matrix3.multiply(matrixQ, earthRotation, rotation1Scratch);
  24229. // Compute pole wander matrix
  24230. var cosxp = Math.cos(eop.xPoleWander);
  24231. var cosyp = Math.cos(eop.yPoleWander);
  24232. var sinxp = Math.sin(eop.xPoleWander);
  24233. var sinyp = Math.sin(eop.yPoleWander);
  24234. var ttt = (dayTT - j2000ttDays) + secondTT / TimeConstants.SECONDS_PER_DAY;
  24235. ttt /= 36525.0;
  24236. // approximate sp value in rad
  24237. var sp = -47.0e-6 * ttt * CesiumMath.RADIANS_PER_DEGREE / 3600.0;
  24238. var cossp = Math.cos(sp);
  24239. var sinsp = Math.sin(sp);
  24240. var fToPfMtx = rotation2Scratch;
  24241. fToPfMtx[0] = cosxp * cossp;
  24242. fToPfMtx[1] = cosxp * sinsp;
  24243. fToPfMtx[2] = sinxp;
  24244. fToPfMtx[3] = -cosyp * sinsp + sinyp * sinxp * cossp;
  24245. fToPfMtx[4] = cosyp * cossp + sinyp * sinxp * sinsp;
  24246. fToPfMtx[5] = -sinyp * cosxp;
  24247. fToPfMtx[6] = -sinyp * sinsp - cosyp * sinxp * cossp;
  24248. fToPfMtx[7] = sinyp * cossp - cosyp * sinxp * sinsp;
  24249. fToPfMtx[8] = cosyp * cosxp;
  24250. return Matrix3.multiply(pfToIcrf, fToPfMtx, result);
  24251. };
  24252. var pointToWindowCoordinatesTemp = new Cartesian4();
  24253. /**
  24254. * Transform a point from model coordinates to window coordinates.
  24255. *
  24256. * @param {Matrix4} modelViewProjectionMatrix The 4x4 model-view-projection matrix.
  24257. * @param {Matrix4} viewportTransformation The 4x4 viewport transformation.
  24258. * @param {Cartesian3} point The point to transform.
  24259. * @param {Cartesian2} [result] The object onto which to store the result.
  24260. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  24261. */
  24262. Transforms.pointToWindowCoordinates = function (modelViewProjectionMatrix, viewportTransformation, point, result) {
  24263. result = Transforms.pointToGLWindowCoordinates(modelViewProjectionMatrix, viewportTransformation, point, result);
  24264. result.y = 2.0 * viewportTransformation[5] - result.y;
  24265. return result;
  24266. };
  24267. /**
  24268. * @private
  24269. */
  24270. Transforms.pointToGLWindowCoordinates = function(modelViewProjectionMatrix, viewportTransformation, point, result) {
  24271. if (!defined(modelViewProjectionMatrix)) {
  24272. throw new DeveloperError('modelViewProjectionMatrix is required.');
  24273. }
  24274. if (!defined(viewportTransformation)) {
  24275. throw new DeveloperError('viewportTransformation is required.');
  24276. }
  24277. if (!defined(point)) {
  24278. throw new DeveloperError('point is required.');
  24279. }
  24280. if (!defined(result)) {
  24281. result = new Cartesian2();
  24282. }
  24283. var tmp = pointToWindowCoordinatesTemp;
  24284. Matrix4.multiplyByVector(modelViewProjectionMatrix, Cartesian4.fromElements(point.x, point.y, point.z, 1, tmp), tmp);
  24285. Cartesian4.multiplyByScalar(tmp, 1.0 / tmp.w, tmp);
  24286. Matrix4.multiplyByVector(viewportTransformation, tmp, tmp);
  24287. return Cartesian2.fromCartesian4(tmp, result);
  24288. };
  24289. var normalScratch = new Cartesian3();
  24290. var rightScratch = new Cartesian3();
  24291. var upScratch = new Cartesian3();
  24292. /**
  24293. * @private
  24294. */
  24295. Transforms.rotationMatrixFromPositionVelocity = function(position, velocity, ellipsoid, result) {
  24296. if (!defined(position)) {
  24297. throw new DeveloperError('position is required.');
  24298. }
  24299. if (!defined(velocity)) {
  24300. throw new DeveloperError('velocity is required.');
  24301. }
  24302. var normal = defaultValue(ellipsoid, Ellipsoid.WGS84).geodeticSurfaceNormal(position, normalScratch);
  24303. var right = Cartesian3.cross(velocity, normal, rightScratch);
  24304. if (Cartesian3.equalsEpsilon(right, Cartesian3.ZERO, CesiumMath.EPSILON6)) {
  24305. right = Cartesian3.clone(Cartesian3.UNIT_X, right);
  24306. }
  24307. var up = Cartesian3.cross(right, velocity, upScratch);
  24308. Cartesian3.cross(velocity, up, right);
  24309. Cartesian3.negate(right, right);
  24310. if (!defined(result)) {
  24311. result = new Matrix3();
  24312. }
  24313. result[0] = velocity.x;
  24314. result[1] = velocity.y;
  24315. result[2] = velocity.z;
  24316. result[3] = right.x;
  24317. result[4] = right.y;
  24318. result[5] = right.z;
  24319. result[6] = up.x;
  24320. result[7] = up.y;
  24321. result[8] = up.z;
  24322. return result;
  24323. };
  24324. var scratchCartographic = new Cartographic();
  24325. var scratchCartesian3Projection = new Cartesian3();
  24326. var scratchCartesian3 = new Cartesian3();
  24327. var scratchCartesian4Origin = new Cartesian4();
  24328. var scratchCartesian4NewOrigin = new Cartesian4();
  24329. var scratchCartesian4NewXAxis = new Cartesian4();
  24330. var scratchCartesian4NewYAxis = new Cartesian4();
  24331. var scratchCartesian4NewZAxis = new Cartesian4();
  24332. var scratchFromENU = new Matrix4();
  24333. var scratchToENU = new Matrix4();
  24334. /**
  24335. * @private
  24336. */
  24337. Transforms.basisTo2D = function(projection, matrix, result) {
  24338. if (!defined(projection)) {
  24339. throw new DeveloperError('projection is required.');
  24340. }
  24341. if (!defined(matrix)) {
  24342. throw new DeveloperError('matrix is required.');
  24343. }
  24344. if (!defined(result)) {
  24345. throw new DeveloperError('result is required.');
  24346. }
  24347. var ellipsoid = projection.ellipsoid;
  24348. var origin = Matrix4.getColumn(matrix, 3, scratchCartesian4Origin);
  24349. var cartographic = ellipsoid.cartesianToCartographic(origin, scratchCartographic);
  24350. var fromENU = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid, scratchFromENU);
  24351. var toENU = Matrix4.inverseTransformation(fromENU, scratchToENU);
  24352. var projectedPosition = projection.project(cartographic, scratchCartesian3Projection);
  24353. var newOrigin = scratchCartesian4NewOrigin;
  24354. newOrigin.x = projectedPosition.z;
  24355. newOrigin.y = projectedPosition.x;
  24356. newOrigin.z = projectedPosition.y;
  24357. newOrigin.w = 1.0;
  24358. var xAxis = Matrix4.getColumn(matrix, 0, scratchCartesian3);
  24359. var xScale = Cartesian3.magnitude(xAxis);
  24360. var newXAxis = Matrix4.multiplyByVector(toENU, xAxis, scratchCartesian4NewXAxis);
  24361. Cartesian4.fromElements(newXAxis.z, newXAxis.x, newXAxis.y, 0.0, newXAxis);
  24362. var yAxis = Matrix4.getColumn(matrix, 1, scratchCartesian3);
  24363. var yScale = Cartesian3.magnitude(yAxis);
  24364. var newYAxis = Matrix4.multiplyByVector(toENU, yAxis, scratchCartesian4NewYAxis);
  24365. Cartesian4.fromElements(newYAxis.z, newYAxis.x, newYAxis.y, 0.0, newYAxis);
  24366. var zAxis = Matrix4.getColumn(matrix, 2, scratchCartesian3);
  24367. var zScale = Cartesian3.magnitude(zAxis);
  24368. var newZAxis = scratchCartesian4NewZAxis;
  24369. Cartesian3.cross(newXAxis, newYAxis, newZAxis);
  24370. Cartesian3.normalize(newZAxis, newZAxis);
  24371. Cartesian3.cross(newYAxis, newZAxis, newXAxis);
  24372. Cartesian3.normalize(newXAxis, newXAxis);
  24373. Cartesian3.cross(newZAxis, newXAxis, newYAxis);
  24374. Cartesian3.normalize(newYAxis, newYAxis);
  24375. Cartesian3.multiplyByScalar(newXAxis, xScale, newXAxis);
  24376. Cartesian3.multiplyByScalar(newYAxis, yScale, newYAxis);
  24377. Cartesian3.multiplyByScalar(newZAxis, zScale, newZAxis);
  24378. Matrix4.setColumn(result, 0, newXAxis, result);
  24379. Matrix4.setColumn(result, 1, newYAxis, result);
  24380. Matrix4.setColumn(result, 2, newZAxis, result);
  24381. Matrix4.setColumn(result, 3, newOrigin, result);
  24382. return result;
  24383. };
  24384. return Transforms;
  24385. });
  24386. /*global define*/
  24387. define('Core/EllipsoidTangentPlane',[
  24388. './AxisAlignedBoundingBox',
  24389. './Cartesian2',
  24390. './Cartesian3',
  24391. './Cartesian4',
  24392. './defaultValue',
  24393. './defined',
  24394. './defineProperties',
  24395. './DeveloperError',
  24396. './Ellipsoid',
  24397. './IntersectionTests',
  24398. './Matrix4',
  24399. './Plane',
  24400. './Ray',
  24401. './Transforms'
  24402. ], function(
  24403. AxisAlignedBoundingBox,
  24404. Cartesian2,
  24405. Cartesian3,
  24406. Cartesian4,
  24407. defaultValue,
  24408. defined,
  24409. defineProperties,
  24410. DeveloperError,
  24411. Ellipsoid,
  24412. IntersectionTests,
  24413. Matrix4,
  24414. Plane,
  24415. Ray,
  24416. Transforms) {
  24417. 'use strict';
  24418. var scratchCart4 = new Cartesian4();
  24419. /**
  24420. * A plane tangent to the provided ellipsoid at the provided origin.
  24421. * If origin is not on the surface of the ellipsoid, it's surface projection will be used.
  24422. * If origin is at the center of the ellipsoid, an exception will be thrown.
  24423. * @alias EllipsoidTangentPlane
  24424. * @constructor
  24425. *
  24426. * @param {Cartesian3} origin The point on the surface of the ellipsoid where the tangent plane touches.
  24427. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid to use.
  24428. *
  24429. * @exception {DeveloperError} origin must not be at the center of the ellipsoid.
  24430. */
  24431. function EllipsoidTangentPlane(origin, ellipsoid) {
  24432. if (!defined(origin)) {
  24433. throw new DeveloperError('origin is required.');
  24434. }
  24435. ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
  24436. origin = ellipsoid.scaleToGeodeticSurface(origin);
  24437. if (!defined(origin)) {
  24438. throw new DeveloperError('origin must not be at the center of the ellipsoid.');
  24439. }
  24440. var eastNorthUp = Transforms.eastNorthUpToFixedFrame(origin, ellipsoid);
  24441. this._ellipsoid = ellipsoid;
  24442. this._origin = origin;
  24443. this._xAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 0, scratchCart4));
  24444. this._yAxis = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 1, scratchCart4));
  24445. var normal = Cartesian3.fromCartesian4(Matrix4.getColumn(eastNorthUp, 2, scratchCart4));
  24446. this._plane = Plane.fromPointNormal(origin, normal);
  24447. }
  24448. defineProperties(EllipsoidTangentPlane.prototype, {
  24449. /**
  24450. * Gets the ellipsoid.
  24451. * @memberof EllipsoidTangentPlane.prototype
  24452. * @type {Ellipsoid}
  24453. */
  24454. ellipsoid : {
  24455. get : function() {
  24456. return this._ellipsoid;
  24457. }
  24458. },
  24459. /**
  24460. * Gets the origin.
  24461. * @memberof EllipsoidTangentPlane.prototype
  24462. * @type {Cartesian3}
  24463. */
  24464. origin : {
  24465. get : function() {
  24466. return this._origin;
  24467. }
  24468. },
  24469. /**
  24470. * Gets the plane which is tangent to the ellipsoid.
  24471. * @memberof EllipsoidTangentPlane.prototype
  24472. * @readonly
  24473. * @type {Plane}
  24474. */
  24475. plane : {
  24476. get : function() {
  24477. return this._plane;
  24478. }
  24479. },
  24480. /**
  24481. * Gets the local X-axis (east) of the tangent plane.
  24482. * @memberof EllipsoidTangentPlane.prototype
  24483. * @readonly
  24484. * @type {Cartesian3}
  24485. */
  24486. xAxis : {
  24487. get : function() {
  24488. return this._xAxis;
  24489. }
  24490. },
  24491. /**
  24492. * Gets the local Y-axis (north) of the tangent plane.
  24493. * @memberof EllipsoidTangentPlane.prototype
  24494. * @readonly
  24495. * @type {Cartesian3}
  24496. */
  24497. yAxis : {
  24498. get : function() {
  24499. return this._yAxis;
  24500. }
  24501. },
  24502. /**
  24503. * Gets the local Z-axis (up) of the tangent plane.
  24504. * @member EllipsoidTangentPlane.prototype
  24505. * @readonly
  24506. * @type {Cartesian3}
  24507. */
  24508. zAxis : {
  24509. get : function() {
  24510. return this._plane.normal;
  24511. }
  24512. }
  24513. });
  24514. var tmp = new AxisAlignedBoundingBox();
  24515. /**
  24516. * Creates a new instance from the provided ellipsoid and the center
  24517. * point of the provided Cartesians.
  24518. *
  24519. * @param {Ellipsoid} ellipsoid The ellipsoid to use.
  24520. * @param {Cartesian3} cartesians The list of positions surrounding the center point.
  24521. */
  24522. EllipsoidTangentPlane.fromPoints = function(cartesians, ellipsoid) {
  24523. if (!defined(cartesians)) {
  24524. throw new DeveloperError('cartesians is required.');
  24525. }
  24526. var box = AxisAlignedBoundingBox.fromPoints(cartesians, tmp);
  24527. return new EllipsoidTangentPlane(box.center, ellipsoid);
  24528. };
  24529. var scratchProjectPointOntoPlaneRay = new Ray();
  24530. var scratchProjectPointOntoPlaneCartesian3 = new Cartesian3();
  24531. /**
  24532. * Computes the projection of the provided 3D position onto the 2D plane, radially outward from the {@link EllipsoidTangentPlane.ellipsoid} coordinate system origin.
  24533. *
  24534. * @param {Cartesian3} cartesian The point to project.
  24535. * @param {Cartesian2} [result] The object onto which to store the result.
  24536. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided. Undefined if there is no intersection point
  24537. */
  24538. EllipsoidTangentPlane.prototype.projectPointOntoPlane = function(cartesian, result) {
  24539. if (!defined(cartesian)) {
  24540. throw new DeveloperError('cartesian is required.');
  24541. }
  24542. var ray = scratchProjectPointOntoPlaneRay;
  24543. ray.origin = cartesian;
  24544. Cartesian3.normalize(cartesian, ray.direction);
  24545. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  24546. if (!defined(intersectionPoint)) {
  24547. Cartesian3.negate(ray.direction, ray.direction);
  24548. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  24549. }
  24550. if (defined(intersectionPoint)) {
  24551. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  24552. var x = Cartesian3.dot(this._xAxis, v);
  24553. var y = Cartesian3.dot(this._yAxis, v);
  24554. if (!defined(result)) {
  24555. return new Cartesian2(x, y);
  24556. }
  24557. result.x = x;
  24558. result.y = y;
  24559. return result;
  24560. }
  24561. return undefined;
  24562. };
  24563. /**
  24564. * Computes the projection of the provided 3D positions onto the 2D plane (where possible), radially outward from the global origin.
  24565. * The resulting array may be shorter than the input array - if a single projection is impossible it will not be included.
  24566. *
  24567. * @see EllipsoidTangentPlane.projectPointOntoPlane
  24568. *
  24569. * @param {Cartesian3[]} cartesians The array of points to project.
  24570. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  24571. * @returns {Cartesian2[]} The modified result parameter or a new array of Cartesian2 instances if none was provided.
  24572. */
  24573. EllipsoidTangentPlane.prototype.projectPointsOntoPlane = function(cartesians, result) {
  24574. if (!defined(cartesians)) {
  24575. throw new DeveloperError('cartesians is required.');
  24576. }
  24577. if (!defined(result)) {
  24578. result = [];
  24579. }
  24580. var count = 0;
  24581. var length = cartesians.length;
  24582. for ( var i = 0; i < length; i++) {
  24583. var p = this.projectPointOntoPlane(cartesians[i], result[count]);
  24584. if (defined(p)) {
  24585. result[count] = p;
  24586. count++;
  24587. }
  24588. }
  24589. result.length = count;
  24590. return result;
  24591. };
  24592. /**
  24593. * Computes the projection of the provided 3D position onto the 2D plane, along the plane normal.
  24594. *
  24595. * @param {Cartesian3} cartesian The point to project.
  24596. * @param {Cartesian2} [result] The object onto which to store the result.
  24597. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if none was provided.
  24598. */
  24599. EllipsoidTangentPlane.prototype.projectPointToNearestOnPlane = function(cartesian, result) {
  24600. if (!defined(cartesian)) {
  24601. throw new DeveloperError('cartesian is required.');
  24602. }
  24603. if (!defined(result)) {
  24604. result = new Cartesian2();
  24605. }
  24606. var ray = scratchProjectPointOntoPlaneRay;
  24607. ray.origin = cartesian;
  24608. Cartesian3.clone(this._plane.normal, ray.direction);
  24609. var intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  24610. if (!defined(intersectionPoint)) {
  24611. Cartesian3.negate(ray.direction, ray.direction);
  24612. intersectionPoint = IntersectionTests.rayPlane(ray, this._plane, scratchProjectPointOntoPlaneCartesian3);
  24613. }
  24614. var v = Cartesian3.subtract(intersectionPoint, this._origin, intersectionPoint);
  24615. var x = Cartesian3.dot(this._xAxis, v);
  24616. var y = Cartesian3.dot(this._yAxis, v);
  24617. result.x = x;
  24618. result.y = y;
  24619. return result;
  24620. };
  24621. /**
  24622. * Computes the projection of the provided 3D positions onto the 2D plane, along the plane normal.
  24623. *
  24624. * @see EllipsoidTangentPlane.projectPointToNearestOnPlane
  24625. *
  24626. * @param {Cartesian3[]} cartesians The array of points to project.
  24627. * @param {Cartesian2[]} [result] The array of Cartesian2 instances onto which to store results.
  24628. * @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>.
  24629. */
  24630. EllipsoidTangentPlane.prototype.projectPointsToNearestOnPlane = function(cartesians, result) {
  24631. if (!defined(cartesians)) {
  24632. throw new DeveloperError('cartesians is required.');
  24633. }
  24634. if (!defined(result)) {
  24635. result = [];
  24636. }
  24637. var length = cartesians.length;
  24638. result.length = length;
  24639. for (var i = 0; i < length; i++) {
  24640. result[i] = this.projectPointToNearestOnPlane(cartesians[i], result[i]);
  24641. }
  24642. return result;
  24643. };
  24644. var projectPointsOntoEllipsoidScratch = new Cartesian3();
  24645. /**
  24646. * Computes the projection of the provided 2D positions onto the 3D ellipsoid.
  24647. *
  24648. * @param {Cartesian2[]} cartesians The array of points to project.
  24649. * @param {Cartesian3[]} [result] The array of Cartesian3 instances onto which to store results.
  24650. * @returns {Cartesian3[]} The modified result parameter or a new array of Cartesian3 instances if none was provided.
  24651. */
  24652. EllipsoidTangentPlane.prototype.projectPointsOntoEllipsoid = function(cartesians, result) {
  24653. if (!defined(cartesians)) {
  24654. throw new DeveloperError('cartesians is required.');
  24655. }
  24656. var length = cartesians.length;
  24657. if (!defined(result)) {
  24658. result = new Array(length);
  24659. } else {
  24660. result.length = length;
  24661. }
  24662. var ellipsoid = this._ellipsoid;
  24663. var origin = this._origin;
  24664. var xAxis = this._xAxis;
  24665. var yAxis = this._yAxis;
  24666. var tmp = projectPointsOntoEllipsoidScratch;
  24667. for ( var i = 0; i < length; ++i) {
  24668. var position = cartesians[i];
  24669. Cartesian3.multiplyByScalar(xAxis, position.x, tmp);
  24670. if (!defined(result[i])) {
  24671. result[i] = new Cartesian3();
  24672. }
  24673. var point = Cartesian3.add(origin, tmp, result[i]);
  24674. Cartesian3.multiplyByScalar(yAxis, position.y, tmp);
  24675. Cartesian3.add(point, tmp, point);
  24676. ellipsoid.scaleToGeocentricSurface(point, point);
  24677. }
  24678. return result;
  24679. };
  24680. return EllipsoidTangentPlane;
  24681. });
  24682. /*global define*/
  24683. define('Core/EllipsoidGeodesic',[
  24684. './Cartesian3',
  24685. './Cartographic',
  24686. './defaultValue',
  24687. './defined',
  24688. './defineProperties',
  24689. './DeveloperError',
  24690. './Ellipsoid',
  24691. './Math'
  24692. ], function(
  24693. Cartesian3,
  24694. Cartographic,
  24695. defaultValue,
  24696. defined,
  24697. defineProperties,
  24698. DeveloperError,
  24699. Ellipsoid,
  24700. CesiumMath) {
  24701. 'use strict';
  24702. function setConstants(ellipsoidGeodesic) {
  24703. var uSquared = ellipsoidGeodesic._uSquared;
  24704. var a = ellipsoidGeodesic._ellipsoid.maximumRadius;
  24705. var b = ellipsoidGeodesic._ellipsoid.minimumRadius;
  24706. var f = (a - b) / a;
  24707. var cosineHeading = Math.cos(ellipsoidGeodesic._startHeading);
  24708. var sineHeading = Math.sin(ellipsoidGeodesic._startHeading);
  24709. var tanU = (1 - f) * Math.tan(ellipsoidGeodesic._start.latitude);
  24710. var cosineU = 1.0 / Math.sqrt(1.0 + tanU * tanU);
  24711. var sineU = cosineU * tanU;
  24712. var sigma = Math.atan2(tanU, cosineHeading);
  24713. var sineAlpha = cosineU * sineHeading;
  24714. var sineSquaredAlpha = sineAlpha * sineAlpha;
  24715. var cosineSquaredAlpha = 1.0 - sineSquaredAlpha;
  24716. var cosineAlpha = Math.sqrt(cosineSquaredAlpha);
  24717. var u2Over4 = uSquared / 4.0;
  24718. var u4Over16 = u2Over4 * u2Over4;
  24719. var u6Over64 = u4Over16 * u2Over4;
  24720. var u8Over256 = u4Over16 * u4Over16;
  24721. var a0 = (1.0 + u2Over4 - 3.0 * u4Over16 / 4.0 + 5.0 * u6Over64 / 4.0 - 175.0 * u8Over256 / 64.0);
  24722. var a1 = (1.0 - u2Over4 + 15.0 * u4Over16 / 8.0 - 35.0 * u6Over64 / 8.0);
  24723. var a2 = (1.0 - 3.0 * u2Over4 + 35.0 * u4Over16 / 4.0);
  24724. var a3 = (1.0 - 5.0 * u2Over4);
  24725. var distanceRatio = a0 * sigma - a1 * Math.sin(2.0 * sigma) * u2Over4 / 2.0 - a2 * Math.sin(4.0 * sigma) * u4Over16 / 16.0 -
  24726. a3 * Math.sin(6.0 * sigma) * u6Over64 / 48.0 - Math.sin(8.0 * sigma) * 5.0 * u8Over256 / 512;
  24727. var constants = ellipsoidGeodesic._constants;
  24728. constants.a = a;
  24729. constants.b = b;
  24730. constants.f = f;
  24731. constants.cosineHeading = cosineHeading;
  24732. constants.sineHeading = sineHeading;
  24733. constants.tanU = tanU;
  24734. constants.cosineU = cosineU;
  24735. constants.sineU = sineU;
  24736. constants.sigma = sigma;
  24737. constants.sineAlpha = sineAlpha;
  24738. constants.sineSquaredAlpha = sineSquaredAlpha;
  24739. constants.cosineSquaredAlpha = cosineSquaredAlpha;
  24740. constants.cosineAlpha = cosineAlpha;
  24741. constants.u2Over4 = u2Over4;
  24742. constants.u4Over16 = u4Over16;
  24743. constants.u6Over64 = u6Over64;
  24744. constants.u8Over256 = u8Over256;
  24745. constants.a0 = a0;
  24746. constants.a1 = a1;
  24747. constants.a2 = a2;
  24748. constants.a3 = a3;
  24749. constants.distanceRatio = distanceRatio;
  24750. }
  24751. function computeC(f, cosineSquaredAlpha) {
  24752. return f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha)) / 16.0;
  24753. }
  24754. function computeDeltaLambda(f, sineAlpha, cosineSquaredAlpha, sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint) {
  24755. var C = computeC(f, cosineSquaredAlpha);
  24756. return (1.0 - C) * f * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint +
  24757. C * cosineSigma * (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0)));
  24758. }
  24759. function vincentyInverseFormula(ellipsoidGeodesic, major, minor, firstLongitude, firstLatitude, secondLongitude, secondLatitude) {
  24760. var eff = (major - minor) / major;
  24761. var l = secondLongitude - firstLongitude;
  24762. var u1 = Math.atan((1 - eff) * Math.tan(firstLatitude));
  24763. var u2 = Math.atan((1 - eff) * Math.tan(secondLatitude));
  24764. var cosineU1 = Math.cos(u1);
  24765. var sineU1 = Math.sin(u1);
  24766. var cosineU2 = Math.cos(u2);
  24767. var sineU2 = Math.sin(u2);
  24768. var cc = cosineU1 * cosineU2;
  24769. var cs = cosineU1 * sineU2;
  24770. var ss = sineU1 * sineU2;
  24771. var sc = sineU1 * cosineU2;
  24772. var lambda = l;
  24773. var lambdaDot = CesiumMath.TWO_PI;
  24774. var cosineLambda = Math.cos(lambda);
  24775. var sineLambda = Math.sin(lambda);
  24776. var sigma;
  24777. var cosineSigma;
  24778. var sineSigma;
  24779. var cosineSquaredAlpha;
  24780. var cosineTwiceSigmaMidpoint;
  24781. do {
  24782. cosineLambda = Math.cos(lambda);
  24783. sineLambda = Math.sin(lambda);
  24784. var temp = cs - sc * cosineLambda;
  24785. sineSigma = Math.sqrt(cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp);
  24786. cosineSigma = ss + cc * cosineLambda;
  24787. sigma = Math.atan2(sineSigma, cosineSigma);
  24788. var sineAlpha;
  24789. if (sineSigma === 0.0) {
  24790. sineAlpha = 0.0;
  24791. cosineSquaredAlpha = 1.0;
  24792. } else {
  24793. sineAlpha = cc * sineLambda / sineSigma;
  24794. cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha;
  24795. }
  24796. lambdaDot = lambda;
  24797. cosineTwiceSigmaMidpoint = cosineSigma - 2.0 * ss / cosineSquaredAlpha;
  24798. if (isNaN(cosineTwiceSigmaMidpoint)) {
  24799. cosineTwiceSigmaMidpoint = 0.0;
  24800. }
  24801. lambda = l + computeDeltaLambda(eff, sineAlpha, cosineSquaredAlpha,
  24802. sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint);
  24803. } while (Math.abs(lambda - lambdaDot) > CesiumMath.EPSILON12);
  24804. var uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor);
  24805. var A = 1.0 + uSquared * (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0)) / 16384.0;
  24806. var B = uSquared * (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0)) / 1024.0;
  24807. var cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint;
  24808. var deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma *
  24809. (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) - B * cosineTwiceSigmaMidpoint *
  24810. (4.0 * sineSigma * sineSigma - 3.0) * (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0) / 6.0) / 4.0);
  24811. var distance = minor * A * (sigma - deltaSigma);
  24812. var startHeading = Math.atan2(cosineU2 * sineLambda, cs - sc * cosineLambda);
  24813. var endHeading = Math.atan2(cosineU1 * sineLambda, cs * cosineLambda - sc);
  24814. ellipsoidGeodesic._distance = distance;
  24815. ellipsoidGeodesic._startHeading = startHeading;
  24816. ellipsoidGeodesic._endHeading = endHeading;
  24817. ellipsoidGeodesic._uSquared = uSquared;
  24818. }
  24819. function computeProperties(ellipsoidGeodesic, start, end, ellipsoid) {
  24820. var firstCartesian = Cartesian3.normalize(ellipsoid.cartographicToCartesian(start, scratchCart2), scratchCart1);
  24821. var lastCartesian = Cartesian3.normalize(ellipsoid.cartographicToCartesian(end, scratchCart2), scratchCart2);
  24822. if (Math.abs(Math.abs(Cartesian3.angleBetween(firstCartesian, lastCartesian)) - Math.PI) < 0.0125) {
  24823. throw new DeveloperError('geodesic position is not unique');
  24824. }
  24825. vincentyInverseFormula(ellipsoidGeodesic, ellipsoid.maximumRadius, ellipsoid.minimumRadius,
  24826. start.longitude, start.latitude, end.longitude, end.latitude);
  24827. ellipsoidGeodesic._start = Cartographic.clone(start, ellipsoidGeodesic._start);
  24828. ellipsoidGeodesic._end = Cartographic.clone(end, ellipsoidGeodesic._end);
  24829. ellipsoidGeodesic._start.height = 0;
  24830. ellipsoidGeodesic._end.height = 0;
  24831. setConstants(ellipsoidGeodesic);
  24832. }
  24833. var scratchCart1 = new Cartesian3();
  24834. var scratchCart2 = new Cartesian3();
  24835. /**
  24836. * Initializes a geodesic on the ellipsoid connecting the two provided planetodetic points.
  24837. *
  24838. * @alias EllipsoidGeodesic
  24839. * @constructor
  24840. *
  24841. * @param {Cartographic} [start] The initial planetodetic point on the path.
  24842. * @param {Cartographic} [end] The final planetodetic point on the path.
  24843. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the geodesic lies.
  24844. */
  24845. function EllipsoidGeodesic(start, end, ellipsoid) {
  24846. var e = defaultValue(ellipsoid, Ellipsoid.WGS84);
  24847. this._ellipsoid = e;
  24848. this._start = new Cartographic();
  24849. this._end = new Cartographic();
  24850. this._constants = {};
  24851. this._startHeading = undefined;
  24852. this._endHeading = undefined;
  24853. this._distance = undefined;
  24854. this._uSquared = undefined;
  24855. if (defined(start) && defined(end)) {
  24856. computeProperties(this, start, end, e);
  24857. }
  24858. }
  24859. defineProperties(EllipsoidGeodesic.prototype, {
  24860. /**
  24861. * Gets the ellipsoid.
  24862. * @memberof EllipsoidGeodesic.prototype
  24863. * @type {Ellipsoid}
  24864. * @readonly
  24865. */
  24866. ellipsoid : {
  24867. get : function() {
  24868. return this._ellipsoid;
  24869. }
  24870. },
  24871. /**
  24872. * Gets the surface distance between the start and end point
  24873. * @memberof EllipsoidGeodesic.prototype
  24874. * @type {Number}
  24875. * @readonly
  24876. */
  24877. surfaceDistance : {
  24878. get : function() {
  24879. if (!defined(this._distance)) {
  24880. throw new DeveloperError('set end positions before getting surfaceDistance');
  24881. }
  24882. return this._distance;
  24883. }
  24884. },
  24885. /**
  24886. * Gets the initial planetodetic point on the path.
  24887. * @memberof EllipsoidGeodesic.prototype
  24888. * @type {Cartographic}
  24889. * @readonly
  24890. */
  24891. start : {
  24892. get : function() {
  24893. return this._start;
  24894. }
  24895. },
  24896. /**
  24897. * Gets the final planetodetic point on the path.
  24898. * @memberof EllipsoidGeodesic.prototype
  24899. * @type {Cartographic}
  24900. * @readonly
  24901. */
  24902. end : {
  24903. get : function() {
  24904. return this._end;
  24905. }
  24906. },
  24907. /**
  24908. * Gets the heading at the initial point.
  24909. * @memberof EllipsoidGeodesic.prototype
  24910. * @type {Number}
  24911. * @readonly
  24912. */
  24913. startHeading : {
  24914. get : function() {
  24915. if (!defined(this._distance)) {
  24916. throw new DeveloperError('set end positions before getting startHeading');
  24917. }
  24918. return this._startHeading;
  24919. }
  24920. },
  24921. /**
  24922. * Gets the heading at the final point.
  24923. * @memberof EllipsoidGeodesic.prototype
  24924. * @type {Number}
  24925. * @readonly
  24926. */
  24927. endHeading : {
  24928. get : function() {
  24929. if (!defined(this._distance)) {
  24930. throw new DeveloperError('set end positions before getting endHeading');
  24931. }
  24932. return this._endHeading;
  24933. }
  24934. }
  24935. });
  24936. /**
  24937. * Sets the start and end points of the geodesic
  24938. *
  24939. * @param {Cartographic} start The initial planetodetic point on the path.
  24940. * @param {Cartographic} end The final planetodetic point on the path.
  24941. */
  24942. EllipsoidGeodesic.prototype.setEndPoints = function(start, end) {
  24943. if (!defined(start)) {
  24944. throw new DeveloperError('start cartographic position is required');
  24945. }
  24946. if (!defined(end)) {
  24947. throw new DeveloperError('end cartgraphic position is required');
  24948. }
  24949. computeProperties(this, start, end, this._ellipsoid);
  24950. };
  24951. /**
  24952. * Provides the location of a point at the indicated portion along the geodesic.
  24953. *
  24954. * @param {Number} fraction The portion of the distance between the initial and final points.
  24955. * @returns {Cartographic} The location of the point along the geodesic.
  24956. */
  24957. EllipsoidGeodesic.prototype.interpolateUsingFraction = function(fraction, result) {
  24958. return this.interpolateUsingSurfaceDistance(this._distance * fraction, result);
  24959. };
  24960. /**
  24961. * Provides the location of a point at the indicated distance along the geodesic.
  24962. *
  24963. * @param {Number} distance The distance from the inital point to the point of interest along the geodesic
  24964. * @returns {Cartographic} The location of the point along the geodesic.
  24965. *
  24966. * @exception {DeveloperError} start and end must be set before calling function interpolateUsingSurfaceDistance
  24967. */
  24968. EllipsoidGeodesic.prototype.interpolateUsingSurfaceDistance = function(distance, result) {
  24969. if (!defined(this._distance)) {
  24970. throw new DeveloperError('start and end must be set before calling function interpolateUsingSurfaceDistance');
  24971. }
  24972. var constants = this._constants;
  24973. var s = constants.distanceRatio + distance / constants.b;
  24974. var cosine2S = Math.cos(2.0 * s);
  24975. var cosine4S = Math.cos(4.0 * s);
  24976. var cosine6S = Math.cos(6.0 * s);
  24977. var sine2S = Math.sin(2.0 * s);
  24978. var sine4S = Math.sin(4.0 * s);
  24979. var sine6S = Math.sin(6.0 * s);
  24980. var sine8S = Math.sin(8.0 * s);
  24981. var s2 = s * s;
  24982. var s3 = s * s2;
  24983. var u8Over256 = constants.u8Over256;
  24984. var u2Over4 = constants.u2Over4;
  24985. var u6Over64 = constants.u6Over64;
  24986. var u4Over16 = constants.u4Over16;
  24987. var sigma = 2.0 * s3 * u8Over256 * cosine2S / 3.0 +
  24988. s * (1.0 - u2Over4 + 7.0 * u4Over16 / 4.0 - 15.0 * u6Over64 / 4.0 + 579.0 * u8Over256 / 64.0 -
  24989. (u4Over16 - 15.0 * u6Over64 / 4.0 + 187.0 * u8Over256 / 16.0) * cosine2S -
  24990. (5.0 * u6Over64 / 4.0 - 115.0 * u8Over256 / 16.0) * cosine4S -
  24991. 29.0 * u8Over256 * cosine6S / 16.0) +
  24992. (u2Over4 / 2.0 - u4Over16 + 71.0 * u6Over64 / 32.0 - 85.0 * u8Over256 / 16.0) * sine2S +
  24993. (5.0 * u4Over16 / 16.0 - 5.0 * u6Over64 / 4.0 + 383.0 * u8Over256 / 96.0) * sine4S -
  24994. s2 * ((u6Over64 - 11.0 * u8Over256 / 2.0) * sine2S + 5.0 * u8Over256 * sine4S / 2.0) +
  24995. (29.0 * u6Over64 / 96.0 - 29.0 * u8Over256 / 16.0) * sine6S +
  24996. 539.0 * u8Over256 * sine8S / 1536.0;
  24997. var theta = Math.asin(Math.sin(sigma) * constants.cosineAlpha);
  24998. var latitude = Math.atan(constants.a / constants.b * Math.tan(theta));
  24999. // Redefine in terms of relative argument of latitude.
  25000. sigma = sigma - constants.sigma;
  25001. var cosineTwiceSigmaMidpoint = Math.cos(2.0 * constants.sigma + sigma);
  25002. var sineSigma = Math.sin(sigma);
  25003. var cosineSigma = Math.cos(sigma);
  25004. var cc = constants.cosineU * cosineSigma;
  25005. var ss = constants.sineU * sineSigma;
  25006. var lambda = Math.atan2(sineSigma * constants.sineHeading, cc - ss * constants.cosineHeading);
  25007. var l = lambda - computeDeltaLambda(constants.f, constants.sineAlpha, constants.cosineSquaredAlpha,
  25008. sigma, sineSigma, cosineSigma, cosineTwiceSigmaMidpoint);
  25009. if (defined(result)) {
  25010. result.longitude = this._start.longitude + l;
  25011. result.latitude = latitude;
  25012. result.height = 0.0;
  25013. return result;
  25014. }
  25015. return new Cartographic(this._start.longitude + l, latitude, 0.0);
  25016. };
  25017. return EllipsoidGeodesic;
  25018. });
  25019. /*global define*/
  25020. define('Core/PolylinePipeline',[
  25021. './Cartesian3',
  25022. './Cartographic',
  25023. './defaultValue',
  25024. './defined',
  25025. './DeveloperError',
  25026. './Ellipsoid',
  25027. './EllipsoidGeodesic',
  25028. './IntersectionTests',
  25029. './isArray',
  25030. './Math',
  25031. './Matrix4',
  25032. './Plane'
  25033. ], function(
  25034. Cartesian3,
  25035. Cartographic,
  25036. defaultValue,
  25037. defined,
  25038. DeveloperError,
  25039. Ellipsoid,
  25040. EllipsoidGeodesic,
  25041. IntersectionTests,
  25042. isArray,
  25043. CesiumMath,
  25044. Matrix4,
  25045. Plane) {
  25046. 'use strict';
  25047. /**
  25048. * @private
  25049. */
  25050. var PolylinePipeline = {};
  25051. PolylinePipeline.numberOfPoints = function(p0, p1, minDistance) {
  25052. var distance = Cartesian3.distance(p0, p1);
  25053. return Math.ceil(distance / minDistance);
  25054. };
  25055. var cartoScratch = new Cartographic();
  25056. PolylinePipeline.extractHeights = function(positions, ellipsoid) {
  25057. var length = positions.length;
  25058. var heights = new Array(length);
  25059. for (var i = 0; i < length; i++) {
  25060. var p = positions[i];
  25061. heights[i] = ellipsoid.cartesianToCartographic(p, cartoScratch).height;
  25062. }
  25063. return heights;
  25064. };
  25065. var wrapLongitudeInversMatrix = new Matrix4();
  25066. var wrapLongitudeOrigin = new Cartesian3();
  25067. var wrapLongitudeXZNormal = new Cartesian3();
  25068. var wrapLongitudeXZPlane = new Plane(Cartesian3.ZERO, 0.0);
  25069. var wrapLongitudeYZNormal = new Cartesian3();
  25070. var wrapLongitudeYZPlane = new Plane(Cartesian3.ZERO, 0.0);
  25071. var wrapLongitudeIntersection = new Cartesian3();
  25072. var wrapLongitudeOffset = new Cartesian3();
  25073. var subdivideHeightsScratchArray = [];
  25074. function subdivideHeights(numPoints, h0, h1) {
  25075. var heights = subdivideHeightsScratchArray;
  25076. heights.length = numPoints;
  25077. var i;
  25078. if (h0 === h1) {
  25079. for (i = 0; i < numPoints; i++) {
  25080. heights[i] = h0;
  25081. }
  25082. return heights;
  25083. }
  25084. var dHeight = h1 - h0;
  25085. var heightPerVertex = dHeight / numPoints;
  25086. for (i = 0; i < numPoints; i++) {
  25087. var h = h0 + i*heightPerVertex;
  25088. heights[i] = h;
  25089. }
  25090. return heights;
  25091. }
  25092. var carto1 = new Cartographic();
  25093. var carto2 = new Cartographic();
  25094. var cartesian = new Cartesian3();
  25095. var scaleFirst = new Cartesian3();
  25096. var scaleLast = new Cartesian3();
  25097. var ellipsoidGeodesic = new EllipsoidGeodesic();
  25098. //Returns subdivided line scaled to ellipsoid surface starting at p1 and ending at p2.
  25099. //Result includes p1, but not include p2. This function is called for a sequence of line segments,
  25100. //and this prevents duplication of end point.
  25101. function generateCartesianArc(p0, p1, minDistance, ellipsoid, h0, h1, array, offset) {
  25102. var first = ellipsoid.scaleToGeodeticSurface(p0, scaleFirst);
  25103. var last = ellipsoid.scaleToGeodeticSurface(p1, scaleLast);
  25104. var numPoints = PolylinePipeline.numberOfPoints(p0, p1, minDistance);
  25105. var start = ellipsoid.cartesianToCartographic(first, carto1);
  25106. var end = ellipsoid.cartesianToCartographic(last, carto2);
  25107. var heights = subdivideHeights(numPoints, h0, h1);
  25108. ellipsoidGeodesic.setEndPoints(start, end);
  25109. var surfaceDistanceBetweenPoints = ellipsoidGeodesic.surfaceDistance / numPoints;
  25110. var index = offset;
  25111. start.height = h0;
  25112. var cart = ellipsoid.cartographicToCartesian(start, cartesian);
  25113. Cartesian3.pack(cart, array, index);
  25114. index += 3;
  25115. for (var i = 1; i < numPoints; i++) {
  25116. var carto = ellipsoidGeodesic.interpolateUsingSurfaceDistance(i * surfaceDistanceBetweenPoints, carto2);
  25117. carto.height = heights[i];
  25118. cart = ellipsoid.cartographicToCartesian(carto, cartesian);
  25119. Cartesian3.pack(cart, array, index);
  25120. index += 3;
  25121. }
  25122. return index;
  25123. }
  25124. /**
  25125. * Breaks a {@link Polyline} into segments such that it does not cross the &plusmn;180 degree meridian of an ellipsoid.
  25126. *
  25127. * @param {Cartesian3[]} positions The polyline's Cartesian positions.
  25128. * @param {Matrix4} [modelMatrix=Matrix4.IDENTITY] The polyline's model matrix. Assumed to be an affine
  25129. * transformation matrix, where the upper left 3x3 elements are a rotation matrix, and
  25130. * the upper three elements in the fourth column are the translation. The bottom row is assumed to be [0, 0, 0, 1].
  25131. * The matrix is not verified to be in the proper form.
  25132. * @returns {Object} An object with a <code>positions</code> property that is an array of positions and a
  25133. * <code>segments</code> property.
  25134. *
  25135. *
  25136. * @example
  25137. * var polylines = new Cesium.PolylineCollection();
  25138. * var polyline = polylines.add(...);
  25139. * var positions = polyline.positions;
  25140. * var modelMatrix = polylines.modelMatrix;
  25141. * var segments = Cesium.PolylinePipeline.wrapLongitude(positions, modelMatrix);
  25142. *
  25143. * @see PolygonPipeline.wrapLongitude
  25144. * @see Polyline
  25145. * @see PolylineCollection
  25146. */
  25147. PolylinePipeline.wrapLongitude = function(positions, modelMatrix) {
  25148. var cartesians = [];
  25149. var segments = [];
  25150. if (defined(positions) && positions.length > 0) {
  25151. modelMatrix = defaultValue(modelMatrix, Matrix4.IDENTITY);
  25152. var inverseModelMatrix = Matrix4.inverseTransformation(modelMatrix, wrapLongitudeInversMatrix);
  25153. var origin = Matrix4.multiplyByPoint(inverseModelMatrix, Cartesian3.ZERO, wrapLongitudeOrigin);
  25154. var xzNormal = Matrix4.multiplyByPointAsVector(inverseModelMatrix, Cartesian3.UNIT_Y, wrapLongitudeXZNormal);
  25155. var xzPlane = Plane.fromPointNormal(origin, xzNormal, wrapLongitudeXZPlane);
  25156. var yzNormal = Matrix4.multiplyByPointAsVector(inverseModelMatrix, Cartesian3.UNIT_X, wrapLongitudeYZNormal);
  25157. var yzPlane = Plane.fromPointNormal(origin, yzNormal, wrapLongitudeYZPlane);
  25158. var count = 1;
  25159. cartesians.push(Cartesian3.clone(positions[0]));
  25160. var prev = cartesians[0];
  25161. var length = positions.length;
  25162. for (var i = 1; i < length; ++i) {
  25163. var cur = positions[i];
  25164. // intersects the IDL if either endpoint is on the negative side of the yz-plane
  25165. if (Plane.getPointDistance(yzPlane, prev) < 0.0 || Plane.getPointDistance(yzPlane, cur) < 0.0) {
  25166. // and intersects the xz-plane
  25167. var intersection = IntersectionTests.lineSegmentPlane(prev, cur, xzPlane, wrapLongitudeIntersection);
  25168. if (defined(intersection)) {
  25169. // move point on the xz-plane slightly away from the plane
  25170. var offset = Cartesian3.multiplyByScalar(xzNormal, 5.0e-9, wrapLongitudeOffset);
  25171. if (Plane.getPointDistance(xzPlane, prev) < 0.0) {
  25172. Cartesian3.negate(offset, offset);
  25173. }
  25174. cartesians.push(Cartesian3.add(intersection, offset, new Cartesian3()));
  25175. segments.push(count + 1);
  25176. Cartesian3.negate(offset, offset);
  25177. cartesians.push(Cartesian3.add(intersection, offset, new Cartesian3()));
  25178. count = 1;
  25179. }
  25180. }
  25181. cartesians.push(Cartesian3.clone(positions[i]));
  25182. count++;
  25183. prev = cur;
  25184. }
  25185. segments.push(count);
  25186. }
  25187. return {
  25188. positions : cartesians,
  25189. lengths : segments
  25190. };
  25191. };
  25192. /**
  25193. * Subdivides polyline and raises all points to the specified height. Returns an array of numbers to represent the positions.
  25194. * @param {Cartesian3[]} positions The array of type {Cartesian3} representing positions.
  25195. * @param {Number|Number[]} [height=0.0] A number or array of numbers representing the heights of each position.
  25196. * @param {Number} [granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  25197. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  25198. * @returns {Number[]} A new array of positions of type {Number} that have been subdivided and raised to the surface of the ellipsoid.
  25199. *
  25200. * @example
  25201. * var positions = Cesium.Cartesian3.fromDegreesArray([
  25202. * -105.0, 40.0,
  25203. * -100.0, 38.0,
  25204. * -105.0, 35.0,
  25205. * -100.0, 32.0
  25206. * ]);
  25207. * var surfacePositions = Cesium.PolylinePipeline.generateArc({
  25208. * positons: positions
  25209. * });
  25210. */
  25211. PolylinePipeline.generateArc = function(options) {
  25212. if (!defined(options)) {
  25213. options = {};
  25214. }
  25215. var positions = options.positions;
  25216. if (!defined(positions)) {
  25217. throw new DeveloperError('options.positions is required.');
  25218. }
  25219. var length = positions.length;
  25220. var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  25221. var height = defaultValue(options.height, 0);
  25222. var hasHeightArray = isArray(height);
  25223. if (length < 1) {
  25224. return [];
  25225. } else if (length === 1) {
  25226. var p = ellipsoid.scaleToGeodeticSurface(positions[0], scaleFirst);
  25227. height = hasHeightArray ? height[0] : height;
  25228. if (height !== 0) {
  25229. var n = ellipsoid.geodeticSurfaceNormal(p, cartesian);
  25230. Cartesian3.multiplyByScalar(n, height, n);
  25231. Cartesian3.add(p, n, p);
  25232. }
  25233. return [p.x, p.y, p.z];
  25234. }
  25235. var minDistance = options.minDistance;
  25236. if (!defined(minDistance)) {
  25237. var granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
  25238. minDistance = CesiumMath.chordLength(granularity, ellipsoid.maximumRadius);
  25239. }
  25240. var numPoints = 0;
  25241. var i;
  25242. for (i = 0; i < length -1; i++) {
  25243. numPoints += PolylinePipeline.numberOfPoints(positions[i], positions[i+1], minDistance);
  25244. }
  25245. var arrayLength = (numPoints + 1) * 3;
  25246. var newPositions = new Array(arrayLength);
  25247. var offset = 0;
  25248. for (i = 0; i < length - 1; i++) {
  25249. var p0 = positions[i];
  25250. var p1 = positions[i + 1];
  25251. var h0 = hasHeightArray ? height[i] : height;
  25252. var h1 = hasHeightArray ? height[i + 1] : height;
  25253. offset = generateCartesianArc(p0, p1, minDistance, ellipsoid, h0, h1, newPositions, offset);
  25254. }
  25255. subdivideHeightsScratchArray.length = 0;
  25256. var lastPoint = positions[length - 1];
  25257. var carto = ellipsoid.cartesianToCartographic(lastPoint, carto1);
  25258. carto.height = hasHeightArray ? height[length - 1] : height;
  25259. var cart = ellipsoid.cartographicToCartesian(carto, cartesian);
  25260. Cartesian3.pack(cart, newPositions, arrayLength - 3);
  25261. return newPositions;
  25262. };
  25263. /**
  25264. * Subdivides polyline and raises all points to the specified height. Returns an array of new {Cartesian3} positions.
  25265. * @param {Cartesian3[]} positions The array of type {Cartesian3} representing positions.
  25266. * @param {Number|Number[]} [height=0.0] A number or array of numbers representing the heights of each position.
  25267. * @param {Number} [granularity = CesiumMath.RADIANS_PER_DEGREE] The distance, in radians, between each latitude and longitude. Determines the number of positions in the buffer.
  25268. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the positions lie.
  25269. * @returns {Cartesian3[]} A new array of cartesian3 positions that have been subdivided and raised to the surface of the ellipsoid.
  25270. *
  25271. * @example
  25272. * var positions = Cesium.Cartesian3.fromDegreesArray([
  25273. * -105.0, 40.0,
  25274. * -100.0, 38.0,
  25275. * -105.0, 35.0,
  25276. * -100.0, 32.0
  25277. * ]);
  25278. * var surfacePositions = Cesium.PolylinePipeline.generateCartesianArc({
  25279. * positons: positions
  25280. * });
  25281. */
  25282. PolylinePipeline.generateCartesianArc = function(options) {
  25283. var numberArray = PolylinePipeline.generateArc(options);
  25284. var size = numberArray.length/3;
  25285. var newPositions = new Array(size);
  25286. for (var i = 0; i < size; i++) {
  25287. newPositions[i] = Cartesian3.unpack(numberArray, i*3);
  25288. }
  25289. return newPositions;
  25290. };
  25291. return PolylinePipeline;
  25292. });
  25293. /*global define*/
  25294. define('Core/PolylineVolumeGeometryLibrary',[
  25295. './Cartesian2',
  25296. './Cartesian3',
  25297. './Cartesian4',
  25298. './Cartographic',
  25299. './CornerType',
  25300. './EllipsoidTangentPlane',
  25301. './Math',
  25302. './Matrix3',
  25303. './Matrix4',
  25304. './PolylinePipeline',
  25305. './Quaternion',
  25306. './Transforms'
  25307. ], function(
  25308. Cartesian2,
  25309. Cartesian3,
  25310. Cartesian4,
  25311. Cartographic,
  25312. CornerType,
  25313. EllipsoidTangentPlane,
  25314. CesiumMath,
  25315. Matrix3,
  25316. Matrix4,
  25317. PolylinePipeline,
  25318. Quaternion,
  25319. Transforms) {
  25320. 'use strict';
  25321. var scratch2Array = [new Cartesian3(), new Cartesian3()];
  25322. var scratchCartesian1 = new Cartesian3();
  25323. var scratchCartesian2 = new Cartesian3();
  25324. var scratchCartesian3 = new Cartesian3();
  25325. var scratchCartesian4 = new Cartesian3();
  25326. var scratchCartesian5 = new Cartesian3();
  25327. var scratchCartesian6 = new Cartesian3();
  25328. var scratchCartesian7 = new Cartesian3();
  25329. var scratchCartesian8 = new Cartesian3();
  25330. var scratchCartesian9 = new Cartesian3();
  25331. var scratch1 = new Cartesian3();
  25332. var scratch2 = new Cartesian3();
  25333. /**
  25334. * @private
  25335. */
  25336. var PolylineVolumeGeometryLibrary = {};
  25337. var cartographic = new Cartographic();
  25338. function scaleToSurface(positions, ellipsoid) {
  25339. var heights = new Array(positions.length);
  25340. for (var i = 0; i < positions.length; i++) {
  25341. var pos = positions[i];
  25342. cartographic = ellipsoid.cartesianToCartographic(pos, cartographic);
  25343. heights[i] = cartographic.height;
  25344. positions[i] = ellipsoid.scaleToGeodeticSurface(pos, pos);
  25345. }
  25346. return heights;
  25347. }
  25348. function subdivideHeights(points, h0, h1, granularity) {
  25349. var p0 = points[0];
  25350. var p1 = points[1];
  25351. var angleBetween = Cartesian3.angleBetween(p0, p1);
  25352. var numPoints = Math.ceil(angleBetween / granularity);
  25353. var heights = new Array(numPoints);
  25354. var i;
  25355. if (h0 === h1) {
  25356. for (i = 0; i < numPoints; i++) {
  25357. heights[i] = h0;
  25358. }
  25359. heights.push(h1);
  25360. return heights;
  25361. }
  25362. var dHeight = h1 - h0;
  25363. var heightPerVertex = dHeight / (numPoints);
  25364. for (i = 1; i < numPoints; i++) {
  25365. var h = h0 + i * heightPerVertex;
  25366. heights[i] = h;
  25367. }
  25368. heights[0] = h0;
  25369. heights.push(h1);
  25370. return heights;
  25371. }
  25372. function computeRotationAngle(start, end, position, ellipsoid) {
  25373. var tangentPlane = new EllipsoidTangentPlane(position, ellipsoid);
  25374. var next = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, start, nextScratch), nextScratch);
  25375. var prev = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, end, prevScratch), prevScratch);
  25376. var angle = Cartesian2.angleBetween(next, prev);
  25377. return (prev.x * next.y - prev.y * next.x >= 0.0) ? -angle : angle;
  25378. }
  25379. var negativeX = new Cartesian3(-1, 0, 0);
  25380. var transform = new Matrix4();
  25381. var translation = new Matrix4();
  25382. var rotationZ = new Matrix3();
  25383. var scaleMatrix = Matrix3.IDENTITY.clone();
  25384. var westScratch = new Cartesian3();
  25385. var finalPosScratch = new Cartesian4();
  25386. var heightCartesian = new Cartesian3();
  25387. function addPosition(center, left, shape, finalPositions, ellipsoid, height, xScalar, repeat) {
  25388. var west = westScratch;
  25389. var finalPosition = finalPosScratch;
  25390. transform = Transforms.eastNorthUpToFixedFrame(center, ellipsoid, transform);
  25391. west = Matrix4.multiplyByPointAsVector(transform, negativeX, west);
  25392. west = Cartesian3.normalize(west, west);
  25393. var angle = computeRotationAngle(west, left, center, ellipsoid);
  25394. rotationZ = Matrix3.fromRotationZ(angle, rotationZ);
  25395. heightCartesian.z = height;
  25396. transform = Matrix4.multiplyTransformation(transform, Matrix4.fromRotationTranslation(rotationZ, heightCartesian, translation), transform);
  25397. var scale = scaleMatrix;
  25398. scale[0] = xScalar;
  25399. for (var j = 0; j < repeat; j++) {
  25400. for (var i = 0; i < shape.length; i += 3) {
  25401. finalPosition = Cartesian3.fromArray(shape, i, finalPosition);
  25402. finalPosition = Matrix3.multiplyByVector(scale, finalPosition, finalPosition);
  25403. finalPosition = Matrix4.multiplyByPoint(transform, finalPosition, finalPosition);
  25404. finalPositions.push(finalPosition.x, finalPosition.y, finalPosition.z);
  25405. }
  25406. }
  25407. return finalPositions;
  25408. }
  25409. var centerScratch = new Cartesian3();
  25410. function addPositions(centers, left, shape, finalPositions, ellipsoid, heights, xScalar) {
  25411. for (var i = 0; i < centers.length; i += 3) {
  25412. var center = Cartesian3.fromArray(centers, i, centerScratch);
  25413. finalPositions = addPosition(center, left, shape, finalPositions, ellipsoid, heights[i / 3], xScalar, 1);
  25414. }
  25415. return finalPositions;
  25416. }
  25417. function convertShapeTo3DDuplicate(shape2D, boundingRectangle) { //orientate 2D shape to XZ plane center at (0, 0, 0), duplicate points
  25418. var length = shape2D.length;
  25419. var shape = new Array(length * 6);
  25420. var index = 0;
  25421. var xOffset = boundingRectangle.x + boundingRectangle.width / 2;
  25422. var yOffset = boundingRectangle.y + boundingRectangle.height / 2;
  25423. var point = shape2D[0];
  25424. shape[index++] = point.x - xOffset;
  25425. shape[index++] = 0.0;
  25426. shape[index++] = point.y - yOffset;
  25427. for (var i = 1; i < length; i++) {
  25428. point = shape2D[i];
  25429. var x = point.x - xOffset;
  25430. var z = point.y - yOffset;
  25431. shape[index++] = x;
  25432. shape[index++] = 0.0;
  25433. shape[index++] = z;
  25434. shape[index++] = x;
  25435. shape[index++] = 0.0;
  25436. shape[index++] = z;
  25437. }
  25438. point = shape2D[0];
  25439. shape[index++] = point.x - xOffset;
  25440. shape[index++] = 0.0;
  25441. shape[index++] = point.y - yOffset;
  25442. return shape;
  25443. }
  25444. function convertShapeTo3D(shape2D, boundingRectangle) { //orientate 2D shape to XZ plane center at (0, 0, 0)
  25445. var length = shape2D.length;
  25446. var shape = new Array(length * 3);
  25447. var index = 0;
  25448. var xOffset = boundingRectangle.x + boundingRectangle.width / 2;
  25449. var yOffset = boundingRectangle.y + boundingRectangle.height / 2;
  25450. for (var i = 0; i < length; i++) {
  25451. shape[index++] = shape2D[i].x - xOffset;
  25452. shape[index++] = 0;
  25453. shape[index++] = shape2D[i].y - yOffset;
  25454. }
  25455. return shape;
  25456. }
  25457. var quaterion = new Quaternion();
  25458. var startPointScratch = new Cartesian3();
  25459. var rotMatrix = new Matrix3();
  25460. function computeRoundCorner(pivot, startPoint, endPoint, cornerType, leftIsOutside, ellipsoid, finalPositions, shape, height, duplicatePoints) {
  25461. var angle = Cartesian3.angleBetween(Cartesian3.subtract(startPoint, pivot, scratch1), Cartesian3.subtract(endPoint, pivot, scratch2));
  25462. var granularity = (cornerType === CornerType.BEVELED) ? 0 : Math.ceil(angle / CesiumMath.toRadians(5));
  25463. var m;
  25464. if (leftIsOutside) {
  25465. m = Matrix3.fromQuaternion(Quaternion.fromAxisAngle(Cartesian3.negate(pivot, scratch1), angle / (granularity + 1), quaterion), rotMatrix);
  25466. } else {
  25467. m = Matrix3.fromQuaternion(Quaternion.fromAxisAngle(pivot, angle / (granularity + 1), quaterion), rotMatrix);
  25468. }
  25469. var left;
  25470. var surfacePoint;
  25471. startPoint = Cartesian3.clone(startPoint, startPointScratch);
  25472. if (granularity > 0) {
  25473. var repeat = duplicatePoints ? 2 : 1;
  25474. for (var i = 0; i < granularity; i++) {
  25475. startPoint = Matrix3.multiplyByVector(m, startPoint, startPoint);
  25476. left = Cartesian3.subtract(startPoint, pivot, scratch1);
  25477. left = Cartesian3.normalize(left, left);
  25478. if (!leftIsOutside) {
  25479. left = Cartesian3.negate(left, left);
  25480. }
  25481. surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2);
  25482. finalPositions = addPosition(surfacePoint, left, shape, finalPositions, ellipsoid, height, 1, repeat);
  25483. }
  25484. } else {
  25485. left = Cartesian3.subtract(startPoint, pivot, scratch1);
  25486. left = Cartesian3.normalize(left, left);
  25487. if (!leftIsOutside) {
  25488. left = Cartesian3.negate(left, left);
  25489. }
  25490. surfacePoint = ellipsoid.scaleToGeodeticSurface(startPoint, scratch2);
  25491. finalPositions = addPosition(surfacePoint, left, shape, finalPositions, ellipsoid, height, 1, 1);
  25492. endPoint = Cartesian3.clone(endPoint, startPointScratch);
  25493. left = Cartesian3.subtract(endPoint, pivot, scratch1);
  25494. left = Cartesian3.normalize(left, left);
  25495. if (!leftIsOutside) {
  25496. left = Cartesian3.negate(left, left);
  25497. }
  25498. surfacePoint = ellipsoid.scaleToGeodeticSurface(endPoint, scratch2);
  25499. finalPositions = addPosition(surfacePoint, left, shape, finalPositions, ellipsoid, height, 1, 1);
  25500. }
  25501. return finalPositions;
  25502. }
  25503. PolylineVolumeGeometryLibrary.removeDuplicatesFromShape = function(shapePositions) {
  25504. var length = shapePositions.length;
  25505. var cleanedPositions = [];
  25506. for (var i0 = length - 1, i1 = 0; i1 < length; i0 = i1++) {
  25507. var v0 = shapePositions[i0];
  25508. var v1 = shapePositions[i1];
  25509. if (!Cartesian2.equals(v0, v1)) {
  25510. cleanedPositions.push(v1); // Shallow copy!
  25511. }
  25512. }
  25513. return cleanedPositions;
  25514. };
  25515. var nextScratch = new Cartesian3();
  25516. var prevScratch = new Cartesian3();
  25517. PolylineVolumeGeometryLibrary.angleIsGreaterThanPi = function(forward, backward, position, ellipsoid) {
  25518. var tangentPlane = new EllipsoidTangentPlane(position, ellipsoid);
  25519. var next = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, forward, nextScratch), nextScratch);
  25520. var prev = tangentPlane.projectPointOntoPlane(Cartesian3.add(position, backward, prevScratch), prevScratch);
  25521. return ((prev.x * next.y) - (prev.y * next.x)) >= 0.0;
  25522. };
  25523. var scratchForwardProjection = new Cartesian3();
  25524. var scratchBackwardProjection = new Cartesian3();
  25525. PolylineVolumeGeometryLibrary.computePositions = function(positions, shape2D, boundingRectangle, geometry, duplicatePoints) {
  25526. var ellipsoid = geometry._ellipsoid;
  25527. var heights = scaleToSurface(positions, ellipsoid);
  25528. var granularity = geometry._granularity;
  25529. var cornerType = geometry._cornerType;
  25530. var shapeForSides = duplicatePoints ? convertShapeTo3DDuplicate(shape2D, boundingRectangle) : convertShapeTo3D(shape2D, boundingRectangle);
  25531. var shapeForEnds = duplicatePoints ? convertShapeTo3D(shape2D, boundingRectangle) : undefined;
  25532. var heightOffset = boundingRectangle.height / 2;
  25533. var width = boundingRectangle.width / 2;
  25534. var length = positions.length;
  25535. var finalPositions = [];
  25536. var ends = duplicatePoints ? [] : undefined;
  25537. var forward = scratchCartesian1;
  25538. var backward = scratchCartesian2;
  25539. var cornerDirection = scratchCartesian3;
  25540. var surfaceNormal = scratchCartesian4;
  25541. var pivot = scratchCartesian5;
  25542. var start = scratchCartesian6;
  25543. var end = scratchCartesian7;
  25544. var left = scratchCartesian8;
  25545. var previousPosition = scratchCartesian9;
  25546. var position = positions[0];
  25547. var nextPosition = positions[1];
  25548. surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);
  25549. forward = Cartesian3.subtract(nextPosition, position, forward);
  25550. forward = Cartesian3.normalize(forward, forward);
  25551. left = Cartesian3.cross(surfaceNormal, forward, left);
  25552. left = Cartesian3.normalize(left, left);
  25553. var h0 = heights[0];
  25554. var h1 = heights[1];
  25555. if (duplicatePoints) {
  25556. ends = addPosition(position, left, shapeForEnds, ends, ellipsoid, h0 + heightOffset, 1, 1);
  25557. }
  25558. previousPosition = Cartesian3.clone(position, previousPosition);
  25559. position = nextPosition;
  25560. backward = Cartesian3.negate(forward, backward);
  25561. var subdividedHeights;
  25562. var subdividedPositions;
  25563. for (var i = 1; i < length - 1; i++) {
  25564. var repeat = duplicatePoints ? 2 : 1;
  25565. nextPosition = positions[i + 1];
  25566. forward = Cartesian3.subtract(nextPosition, position, forward);
  25567. forward = Cartesian3.normalize(forward, forward);
  25568. cornerDirection = Cartesian3.add(forward, backward, cornerDirection);
  25569. cornerDirection = Cartesian3.normalize(cornerDirection, cornerDirection);
  25570. surfaceNormal = ellipsoid.geodeticSurfaceNormal(position, surfaceNormal);
  25571. var forwardProjection = Cartesian3.multiplyByScalar(surfaceNormal, Cartesian3.dot(forward, surfaceNormal), scratchForwardProjection);
  25572. Cartesian3.subtract(forward, forwardProjection, forwardProjection);
  25573. Cartesian3.normalize(forwardProjection, forwardProjection);
  25574. var backwardProjection = Cartesian3.multiplyByScalar(surfaceNormal, Cartesian3.dot(backward, surfaceNormal), scratchBackwardProjection);
  25575. Cartesian3.subtract(backward, backwardProjection, backwardProjection);
  25576. Cartesian3.normalize(backwardProjection, backwardProjection);
  25577. var doCorner = !CesiumMath.equalsEpsilon(Math.abs(Cartesian3.dot(forwardProjection, backwardProjection)), 1.0, CesiumMath.EPSILON7);
  25578. if (doCorner) {
  25579. cornerDirection = Cartesian3.cross(cornerDirection, surfaceNormal, cornerDirection);
  25580. cornerDirection = Cartesian3.cross(surfaceNormal, cornerDirection, cornerDirection);
  25581. cornerDirection = Cartesian3.normalize(cornerDirection, cornerDirection);
  25582. var scalar = 1 / Math.max(0.25, (Cartesian3.magnitude(Cartesian3.cross(cornerDirection, backward, scratch1))));
  25583. var leftIsOutside = PolylineVolumeGeometryLibrary.angleIsGreaterThanPi(forward, backward, position, ellipsoid);
  25584. if (leftIsOutside) {
  25585. pivot = Cartesian3.add(position, Cartesian3.multiplyByScalar(cornerDirection, scalar * width, cornerDirection), pivot);
  25586. start = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, width, start), start);
  25587. scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
  25588. scratch2Array[1] = Cartesian3.clone(start, scratch2Array[1]);
  25589. subdividedHeights = subdivideHeights(scratch2Array, h0 + heightOffset, h1 + heightOffset, granularity);
  25590. subdividedPositions = PolylinePipeline.generateArc({
  25591. positions: scratch2Array,
  25592. granularity: granularity,
  25593. ellipsoid: ellipsoid
  25594. });
  25595. finalPositions = addPositions(subdividedPositions, left, shapeForSides, finalPositions, ellipsoid, subdividedHeights, 1);
  25596. left = Cartesian3.cross(surfaceNormal, forward, left);
  25597. left = Cartesian3.normalize(left, left);
  25598. end = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, width, end), end);
  25599. if (cornerType === CornerType.ROUNDED || cornerType === CornerType.BEVELED) {
  25600. computeRoundCorner(pivot, start, end, cornerType, leftIsOutside, ellipsoid, finalPositions, shapeForSides, h1 + heightOffset, duplicatePoints);
  25601. } else {
  25602. cornerDirection = Cartesian3.negate(cornerDirection, cornerDirection);
  25603. finalPositions = addPosition(position, cornerDirection, shapeForSides, finalPositions, ellipsoid, h1 + heightOffset, scalar, repeat);
  25604. }
  25605. previousPosition = Cartesian3.clone(end, previousPosition);
  25606. } else {
  25607. pivot = Cartesian3.add(position, Cartesian3.multiplyByScalar(cornerDirection, scalar * width, cornerDirection), pivot);
  25608. start = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, -width, start), start);
  25609. scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
  25610. scratch2Array[1] = Cartesian3.clone(start, scratch2Array[1]);
  25611. subdividedHeights = subdivideHeights(scratch2Array, h0 + heightOffset, h1 + heightOffset, granularity);
  25612. subdividedPositions = PolylinePipeline.generateArc({
  25613. positions: scratch2Array,
  25614. granularity: granularity,
  25615. ellipsoid: ellipsoid
  25616. });
  25617. finalPositions = addPositions(subdividedPositions, left, shapeForSides, finalPositions, ellipsoid, subdividedHeights, 1);
  25618. left = Cartesian3.cross(surfaceNormal, forward, left);
  25619. left = Cartesian3.normalize(left, left);
  25620. end = Cartesian3.add(pivot, Cartesian3.multiplyByScalar(left, -width, end), end);
  25621. if (cornerType === CornerType.ROUNDED || cornerType === CornerType.BEVELED) {
  25622. computeRoundCorner(pivot, start, end, cornerType, leftIsOutside, ellipsoid, finalPositions, shapeForSides, h1 + heightOffset, duplicatePoints);
  25623. } else {
  25624. finalPositions = addPosition(position, cornerDirection, shapeForSides, finalPositions, ellipsoid, h1 + heightOffset, scalar, repeat);
  25625. }
  25626. previousPosition = Cartesian3.clone(end, previousPosition);
  25627. }
  25628. backward = Cartesian3.negate(forward, backward);
  25629. } else {
  25630. finalPositions = addPosition(previousPosition, left, shapeForSides, finalPositions, ellipsoid, h0 + heightOffset, 1, 1);
  25631. previousPosition = position;
  25632. }
  25633. h0 = h1;
  25634. h1 = heights[i + 1];
  25635. position = nextPosition;
  25636. }
  25637. scratch2Array[0] = Cartesian3.clone(previousPosition, scratch2Array[0]);
  25638. scratch2Array[1] = Cartesian3.clone(position, scratch2Array[1]);
  25639. subdividedHeights = subdivideHeights(scratch2Array, h0 + heightOffset, h1 + heightOffset, granularity);
  25640. subdividedPositions = PolylinePipeline.generateArc({
  25641. positions: scratch2Array,
  25642. granularity: granularity,
  25643. ellipsoid: ellipsoid
  25644. });
  25645. finalPositions = addPositions(subdividedPositions, left, shapeForSides, finalPositions, ellipsoid, subdividedHeights, 1);
  25646. if (duplicatePoints) {
  25647. ends = addPosition(position, left, shapeForEnds, ends, ellipsoid, h1 + heightOffset, 1, 1);
  25648. }
  25649. length = finalPositions.length;
  25650. var posLength = duplicatePoints ? length + ends.length : length;
  25651. var combinedPositions = new Float64Array(posLength);
  25652. combinedPositions.set(finalPositions);
  25653. if (duplicatePoints) {
  25654. combinedPositions.set(ends, length);
  25655. }
  25656. return combinedPositions;
  25657. };
  25658. return PolylineVolumeGeometryLibrary;
  25659. });
  25660. /*global define*/
  25661. define('Core/VertexFormat',[
  25662. './defaultValue',
  25663. './defined',
  25664. './DeveloperError',
  25665. './freezeObject'
  25666. ], function(
  25667. defaultValue,
  25668. defined,
  25669. DeveloperError,
  25670. freezeObject) {
  25671. 'use strict';
  25672. /**
  25673. * A vertex format defines what attributes make up a vertex. A VertexFormat can be provided
  25674. * to a {@link Geometry} to request that certain properties be computed, e.g., just position,
  25675. * position and normal, etc.
  25676. *
  25677. * @param {Object} [options] An object with boolean properties corresponding to VertexFormat properties as shown in the code example.
  25678. *
  25679. * @alias VertexFormat
  25680. * @constructor
  25681. *
  25682. * @example
  25683. * // Create a vertex format with position and 2D texture coordinate attributes.
  25684. * var format = new Cesium.VertexFormat({
  25685. * position : true,
  25686. * st : true
  25687. * });
  25688. *
  25689. * @see Geometry#attributes
  25690. * @see Packable
  25691. */
  25692. function VertexFormat(options) {
  25693. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  25694. /**
  25695. * When <code>true</code>, the vertex has a 3D position attribute.
  25696. * <p>
  25697. * 64-bit floating-point (for precision). 3 components per attribute.
  25698. * </p>
  25699. *
  25700. * @type Boolean
  25701. *
  25702. * @default false
  25703. */
  25704. this.position = defaultValue(options.position, false);
  25705. /**
  25706. * When <code>true</code>, the vertex has a normal attribute (normalized), which is commonly used for lighting.
  25707. * <p>
  25708. * 32-bit floating-point. 3 components per attribute.
  25709. * </p>
  25710. *
  25711. * @type Boolean
  25712. *
  25713. * @default false
  25714. */
  25715. this.normal = defaultValue(options.normal, false);
  25716. /**
  25717. * When <code>true</code>, the vertex has a 2D texture coordinate attribute.
  25718. * <p>
  25719. * 32-bit floating-point. 2 components per attribute
  25720. * </p>
  25721. *
  25722. * @type Boolean
  25723. *
  25724. * @default false
  25725. */
  25726. this.st = defaultValue(options.st, false);
  25727. /**
  25728. * When <code>true</code>, the vertex has a binormal attribute (normalized), which is used for tangent-space effects like bump mapping.
  25729. * <p>
  25730. * 32-bit floating-point. 3 components per attribute.
  25731. * </p>
  25732. *
  25733. * @type Boolean
  25734. *
  25735. * @default false
  25736. */
  25737. this.binormal = defaultValue(options.binormal, false);
  25738. /**
  25739. * When <code>true</code>, the vertex has a tangent attribute (normalized), which is used for tangent-space effects like bump mapping.
  25740. * <p>
  25741. * 32-bit floating-point. 3 components per attribute.
  25742. * </p>
  25743. *
  25744. * @type Boolean
  25745. *
  25746. * @default false
  25747. */
  25748. this.tangent = defaultValue(options.tangent, false);
  25749. /**
  25750. * When <code>true</code>, the vertex has an RGB color attribute.
  25751. * <p>
  25752. * 8-bit unsigned byte. 3 components per attribute.
  25753. * </p>
  25754. *
  25755. * @type Boolean
  25756. *
  25757. * @default false
  25758. */
  25759. this.color = defaultValue(options.color, false);
  25760. }
  25761. /**
  25762. * An immutable vertex format with only a position attribute.
  25763. *
  25764. * @type {VertexFormat}
  25765. * @constant
  25766. *
  25767. * @see VertexFormat#position
  25768. */
  25769. VertexFormat.POSITION_ONLY = freezeObject(new VertexFormat({
  25770. position : true
  25771. }));
  25772. /**
  25773. * An immutable vertex format with position and normal attributes.
  25774. * This is compatible with per-instance color appearances like {@link PerInstanceColorAppearance}.
  25775. *
  25776. * @type {VertexFormat}
  25777. * @constant
  25778. *
  25779. * @see VertexFormat#position
  25780. * @see VertexFormat#normal
  25781. */
  25782. VertexFormat.POSITION_AND_NORMAL = freezeObject(new VertexFormat({
  25783. position : true,
  25784. normal : true
  25785. }));
  25786. /**
  25787. * An immutable vertex format with position, normal, and st attributes.
  25788. * This is compatible with {@link MaterialAppearance} when {@link MaterialAppearance#materialSupport}
  25789. * is <code>TEXTURED/code>.
  25790. *
  25791. * @type {VertexFormat}
  25792. * @constant
  25793. *
  25794. * @see VertexFormat#position
  25795. * @see VertexFormat#normal
  25796. * @see VertexFormat#st
  25797. */
  25798. VertexFormat.POSITION_NORMAL_AND_ST = freezeObject(new VertexFormat({
  25799. position : true,
  25800. normal : true,
  25801. st : true
  25802. }));
  25803. /**
  25804. * An immutable vertex format with position and st attributes.
  25805. * This is compatible with {@link EllipsoidSurfaceAppearance}.
  25806. *
  25807. * @type {VertexFormat}
  25808. * @constant
  25809. *
  25810. * @see VertexFormat#position
  25811. * @see VertexFormat#st
  25812. */
  25813. VertexFormat.POSITION_AND_ST = freezeObject(new VertexFormat({
  25814. position : true,
  25815. st : true
  25816. }));
  25817. /**
  25818. * An immutable vertex format with position and color attributes.
  25819. *
  25820. * @type {VertexFormat}
  25821. * @constant
  25822. *
  25823. * @see VertexFormat#position
  25824. * @see VertexFormat#color
  25825. */
  25826. VertexFormat.POSITION_AND_COLOR = freezeObject(new VertexFormat({
  25827. position : true,
  25828. color : true
  25829. }));
  25830. /**
  25831. * An immutable vertex format with well-known attributes: position, normal, st, binormal, and tangent.
  25832. *
  25833. * @type {VertexFormat}
  25834. * @constant
  25835. *
  25836. * @see VertexFormat#position
  25837. * @see VertexFormat#normal
  25838. * @see VertexFormat#st
  25839. * @see VertexFormat#binormal
  25840. * @see VertexFormat#tangent
  25841. */
  25842. VertexFormat.ALL = freezeObject(new VertexFormat({
  25843. position : true,
  25844. normal : true,
  25845. st : true,
  25846. binormal : true,
  25847. tangent : true
  25848. }));
  25849. /**
  25850. * An immutable vertex format with position, normal, and st attributes.
  25851. * This is compatible with most appearances and materials; however
  25852. * normal and st attributes are not always required. When this is
  25853. * known in advance, another <code>VertexFormat</code> should be used.
  25854. *
  25855. * @type {VertexFormat}
  25856. * @constant
  25857. *
  25858. * @see VertexFormat#position
  25859. * @see VertexFormat#normal
  25860. */
  25861. VertexFormat.DEFAULT = VertexFormat.POSITION_NORMAL_AND_ST;
  25862. /**
  25863. * The number of elements used to pack the object into an array.
  25864. * @type {Number}
  25865. */
  25866. VertexFormat.packedLength = 6;
  25867. /**
  25868. * Stores the provided instance into the provided array.
  25869. *
  25870. * @param {VertexFormat} value The value to pack.
  25871. * @param {Number[]} array The array to pack into.
  25872. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  25873. *
  25874. * @returns {Number[]} The array that was packed into
  25875. */
  25876. VertexFormat.pack = function(value, array, startingIndex) {
  25877. if (!defined(value)) {
  25878. throw new DeveloperError('value is required');
  25879. }
  25880. if (!defined(array)) {
  25881. throw new DeveloperError('array is required');
  25882. }
  25883. startingIndex = defaultValue(startingIndex, 0);
  25884. array[startingIndex++] = value.position ? 1.0 : 0.0;
  25885. array[startingIndex++] = value.normal ? 1.0 : 0.0;
  25886. array[startingIndex++] = value.st ? 1.0 : 0.0;
  25887. array[startingIndex++] = value.binormal ? 1.0 : 0.0;
  25888. array[startingIndex++] = value.tangent ? 1.0 : 0.0;
  25889. array[startingIndex++] = value.color ? 1.0 : 0.0;
  25890. return array;
  25891. };
  25892. /**
  25893. * Retrieves an instance from a packed array.
  25894. *
  25895. * @param {Number[]} array The packed array.
  25896. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  25897. * @param {VertexFormat} [result] The object into which to store the result.
  25898. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided.
  25899. */
  25900. VertexFormat.unpack = function(array, startingIndex, result) {
  25901. if (!defined(array)) {
  25902. throw new DeveloperError('array is required');
  25903. }
  25904. startingIndex = defaultValue(startingIndex, 0);
  25905. if (!defined(result)) {
  25906. result = new VertexFormat();
  25907. }
  25908. result.position = array[startingIndex++] === 1.0;
  25909. result.normal = array[startingIndex++] === 1.0;
  25910. result.st = array[startingIndex++] === 1.0;
  25911. result.binormal = array[startingIndex++] === 1.0;
  25912. result.tangent = array[startingIndex++] === 1.0;
  25913. result.color = array[startingIndex++] === 1.0;
  25914. return result;
  25915. };
  25916. /**
  25917. * Duplicates a VertexFormat instance.
  25918. *
  25919. * @param {VertexFormat} cartesian The vertex format to duplicate.
  25920. * @param {VertexFormat} [result] The object onto which to store the result.
  25921. * @returns {VertexFormat} The modified result parameter or a new VertexFormat instance if one was not provided. (Returns undefined if vertexFormat is undefined)
  25922. */
  25923. VertexFormat.clone = function(vertexFormat, result) {
  25924. if (!defined(vertexFormat)) {
  25925. return undefined;
  25926. }
  25927. if (!defined(result)) {
  25928. result = new VertexFormat();
  25929. }
  25930. result.position = vertexFormat.position;
  25931. result.normal = vertexFormat.normal;
  25932. result.st = vertexFormat.st;
  25933. result.binormal = vertexFormat.binormal;
  25934. result.tangent = vertexFormat.tangent;
  25935. result.color = vertexFormat.color;
  25936. return result;
  25937. };
  25938. return VertexFormat;
  25939. });
  25940. /*global define*/
  25941. define('Core/PolylineVolumeGeometry',[
  25942. './arrayRemoveDuplicates',
  25943. './BoundingRectangle',
  25944. './BoundingSphere',
  25945. './Cartesian2',
  25946. './Cartesian3',
  25947. './ComponentDatatype',
  25948. './CornerType',
  25949. './defaultValue',
  25950. './defined',
  25951. './DeveloperError',
  25952. './Ellipsoid',
  25953. './Geometry',
  25954. './GeometryAttribute',
  25955. './GeometryAttributes',
  25956. './GeometryPipeline',
  25957. './IndexDatatype',
  25958. './Math',
  25959. './oneTimeWarning',
  25960. './PolygonPipeline',
  25961. './PolylineVolumeGeometryLibrary',
  25962. './PrimitiveType',
  25963. './VertexFormat',
  25964. './WindingOrder'
  25965. ], function(
  25966. arrayRemoveDuplicates,
  25967. BoundingRectangle,
  25968. BoundingSphere,
  25969. Cartesian2,
  25970. Cartesian3,
  25971. ComponentDatatype,
  25972. CornerType,
  25973. defaultValue,
  25974. defined,
  25975. DeveloperError,
  25976. Ellipsoid,
  25977. Geometry,
  25978. GeometryAttribute,
  25979. GeometryAttributes,
  25980. GeometryPipeline,
  25981. IndexDatatype,
  25982. CesiumMath,
  25983. oneTimeWarning,
  25984. PolygonPipeline,
  25985. PolylineVolumeGeometryLibrary,
  25986. PrimitiveType,
  25987. VertexFormat,
  25988. WindingOrder) {
  25989. 'use strict';
  25990. function computeAttributes(combinedPositions, shape, boundingRectangle, vertexFormat) {
  25991. var attributes = new GeometryAttributes();
  25992. if (vertexFormat.position) {
  25993. attributes.position = new GeometryAttribute({
  25994. componentDatatype : ComponentDatatype.DOUBLE,
  25995. componentsPerAttribute : 3,
  25996. values : combinedPositions
  25997. });
  25998. }
  25999. var shapeLength = shape.length;
  26000. var vertexCount = combinedPositions.length / 3;
  26001. var length = (vertexCount - shapeLength * 2) / (shapeLength * 2);
  26002. var firstEndIndices = PolygonPipeline.triangulate(shape);
  26003. var indicesCount = (length - 1) * (shapeLength) * 6 + firstEndIndices.length * 2;
  26004. var indices = IndexDatatype.createTypedArray(vertexCount, indicesCount);
  26005. var i, j;
  26006. var ll, ul, ur, lr;
  26007. var offset = shapeLength * 2;
  26008. var index = 0;
  26009. for (i = 0; i < length - 1; i++) {
  26010. for (j = 0; j < shapeLength - 1; j++) {
  26011. ll = j * 2 + i * shapeLength * 2;
  26012. lr = ll + offset;
  26013. ul = ll + 1;
  26014. ur = ul + offset;
  26015. indices[index++] = ul;
  26016. indices[index++] = ll;
  26017. indices[index++] = ur;
  26018. indices[index++] = ur;
  26019. indices[index++] = ll;
  26020. indices[index++] = lr;
  26021. }
  26022. ll = shapeLength * 2 - 2 + i * shapeLength * 2;
  26023. ul = ll + 1;
  26024. ur = ul + offset;
  26025. lr = ll + offset;
  26026. indices[index++] = ul;
  26027. indices[index++] = ll;
  26028. indices[index++] = ur;
  26029. indices[index++] = ur;
  26030. indices[index++] = ll;
  26031. indices[index++] = lr;
  26032. }
  26033. if (vertexFormat.st || vertexFormat.tangent || vertexFormat.binormal) { // st required for tangent/binormal calculation
  26034. var st = new Float32Array(vertexCount * 2);
  26035. var lengthSt = 1 / (length - 1);
  26036. var heightSt = 1 / (boundingRectangle.height);
  26037. var heightOffset = boundingRectangle.height / 2;
  26038. var s, t;
  26039. var stindex = 0;
  26040. for (i = 0; i < length; i++) {
  26041. s = i * lengthSt;
  26042. t = heightSt * (shape[0].y + heightOffset);
  26043. st[stindex++] = s;
  26044. st[stindex++] = t;
  26045. for (j = 1; j < shapeLength; j++) {
  26046. t = heightSt * (shape[j].y + heightOffset);
  26047. st[stindex++] = s;
  26048. st[stindex++] = t;
  26049. st[stindex++] = s;
  26050. st[stindex++] = t;
  26051. }
  26052. t = heightSt * (shape[0].y + heightOffset);
  26053. st[stindex++] = s;
  26054. st[stindex++] = t;
  26055. }
  26056. for (j = 0; j < shapeLength; j++) {
  26057. s = 0;
  26058. t = heightSt * (shape[j].y + heightOffset);
  26059. st[stindex++] = s;
  26060. st[stindex++] = t;
  26061. }
  26062. for (j = 0; j < shapeLength; j++) {
  26063. s = (length - 1) * lengthSt;
  26064. t = heightSt * (shape[j].y + heightOffset);
  26065. st[stindex++] = s;
  26066. st[stindex++] = t;
  26067. }
  26068. attributes.st = new GeometryAttribute({
  26069. componentDatatype : ComponentDatatype.FLOAT,
  26070. componentsPerAttribute : 2,
  26071. values : new Float32Array(st)
  26072. });
  26073. }
  26074. var endOffset = vertexCount - shapeLength * 2;
  26075. for (i = 0; i < firstEndIndices.length; i += 3) {
  26076. var v0 = firstEndIndices[i] + endOffset;
  26077. var v1 = firstEndIndices[i + 1] + endOffset;
  26078. var v2 = firstEndIndices[i + 2] + endOffset;
  26079. indices[index++] = v0;
  26080. indices[index++] = v1;
  26081. indices[index++] = v2;
  26082. indices[index++] = v2 + shapeLength;
  26083. indices[index++] = v1 + shapeLength;
  26084. indices[index++] = v0 + shapeLength;
  26085. }
  26086. var geometry = new Geometry({
  26087. attributes : attributes,
  26088. indices : indices,
  26089. boundingSphere : BoundingSphere.fromVertices(combinedPositions),
  26090. primitiveType : PrimitiveType.TRIANGLES
  26091. });
  26092. if (vertexFormat.normal) {
  26093. geometry = GeometryPipeline.computeNormal(geometry);
  26094. }
  26095. if (vertexFormat.tangent || vertexFormat.binormal) {
  26096. try {
  26097. geometry = GeometryPipeline.computeBinormalAndTangent(geometry);
  26098. } catch (e) {
  26099. oneTimeWarning('polyline-volume-tangent-binormal', 'Unable to compute tangents and binormals for polyline volume geometry');
  26100. //TODO https://github.com/AnalyticalGraphicsInc/cesium/issues/3609
  26101. }
  26102. if (!vertexFormat.tangent) {
  26103. geometry.attributes.tangent = undefined;
  26104. }
  26105. if (!vertexFormat.binormal) {
  26106. geometry.attributes.binormal = undefined;
  26107. }
  26108. if (!vertexFormat.st) {
  26109. geometry.attributes.st = undefined;
  26110. }
  26111. }
  26112. return geometry;
  26113. }
  26114. /**
  26115. * A description of a polyline with a volume (a 2D shape extruded along a polyline).
  26116. *
  26117. * @alias PolylineVolumeGeometry
  26118. * @constructor
  26119. *
  26120. * @param {Object} options Object with the following properties:
  26121. * @param {Cartesian3[]} options.polylinePositions An array of {@link Cartesain3} positions that define the center of the polyline volume.
  26122. * @param {Cartesian2[]} options.shapePositions An array of {@link Cartesian2} positions that define the shape to be extruded along the polyline
  26123. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid to be used as a reference.
  26124. * @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.
  26125. * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
  26126. * @param {CornerType} [options.cornerType=CornerType.ROUNDED] Determines the style of the corners.
  26127. *
  26128. * @see PolylineVolumeGeometry#createGeometry
  26129. *
  26130. * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Polyline%20Volume.html|Cesium Sandcastle Polyline Volume Demo}
  26131. *
  26132. * @example
  26133. * function computeCircle(radius) {
  26134. * var positions = [];
  26135. * for (var i = 0; i < 360; i++) {
  26136. * var radians = Cesium.Math.toRadians(i);
  26137. * positions.push(new Cesium.Cartesian2(radius * Math.cos(radians), radius * Math.sin(radians)));
  26138. * }
  26139. * return positions;
  26140. * }
  26141. *
  26142. * var volume = new Cesium.PolylineVolumeGeometry({
  26143. * vertexFormat : Cesium.VertexFormat.POSITION_ONLY,
  26144. * polylinePositions : Cesium.Cartesian3.fromDegreesArray([
  26145. * -72.0, 40.0,
  26146. * -70.0, 35.0
  26147. * ]),
  26148. * shapePositions : computeCircle(100000.0)
  26149. * });
  26150. */
  26151. function PolylineVolumeGeometry(options) {
  26152. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  26153. var positions = options.polylinePositions;
  26154. var shape = options.shapePositions;
  26155. if (!defined(positions)) {
  26156. throw new DeveloperError('options.polylinePositions is required.');
  26157. }
  26158. if (!defined(shape)) {
  26159. throw new DeveloperError('options.shapePositions is required.');
  26160. }
  26161. this._positions = positions;
  26162. this._shape = shape;
  26163. this._ellipsoid = Ellipsoid.clone(defaultValue(options.ellipsoid, Ellipsoid.WGS84));
  26164. this._cornerType = defaultValue(options.cornerType, CornerType.ROUNDED);
  26165. this._vertexFormat = VertexFormat.clone(defaultValue(options.vertexFormat, VertexFormat.DEFAULT));
  26166. this._granularity = defaultValue(options.granularity, CesiumMath.RADIANS_PER_DEGREE);
  26167. this._workerName = 'createPolylineVolumeGeometry';
  26168. var numComponents = 1 + positions.length * Cartesian3.packedLength;
  26169. numComponents += 1 + shape.length * Cartesian2.packedLength;
  26170. /**
  26171. * The number of elements used to pack the object into an array.
  26172. * @type {Number}
  26173. */
  26174. this.packedLength = numComponents + Ellipsoid.packedLength + VertexFormat.packedLength + 2;
  26175. }
  26176. /**
  26177. * Stores the provided instance into the provided array.
  26178. *
  26179. * @param {PolylineVolumeGeometry} value The value to pack.
  26180. * @param {Number[]} array The array to pack into.
  26181. * @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
  26182. *
  26183. * @returns {Number[]} The array that was packed into
  26184. */
  26185. PolylineVolumeGeometry.pack = function(value, array, startingIndex) {
  26186. if (!defined(value)) {
  26187. throw new DeveloperError('value is required');
  26188. }
  26189. if (!defined(array)) {
  26190. throw new DeveloperError('array is required');
  26191. }
  26192. startingIndex = defaultValue(startingIndex, 0);
  26193. var i;
  26194. var positions = value._positions;
  26195. var length = positions.length;
  26196. array[startingIndex++] = length;
  26197. for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
  26198. Cartesian3.pack(positions[i], array, startingIndex);
  26199. }
  26200. var shape = value._shape;
  26201. length = shape.length;
  26202. array[startingIndex++] = length;
  26203. for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
  26204. Cartesian2.pack(shape[i], array, startingIndex);
  26205. }
  26206. Ellipsoid.pack(value._ellipsoid, array, startingIndex);
  26207. startingIndex += Ellipsoid.packedLength;
  26208. VertexFormat.pack(value._vertexFormat, array, startingIndex);
  26209. startingIndex += VertexFormat.packedLength;
  26210. array[startingIndex++] = value._cornerType;
  26211. array[startingIndex] = value._granularity;
  26212. return array;
  26213. };
  26214. var scratchEllipsoid = Ellipsoid.clone(Ellipsoid.UNIT_SPHERE);
  26215. var scratchVertexFormat = new VertexFormat();
  26216. var scratchOptions = {
  26217. polylinePositions : undefined,
  26218. shapePositions : undefined,
  26219. ellipsoid : scratchEllipsoid,
  26220. vertexFormat : scratchVertexFormat,
  26221. cornerType : undefined,
  26222. granularity : undefined
  26223. };
  26224. /**
  26225. * Retrieves an instance from a packed array.
  26226. *
  26227. * @param {Number[]} array The packed array.
  26228. * @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
  26229. * @param {PolylineVolumeGeometry} [result] The object into which to store the result.
  26230. * @returns {PolylineVolumeGeometry} The modified result parameter or a new PolylineVolumeGeometry instance if one was not provided.
  26231. */
  26232. PolylineVolumeGeometry.unpack = function(array, startingIndex, result) {
  26233. if (!defined(array)) {
  26234. throw new DeveloperError('array is required');
  26235. }
  26236. startingIndex = defaultValue(startingIndex, 0);
  26237. var i;
  26238. var length = array[startingIndex++];
  26239. var positions = new Array(length);
  26240. for (i = 0; i < length; ++i, startingIndex += Cartesian3.packedLength) {
  26241. positions[i] = Cartesian3.unpack(array, startingIndex);
  26242. }
  26243. length = array[startingIndex++];
  26244. var shape = new Array(length);
  26245. for (i = 0; i < length; ++i, startingIndex += Cartesian2.packedLength) {
  26246. shape[i] = Cartesian2.unpack(array, startingIndex);
  26247. }
  26248. var ellipsoid = Ellipsoid.unpack(array, startingIndex, scratchEllipsoid);
  26249. startingIndex += Ellipsoid.packedLength;
  26250. var vertexFormat = VertexFormat.unpack(array, startingIndex, scratchVertexFormat);
  26251. startingIndex += VertexFormat.packedLength;
  26252. var cornerType = array[startingIndex++];
  26253. var granularity = array[startingIndex];
  26254. if (!defined(result)) {
  26255. scratchOptions.polylinePositions = positions;
  26256. scratchOptions.shapePositions = shape;
  26257. scratchOptions.cornerType = cornerType;
  26258. scratchOptions.granularity = granularity;
  26259. return new PolylineVolumeGeometry(scratchOptions);
  26260. }
  26261. result._positions = positions;
  26262. result._shape = shape;
  26263. result._ellipsoid = Ellipsoid.clone(ellipsoid, result._ellipsoid);
  26264. result._vertexFormat = VertexFormat.clone(vertexFormat, result._vertexFormat);
  26265. result._cornerType = cornerType;
  26266. result._granularity = granularity;
  26267. return result;
  26268. };
  26269. var brScratch = new BoundingRectangle();
  26270. /**
  26271. * Computes the geometric representation of a polyline with a volume, including its vertices, indices, and a bounding sphere.
  26272. *
  26273. * @param {PolylineVolumeGeometry} polylineVolumeGeometry A description of the polyline volume.
  26274. * @returns {Geometry|undefined} The computed vertices and indices.
  26275. */
  26276. PolylineVolumeGeometry.createGeometry = function(polylineVolumeGeometry) {
  26277. var positions = polylineVolumeGeometry._positions;
  26278. var cleanPositions = arrayRemoveDuplicates(positions, Cartesian3.equalsEpsilon);
  26279. var shape2D = polylineVolumeGeometry._shape;
  26280. shape2D = PolylineVolumeGeometryLibrary.removeDuplicatesFromShape(shape2D);
  26281. if (cleanPositions.length < 2 || shape2D.length < 3) {
  26282. return undefined;
  26283. }
  26284. if (PolygonPipeline.computeWindingOrder2D(shape2D) === WindingOrder.CLOCKWISE) {
  26285. shape2D.reverse();
  26286. }
  26287. var boundingRectangle = BoundingRectangle.fromPoints(shape2D, brScratch);
  26288. var computedPositions = PolylineVolumeGeometryLibrary.computePositions(cleanPositions, shape2D, boundingRectangle, polylineVolumeGeometry, true);
  26289. return computeAttributes(computedPositions, shape2D, boundingRectangle, polylineVolumeGeometry._vertexFormat);
  26290. };
  26291. return PolylineVolumeGeometry;
  26292. });
  26293. /*global define*/
  26294. define('Workers/createPolylineVolumeGeometry',[
  26295. '../Core/defined',
  26296. '../Core/Ellipsoid',
  26297. '../Core/PolylineVolumeGeometry'
  26298. ], function(
  26299. defined,
  26300. Ellipsoid,
  26301. PolylineVolumeGeometry) {
  26302. 'use strict';
  26303. function createPolylineVolumeGeometry(polylineVolumeGeometry, offset) {
  26304. if (defined(offset)) {
  26305. polylineVolumeGeometry = PolylineVolumeGeometry.unpack(polylineVolumeGeometry, offset);
  26306. }
  26307. polylineVolumeGeometry._ellipsoid = Ellipsoid.clone(polylineVolumeGeometry._ellipsoid);
  26308. return PolylineVolumeGeometry.createGeometry(polylineVolumeGeometry);
  26309. }
  26310. return createPolylineVolumeGeometry;
  26311. });
  26312. }());